-
-
Notifications
You must be signed in to change notification settings - Fork 48.7k
Added sliding_window_attention #12212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
d6609cb
Create README.md
Pritam3355 28b1f02
Update README.md
Pritam3355 998eed4
Add files via upload
Pritam3355 7019bf4
Delete llm_experiments directory
Pritam3355 f3d43e8
Create README.md
Pritam3355 2dad12b
Add files via upload
Pritam3355 4ecdca1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] f8510d7
Add files via upload
Pritam3355 fb102e6
Delete neural_network/chatbot/main.py
Pritam3355 6e7a428
Delete neural_network/chatbot/llm_service.py
Pritam3355 922a230
Delete neural_network/chatbot/chatbot.py
Pritam3355 a1d4cd9
Delete neural_network/chatbot/db.py
Pritam3355 508249e
Update README.md
Pritam3355 4af7a67
Add files via upload
Pritam3355 7c49052
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 276528d
Add files via upload
Pritam3355 789e975
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 3e4430d
Add files via upload
Pritam3355 322434d
Add files via upload
Pritam3355 5d91b30
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 30170fd
Delete neural_network/chatbot directory
Pritam3355 b23cc1a
Add files via upload
Pritam3355 b3c2a73
Add files via upload
Pritam3355 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
""" | ||
- - - - - -- - - - - - - - - - - - - - - - - - - - - - - | ||
Name - - sliding_window_attention.py | ||
Goal - - Implement a neural network architecture using sliding window attention for sequence modeling tasks. | ||
Detail: Total 5 layers neural network | ||
* Input layer | ||
* Sliding Window Attention Layer | ||
* Feedforward Layer | ||
* Output Layer | ||
Author: Stephen Lee | ||
Github: [email protected] | ||
Date: 2024.10.20 | ||
References: | ||
1. Choromanska, A., et al. (2020). "On the Importance of Initialization and Momentum in Deep Learning." *Proceedings of the 37th International Conference on Machine Learning*. | ||
2. Dai, Z., et al. (2020). "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention." *arXiv preprint arXiv:2006.16236*. | ||
3. [Attention Mechanisms in Neural Networks](https://en.wikipedia.org/wiki/Attention_(machine_learning)) | ||
- - - - - -- - - - - - - - - - - - - - - - - - - - - - - | ||
""" | ||
|
||
import numpy as np | ||
|
||
|
||
class SlidingWindowAttention: | ||
"""Sliding Window Attention Module. | ||
|
||
This class implements a sliding window attention mechanism where the model | ||
attends to a fixed-size window of context around each token. | ||
|
||
Attributes: | ||
window_size (int): The size of the attention window. | ||
embed_dim (int): The dimensionality of the input embeddings. | ||
""" | ||
|
||
def __init__(self, embed_dim: int, window_size: int): | ||
""" | ||
Initialize the SlidingWindowAttention module. | ||
|
||
Args: | ||
embed_dim (int): The dimensionality of the input embeddings. | ||
window_size (int): The size of the attention window. | ||
""" | ||
self.window_size = window_size | ||
self.embed_dim = embed_dim | ||
self.attention_weights = np.random.randn(embed_dim, embed_dim) | ||
|
||
def forward(self, x: np.ndarray) -> np.ndarray: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please provide descriptive name for the parameter: |
||
""" | ||
Forward pass for the sliding window attention. | ||
|
||
Args: | ||
x (np.ndarray): Input tensor of shape (batch_size, seq_length, embed_dim). | ||
|
||
Returns: | ||
np.ndarray: Output tensor of shape (batch_size, seq_length, embed_dim). | ||
|
||
>>> x = np.random.randn(2, 10, 4) # Batch size 2, sequence length 10, embedding dimension 4 | ||
>>> attention = SlidingWindowAttention(embed_dim=4, window_size=3) | ||
>>> output = attention.forward(x) | ||
>>> output.shape | ||
(2, 10, 4) | ||
>>> (output.sum() != 0).item() # Check if output is non-zero | ||
True | ||
""" | ||
batch_size, seq_length, _ = x.shape | ||
output = np.zeros_like(x) | ||
|
||
for i in range(seq_length): | ||
# Define the window range | ||
start = max(0, i - self.window_size // 2) | ||
end = min(seq_length, i + self.window_size // 2 + 1) | ||
|
||
# Extract the local window | ||
local_window = x[:, start:end, :] | ||
|
||
# Compute attention scores | ||
attention_scores = np.matmul(local_window, self.attention_weights) | ||
|
||
# Average the attention scores | ||
output[:, i, :] = np.mean(attention_scores, axis=1) | ||
|
||
return output | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() | ||
|
||
# Example usage | ||
x = np.random.randn( | ||
2, 10, 4 | ||
) # Batch size 2, sequence length 10, embedding dimension 4 | ||
attention = SlidingWindowAttention(embed_dim=4, window_size=3) | ||
output = attention.forward(x) | ||
print(output) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please provide return type hint for the function:
__init__
. If the function does not return a value, please provide the type hint as:def function() -> None: