-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
58 lines (43 loc) · 1.25 KB
/
Copy pathtrain.py
File metadata and controls
58 lines (43 loc) · 1.25 KB
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
50
51
52
53
54
55
56
57
58
import torch
import torch.nn as nn
import torch.nn.functional as F
class Solution:
def train(
self,
model: nn.Module,
data: torch.Tensor,
epochs: int,
context_length: int,
batch_size: int,
lr: float
) -> float:
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
final_loss = None
for epoch in range(epochs):
torch.manual_seed(epoch)
starts = torch.randint(
0,
len(data) - context_length,
(batch_size,)
)
X = torch.stack([
data[i:i + context_length]
for i in starts
])
Y = torch.stack([
data[i + 1:i + 1 + context_length]
for i in starts
])
logits = model(X) # (B, T, C)
B, T, C = logits.shape
logits_flat = logits.view(B * T, C)
targets_flat = Y.view(B * T)
loss = F.cross_entropy(
logits_flat,
targets_flat
)
optimizer.zero_grad()
loss.backward()
optimizer.step()
final_loss = loss.item()
return round(final_loss, 4)