Skip to content

Commit 692d38f

Browse files
Pritam3355pre-commit-ci[bot]cclauss
authored
shortened the lines (#12214)
* Create README.md * Update README.md * Add files via upload * Delete llm_experiments directory * Create README.md * Add files via upload * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add files via upload * Delete neural_network/chatbot/main.py * Delete neural_network/chatbot/llm_service.py * Delete neural_network/chatbot/chatbot.py * Delete neural_network/chatbot/db.py * Update README.md * Add files via upload * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add files via upload made changes suggested by auto-checker * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add files via upload * Add files via upload * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Delete neural_network/chatbot directory * Add files via upload * Add files via upload * Add files via upload * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add files via upload * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updating DIRECTORY.md * Rename batch_size variable to _batch_size --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com>
1 parent c0fd8de commit 692d38f

2 files changed

Lines changed: 103 additions & 0 deletions

File tree

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -966,6 +966,7 @@
966966
* [Happy Number](maths/special_numbers/happy_number.py)
967967
* [Harshad Numbers](maths/special_numbers/harshad_numbers.py)
968968
* [Hexagonal Number](maths/special_numbers/hexagonal_number.py)
969+
* [Jacobsthal Number](maths/special_numbers/jacobsthal_number.py)
969970
* [Kaprekar Constant](maths/special_numbers/kaprekar_constant.py)
970971
* [Kaprekar Number](maths/special_numbers/kaprekar_number.py)
971972
* [Krishnamurthy Number](maths/special_numbers/krishnamurthy_number.py)
@@ -1058,6 +1059,7 @@
10581059
* [Nesterov Accelerated Sgd](neural_network/optimizers/nesterov_accelerated_sgd.py)
10591060
* [Perceptron](neural_network/perceptron.py)
10601061
* [Simple Neural Network](neural_network/simple_neural_network.py)
1062+
* [Sliding Window Attention](neural_network/sliding_window_attention.py)
10611063
* [Two Hidden Layers Neural Network](neural_network/two_hidden_layers_neural_network.py)
10621064

10631065
## [Other](other)
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
"""
2+
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
3+
Name - - sliding_window_attention.py
4+
Goal - - Implement a neural network architecture using sliding
5+
window attention for sequence modeling tasks.
6+
Detail: Total 5 layers neural network
7+
* Input layer
8+
* Sliding Window Attention Layer
9+
* Feedforward Layer
10+
* Output Layer
11+
Author: Stephen Lee
12+
Github: 245885195@qq.com
13+
Date: 2024.10.20
14+
References:
15+
1. Choromanska, A., et al. (2020). "On the Importance of
16+
Initialization and Momentum in Deep Learning." *Proceedings
17+
of the 37th International Conference on Machine Learning*.
18+
2. Dai, Z., et al. (2020). "Transformers are RNNs: Fast
19+
Autoregressive Transformers with Linear Attention."
20+
*arXiv preprint arXiv:2006.16236*.
21+
3. [Attention Mechanisms in Neural Networks](https://en.wikipedia.org/wiki/Attention_(machine_learning))
22+
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
23+
"""
24+
25+
import numpy as np
26+
27+
28+
class SlidingWindowAttention:
29+
"""Sliding Window Attention Module.
30+
31+
This class implements a sliding window attention mechanism where
32+
the model attends to a fixed-size window of context around each token.
33+
34+
Attributes:
35+
window_size (int): The size of the attention window.
36+
embed_dim (int): The dimensionality of the input embeddings.
37+
"""
38+
39+
def __init__(self, embed_dim: int, window_size: int) -> None:
40+
"""
41+
Initialize the SlidingWindowAttention module.
42+
43+
Args:
44+
embed_dim (int): The dimensionality of the input embeddings.
45+
window_size (int): The size of the attention window.
46+
"""
47+
self.window_size = window_size
48+
self.embed_dim = embed_dim
49+
rng = np.random.default_rng()
50+
self.attention_weights = rng.standard_normal((embed_dim, embed_dim))
51+
52+
def forward(self, input_tensor: np.ndarray) -> np.ndarray:
53+
"""
54+
Forward pass for the sliding window attention.
55+
56+
Args:
57+
input_tensor (np.ndarray): Input tensor of shape (batch_size,
58+
seq_length, embed_dim).
59+
60+
Returns:
61+
np.ndarray: Output tensor of shape (batch_size, seq_length, embed_dim).
62+
63+
>>> x = np.random.randn(2, 10, 4) # Batch size 2, sequence
64+
>>> attention = SlidingWindowAttention(embed_dim=4, window_size=3)
65+
>>> output = attention.forward(x)
66+
>>> output.shape
67+
(2, 10, 4)
68+
>>> (output.sum() != 0).item() # Check if output is non-zero
69+
True
70+
"""
71+
_batch_size, seq_length, _ = input_tensor.shape
72+
output = np.zeros_like(input_tensor)
73+
74+
for i in range(seq_length):
75+
# Define the window range
76+
start = max(0, i - self.window_size // 2)
77+
end = min(seq_length, i + self.window_size // 2 + 1)
78+
79+
# Extract the local window
80+
local_window = input_tensor[:, start:end, :]
81+
82+
# Compute attention scores
83+
attention_scores = np.matmul(local_window, self.attention_weights)
84+
85+
# Average the attention scores
86+
output[:, i, :] = np.mean(attention_scores, axis=1)
87+
88+
return output
89+
90+
91+
if __name__ == "__main__":
92+
import doctest
93+
94+
doctest.testmod()
95+
96+
# usage
97+
rng = np.random.default_rng()
98+
x = rng.standard_normal((2, 10, 4)) # Batch size 2,
99+
attention = SlidingWindowAttention(embed_dim=4, window_size=3)
100+
output = attention.forward(x)
101+
print(output)

0 commit comments

Comments
 (0)