Schwertlilien
As a recoder: notes and ideas.

2026-4-11—手撕部分

MLP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import torch
import torch.nn as nn

class SimpleMLP(nn.Module):
def __init__(self, input_dim, hidden_dim,output_dim):
super().__init()
self.layers=nn.Sequential(
nn.Flatten(),
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, x):
return self.layers(x)

model=SimpleMLP(input_dim=32*32,hidden_dim=128,output_dim=10)
x=torch.randn(4,1,32,32)
logits=model(x)
print(logits.shape)

Self-Attn

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
import torch
import torch.nn as nn

def self_attention(q,k,v,mask=None):
# q,k,v:[Batch_size,Head_Dim,Seq_len,Dim]
d_k=q.size(-1)

scores=torch.matmul(q,k.transpose(-2,-1)/torch.sqrt(d_k,dtype=torch.float32))

if mask is not None:
scores=scores.masked_fill(mask==0,-1e9)
# masked_fill 是 PyTorch 里 torch.Tensor 的成员函数
# 按照 mask 矩阵,把张量里对应位置的值替换成你指定的数
attn_weights=F.softmax(scores,dim=-1)
output=torch.matmul(attn_weights,v)
return output,attn_weights

Batch_size=2
Seq_len=5
Dim=64

q=torch.randn(Batch_size,Seq_len,Dim)
k=torch.randn(Batch_size,Seq_len,Dim)
v=torch.randn(Batch_size,Seq_len,Dim)

attn_output,attn_weights=self.attention(q,k,v)
# attn_output.shape=[2,5,64]
# 维度没有发生变化。
搜索
匹配结果数:
未搜索到匹配的文章。