RNN

Ivan Lv6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class GRUCell(nn.Module):
def __init__(
self,
input_dim,
hidden_dim
):
super().__init__()
self.fc1 = nn.Linear(input_dim, 3 * hidden_dim)
self.fc2 = nn.Linear(hidden_dim, 3 * hidden_dim)

def forward(self, x, h):
x1, x2, x3 = self.fc1(x).chunk(3, dim=-1)
h1, h2, h3 = self.fc2(h).chunk(3, dim=-1)
h_old = torch.sigmoid(x1 + h1) * h
z = torch.sigmoid(x2 + h2)
h_new = torch.tanh(x3 + h3)
return z * h_old + (1-z) * h_new


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

class LSTMCell(nn.Module):
def __init__(
self,
input_dim,
hidden_dim
):
super().__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.fc3 = nn.Linear(input_dim, hidden_dim)
self.fc4 = nn.Linear(hidden_dim, hidden_dim)
self.fc5 = nn.Linear(input_dim, hidden_dim)
self.fc6 = nn.Linear(hidden_dim, hidden_dim)
self.fc7 = nn.Linear(input_dim, hidden_dim)
self.fc8 = nn.Linear(hidden_dim, hidden_dim)

def forward(self, x, lm, sm):
# phase 1: forget gate
lm = lm * F.sigmoid(self.fc1(x) + self.fc2(sm))
# phase 2: input gate
new_lm = F.tanh(self.fc3(x) + self.fc4(sm))
new_lm = F.sigmoid(self.fc5(x) + self.fc6(sm)) * new_lm
lm = lm + new_lm
# phase 3: output gate
sm = F.sigmoid(self.fc7(x) + self.fc8(sm)) * F.tanh(lm)
return lm, sm


class LSTM(nn.Module):
def __init__(
self,
input_dim,
hidden_dim
):
super().__init__()
self.hidden_dim = hidden_dim
self.cell = LSTMCell(input_dim, hidden_dim)

def forward(self, x):
# x: B, T, C
B, T, C = x.shape
lm = torch.zeros((B, self.hidden_dim), device=x.device)
sm = torch.zeros((B, self.hidden_dim), device=x.device)
outputs = []
for t in range(T):
lm, sm = self.cell(x[:, t, :], lm, sm)
outputs.append(sm)
return torch.stack(outputs, dim=1) # (B, T, H)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# __init__
self.fc1 = nn.Linear(input_dim, hidden_dim * 4)
self.fc2 = nn.Linear(hidden_dim, hidden_dim * 4)

# forward
x1, x2, x3 = self.fc1(x).chunk(4, dim=-1)
sm1, sm2, sm3 = self.fc2(sm).chunk(4, dim=-1)

lm = lm * torch.sigmoid(x1 + sm1)

new_lm = torch.sigmoid(x2 + sm2) * torch.tanh(x3 + sm3)
lm = lm + new_lm

sm = torch.sigmoid(x4 + sm4) * torch.tanh(lm)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Attention(nn.Module):
def __init__(
self,
d_model,
n_heads
):
super().__init__()
assert d_model % n_heads == 0
self.n_heads = n_heads
head_dim = d_model // n_heads
self.scale = 1.0 / math.sqrt(head_dim)
self.q_proj = nn.Linear(d_model, d_model)
self.k_proj = nn.Linear(d_model, d_model)
self.v_proj = nn.Linear(d_model, d_model)
self.out_proj = nn.Linear(d_model, d_model)

def forward(self, q, k, v, mask=None):
# qkv: (B, T, C)
# mask: (B, T, T)
q = rearrange(self.q_proj(q), "b t (h d) -> b h t d", h=self.n_heads)
k = rearrange(self.k_proj(k), "b t (h d) -> b h t d", h=self.n_heads)
v = rearrange(self.v_proj(v), "b t (h d) -> b h t d", h=self.n_heads)

scores = q @ k.transpose(-2, -1) * self.scale # (B, T, T)
if mask is not None:
mask = rearrange(mask, "b tq tk -> b 1 tq tk")
scores.masked_fill_(mask, -float('inf'))
weights = scores.softmax(dim=-1)
out = weights @ v
out = rearrange(out, "b h t d -> b t (h d)")
return self.out_proj(out) # (B, T, d_model)


causal_attn = Attention(128)
T = inputs.size(1)
mask = torch.ones(T, T, dtype=torch.bool).triu(1)
y = causal_attn(x, x, x, mask)

cross_attn = Attention(128)
cross_attn(y, x, y)
  • Title: RNN
  • Author: Ivan
  • Created at : 2026-11-19 00:00:00
  • Updated at : 2026-11-19 23:50:23
  • Link: https://ivanfan-van.github.io/2026/11/19/note-1-inbox-a0fd60c172267b7a/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
RNN