-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathc51969c2-d04c-40a7-bcea-c092c3c2d11a.txt
2073 lines (2006 loc) · 103 KB
/
c51969c2-d04c-40a7-bcea-c092c3c2d11a.txt
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
with open(sys.argv[0]) as f:
code = f.read() # read the code of this file ASAP, for logging
import uuid
import time
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
import torch
torch.empty(1, device='cuda', requires_grad=True).backward() # prevents a bug on some systems
from torch import Tensor, nn
import torch.nn.functional as F
import torch.distributed as dist
# use of FlexAttention contributed by @KoszarskyB
from torch.nn.attention.flex_attention import BlockMask, flex_attention
torch._inductor.config.coordinate_descent_tuning = True
# -----------------------------------------------------------------------------
# Custom operators
@torch.library.custom_op("nanogpt::mm", mutates_args=())
def mm_op(x: Tensor, w: Tensor, x_s: float, w_s: float, grad_s: float) -> tuple[Tensor, Tensor, Tensor]:
@torch.compile
def impl(x: Tensor, w: Tensor):
assert x.is_contiguous() and w.is_contiguous()
x_f8 = x.mul(x_s).to(torch.float8_e4m3fn)
w_f8 = w.mul(w_s).to(torch.float8_e4m3fn)
out = torch._scaled_mm(
x_f8,
w_f8.t(),
out_dtype=torch.bfloat16,
scale_a=x.new_tensor(1 / x_s, dtype=torch.float32),
scale_b=x.new_tensor(1 / w_s, dtype=torch.float32),
use_fast_accum=True,
)
return out, x_f8, w_f8
return impl(x, w)
@mm_op.register_fake
def _(x: Tensor, w: Tensor, *_):
assert x.ndim == w.ndim == 2
assert x.shape[1] == w.shape[1]
assert x.device == w.device
assert x.is_contiguous() and w.is_contiguous()
return x @ w.t(), x.to(torch.float8_e4m3fn), w.to(torch.float8_e4m3fn)
@torch.library.custom_op("nanogpt::mm_backward", mutates_args=())
def mm_backward_op(g: Tensor, x_f8: Tensor, w_f8: Tensor, x_s: float, w_s: float, grad_s: float) -> tuple[Tensor, Tensor]:
@torch.compile
def impl(grad: Tensor, x_f8: Tensor, w_f8: Tensor):
assert grad.is_contiguous()
x_inv_s = grad.new_tensor(1 / x_s, dtype=torch.float32)
w_inv_s = grad.new_tensor(1 / w_s, dtype=torch.float32)
grad_inv_s = grad.new_tensor(1 / grad_s, dtype=torch.float32)
grad_f8 = grad.mul(grad_s).to(torch.float8_e5m2)
grad_x = torch._scaled_mm(
grad_f8,
w_f8.t().contiguous().t(),
out_dtype=torch.bfloat16,
scale_a=grad_inv_s,
scale_b=w_inv_s,
use_fast_accum=False,
)
# faster than grad_f8_t @ x_f8, for (d_out, d_in) == (50304, 768)
grad_w = torch._scaled_mm(
x_f8.t().contiguous(),
grad_f8.t().contiguous().t(),
out_dtype=torch.float32,
scale_a=x_inv_s,
scale_b=grad_inv_s,
use_fast_accum=False,
).t()
return grad_x, grad_w
return impl(g, x_f8, w_f8)
@mm_backward_op.register_fake
def _(g: Tensor, x_f8: Tensor, w_f8: Tensor, *_):
return x_f8.to(torch.bfloat16), w_f8.to(torch.float32)
def backward(ctx, grad_out: Tensor, *_):
x_f8, w_f8 = ctx.saved_tensors
x_s, w_s, grad_s = ctx.scales
grad_x, grad_w = torch.ops.nanogpt.mm_backward(
grad_out, x_f8, w_f8, x_s, w_s, grad_s
)
return grad_x, grad_w, None, None, None
def setup_context(ctx: torch.autograd.function.FunctionCtx, inputs, output):
*_, x_s, w_s, grad_s = inputs
_, x_f8, w_f8 = output
ctx.save_for_backward(x_f8, w_f8)
ctx.scales = x_s, w_s, grad_s
ctx.set_materialize_grads(False)
mm_op.register_autograd(backward, setup_context=setup_context)
def lm_head_fp8(x: Tensor, w: Tensor) -> Tensor:
_x = x.flatten(0, -2)
out: Tensor = torch.ops.nanogpt.mm(_x, w, x_s=2.0, w_s=32.0, grad_s=2.0**29)[0]
return out.reshape(*x.shape[:-1], -1)
# -----------------------------------------------------------------------------
# Muon optimizer
@torch.compile
def zeropower_via_newtonschulz5(G: Tensor, steps: int) -> Tensor:
"""
Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a
quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose
of minimizing steps, it turns out to be empirically effective to keep increasing the slope at
zero even beyond the point where the iteration no longer converges all the way to one everywhere
on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T
where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model
performance at all relative to UV^T, where USV^T = G is the SVD.
"""
assert len(G.shape) == 2
a, b, c = (3.4445, -4.7750, 2.0315)
X = G.bfloat16()
if G.size(0) > G.size(1):
X = X.T
# Ensure spectral norm is at most 1
X = X / (X.norm() + 1e-7)
# Perform the NS iterations
for _ in range(steps):
A = X @ X.T
B = b * A + c * A @ A # adapted from suggestion by @jxbz, @leloykun, and @YouJiacheng
X = a * X + B @ X
if G.size(0) > G.size(1):
X = X.T
return X
class Muon(torch.optim.Optimizer):
"""
Muon - MomentUm Orthogonalized by Newton-schulz
Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-
processing step, in which each 2D parameter's update is replaced with the nearest orthogonal
matrix. To efficiently orthogonalize each update, we use a Newton-Schulz iteration, which has
the advantage that it can be stably run in bfloat16 on the GPU.
Some warnings:
- This optimizer assumes that all parameters passed in are 2D.
- It should not be used for the embedding layer, the final fully connected layer, or any {0,1}-D
parameters; those should all be optimized by a standard method (e.g., AdamW).
- To use it with 4D convolutional filters, it works well to just flatten their last 3 dimensions.
- We believe it is unlikely to work well for training with small batch size.
- We believe it may not work well for finetuning pretrained models, but we haven't tested this.
- We have not yet tried this optimizer for training scenarios larger than NanoGPT (124M).
Arguments:
lr: The learning rate used by the internal SGD.
momentum: The momentum used by the internal SGD.
nesterov: Whether to use Nesterov-style momentum in the internal SGD. (recommended)
ns_steps: The number of Newton-Schulz iteration steps to use.
"""
def __init__(self, params, lr=0.02, momentum=0.95, nesterov=True, ns_steps=5, rank=0, world_size=1):
self.rank = rank
self.world_size = world_size
defaults = dict(lr=lr, momentum=momentum, nesterov=nesterov, ns_steps=ns_steps)
params: list[Tensor] = [*params]
assert all(isinstance(p, Tensor) for p in params)
sizes = {p.numel() for p in params}
def create_update_buffer(size: int):
b = torch.empty(self.world_size, size, dtype=torch.bfloat16, device="cuda")
return dict(update_buffer=b, update_buffer_views=[b[i] for i in range(self.world_size)])
param_groups = [
dict(params=[p for p in params if p.numel() == size], **create_update_buffer(size)) for size in sizes]
super().__init__(param_groups, defaults)
@torch.no_grad()
def step(self):
for group in self.param_groups:
lr = group['lr']
momentum = group['momentum']
nesterov = group['nesterov']
ns_steps = group['ns_steps']
update_buffer = group['update_buffer']
update_buffer_views: list[Tensor] = group['update_buffer_views']
# generate weight updates in distributed fashion
params: list[Tensor] = group['params']
handle = None
params_world = None
def update_prev():
if params_world is None:
return
assert handle is not None
handle.wait()
for p_world, g_world in zip(params_world, update_buffer_views):
p_world.add_(
g_world.view_as(p_world),
alpha=-lr * max(1, p_world.size(0) / p_world.size(1)) ** 0.5,
)
for base_i in range(len(params))[::self.world_size]:
if base_i + self.rank < len(params):
p = params[base_i + self.rank]
g = p.grad
assert g is not None
state = self.state[p]
if 'momentum_buffer' not in state:
state['momentum_buffer'] = torch.zeros_like(g)
buf: Tensor = state['momentum_buffer']
buf.lerp_(g, 1 - momentum)
g = g.lerp_(buf, momentum) if nesterov else buf
g = zeropower_via_newtonschulz5(g, steps=ns_steps).flatten()
else:
g = update_buffer_views[self.rank]
update_prev() # async all_gather instead of sync all_reduce by @YouJiacheng
handle = dist.all_gather_into_tensor(update_buffer, g, async_op=True)
params_world = params[base_i : base_i + self.world_size]
update_prev()
# -----------------------------------------------------------------------------
# PyTorch nn.Module definitions for the GPT-2 model
def norm(x):
return F.rms_norm(x, (x.size(-1),))
class CastedLinear(nn.Linear):
def __init__(self, in_features: int, out_features: int):
super().__init__(in_features, out_features, bias=False)
def reset_parameters(self) -> None:
std = 0.5 * (self.in_features ** -0.5) # 0.5 is a bit better than the default 1/sqrt(3)
bound = (3 ** 0.5) * std
with torch.no_grad():
self.weight.uniform_(-bound, bound)
def forward(self, x):
return F.linear(x, self.weight.type_as(x))
class Rotary(nn.Module):
def __init__(self, dim: int, max_seq_len=65536):
super().__init__()
# half-truncate RoPE by @YouJiacheng (w/ base freq tuning)
angular_freq = (1 / 1024) ** torch.linspace(0, 1, steps=dim//4, dtype=torch.float32)
angular_freq = torch.cat([angular_freq, angular_freq.new_zeros(dim//4)])
t = torch.arange(max_seq_len, dtype=torch.float32)
theta = torch.einsum('i,j -> ij', t, angular_freq)
self.cos = nn.Buffer(theta.cos(), persistent=False)
self.sin = nn.Buffer(theta.sin(), persistent=False)
def forward(self, x_BTHD: Tensor):
assert self.cos.size(0) >= x_BTHD.size(-3)
cos, sin = self.cos[None, :x_BTHD.size(-3), None, :], self.sin[None, :x_BTHD.size(-3), None, :]
x1, x2 = x_BTHD.to(dtype=torch.float32).chunk(2, dim=-1)
y1 = x1 * cos + x2 * sin
y2 = x1 * (-sin) + x2 * cos
return torch.cat((y1, y2), 3).type_as(x_BTHD)
class CausalSelfAttention(nn.Module):
def __init__(self, dim: int, num_heads: int):
super().__init__()
assert dim % num_heads == 0
self.num_heads = num_heads
self.c_q = CastedLinear(dim, dim)
self.c_k = CastedLinear(dim, dim)
self.c_v = CastedLinear(dim, dim)
self.lambdas = nn.Parameter(torch.tensor([0.5, 0.5]))
self.rotary = Rotary(dim // num_heads) # dim // num_heads = head_dim
self.c_proj = CastedLinear(dim, dim)
self.c_proj.weight.detach().zero_() # zero init suggested by @Grad62304977
def forward(self, x: Tensor, ve: Tensor | None, block_mask: BlockMask):
B, T = x.size(0), x.size(1) # batch size, sequence length
assert B == 1, 'Must use batch size = 1 for FlexAttention'
q = self.c_q(x).view(B, T, self.num_heads, -1)
k = self.c_k(x).view(B, T, self.num_heads, -1)
v = self.c_v(x).view(B, T, self.num_heads, -1)
if ve is not None:
v = self.lambdas[0] * v + self.lambdas[1] * ve.view_as(v) # @KoszarskyB & @Grad62304977
else: # skip mid-layers token value embeddings by @YouJiacheng
v = self.lambdas[0] * v
q, k = norm(q), norm(k) # QK norm @Grad62304977
q, k = self.rotary(q), self.rotary(k)
y = flex_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), block_mask=block_mask)
y = y.transpose(1, 2).contiguous().view_as(x) # re-assemble all head outputs side by side
y = self.c_proj(y)
return y
class MLP(nn.Module):
def __init__(self, dim):
super().__init__()
self.c_fc = CastedLinear(dim, 4 * dim)
self.c_proj = CastedLinear(4 * dim, dim)
self.c_proj.weight.detach().zero_() # zero init suggested by @Grad62304977
def forward(self, x):
x = self.c_fc(x)
x = F.relu(x).square() # https://arxiv.org/abs/2109.08668v2; ~1-2% better than GELU; suggested by @SKYLINEZ007 and @Grad62304977
x = self.c_proj(x)
return x
class Block(nn.Module):
def __init__(self, model_dim: int, num_heads: int, layer_idx: int):
super().__init__()
# skip attention of blocks.7 (the 8th layer) by @YouJiacheng
self.attn = CausalSelfAttention(model_dim, num_heads) if layer_idx != 7 else None
self.mlp = MLP(model_dim)
self.lambdas = nn.Parameter(torch.tensor([1., 0.]))
def forward(self, x, ve, x0, block_mask):
x = self.lambdas[0] * x + self.lambdas[1] * x0
if self.attn is not None:
x = x + self.attn(norm(x), ve, block_mask)
x = x + self.mlp(norm(x))
return x
class ValueEmbedding(nn.Module):
def __init__(self, num_embeddings: int, embedding_dim: int):
super().__init__()
self.embed = nn.ModuleList([nn.Embedding(num_embeddings, embedding_dim) for _ in range(3)])
def forward(self, input_seq) -> list[Tensor | None]:
ve = [emb(input_seq) for emb in self.embed]
# 012 ... 012 structure on token value embeddings by @YouJiacheng, improved on @leloykun's U-net structure
ve = [ve[0], ve[1], ve[2], None, None, None, None, None, None, ve[0], ve[1], ve[2]]
return ve
# -----------------------------------------------------------------------------
# The main GPT-2 model
def next_multiple_of_n(v: float | int, *, n: int):
return next(x for x in range(n, int(v) + 1 + n, n) if x >= v)
class GPT(nn.Module):
def __init__(self, vocab_size: int, num_layers: int, num_heads: int, model_dim: int):
super().__init__()
self.embed = nn.Embedding(vocab_size, model_dim)
# token value embeddings by @KoszarskyB - inspired by @Grad62304977's value residual learning
self.value_embeds = ValueEmbedding(vocab_size, model_dim)
self.blocks = nn.ModuleList([Block(model_dim, num_heads, layer_idx) for layer_idx in range(num_layers)])
# U-net design by @brendanh0gan
self.num_encoder_layers = num_layers // 2 # Half of the layers for encoder
self.num_decoder_layers = num_layers - self.num_encoder_layers # Remaining for decoder
# Add learnable skip connection weights for decoder layers
self.skip_weights = nn.Parameter(torch.ones(self.num_decoder_layers))
# there are only 50257 unique GPT-2 tokens; we extend to nearest multiple of 128 for efficiency.
# suggested to me by @Grad62304977. this originates from Karpathy's experiments.
self.lm_head = CastedLinear(model_dim, next_multiple_of_n(vocab_size, n=128))
self.lm_head.weight.detach().zero_() # @Grad62304977
def forward(self, input_seq: Tensor, target_seq: Tensor, sliding_window_num_blocks: Tensor):
BLOCK_SIZE = 128
assert input_seq.ndim == 1
assert len(input_seq) % BLOCK_SIZE == 0
NUM_BLOCKS = len(input_seq) // BLOCK_SIZE
docs = (input_seq == 50256).cumsum(0)
docs_low = docs.view(-1, BLOCK_SIZE)[:, 0].contiguous()
docs_high = docs.view(-1, BLOCK_SIZE)[:, -1].contiguous()
def document_causal(b, h, q_idx, kv_idx):
causal_mask = q_idx >= kv_idx
document_mask = docs[q_idx] == docs[kv_idx]
return causal_mask & document_mask
def dense_to_ordered(dense_mask: Tensor):
num_blocks = dense_mask.sum(dim=-1, dtype=torch.int32)
indices = dense_mask.argsort(dim=-1, descending=True, stable=True).to(torch.int32)
return num_blocks[None, None].contiguous(), indices[None, None].contiguous()
# manual block mask creation by @YouJiacheng
def create_doc_swc_block_mask(sliding_window_num_blocks: Tensor):
kv_idx = block_idx = torch.arange(NUM_BLOCKS, dtype=torch.int32, device="cuda")
q_idx = block_idx[:, None]
causal_bm = q_idx >= kv_idx
causal_full_bm = q_idx > kv_idx
window_bm = q_idx - kv_idx < sliding_window_num_blocks
window_full_bm = window_bm # block-wise sliding window by @YouJiacheng
# document_bm = (docs_low[q_idx] <= docs_high[kv_idx]) & (docs_low[kv_idx] <= docs_high[q_idx])
document_bm = (docs_low[:, None] <= docs_high) & (docs_low <= docs_high[:, None])
document_full_bm = (docs_low[:, None] == docs_high) & (docs_low == docs_high[:, None])
nonzero_bm = causal_bm & window_bm & document_bm
full_bm = causal_full_bm & window_full_bm & document_full_bm
kv_num_blocks, kv_indices = dense_to_ordered(nonzero_bm & ~full_bm)
full_kv_num_blocks, full_kv_indices = dense_to_ordered(full_bm)
return BlockMask.from_kv_blocks(
kv_num_blocks,
kv_indices,
full_kv_num_blocks,
full_kv_indices,
BLOCK_SIZE=BLOCK_SIZE,
mask_mod=document_causal,
)
block_mask = create_doc_swc_block_mask(sliding_window_num_blocks)
x = x0 = norm(self.embed(input_seq)[None]) # use of norm here by @Grad62304977
ve = self.value_embeds(input_seq)
ve_enc, ve_dec = ve[:self.num_encoder_layers], ve[self.num_encoder_layers:]
assert len(ve_enc) == self.num_encoder_layers and len(ve_dec) == self.num_decoder_layers
# Store outputs for U-Net skip connections
skip_connections = []
# Encoder pass - process only the first half of the blocks
for i in range(self.num_encoder_layers):
x = self.blocks[i](x, ve_enc[i], x0, block_mask)
skip_connections.append(x)
# Decoder pass - process the remaining blocks with weighted skip connections
for i in range(self.num_decoder_layers):
x = x + self.skip_weights[i] * skip_connections.pop()
x = self.blocks[self.num_encoder_layers + i](x, ve_dec[i], x0, block_mask)
x = norm(x)
logits = lm_head_fp8(x, self.lm_head.weight) if self.training else self.lm_head(x)
# @Grad62304977 added tanh softcapping, @KoszarskyB reduced it from 30 to 15, @YouJiacheng shifted it by +15 (2*sigmoid(2*x)=tanh(x)+1)
logits = 30 * torch.sigmoid(logits.float() / 7.5)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), target_seq)
return loss
# -----------------------------------------------------------------------------
# Our own simple Distributed Data Loader
def _load_data_shard(file: Path):
header = torch.from_file(f"{file}", False, 256, dtype=torch.int32) # header is 256 int32
assert header[0] == 20240520, 'magic number mismatch in the data .bin file'
assert header[1] == 1, 'unsupported version'
num_tokens = int(header[2]) # number of tokens (claimed)
with file.open('rb', buffering=0) as f:
tokens = torch.empty(num_tokens, dtype=torch.uint16, pin_memory=True) # avoid pin_memory copy by @YouJiacheng
f.seek(256 * 4)
nbytes = f.readinto(tokens.numpy()) # avoid bytes->array copy by @YouJiacheng
assert nbytes == 2 * num_tokens, 'number of tokens read does not match header'
return tokens
def distributed_data_generator(filename_pattern: str, batch_size: int, rank : int, world_size : int):
files = sorted(Path.cwd().glob(filename_pattern))
assert batch_size % world_size == 0
local_batch_size = batch_size // world_size
file_iter = iter(files) # use cycle(files) if you want to do multi-epoch training
tokens, pos = _load_data_shard(next(file_iter)), 0
while True:
if pos + batch_size + 1 >= len(tokens):
tokens, pos = _load_data_shard(next(file_iter)), 0
buf = tokens[pos + rank * local_batch_size:][:local_batch_size + 1]
inputs = buf[:-1].to(device="cuda", dtype=torch.int32, non_blocking=True) # no sync on host side;
targets = buf[1:].to(device="cuda", dtype=torch.int64, non_blocking=True) # H2D in another stream isn't helpful.
pos += batch_size
yield inputs, targets
# -----------------------------------------------------------------------------
# int main
@dataclass
class Hyperparameters:
# data
train_files = 'data/fineweb10B/fineweb_train_*.bin' # input .bin to train on
val_files = 'data/fineweb10B/fineweb_val_*.bin' # input .bin to eval validation loss on
val_tokens = 10485760 # how many tokens of validation data? it's important to keep this fixed for consistent comparisons
# optimization
batch_size = 8*64*1024 # batch size in tokens
num_iterations = 1395 # number of iterations to run
cooldown_frac = 0.4 # fraction of training spent cooling down the learning rate
# evaluation and logging
val_loss_every = 125 # every how many steps to evaluate val loss? 0 for only at the end
# implementation
seq_len = 64*1024 # FlexAttention sequence length
save_checkpoint = False
args = Hyperparameters()
# torchrun sets these env variables
rank = int(os.environ['RANK'])
world_size = int(os.environ['WORLD_SIZE'])
assert torch.cuda.is_available()
device = torch.device('cuda', int(os.environ['LOCAL_RANK']))
torch.cuda.set_device(device)
dist.init_process_group(backend='nccl', device_id=device)
dist.barrier()
master_process = (rank == 0) # this process will do logging, checkpointing etc.
# begin logging
logfile = None
if master_process:
run_id = uuid.uuid4()
os.makedirs('logs', exist_ok=True)
logfile = f'logs/{run_id}.txt'
print(logfile)
def print0(s, console=False):
if master_process:
with open(logfile, 'a') as f:
if console:
print(s)
print(s, file=f)
# begin by printing this file (the Python code)
print0(code)
print0('='*100)
# log information about the hardware/software environment this is running on
print0(f'Running Python {sys.version}')
print0(f'Running PyTorch {torch.version.__version__} compiled for CUDA {torch.version.cuda}')
def nvidia_smi():
import subprocess # avoid top level import
return subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout
print0(nvidia_smi())
print0('='*100)
# load data
train_loader = distributed_data_generator(args.train_files, args.batch_size, rank, world_size)
model = GPT(vocab_size=50257, num_layers=12, num_heads=6, model_dim=768).cuda()
for m in model.modules():
if isinstance(m, nn.Embedding):
m.bfloat16()
for param in model.parameters():
dist.broadcast(param.detach(), 0)
# collect the parameters to optimize
hidden_matrix_params = [p for p in model.blocks.parameters() if p.ndim == 2]
embed_params = [model.embed.weight, *model.value_embeds.parameters()]
scalar_params = [p for p in model.parameters() if p.ndim < 2]
head_params = [model.lm_head.weight]
# init the optimizer(s)
adam_params = [dict(params=head_params, lr=0.008), dict(params=embed_params, lr=0.6), dict(params=scalar_params, lr=0.04)]
optimizer1 = torch.optim.Adam(adam_params, betas=(0.8, 0.95), fused=True)
optimizer2 = Muon(hidden_matrix_params, lr=0.05, momentum=0.95, rank=rank, world_size=world_size)
optimizers = [optimizer1, optimizer2]
# learning rate schedule: stable then decay
def get_lr(it: int):
t = 1 - it / args.num_iterations # time remaining in training
assert 1 >= t >= 0
w = min(t / args.cooldown_frac, 1.0) # 1 -> 0
return w * 1.0 + (1 - w) * 0.1
schedulers = [torch.optim.lr_scheduler.LambdaLR(opt, get_lr) for opt in optimizers]
@lru_cache(1)
def sw_num_blks(window_size: int):
return torch.tensor(window_size // 128, dtype=torch.int32, pin_memory=True).cuda(non_blocking=True)
model: nn.Module = torch.compile(model)
training_time_ms = 0
# start the clock
torch.cuda.synchronize()
t0 = time.perf_counter()
# begin training
train_steps = args.num_iterations
for step in range(train_steps + 1):
last_step = (step == train_steps)
# This effectively ignores timing first 10 steps, which are slower for weird reasons.
# Alternately, and slightly more correctly in terms of benchmarking, we could do 10
# steps with dummy data first, and then re-initialize the model and reset the loader.
if step == 10:
training_time_ms = 0
t0 = time.perf_counter()
timed_steps = float('nan') if step <= 11 else (step - 10) + 1 # <= 11 to avoid bug in val
# Linearly increase the block-wise sliding window size over training 128 -> 1792:
# increase by @fernbear.bsky.social; block-wise by @YouJiacheng
window_size = next_multiple_of_n(1728 * step / train_steps, n=128)
# --------------- VALIDATION SECTION -----------------
if last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0):
# stop the clock
torch.cuda.synchronize()
training_time_ms += 1000 * (time.perf_counter() - t0)
model.eval()
val_bs = world_size * args.seq_len
assert args.val_tokens % val_bs == 0
val_steps = args.val_tokens // val_bs
val_loader = distributed_data_generator(args.val_files, val_bs, rank, world_size)
val_loss = 0
with torch.no_grad():
for _ in range(val_steps):
x, y = next(val_loader)
val_loss += model(x, y, sw_num_blks(window_size))
val_loss /= val_steps
del val_loader
dist.all_reduce(val_loss, op=dist.ReduceOp.AVG)
print0(f'step:{step}/{train_steps} val_loss:{val_loss:.4f} train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms/(timed_steps-1):.2f}ms', console=True)
model.train()
# start the clock again
torch.cuda.synchronize()
t0 = time.perf_counter()
if last_step:
if master_process and args.save_checkpoint:
log = dict(step=step, code=code, model=model.state_dict(), optimizers=[opt.state_dict() for opt in optimizers])
os.makedirs(f'logs/{run_id}', exist_ok=True)
torch.save(log, f'logs/{run_id}/state_step{step:06d}.pt')
# the last step only has the validation loop, so break to avoid training
break
# --------------- TRAINING SECTION BEGIN -----------------
inputs, targets = next(train_loader)
for input_seq, target_seq in zip(inputs.split(args.seq_len), targets.split(args.seq_len)):
model(input_seq, target_seq, sw_num_blks(window_size)).backward()
for param in model.parameters():
dist.all_reduce(param.grad, op=dist.ReduceOp.AVG)
# momentum warmup for Muon
frac = min(step / 300, 1)
for group in optimizer2.param_groups:
group['momentum'] = (1 - frac) * 0.85 + frac * 0.95
# step the optimizers and schedulers
for opt, sched in zip(optimizers, schedulers):
opt.step()
sched.step()
# null the gradients
model.zero_grad(set_to_none=True)
# logging
approx_time = training_time_ms + 1000 * (time.perf_counter() - t0)
print0(f'step:{step+1}/{train_steps} train_time:{approx_time:.0f}ms step_avg:{approx_time/timed_steps:.2f}ms', console=True)
print0(
f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB "
f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB"
)
dist.destroy_process_group()
====================================================================================================
Running Python 3.12.7 (main, Jan 16 2025, 08:58:39) [GCC 13.2.0]
Running PyTorch 2.7.0.dev20250110+cu126 compiled for CUDA 12.6
Thu Jan 16 10:26:28 2025
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 550.127.05 Driver Version: 550.127.05 CUDA Version: 12.6 |
|-----------------------------------------+------------------------+----------------------+
| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|=========================================+========================+======================|
| 0 NVIDIA H100 80GB HBM3 On | 00000000:61:00.0 Off | 0 |
| N/A 31C P0 133W / 700W | 7746MiB / 81559MiB | 0% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
| 1 NVIDIA H100 80GB HBM3 On | 00000000:62:00.0 Off | 0 |
| N/A 32C P0 125W / 700W | 3456MiB / 81559MiB | 0% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
| 2 NVIDIA H100 80GB HBM3 On | 00000000:63:00.0 Off | 0 |
| N/A 34C P0 127W / 700W | 3456MiB / 81559MiB | 0% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
| 3 NVIDIA H100 80GB HBM3 On | 00000000:64:00.0 Off | 0 |
| N/A 30C P0 116W / 700W | 3456MiB / 81559MiB | 0% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
| 4 NVIDIA H100 80GB HBM3 On | 00000000:6A:00.0 Off | 0 |
| N/A 30C P0 113W / 700W | 3456MiB / 81559MiB | 0% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
| 5 NVIDIA H100 80GB HBM3 On | 00000000:6B:00.0 Off | 0 |
| N/A 35C P0 124W / 700W | 3456MiB / 81559MiB | 0% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
| 6 NVIDIA H100 80GB HBM3 On | 00000000:6C:00.0 Off | 0 |
| N/A 35C P0 126W / 700W | 3456MiB / 81559MiB | 0% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
| 7 NVIDIA H100 80GB HBM3 On | 00000000:6D:00.0 Off | 0 |
| N/A 30C P0 126W / 700W | 3216MiB / 81559MiB | 0% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
+-----------------------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=========================================================================================|
+-----------------------------------------------------------------------------------------+
====================================================================================================
step:0/1395 val_loss:10.8258 train_time:0ms step_avg:nanms
step:1/1395 train_time:26881ms step_avg:nanms
step:2/1395 train_time:27284ms step_avg:nanms
step:3/1395 train_time:27403ms step_avg:nanms
step:4/1395 train_time:27526ms step_avg:nanms
step:5/1395 train_time:27650ms step_avg:nanms
step:6/1395 train_time:27773ms step_avg:nanms
step:7/1395 train_time:27896ms step_avg:nanms
step:8/1395 train_time:28018ms step_avg:nanms
step:9/1395 train_time:28142ms step_avg:nanms
step:10/1395 train_time:28267ms step_avg:nanms
step:11/1395 train_time:123ms step_avg:nanms
step:12/1395 train_time:247ms step_avg:nanms
step:13/1395 train_time:371ms step_avg:123.56ms
step:14/1395 train_time:495ms step_avg:123.70ms
step:15/1395 train_time:619ms step_avg:123.78ms
step:16/1395 train_time:742ms step_avg:123.65ms
step:17/1395 train_time:866ms step_avg:123.74ms
step:18/1395 train_time:991ms step_avg:123.93ms
step:19/1395 train_time:1117ms step_avg:124.10ms
step:20/1395 train_time:1241ms step_avg:124.07ms
step:21/1395 train_time:1365ms step_avg:124.09ms
step:22/1395 train_time:1490ms step_avg:124.14ms
step:23/1395 train_time:1614ms step_avg:124.17ms
step:24/1395 train_time:1737ms step_avg:124.09ms
step:25/1395 train_time:1860ms step_avg:124.03ms
step:26/1395 train_time:1985ms step_avg:124.09ms
step:27/1395 train_time:2109ms step_avg:124.05ms
step:28/1395 train_time:2233ms step_avg:124.04ms
step:29/1395 train_time:2357ms step_avg:124.03ms
step:30/1395 train_time:2480ms step_avg:124.02ms
step:31/1395 train_time:2603ms step_avg:123.97ms
step:32/1395 train_time:2727ms step_avg:123.95ms
step:33/1395 train_time:2850ms step_avg:123.93ms
step:34/1395 train_time:2975ms step_avg:123.98ms
step:35/1395 train_time:3100ms step_avg:123.98ms
step:36/1395 train_time:3224ms step_avg:123.99ms
step:37/1395 train_time:3349ms step_avg:124.04ms
step:38/1395 train_time:3473ms step_avg:124.03ms
step:39/1395 train_time:3598ms step_avg:124.07ms
step:40/1395 train_time:3723ms step_avg:124.09ms
step:41/1395 train_time:3847ms step_avg:124.08ms
step:42/1395 train_time:3971ms step_avg:124.08ms
step:43/1395 train_time:4095ms step_avg:124.08ms
step:44/1395 train_time:4220ms step_avg:124.11ms
step:45/1395 train_time:4343ms step_avg:124.07ms
step:46/1395 train_time:4469ms step_avg:124.15ms
step:47/1395 train_time:4593ms step_avg:124.15ms
step:48/1395 train_time:4717ms step_avg:124.13ms
step:49/1395 train_time:4842ms step_avg:124.14ms
step:50/1395 train_time:4965ms step_avg:124.12ms
step:51/1395 train_time:5090ms step_avg:124.14ms
step:52/1395 train_time:5215ms step_avg:124.17ms
step:53/1395 train_time:5339ms step_avg:124.16ms
step:54/1395 train_time:5463ms step_avg:124.15ms
step:55/1395 train_time:5587ms step_avg:124.16ms
step:56/1395 train_time:5711ms step_avg:124.16ms
step:57/1395 train_time:5836ms step_avg:124.17ms
step:58/1395 train_time:5960ms step_avg:124.17ms
step:59/1395 train_time:6084ms step_avg:124.17ms
step:60/1395 train_time:6210ms step_avg:124.19ms
step:61/1395 train_time:6333ms step_avg:124.18ms
step:62/1395 train_time:6457ms step_avg:124.18ms
step:63/1395 train_time:6581ms step_avg:124.17ms
step:64/1395 train_time:6705ms step_avg:124.17ms
step:65/1395 train_time:6831ms step_avg:124.20ms
step:66/1395 train_time:6955ms step_avg:124.20ms
step:67/1395 train_time:7080ms step_avg:124.20ms
step:68/1395 train_time:7203ms step_avg:124.20ms
step:69/1395 train_time:7327ms step_avg:124.18ms
step:70/1395 train_time:7452ms step_avg:124.20ms
step:71/1395 train_time:7576ms step_avg:124.20ms
step:72/1395 train_time:7700ms step_avg:124.20ms
step:73/1395 train_time:7824ms step_avg:124.19ms
step:74/1395 train_time:7949ms step_avg:124.20ms
step:75/1395 train_time:8073ms step_avg:124.20ms
step:76/1395 train_time:8198ms step_avg:124.21ms
step:77/1395 train_time:8322ms step_avg:124.21ms
step:78/1395 train_time:8445ms step_avg:124.19ms
step:79/1395 train_time:8569ms step_avg:124.18ms
step:80/1395 train_time:8693ms step_avg:124.18ms
step:81/1395 train_time:8818ms step_avg:124.20ms
step:82/1395 train_time:8941ms step_avg:124.18ms
step:83/1395 train_time:9065ms step_avg:124.17ms
step:84/1395 train_time:9190ms step_avg:124.19ms
step:85/1395 train_time:9314ms step_avg:124.19ms
step:86/1395 train_time:9439ms step_avg:124.19ms
step:87/1395 train_time:9562ms step_avg:124.19ms
step:88/1395 train_time:9688ms step_avg:124.20ms
step:89/1395 train_time:9812ms step_avg:124.21ms
step:90/1395 train_time:9936ms step_avg:124.20ms
step:91/1395 train_time:10059ms step_avg:124.18ms
step:92/1395 train_time:10182ms step_avg:124.18ms
step:93/1395 train_time:10306ms step_avg:124.17ms
step:94/1395 train_time:10431ms step_avg:124.18ms
step:95/1395 train_time:10556ms step_avg:124.19ms
step:96/1395 train_time:10681ms step_avg:124.20ms
step:97/1395 train_time:10806ms step_avg:124.21ms
step:98/1395 train_time:10930ms step_avg:124.21ms
step:99/1395 train_time:11054ms step_avg:124.20ms
step:100/1395 train_time:11178ms step_avg:124.20ms
step:101/1395 train_time:11301ms step_avg:124.19ms
step:102/1395 train_time:11425ms step_avg:124.19ms
step:103/1395 train_time:11551ms step_avg:124.20ms
step:104/1395 train_time:11676ms step_avg:124.22ms
step:105/1395 train_time:11802ms step_avg:124.23ms
step:106/1395 train_time:11928ms step_avg:124.25ms
step:107/1395 train_time:12055ms step_avg:124.28ms
step:108/1395 train_time:12182ms step_avg:124.30ms
step:109/1395 train_time:12308ms step_avg:124.32ms
step:110/1395 train_time:12434ms step_avg:124.34ms
step:111/1395 train_time:12561ms step_avg:124.37ms
step:112/1395 train_time:12690ms step_avg:124.41ms
step:113/1395 train_time:12817ms step_avg:124.44ms
step:114/1395 train_time:12944ms step_avg:124.46ms
step:115/1395 train_time:13071ms step_avg:124.49ms
step:116/1395 train_time:13199ms step_avg:124.51ms
step:117/1395 train_time:13325ms step_avg:124.53ms
step:118/1395 train_time:13451ms step_avg:124.54ms
step:119/1395 train_time:13578ms step_avg:124.57ms
step:120/1395 train_time:13705ms step_avg:124.59ms
step:121/1395 train_time:13833ms step_avg:124.62ms
step:122/1395 train_time:13960ms step_avg:124.64ms
step:123/1395 train_time:14087ms step_avg:124.66ms
step:124/1395 train_time:14214ms step_avg:124.68ms
step:125/1395 train_time:14341ms step_avg:124.70ms
step:125/1395 val_loss:4.3745 train_time:14441ms step_avg:125.57ms
step:126/1395 train_time:14475ms step_avg:124.78ms
step:127/1395 train_time:14609ms step_avg:124.86ms
step:128/1395 train_time:14736ms step_avg:124.88ms
step:129/1395 train_time:14862ms step_avg:124.89ms
step:130/1395 train_time:14988ms step_avg:124.90ms
step:131/1395 train_time:15115ms step_avg:124.91ms
step:132/1395 train_time:15241ms step_avg:124.93ms
step:133/1395 train_time:15368ms step_avg:124.94ms
step:134/1395 train_time:15494ms step_avg:124.95ms
step:135/1395 train_time:15621ms step_avg:124.96ms
step:136/1395 train_time:15748ms step_avg:124.99ms
step:137/1395 train_time:15877ms step_avg:125.02ms
step:138/1395 train_time:16004ms step_avg:125.03ms
step:139/1395 train_time:16130ms step_avg:125.04ms
step:140/1395 train_time:16255ms step_avg:125.04ms
step:141/1395 train_time:16382ms step_avg:125.05ms
step:142/1395 train_time:16508ms step_avg:125.06ms
step:143/1395 train_time:16634ms step_avg:125.07ms
step:144/1395 train_time:16762ms step_avg:125.09ms
step:145/1395 train_time:16890ms step_avg:125.11ms
step:146/1395 train_time:17016ms step_avg:125.12ms
step:147/1395 train_time:17143ms step_avg:125.13ms
step:148/1395 train_time:17270ms step_avg:125.14ms
step:149/1395 train_time:17397ms step_avg:125.16ms
step:150/1395 train_time:17524ms step_avg:125.17ms
step:151/1395 train_time:17650ms step_avg:125.18ms
step:152/1395 train_time:17776ms step_avg:125.19ms
step:153/1395 train_time:17903ms step_avg:125.19ms
step:154/1395 train_time:18029ms step_avg:125.20ms
step:155/1395 train_time:18155ms step_avg:125.21ms
step:156/1395 train_time:18282ms step_avg:125.22ms
step:157/1395 train_time:18409ms step_avg:125.23ms
step:158/1395 train_time:18535ms step_avg:125.24ms
step:159/1395 train_time:18662ms step_avg:125.25ms
step:160/1395 train_time:18789ms step_avg:125.26ms
step:161/1395 train_time:18916ms step_avg:125.27ms
step:162/1395 train_time:19042ms step_avg:125.27ms
step:163/1395 train_time:19169ms step_avg:125.29ms
step:164/1395 train_time:19295ms step_avg:125.29ms
step:165/1395 train_time:19422ms step_avg:125.30ms
step:166/1395 train_time:19549ms step_avg:125.31ms
step:167/1395 train_time:19675ms step_avg:125.32ms
step:168/1395 train_time:19802ms step_avg:125.33ms
step:169/1395 train_time:19928ms step_avg:125.34ms
step:170/1395 train_time:20055ms step_avg:125.34ms
step:171/1395 train_time:20182ms step_avg:125.35ms
step:172/1395 train_time:20309ms step_avg:125.36ms
step:173/1395 train_time:20435ms step_avg:125.37ms
step:174/1395 train_time:20561ms step_avg:125.37ms
step:175/1395 train_time:20688ms step_avg:125.38ms
step:176/1395 train_time:20814ms step_avg:125.39ms
step:177/1395 train_time:20941ms step_avg:125.40ms
step:178/1395 train_time:21068ms step_avg:125.40ms
step:179/1395 train_time:21194ms step_avg:125.41ms
step:180/1395 train_time:21321ms step_avg:125.42ms
step:181/1395 train_time:21448ms step_avg:125.42ms
step:182/1395 train_time:21574ms step_avg:125.43ms
step:183/1395 train_time:21701ms step_avg:125.44ms
step:184/1395 train_time:21827ms step_avg:125.45ms
step:185/1395 train_time:21954ms step_avg:125.45ms
step:186/1395 train_time:22080ms step_avg:125.46ms
step:187/1395 train_time:22208ms step_avg:125.47ms
step:188/1395 train_time:22334ms step_avg:125.47ms
step:189/1395 train_time:22462ms step_avg:125.49ms
step:190/1395 train_time:22589ms step_avg:125.50ms
step:191/1395 train_time:22716ms step_avg:125.50ms
step:192/1395 train_time:22843ms step_avg:125.51ms
step:193/1395 train_time:22971ms step_avg:125.52ms
step:194/1395 train_time:23097ms step_avg:125.53ms
step:195/1395 train_time:23223ms step_avg:125.53ms
step:196/1395 train_time:23349ms step_avg:125.53ms
step:197/1395 train_time:23475ms step_avg:125.53ms
step:198/1395 train_time:23602ms step_avg:125.54ms
step:199/1395 train_time:23728ms step_avg:125.55ms
step:200/1395 train_time:23855ms step_avg:125.55ms
step:201/1395 train_time:23983ms step_avg:125.57ms
step:202/1395 train_time:24111ms step_avg:125.58ms
step:203/1395 train_time:24238ms step_avg:125.59ms
step:204/1395 train_time:24365ms step_avg:125.59ms
step:205/1395 train_time:24492ms step_avg:125.60ms
step:206/1395 train_time:24617ms step_avg:125.60ms
step:207/1395 train_time:24744ms step_avg:125.60ms
step:208/1395 train_time:24871ms step_avg:125.61ms
step:209/1395 train_time:25000ms step_avg:125.63ms
step:210/1395 train_time:25129ms step_avg:125.64ms
step:211/1395 train_time:25257ms step_avg:125.66ms
step:212/1395 train_time:25387ms step_avg:125.68ms
step:213/1395 train_time:25516ms step_avg:125.70ms
step:214/1395 train_time:25645ms step_avg:125.71ms
step:215/1395 train_time:25775ms step_avg:125.73ms
step:216/1395 train_time:25904ms step_avg:125.75ms
step:217/1395 train_time:26032ms step_avg:125.76ms
step:218/1395 train_time:26159ms step_avg:125.76ms
step:219/1395 train_time:26289ms step_avg:125.79ms
step:220/1395 train_time:26418ms step_avg:125.80ms
step:221/1395 train_time:26548ms step_avg:125.82ms
step:222/1395 train_time:26678ms step_avg:125.84ms
step:223/1395 train_time:26807ms step_avg:125.86ms
step:224/1395 train_time:26937ms step_avg:125.87ms
step:225/1395 train_time:27066ms step_avg:125.89ms
step:226/1395 train_time:27196ms step_avg:125.91ms
step:227/1395 train_time:27325ms step_avg:125.92ms
step:228/1395 train_time:27455ms step_avg:125.94ms
step:229/1395 train_time:27584ms step_avg:125.95ms
step:230/1395 train_time:27714ms step_avg:125.97ms
step:231/1395 train_time:27843ms step_avg:125.99ms
step:232/1395 train_time:27972ms step_avg:126.00ms
step:233/1395 train_time:28101ms step_avg:126.02ms
step:234/1395 train_time:28230ms step_avg:126.03ms
step:235/1395 train_time:28359ms step_avg:126.04ms
step:236/1395 train_time:28489ms step_avg:126.06ms
step:237/1395 train_time:28619ms step_avg:126.08ms
step:238/1395 train_time:28748ms step_avg:126.09ms
step:239/1395 train_time:28878ms step_avg:126.10ms
step:240/1395 train_time:29007ms step_avg:126.12ms
step:241/1395 train_time:29136ms step_avg:126.13ms
step:242/1395 train_time:29264ms step_avg:126.14ms
step:243/1395 train_time:29394ms step_avg:126.15ms
step:244/1395 train_time:29523ms step_avg:126.17ms
step:245/1395 train_time:29652ms step_avg:126.18ms
step:246/1395 train_time:29781ms step_avg:126.19ms
step:247/1395 train_time:29911ms step_avg:126.21ms
step:248/1395 train_time:30039ms step_avg:126.21ms
step:249/1395 train_time:30168ms step_avg:126.23ms
step:250/1395 train_time:30299ms step_avg:126.25ms
step:250/1395 val_loss:3.9501 train_time:30403ms step_avg:126.68ms
step:251/1395 train_time:30437ms step_avg:126.29ms
step:252/1395 train_time:30573ms step_avg:126.33ms
step:253/1395 train_time:30701ms step_avg:126.34ms
step:254/1395 train_time:30830ms step_avg:126.35ms
step:255/1395 train_time:30958ms step_avg:126.36ms
step:256/1395 train_time:31086ms step_avg:126.37ms
step:257/1395 train_time:31215ms step_avg:126.38ms
step:258/1395 train_time:31343ms step_avg:126.38ms
step:259/1395 train_time:31473ms step_avg:126.40ms
step:260/1395 train_time:31603ms step_avg:126.41ms
step:261/1395 train_time:31733ms step_avg:126.43ms
step:262/1395 train_time:31863ms step_avg:126.44ms
step:263/1395 train_time:31991ms step_avg:126.45ms
step:264/1395 train_time:32120ms step_avg:126.46ms
step:265/1395 train_time:32249ms step_avg:126.47ms
step:266/1395 train_time:32378ms step_avg:126.47ms
step:267/1395 train_time:32507ms step_avg:126.49ms
step:268/1395 train_time:32637ms step_avg:126.50ms
step:269/1395 train_time:32766ms step_avg:126.51ms
step:270/1395 train_time:32895ms step_avg:126.52ms
step:271/1395 train_time:33024ms step_avg:126.53ms
step:272/1395 train_time:33154ms step_avg:126.54ms
step:273/1395 train_time:33283ms step_avg:126.55ms
step:274/1395 train_time:33412ms step_avg:126.56ms
step:275/1395 train_time:33541ms step_avg:126.57ms
step:276/1395 train_time:33671ms step_avg:126.58ms
step:277/1395 train_time:33799ms step_avg:126.59ms
step:278/1395 train_time:33929ms step_avg:126.60ms
step:279/1395 train_time:34058ms step_avg:126.61ms
step:280/1395 train_time:34186ms step_avg:126.62ms
step:281/1395 train_time:34316ms step_avg:126.63ms
step:282/1395 train_time:34446ms step_avg:126.64ms
step:283/1395 train_time:34575ms step_avg:126.65ms
step:284/1395 train_time:34706ms step_avg:126.66ms
step:285/1395 train_time:34836ms step_avg:126.68ms
step:286/1395 train_time:34965ms step_avg:126.68ms
step:287/1395 train_time:35093ms step_avg:126.69ms
step:288/1395 train_time:35222ms step_avg:126.70ms
step:289/1395 train_time:35352ms step_avg:126.71ms
step:290/1395 train_time:35480ms step_avg:126.72ms
step:291/1395 train_time:35611ms step_avg:126.73ms
step:292/1395 train_time:35741ms step_avg:126.74ms
step:293/1395 train_time:35872ms step_avg:126.75ms
step:294/1395 train_time:36001ms step_avg:126.77ms
step:295/1395 train_time:36131ms step_avg:126.78ms
step:296/1395 train_time:36261ms step_avg:126.79ms
step:297/1395 train_time:36390ms step_avg:126.79ms
step:298/1395 train_time:36518ms step_avg:126.80ms
step:299/1395 train_time:36648ms step_avg:126.81ms
step:300/1395 train_time:36778ms step_avg:126.82ms
step:301/1395 train_time:36908ms step_avg:126.83ms
step:302/1395 train_time:37039ms step_avg:126.85ms
step:303/1395 train_time:37169ms step_avg:126.85ms
step:304/1395 train_time:37298ms step_avg:126.86ms
step:305/1395 train_time:37427ms step_avg:126.87ms
step:306/1395 train_time:37558ms step_avg:126.88ms
step:307/1395 train_time:37686ms step_avg:126.89ms
step:308/1395 train_time:37817ms step_avg:126.90ms
step:309/1395 train_time:37947ms step_avg:126.91ms
step:310/1395 train_time:38077ms step_avg:126.92ms
step:311/1395 train_time:38206ms step_avg:126.93ms
step:312/1395 train_time:38336ms step_avg:126.94ms
step:313/1395 train_time:38468ms step_avg:126.96ms
step:314/1395 train_time:38600ms step_avg:126.97ms
step:315/1395 train_time:38730ms step_avg:126.98ms
step:316/1395 train_time:38862ms step_avg:127.00ms
step:317/1395 train_time:38993ms step_avg:127.01ms
step:318/1395 train_time:39123ms step_avg:127.02ms
step:319/1395 train_time:39257ms step_avg:127.04ms
step:320/1395 train_time:39388ms step_avg:127.06ms
step:321/1395 train_time:39519ms step_avg:127.07ms
step:322/1395 train_time:39650ms step_avg:127.08ms
step:323/1395 train_time:39780ms step_avg:127.09ms
step:324/1395 train_time:39912ms step_avg:127.11ms
step:325/1395 train_time:40043ms step_avg:127.12ms
step:326/1395 train_time:40175ms step_avg:127.14ms
step:327/1395 train_time:40306ms step_avg:127.15ms
step:328/1395 train_time:40438ms step_avg:127.16ms
step:329/1395 train_time:40571ms step_avg:127.18ms
step:330/1395 train_time:40701ms step_avg:127.19ms
step:331/1395 train_time:40833ms step_avg:127.21ms
step:332/1395 train_time:40966ms step_avg:127.22ms
step:333/1395 train_time:41097ms step_avg:127.23ms