File size: 32,436 Bytes
17a7426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "torch.cuda.is_available()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import glob\n",
    "import math\n",
    "import sys\n",
    "import time\n",
    "from pathlib import Path\n",
    "from typing import Optional, Tuple, Union\n",
    "\n",
    "import lightning as L\n",
    "import torch\n",
    "from lightning.fabric.loggers import CSVLogger\n",
    "from lightning.fabric.strategies import FSDPStrategy\n",
    "from torch.utils.data import DataLoader\n",
    "\n",
    "# # support running without installing as a package\n",
    "# wd = Path(__file__).parent.parent.resolve()\n",
    "# sys.path.append(str(wd))\n",
    "\n",
    "from tsai_gpt.model import GPT, Block, Config\n",
    "from tsai_gpt.packed_dataset import CombinedDataset, PackedDataset\n",
    "from tsai_gpt.speed_monitor import SpeedMonitorBase, estimate_flops, measure_flops\n",
    "from tsai_gpt.speed_monitor import SpeedMonitorFabric as SpeedMonitor\n",
    "from tsai_gpt.utils import (\n",
    "    chunked_cross_entropy,\n",
    "    get_default_supported_precision,\n",
    "    num_parameters,\n",
    "    load_checkpoint,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_name = \"pythia-160m\"\n",
    "name = \"redpajama\"\n",
    "out_dir = Path(\"out\") / name\n",
    "save_interval = 1000\n",
    "eval_interval = 1000\n",
    "eval_iters = 100\n",
    "log_interval = 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Hyperparameters\n",
    "learning_rate = 6e-3\n",
    "batch_size = 32\n",
    "micro_batch_size = 8\n",
    "gradient_accumulation_steps = batch_size // micro_batch_size\n",
    "assert gradient_accumulation_steps > 0\n",
    "# max_iters = 600000  # num_epochs * (epoch_size // micro_batch_size) // devices\n",
    "max_iters = 15000\n",
    "weight_decay = 1e-1\n",
    "beta1 = 0.9\n",
    "beta2 = 0.95\n",
    "grad_clip = 1.0\n",
    "decay_lr = True\n",
    "warmup_iters = 2000\n",
    "lr_decay_iters = max_iters\n",
    "min_lr = 6e-6"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Data proportions from https://arxiv.org/pdf/2302.13971.pdf Table 1\n",
    "data_config = [\n",
    "    (\"arxiv\", 2.5),\n",
    "    (\"book\", 4.5),\n",
    "    (\"c4\", 15.0),\n",
    "    (\"cc\", 67.0),\n",
    "    (\"github\", 4.5),\n",
    "    (\"stackexchange\", 2.0),\n",
    "    (\"wikipedia\", 4.5),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "hparams = {\n",
    "    k: v\n",
    "    for k, v in locals().items()\n",
    "    if isinstance(v, (int, float, str)) and not k.startswith(\"_\")\n",
    "}\n",
    "logger = CSVLogger(\"out\", name, flush_logs_every_n_steps=log_interval)\n",
    "\n",
    "\n",
    "def setup(\n",
    "    devices: int = 4,\n",
    "    train_data_dir: Path = Path(\"data/redpajama_sample\"),\n",
    "    val_data_dir: Optional[Path] = None,\n",
    "    precision: Optional[str] = None,\n",
    "    resume: Union[bool, Path] = False,\n",
    ") -> None:\n",
    "    precision = precision or get_default_supported_precision(training=True)\n",
    "\n",
    "    if devices > 1:\n",
    "        strategy = FSDPStrategy(\n",
    "            auto_wrap_policy={Block},\n",
    "            activation_checkpointing_policy={Block},\n",
    "            state_dict_type=\"full\",\n",
    "            limit_all_gathers=True,\n",
    "            cpu_offload=False,\n",
    "        )\n",
    "    else:\n",
    "        strategy = \"auto\"\n",
    "\n",
    "    fabric = L.Fabric(\n",
    "        devices=devices, strategy=strategy, precision=precision, loggers=logger\n",
    "    )\n",
    "    fabric.print(hparams)\n",
    "    fabric.launch(main, train_data_dir, val_data_dir, resume)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_copy = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def main(\n",
    "    fabric: L.Fabric,\n",
    "    train_data_dir: Path,\n",
    "    val_data_dir: Path,\n",
    "    resume: Union[bool, Path],\n",
    ") -> None:\n",
    "    global model_copy\n",
    "    speed_monitor = SpeedMonitor(fabric, window_size=50, time_unit=\"seconds\")\n",
    "\n",
    "    if fabric.global_rank == 0:\n",
    "        out_dir.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "    config = Config.from_name(model_name)\n",
    "\n",
    "    train_dataloader, val_dataloader = create_dataloaders(\n",
    "        batch_size=micro_batch_size,\n",
    "        block_size=config.block_size,\n",
    "        fabric=fabric,\n",
    "        train_data_dir=train_data_dir,\n",
    "        val_data_dir=val_data_dir,\n",
    "        seed=(1337 + fabric.global_rank),\n",
    "    )\n",
    "    if val_dataloader is None:\n",
    "        train_dataloader = fabric.setup_dataloaders(train_dataloader)\n",
    "    else:\n",
    "        train_dataloader, val_dataloader = fabric.setup_dataloaders(\n",
    "            train_dataloader, val_dataloader\n",
    "        )\n",
    "\n",
    "    fabric.seed_everything(1337)  # same seed for every process to init model (FSDP)\n",
    "\n",
    "    fabric.print(f\"Loading model with {config.__dict__}\")\n",
    "    t0 = time.perf_counter()\n",
    "    import torch\n",
    "    import torch.nn as nn\n",
    "\n",
    "    def _init_weights(module: nn.Module) -> None:\n",
    "        \"\"\"Meant to be used with `gpt.apply(gpt._init_weights)`.\"\"\"\n",
    "        if isinstance(module, nn.Linear):\n",
    "            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
    "            if module.bias is not None:\n",
    "                torch.nn.init.zeros_(module.bias)\n",
    "        elif isinstance(module, nn.Embedding):\n",
    "            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
    "\n",
    "    with fabric.init_module(empty_init=True):\n",
    "        model = GPT(config)\n",
    "        model.apply(_init_weights)\n",
    "    model.apply(_init_weights)\n",
    "\n",
    "    # checkpoint_path = Path(\"out/redpajama/iter-000999-ckpt.pth\")\n",
    "\n",
    "    # load_checkpoint(fabric, model, checkpoint_path)\n",
    "\n",
    "    # print(model.transformer.h[0].mlp.fc.weight)\n",
    "\n",
    "    fabric.print(f\"Time to instantiate model: {time.perf_counter() - t0:.02f} seconds.\")\n",
    "    fabric.print(f\"Total parameters {num_parameters(model):,}\")\n",
    "\n",
    "    model = fabric.setup(model)\n",
    "    optimizer = torch.optim.AdamW(\n",
    "        model.parameters(),\n",
    "        lr=learning_rate,\n",
    "        weight_decay=weight_decay,\n",
    "        betas=(beta1, beta2),\n",
    "        foreach=False,\n",
    "    )\n",
    "\n",
    "    # model_copy = model\n",
    "\n",
    "    optimizer = fabric.setup_optimizers(optimizer)\n",
    "\n",
    "    state = {\n",
    "        \"model\": model,\n",
    "        \"optimizer\": optimizer,\n",
    "        \"hparams\": hparams,\n",
    "        \"iter_num\": 0,\n",
    "        \"step_count\": 0,\n",
    "    }\n",
    "\n",
    "    if resume is True:\n",
    "        resume = max(out_dir.glob(\"*.pth\"), key=lambda p: int(p.name.split(\"-\")[1]))\n",
    "    if resume:\n",
    "        fabric.print(f\"Resuming training from {resume}\")\n",
    "        fabric.load(resume, state)\n",
    "\n",
    "    train_time = time.perf_counter()\n",
    "    train(fabric, state, train_dataloader, val_dataloader, speed_monitor)\n",
    "    fabric.print(f\"Training time: {(time.perf_counter()-train_time):.2f}s\")\n",
    "    if fabric.device.type == \"cuda\":\n",
    "        fabric.print(f\"Memory used: {torch.cuda.max_memory_allocated() / 1e9:.02f} GB\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def train(\n",
    "    fabric: L.Fabric,\n",
    "    state: dict,\n",
    "    train_dataloader: DataLoader,\n",
    "    val_dataloader: DataLoader,\n",
    "    speed_monitor: SpeedMonitorBase,\n",
    ") -> None:\n",
    "    model = state[\"model\"]\n",
    "    optimizer = state[\"optimizer\"]\n",
    "\n",
    "    if val_dataloader is not None:\n",
    "        validate(fabric, model, val_dataloader)  # sanity check\n",
    "\n",
    "    with torch.device(\"meta\"):\n",
    "        meta_model = GPT(model.config)\n",
    "        # \"estimated\" is not as precise as \"measured\". Estimated is optimistic but widely used in the wild.\n",
    "        # When comparing MFU or FLOP numbers with other projects that use estimated FLOPs,\n",
    "        # consider passing `SpeedMonitor(flops_per_batch=estimated_flops)` instead\n",
    "        estimated_flops = estimate_flops(meta_model) * micro_batch_size\n",
    "        fabric.print(\n",
    "            f\"Estimated TFLOPs: {estimated_flops * fabric.world_size / 1e12:.2f}\"\n",
    "        )\n",
    "        x = torch.randint(0, 1, (micro_batch_size, model.max_seq_length))\n",
    "        measured_flops = measure_flops(meta_model, x)\n",
    "        fabric.print(\n",
    "            f\"Measured TFLOPs: {measured_flops * fabric.world_size / 1e12:.2f}\"\n",
    "        )\n",
    "        del meta_model, x\n",
    "\n",
    "    total_lengths = 0\n",
    "    total_t0 = time.perf_counter()\n",
    "\n",
    "    for state[\"iter_num\"], train_data in enumerate(train_dataloader, state[\"iter_num\"]):\n",
    "        if state[\"iter_num\"] >= max_iters:\n",
    "            checkpoint_path = out_dir / f\"iter-{state['iter_num']:06d}-ckpt.pth\"\n",
    "            fabric.print(f\"Saving checkpoint to {str(checkpoint_path)!r}\")\n",
    "            fabric.save(checkpoint_path, state)\n",
    "            break\n",
    "\n",
    "        # determine and set the learning rate for this iteration\n",
    "        lr = get_lr(state[\"iter_num\"]) if decay_lr else learning_rate\n",
    "        for param_group in optimizer.param_groups:\n",
    "            param_group[\"lr\"] = lr\n",
    "\n",
    "        iter_t0 = time.perf_counter()\n",
    "\n",
    "        input_ids = train_data[:, 0 : model.max_seq_length].contiguous()\n",
    "        targets = train_data[:, 1 : model.max_seq_length + 1].contiguous()\n",
    "\n",
    "        is_accumulating = (state[\"iter_num\"] + 1) % gradient_accumulation_steps != 0\n",
    "        with fabric.no_backward_sync(model, enabled=is_accumulating):\n",
    "            logits = model(input_ids)\n",
    "            loss = chunked_cross_entropy(logits, targets, chunk_size=0)\n",
    "            fabric.backward(loss / gradient_accumulation_steps)\n",
    "\n",
    "        # return\n",
    "\n",
    "        if not is_accumulating:\n",
    "            fabric.clip_gradients(model, optimizer, max_norm=grad_clip)\n",
    "            optimizer.step()\n",
    "            optimizer.zero_grad()\n",
    "            state[\"step_count\"] += 1\n",
    "\n",
    "        t1 = time.perf_counter()\n",
    "        total_lengths += input_ids.size(1)\n",
    "        speed_monitor.on_train_batch_end(\n",
    "            (state[\"iter_num\"] + 1) * micro_batch_size,\n",
    "            t1 - total_t0,\n",
    "            # this assumes that device FLOPs are the same and that all devices have the same batch size\n",
    "            fabric.world_size,\n",
    "            flops_per_batch=measured_flops,\n",
    "            lengths=total_lengths,\n",
    "        )\n",
    "        if state[\"iter_num\"] % log_interval == 0:\n",
    "            fabric.print(\n",
    "                f\"iter {state['iter_num']} step {state['step_count']}: loss {loss.item():.4f}, LR: {lr:.6f}, iter time:\"\n",
    "                f\" {(t1 - iter_t0) * 1000:.2f}ms{' (optimizer.step)' if not is_accumulating else ''}\"\n",
    "            )\n",
    "\n",
    "        if (\n",
    "            val_dataloader is not None\n",
    "            and not is_accumulating\n",
    "            and state[\"step_count\"] % eval_interval == 0\n",
    "        ):\n",
    "            t0 = time.perf_counter()\n",
    "            val_loss = validate(fabric, model, val_dataloader)\n",
    "            t1 = time.perf_counter() - t0\n",
    "            speed_monitor.eval_end(t1)\n",
    "            fabric.print(\n",
    "                f\"step {state['iter_num']}: val loss {val_loss.item():.4f}, val time: {t1 * 1000:.2f}ms\"\n",
    "            )\n",
    "            fabric.barrier()\n",
    "        if not is_accumulating and state[\"step_count\"] % save_interval == 0:\n",
    "            checkpoint_path = out_dir / f\"iter-{state['iter_num']:06d}-ckpt.pth\"\n",
    "            fabric.print(f\"Saving checkpoint to {str(checkpoint_path)!r}\")\n",
    "            fabric.save(checkpoint_path, state)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "@torch.inference_mode()\n",
    "def validate(\n",
    "    fabric: L.Fabric, model: torch.nn.Module, val_dataloader: DataLoader\n",
    ") -> torch.Tensor:\n",
    "    fabric.print(\"Validating ...\")\n",
    "    model.eval()\n",
    "\n",
    "    losses = torch.zeros(eval_iters, device=fabric.device)\n",
    "    for k, val_data in enumerate(val_dataloader):\n",
    "        input_ids = val_data[:, 0 : model.max_seq_length].contiguous()\n",
    "        targets = val_data[:, 1 : model.max_seq_length + 1].contiguous()\n",
    "        logits = model(input_ids)\n",
    "        losses[k] = chunked_cross_entropy(logits, targets, chunk_size=0)\n",
    "    out = losses.mean()\n",
    "\n",
    "    model.train()\n",
    "    return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_dataloader(\n",
    "    batch_size: int,\n",
    "    block_size: int,\n",
    "    data_dir: Path,\n",
    "    fabric: L.Fabric,\n",
    "    shuffle: bool = True,\n",
    "    seed: int = 12345,\n",
    ") -> DataLoader:\n",
    "    datasets = []\n",
    "    for prefix, _ in data_config:\n",
    "        filenames = glob.glob(str(data_dir / f\"{prefix}*\"))\n",
    "        dataset = PackedDataset(\n",
    "            filenames,\n",
    "            n_chunks=4,\n",
    "            block_size=block_size,\n",
    "            shuffle=shuffle,\n",
    "            seed=seed,\n",
    "            num_processes=fabric.world_size,\n",
    "            process_rank=fabric.global_rank,\n",
    "        )\n",
    "        datasets.append(dataset)\n",
    "\n",
    "    if not datasets:\n",
    "        raise RuntimeError(\n",
    "            f\"No data found at {data_dir}. Make sure you ran prepare_redpajama.py to create the dataset.\"\n",
    "        )\n",
    "\n",
    "    weights = [weight for _, weight in data_config]\n",
    "    sum_weights = sum(weights)\n",
    "    weights = [el / sum_weights for el in weights]\n",
    "\n",
    "    combined_dataset = CombinedDataset(datasets=datasets, seed=seed, weights=weights)\n",
    "\n",
    "    return DataLoader(\n",
    "        combined_dataset, batch_size=batch_size, shuffle=False, pin_memory=True\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_dataloaders(\n",
    "    batch_size: int,\n",
    "    block_size: int,\n",
    "    fabric: L.Fabric,\n",
    "    train_data_dir: Path = Path(\"data/redpajama_sample\"),\n",
    "    val_data_dir: Optional[Path] = None,\n",
    "    seed: int = 12345,\n",
    ") -> Tuple[DataLoader, DataLoader]:\n",
    "    # Increase by one because we need the next word as well\n",
    "    effective_block_size = block_size + 1\n",
    "    train_dataloader = create_dataloader(\n",
    "        batch_size=batch_size,\n",
    "        block_size=effective_block_size,\n",
    "        fabric=fabric,\n",
    "        data_dir=train_data_dir,\n",
    "        shuffle=True,\n",
    "        seed=seed,\n",
    "    )\n",
    "    val_dataloader = (\n",
    "        create_dataloader(\n",
    "            batch_size=batch_size,\n",
    "            block_size=effective_block_size,\n",
    "            fabric=fabric,\n",
    "            data_dir=val_data_dir,\n",
    "            shuffle=False,\n",
    "            seed=seed,\n",
    "        )\n",
    "        if val_data_dir\n",
    "        else None\n",
    "    )\n",
    "    return train_dataloader, val_dataloader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_lr(it: int) -> float:\n",
    "    # 1) linear warmup for warmup_iters steps\n",
    "    if it < warmup_iters:\n",
    "        return learning_rate * it / warmup_iters\n",
    "    # 2) if it > lr_decay_iters, return min learning rate\n",
    "    if it > lr_decay_iters:\n",
    "        return min_lr\n",
    "    # 3) in between, use cosine decay down to min learning rate\n",
    "    decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)\n",
    "    assert 0 <= decay_ratio <= 1\n",
    "    coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))  # coeff ranges 0..1\n",
    "    return min_lr + coeff * (learning_rate - min_lr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using bfloat16 Automatic Mixed Precision (AMP)\n",
      "Seed set to 1337\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'model_name': 'pythia-160m', 'name': 'redpajama', 'save_interval': 1000, 'eval_interval': 1000, 'eval_iters': 100, 'log_interval': 100, 'learning_rate': 0.006, 'batch_size': 32, 'micro_batch_size': 8, 'gradient_accumulation_steps': 4, 'max_iters': 15000, 'weight_decay': 0.1, 'beta1': 0.9, 'beta2': 0.95, 'grad_clip': 1.0, 'decay_lr': True, 'warmup_iters': 2000, 'lr_decay_iters': 15000, 'min_lr': 6e-06}\n",
      "Loading model with {'name': 'pythia-160m', 'hf_config': {'org': 'EleutherAI', 'name': 'pythia-160m-deduped'}, 'block_size': 2048, 'vocab_size': 50254, 'padding_multiple': 128, 'padded_vocab_size': 50304, 'n_layer': 12, 'n_head': 12, 'n_embd': 768, 'rotary_percentage': 0.25, 'parallel_residual': True, 'bias': True, 'lm_head_bias': False, 'n_query_groups': 12, 'shared_attention_norm': False, '_norm_class': 'LayerNorm', 'norm_eps': 1e-05, '_mlp_class': 'GptNeoxMLP', 'gelu_approximate': 'none', 'intermediate_size': 3072, 'rope_condense_ratio': 1, 'rope_base': 10000, 'head_size': 64, 'rope_n_elem': 16}\n",
      "Time to instantiate model: 1.99 seconds.\n",
      "Total parameters 162,322,944\n",
      "Estimated TFLOPs: 22.14\n",
      "Measured TFLOPs: 15.86\n",
      "iter 0 step 0: loss 11.0478, LR: 0.000000, iter time: 1312.30ms\n",
      "iter 100 step 25: loss 7.3711, LR: 0.000300, iter time: 282.00ms\n",
      "iter 200 step 50: loss 5.9653, LR: 0.000600, iter time: 293.93ms\n",
      "iter 300 step 75: loss 6.1456, LR: 0.000900, iter time: 290.72ms\n",
      "iter 400 step 100: loss 6.4233, LR: 0.001200, iter time: 291.77ms\n",
      "iter 500 step 125: loss 5.8922, LR: 0.001500, iter time: 292.98ms\n",
      "iter 600 step 150: loss 5.7330, LR: 0.001800, iter time: 292.54ms\n",
      "iter 700 step 175: loss 5.2412, LR: 0.002100, iter time: 293.18ms\n",
      "iter 800 step 200: loss 4.7973, LR: 0.002400, iter time: 291.61ms\n",
      "iter 900 step 225: loss 5.4157, LR: 0.002700, iter time: 292.85ms\n",
      "iter 1000 step 250: loss 5.1732, LR: 0.003000, iter time: 292.74ms\n",
      "iter 1100 step 275: loss 5.1144, LR: 0.003300, iter time: 291.97ms\n",
      "iter 1200 step 300: loss 4.6204, LR: 0.003600, iter time: 291.41ms\n",
      "iter 1300 step 325: loss 5.2649, LR: 0.003900, iter time: 292.33ms\n",
      "iter 1400 step 350: loss 5.3906, LR: 0.004200, iter time: 291.61ms\n",
      "iter 1500 step 375: loss 5.1544, LR: 0.004500, iter time: 292.87ms\n",
      "iter 1600 step 400: loss 5.2281, LR: 0.004800, iter time: 291.19ms\n",
      "iter 1700 step 425: loss 4.6215, LR: 0.005100, iter time: 290.65ms\n",
      "iter 1800 step 450: loss 5.1470, LR: 0.005400, iter time: 291.07ms\n",
      "iter 1900 step 475: loss 5.1262, LR: 0.005700, iter time: 291.85ms\n",
      "iter 2000 step 500: loss 4.7982, LR: 0.006000, iter time: 291.74ms\n",
      "iter 2100 step 525: loss 4.7870, LR: 0.005999, iter time: 291.40ms\n",
      "iter 2200 step 550: loss 4.6758, LR: 0.005997, iter time: 291.24ms\n",
      "iter 2300 step 575: loss 4.2770, LR: 0.005992, iter time: 290.94ms\n",
      "iter 2400 step 600: loss 4.9993, LR: 0.005986, iter time: 290.82ms\n",
      "iter 2500 step 625: loss 4.7006, LR: 0.005978, iter time: 291.72ms\n",
      "iter 2600 step 650: loss 4.4606, LR: 0.005969, iter time: 291.41ms\n",
      "iter 2700 step 675: loss 4.2507, LR: 0.005957, iter time: 291.65ms\n",
      "iter 2800 step 700: loss 4.2737, LR: 0.005944, iter time: 298.98ms\n",
      "iter 2900 step 725: loss 3.2729, LR: 0.005929, iter time: 291.06ms\n",
      "iter 3000 step 750: loss 3.6851, LR: 0.005913, iter time: 290.95ms\n",
      "iter 3100 step 775: loss 4.3133, LR: 0.005895, iter time: 291.41ms\n",
      "iter 3200 step 800: loss 4.0082, LR: 0.005875, iter time: 290.55ms\n",
      "iter 3300 step 825: loss 4.4818, LR: 0.005853, iter time: 291.40ms\n",
      "iter 3400 step 850: loss 4.0966, LR: 0.005830, iter time: 291.75ms\n",
      "iter 3500 step 875: loss 3.3417, LR: 0.005805, iter time: 291.56ms\n",
      "iter 3600 step 900: loss 3.3930, LR: 0.005779, iter time: 291.98ms\n",
      "iter 3700 step 925: loss 3.9926, LR: 0.005751, iter time: 291.38ms\n",
      "iter 3800 step 950: loss 4.4130, LR: 0.005721, iter time: 290.98ms\n",
      "iter 3900 step 975: loss 4.2273, LR: 0.005690, iter time: 290.82ms\n",
      "Saving checkpoint to 'out/redpajama/iter-003999-ckpt.pth'\n",
      "iter 4000 step 1000: loss 4.1836, LR: 0.005657, iter time: 289.39ms\n",
      "iter 4100 step 1025: loss 3.8898, LR: 0.005622, iter time: 290.57ms\n",
      "iter 4200 step 1050: loss 3.2994, LR: 0.005586, iter time: 290.66ms\n",
      "iter 4300 step 1075: loss 3.5536, LR: 0.005549, iter time: 291.97ms\n",
      "iter 4400 step 1100: loss 4.0568, LR: 0.005510, iter time: 290.74ms\n",
      "iter 4500 step 1125: loss 4.0688, LR: 0.005469, iter time: 291.51ms\n",
      "iter 4600 step 1150: loss 3.9602, LR: 0.005428, iter time: 291.69ms\n",
      "iter 4700 step 1175: loss 3.9015, LR: 0.005384, iter time: 291.05ms\n",
      "iter 4800 step 1200: loss 3.9838, LR: 0.005340, iter time: 290.89ms\n",
      "iter 4900 step 1225: loss 4.1498, LR: 0.005294, iter time: 291.43ms\n",
      "iter 5000 step 1250: loss 3.9890, LR: 0.005246, iter time: 292.04ms\n",
      "iter 5100 step 1275: loss 3.7998, LR: 0.005198, iter time: 291.67ms\n",
      "iter 5200 step 1300: loss 4.3898, LR: 0.005148, iter time: 292.07ms\n",
      "iter 5300 step 1325: loss 3.8301, LR: 0.005096, iter time: 291.71ms\n",
      "iter 5400 step 1350: loss 3.9250, LR: 0.005044, iter time: 291.87ms\n",
      "iter 5500 step 1375: loss 3.4592, LR: 0.004990, iter time: 292.45ms\n",
      "iter 5600 step 1400: loss 3.9057, LR: 0.004936, iter time: 292.48ms\n",
      "iter 5700 step 1425: loss 3.4640, LR: 0.004880, iter time: 292.17ms\n",
      "iter 5800 step 1450: loss 3.5189, LR: 0.004823, iter time: 291.53ms\n",
      "iter 5900 step 1475: loss 3.8723, LR: 0.004765, iter time: 291.76ms\n",
      "iter 6000 step 1500: loss 3.5505, LR: 0.004705, iter time: 291.40ms\n",
      "iter 6100 step 1525: loss 2.7599, LR: 0.004645, iter time: 290.44ms\n",
      "iter 6200 step 1550: loss 4.0639, LR: 0.004584, iter time: 290.73ms\n",
      "iter 6300 step 1575: loss 3.9124, LR: 0.004522, iter time: 290.77ms\n",
      "iter 6400 step 1600: loss 3.7831, LR: 0.004459, iter time: 290.48ms\n",
      "iter 6500 step 1625: loss 3.6439, LR: 0.004396, iter time: 291.02ms\n",
      "iter 6600 step 1650: loss 3.6231, LR: 0.004331, iter time: 293.27ms\n",
      "iter 6700 step 1675: loss 3.4389, LR: 0.004266, iter time: 291.11ms\n",
      "iter 6800 step 1700: loss 3.5385, LR: 0.004200, iter time: 290.80ms\n",
      "iter 6900 step 1725: loss 3.4988, LR: 0.004133, iter time: 291.01ms\n",
      "iter 7000 step 1750: loss 3.8966, LR: 0.004066, iter time: 290.56ms\n",
      "iter 7100 step 1775: loss 3.6816, LR: 0.003998, iter time: 290.93ms\n",
      "iter 7200 step 1800: loss 3.4510, LR: 0.003929, iter time: 291.20ms\n",
      "iter 7300 step 1825: loss 3.9102, LR: 0.003860, iter time: 292.28ms\n",
      "iter 7400 step 1850: loss 3.6360, LR: 0.003790, iter time: 291.56ms\n",
      "iter 7500 step 1875: loss 3.8664, LR: 0.003720, iter time: 290.58ms\n",
      "iter 7600 step 1900: loss 3.6073, LR: 0.003650, iter time: 291.40ms\n",
      "iter 7700 step 1925: loss 2.9199, LR: 0.003579, iter time: 290.78ms\n",
      "iter 7800 step 1950: loss 2.7844, LR: 0.003508, iter time: 290.67ms\n",
      "iter 7900 step 1975: loss 3.1176, LR: 0.003436, iter time: 291.73ms\n",
      "Saving checkpoint to 'out/redpajama/iter-007999-ckpt.pth'\n",
      "iter 8000 step 2000: loss 3.7936, LR: 0.003364, iter time: 290.49ms\n",
      "iter 8100 step 2025: loss 3.6197, LR: 0.003292, iter time: 290.46ms\n",
      "iter 8200 step 2050: loss 3.7480, LR: 0.003220, iter time: 291.78ms\n",
      "iter 8300 step 2075: loss 3.6900, LR: 0.003148, iter time: 291.11ms\n",
      "iter 8400 step 2100: loss 2.8864, LR: 0.003075, iter time: 291.39ms\n",
      "iter 8500 step 2125: loss 3.6963, LR: 0.003003, iter time: 291.51ms\n",
      "iter 8600 step 2150: loss 3.7093, LR: 0.002931, iter time: 291.80ms\n",
      "iter 8700 step 2175: loss 3.3042, LR: 0.002858, iter time: 290.53ms\n",
      "iter 8800 step 2200: loss 3.0944, LR: 0.002786, iter time: 290.83ms\n",
      "iter 8900 step 2225: loss 3.4312, LR: 0.002714, iter time: 290.81ms\n",
      "iter 9000 step 2250: loss 3.5048, LR: 0.002642, iter time: 290.99ms\n",
      "iter 9100 step 2275: loss 3.2803, LR: 0.002570, iter time: 291.00ms\n",
      "iter 9200 step 2300: loss 3.5930, LR: 0.002498, iter time: 292.10ms\n",
      "iter 9300 step 2325: loss 2.2495, LR: 0.002427, iter time: 290.29ms\n",
      "iter 9400 step 2350: loss 2.9088, LR: 0.002356, iter time: 290.19ms\n",
      "iter 9500 step 2375: loss 2.6597, LR: 0.002286, iter time: 291.29ms\n",
      "iter 9600 step 2400: loss 3.6206, LR: 0.002216, iter time: 291.64ms\n",
      "iter 9700 step 2425: loss 2.3134, LR: 0.002146, iter time: 289.83ms\n",
      "iter 9800 step 2450: loss 2.4301, LR: 0.002077, iter time: 289.59ms\n",
      "iter 9900 step 2475: loss 2.4800, LR: 0.002008, iter time: 290.77ms\n",
      "iter 10000 step 2500: loss 2.2368, LR: 0.001940, iter time: 290.11ms\n",
      "iter 10100 step 2525: loss 3.1508, LR: 0.001873, iter time: 291.03ms\n",
      "iter 10200 step 2550: loss 3.2954, LR: 0.001806, iter time: 291.14ms\n",
      "iter 10300 step 2575: loss 3.0130, LR: 0.001740, iter time: 291.20ms\n",
      "iter 10400 step 2600: loss 3.0044, LR: 0.001675, iter time: 290.75ms\n",
      "iter 10500 step 2625: loss 2.8596, LR: 0.001610, iter time: 290.14ms\n",
      "iter 10600 step 2650: loss 2.0126, LR: 0.001547, iter time: 290.53ms\n",
      "iter 10700 step 2675: loss 3.0040, LR: 0.001484, iter time: 292.51ms\n",
      "iter 10800 step 2700: loss 3.4691, LR: 0.001422, iter time: 290.79ms\n",
      "iter 10900 step 2725: loss 3.3719, LR: 0.001361, iter time: 291.21ms\n",
      "iter 11000 step 2750: loss 2.9904, LR: 0.001301, iter time: 292.52ms\n",
      "iter 11100 step 2775: loss 2.7121, LR: 0.001241, iter time: 291.23ms\n",
      "iter 11200 step 2800: loss 3.2472, LR: 0.001183, iter time: 291.06ms\n",
      "iter 11300 step 2825: loss 3.3517, LR: 0.001126, iter time: 291.27ms\n",
      "iter 11400 step 2850: loss 3.2715, LR: 0.001070, iter time: 292.14ms\n",
      "iter 11500 step 2875: loss 3.4200, LR: 0.001016, iter time: 290.81ms\n",
      "iter 11600 step 2900: loss 3.4924, LR: 0.000962, iter time: 291.75ms\n",
      "iter 11700 step 2925: loss 2.2736, LR: 0.000910, iter time: 290.48ms\n",
      "iter 11800 step 2950: loss 3.1776, LR: 0.000858, iter time: 291.91ms\n",
      "iter 11900 step 2975: loss 3.1710, LR: 0.000808, iter time: 291.62ms\n",
      "Saving checkpoint to 'out/redpajama/iter-011999-ckpt.pth'\n",
      "iter 12000 step 3000: loss 3.6688, LR: 0.000760, iter time: 290.94ms\n",
      "iter 12100 step 3025: loss 3.0179, LR: 0.000712, iter time: 290.84ms\n",
      "iter 12200 step 3050: loss 3.2257, LR: 0.000666, iter time: 291.06ms\n",
      "iter 12300 step 3075: loss 3.1653, LR: 0.000622, iter time: 292.47ms\n",
      "iter 12400 step 3100: loss 3.4042, LR: 0.000578, iter time: 291.42ms\n",
      "iter 12500 step 3125: loss 3.1884, LR: 0.000537, iter time: 290.93ms\n",
      "iter 12600 step 3150: loss 3.4705, LR: 0.000496, iter time: 291.49ms\n",
      "iter 12700 step 3175: loss 3.5805, LR: 0.000457, iter time: 291.72ms\n",
      "iter 12800 step 3200: loss 2.8953, LR: 0.000420, iter time: 292.49ms\n",
      "iter 12900 step 3225: loss 3.3408, LR: 0.000384, iter time: 297.87ms\n",
      "iter 13000 step 3250: loss 3.0779, LR: 0.000349, iter time: 298.95ms\n",
      "iter 13100 step 3275: loss 2.5973, LR: 0.000316, iter time: 291.06ms\n",
      "iter 13200 step 3300: loss 3.5901, LR: 0.000285, iter time: 291.16ms\n",
      "iter 13300 step 3325: loss 2.4544, LR: 0.000255, iter time: 290.62ms\n",
      "iter 13400 step 3350: loss 2.9969, LR: 0.000227, iter time: 290.56ms\n",
      "iter 13500 step 3375: loss 3.1975, LR: 0.000201, iter time: 291.62ms\n",
      "iter 13600 step 3400: loss 2.8946, LR: 0.000176, iter time: 290.60ms\n",
      "iter 13700 step 3425: loss 3.4701, LR: 0.000153, iter time: 291.61ms\n",
      "iter 13800 step 3450: loss 2.6274, LR: 0.000131, iter time: 289.90ms\n",
      "iter 13900 step 3475: loss 3.3881, LR: 0.000111, iter time: 291.66ms\n",
      "iter 14000 step 3500: loss 3.0832, LR: 0.000093, iter time: 291.88ms\n",
      "iter 14100 step 3525: loss 3.2224, LR: 0.000077, iter time: 291.17ms\n",
      "iter 14200 step 3550: loss 3.5854, LR: 0.000062, iter time: 290.77ms\n",
      "iter 14300 step 3575: loss 3.3620, LR: 0.000049, iter time: 292.27ms\n",
      "iter 14400 step 3600: loss 3.5590, LR: 0.000037, iter time: 291.91ms\n",
      "iter 14500 step 3625: loss 3.2781, LR: 0.000028, iter time: 290.50ms\n",
      "iter 14600 step 3650: loss 3.4279, LR: 0.000020, iter time: 291.54ms\n",
      "iter 14700 step 3675: loss 2.8695, LR: 0.000014, iter time: 291.52ms\n",
      "iter 14800 step 3700: loss 2.8212, LR: 0.000009, iter time: 291.34ms\n",
      "iter 14900 step 3725: loss 3.3649, LR: 0.000007, iter time: 292.48ms\n",
      "Saving checkpoint to 'out/redpajama/iter-015000-ckpt.pth'\n",
      "Training time: 4615.15s\n",
      "Memory used: 21.58 GB\n"
     ]
    }
   ],
   "source": [
    "torch.set_float32_matmul_precision(\"medium\")\n",
    "setup(devices=1, train_data_dir=Path(\"data/lit-redpajama-sample\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}