LDJA commited on
Commit
f709e5d
1 Parent(s): 35cdf3e
app/app.py CHANGED
@@ -19,7 +19,7 @@ def prepare_data():
19
  st.title("Sortie de la commande Python")
20
 
21
  # Commande Python à exécuter
22
- command = "python3 ../data/shakespeare_char/prepare.py"
23
 
24
  # Sorties de la commmande
25
  stdout, stderr = run_command(command)
@@ -43,7 +43,7 @@ def train_model():
43
  st.title("Sortie de la commande Python")
44
 
45
  # Commande Python à exécuter
46
- command = "python3 ../train.py ../config/train_shakespeare_char.py --device=cpu --compile=False --eval_iters=20 --log_interval=1 --block_size=64 --batch_size=12 --n_layer=4 --n_head=4 --n_embd=128 --max_iters=2000 --lr_decay_iters=2000 --dropout=0.0"
47
 
48
  # Sorties de la commande
49
  stdout, stderr = run_command(command)
 
19
  st.title("Sortie de la commande Python")
20
 
21
  # Commande Python à exécuter
22
+ command = "python3 data/shakespeare_char/prepare.py"
23
 
24
  # Sorties de la commmande
25
  stdout, stderr = run_command(command)
 
43
  st.title("Sortie de la commande Python")
44
 
45
  # Commande Python à exécuter
46
+ command = "python3 train.py config/train_shakespeare_char.py --device=cpu --compile=False --eval_iters=20 --log_interval=1 --block_size=64 --batch_size=12 --n_layer=4 --n_head=4 --n_embd=128 --max_iters=2000 --lr_decay_iters=2000 --dropout=0.0"
47
 
48
  # Sorties de la commande
49
  stdout, stderr = run_command(command)
app/config/eval_gpt2.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # evaluate the base gpt2
2
+ # n_layer=12, n_head=12, n_embd=768
3
+ # 124M parameters
4
+ batch_size = 8
5
+ eval_iters = 500 # use more iterations to get good estimate
6
+ eval_only = True
7
+ wandb_log = False
8
+ init_from = 'gpt2'
app/config/eval_gpt2_large.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # evaluate the base gpt2
2
+ # n_layer=36, n_head=20, n_embd=1280
3
+ # 774M parameters
4
+ batch_size = 8
5
+ eval_iters = 500 # use more iterations to get good estimate
6
+ eval_only = True
7
+ wandb_log = False
8
+ init_from = 'gpt2-large'
app/config/eval_gpt2_medium.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # evaluate the base gpt2
2
+ # n_layer=24, n_head=16, n_embd=1024
3
+ # 350M parameters
4
+ batch_size = 8
5
+ eval_iters = 500 # use more iterations to get good estimate
6
+ eval_only = True
7
+ wandb_log = False
8
+ init_from = 'gpt2-medium'
app/config/eval_gpt2_xl.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # evaluate the base gpt2
2
+ # n_layer=48, n_head=25, n_embd=1600
3
+ # 1558M parameters
4
+ batch_size = 8
5
+ eval_iters = 500 # use more iterations to get good estimate
6
+ eval_only = True
7
+ wandb_log = False
8
+ init_from = 'gpt2-xl'
app/config/finetune_shakespeare.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ out_dir = 'out-shakespeare'
4
+ eval_interval = 5
5
+ eval_iters = 40
6
+ wandb_log = False # feel free to turn on
7
+ wandb_project = 'shakespeare'
8
+ wandb_run_name = 'ft-' + str(time.time())
9
+
10
+ dataset = 'shakespeare'
11
+ init_from = 'gpt2-xl' # this is the largest GPT-2 model
12
+
13
+ # only save checkpoints if the validation loss improves
14
+ always_save_checkpoint = False
15
+
16
+ # the number of examples per iter:
17
+ # 1 batch_size * 32 grad_accum * 1024 tokens = 32,768 tokens/iter
18
+ # shakespeare has 301,966 tokens, so 1 epoch ~= 9.2 iters
19
+ batch_size = 1
20
+ gradient_accumulation_steps = 32
21
+ max_iters = 20
22
+
23
+ # finetune at constant LR
24
+ learning_rate = 3e-5
25
+ decay_lr = False
app/config/train_gpt2.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # config for training GPT-2 (124M) down to very nice loss of ~2.85 on 1 node of 8X A100 40GB
2
+ # launch as the following (e.g. in a screen session) and wait ~5 days:
3
+ # $ torchrun --standalone --nproc_per_node=8 train.py config/train_gpt2.py
4
+
5
+ wandb_log = True
6
+ wandb_project = 'owt'
7
+ wandb_run_name='gpt2-124M'
8
+
9
+ # these make the total batch size be ~0.5M
10
+ # 12 batch size * 1024 block size * 5 gradaccum * 8 GPUs = 491,520
11
+ batch_size = 12
12
+ block_size = 1024
13
+ gradient_accumulation_steps = 5 * 8
14
+
15
+ # this makes total number of tokens be 300B
16
+ max_iters = 600000
17
+ lr_decay_iters = 600000
18
+
19
+ # eval stuff
20
+ eval_interval = 1000
21
+ eval_iters = 200
22
+ log_interval = 10
23
+
24
+ # weight decay
25
+ weight_decay = 1e-1
app/config/train_shakespeare_char.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # train a miniature character-level shakespeare model
2
+ # good for debugging and playing on macbooks and such
3
+
4
+ out_dir = 'out-shakespeare-char'
5
+ eval_interval = 250 # keep frequent because we'll overfit
6
+ eval_iters = 200
7
+ log_interval = 10 # don't print too too often
8
+
9
+ # we expect to overfit on this small dataset, so only save when val improves
10
+ always_save_checkpoint = False
11
+
12
+ wandb_log = False # override via command line if you like
13
+ wandb_project = 'shakespeare-char'
14
+ wandb_run_name = 'mini-gpt'
15
+
16
+ dataset = 'shakespeare_char'
17
+ gradient_accumulation_steps = 1
18
+ batch_size = 64
19
+ block_size = 256 # context of up to 256 previous characters
20
+
21
+ # baby GPT model :)
22
+ n_layer = 6
23
+ n_head = 6
24
+ n_embd = 384
25
+ dropout = 0.2
26
+
27
+ learning_rate = 1e-3 # with baby networks can afford to go a bit higher
28
+ max_iters = 5000
29
+ lr_decay_iters = 5000 # make equal to max_iters usually
30
+ min_lr = 1e-4 # learning_rate / 10 usually
31
+ beta2 = 0.99 # make a bit bigger because number of tokens per iter is small
32
+
33
+ warmup_iters = 100 # not super necessary potentially
34
+
35
+ # on macbook also add
36
+ # device = 'cpu' # run on cpu only
37
+ # compile = False # do not torch compile the model
app/data/openwebtext/prepare.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # saves the openwebtext dataset to a binary file for training. following was helpful:
2
+ # https://github.com/HazyResearch/flash-attention/blob/main/training/src/datamodules/language_modeling_hf.py
3
+
4
+ import os
5
+ from tqdm import tqdm
6
+ import numpy as np
7
+ import tiktoken
8
+ from datasets import load_dataset # huggingface datasets
9
+
10
+ # number of workers in .map() call
11
+ # good number to use is ~order number of cpu cores // 2
12
+ num_proc = 8
13
+
14
+ # number of workers in load_dataset() call
15
+ # best number might be different from num_proc above as it also depends on NW speed.
16
+ # it is better than 1 usually though
17
+ num_proc_load_dataset = num_proc
18
+
19
+ if __name__ == '__main__':
20
+ # takes 54GB in huggingface .cache dir, about 8M documents (8,013,769)
21
+ dataset = load_dataset("openwebtext", num_proc=num_proc_load_dataset)
22
+
23
+ # owt by default only contains the 'train' split, so create a test split
24
+ split_dataset = dataset["train"].train_test_split(test_size=0.0005, seed=2357, shuffle=True)
25
+ split_dataset['val'] = split_dataset.pop('test') # rename the test split to val
26
+
27
+ # this results in:
28
+ # >>> split_dataset
29
+ # DatasetDict({
30
+ # train: Dataset({
31
+ # features: ['text'],
32
+ # num_rows: 8009762
33
+ # })
34
+ # val: Dataset({
35
+ # features: ['text'],
36
+ # num_rows: 4007
37
+ # })
38
+ # })
39
+
40
+ # we now want to tokenize the dataset. first define the encoding function (gpt2 bpe)
41
+ enc = tiktoken.get_encoding("gpt2")
42
+ def process(example):
43
+ ids = enc.encode_ordinary(example['text']) # encode_ordinary ignores any special tokens
44
+ ids.append(enc.eot_token) # add the end of text token, e.g. 50256 for gpt2 bpe
45
+ # note: I think eot should be prepended not appended... hmm. it's called "eot" though...
46
+ out = {'ids': ids, 'len': len(ids)}
47
+ return out
48
+
49
+ # tokenize the dataset
50
+ tokenized = split_dataset.map(
51
+ process,
52
+ remove_columns=['text'],
53
+ desc="tokenizing the splits",
54
+ num_proc=num_proc,
55
+ )
56
+
57
+ # concatenate all the ids in each dataset into one large file we can use for training
58
+ for split, dset in tokenized.items():
59
+ arr_len = np.sum(dset['len'], dtype=np.uint64)
60
+ filename = os.path.join(os.path.dirname(__file__), f'{split}.bin')
61
+ dtype = np.uint16 # (can do since enc.max_token_value == 50256 is < 2**16)
62
+ arr = np.memmap(filename, dtype=dtype, mode='w+', shape=(arr_len,))
63
+ total_batches = 1024
64
+
65
+ idx = 0
66
+ for batch_idx in tqdm(range(total_batches), desc=f'writing {filename}'):
67
+ # Batch together samples for faster write
68
+ batch = dset.shard(num_shards=total_batches, index=batch_idx, contiguous=True).with_format('numpy')
69
+ arr_batch = np.concatenate(batch['ids'])
70
+ # Write into mmap
71
+ arr[idx : idx + len(arr_batch)] = arr_batch
72
+ idx += len(arr_batch)
73
+ arr.flush()
74
+
75
+ # train.bin is ~17GB, val.bin ~8.5MB
76
+ # train has ~9B tokens (9,035,582,198)
77
+ # val has ~4M tokens (4,434,897)
78
+
79
+ # to read the bin files later, e.g. with numpy:
80
+ # m = np.memmap('train.bin', dtype=np.uint16, mode='r')
app/data/openwebtext/readme.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ## openwebtext dataset
3
+
4
+ after running `prepare.py` (preprocess) we get:
5
+
6
+ - train.bin is ~17GB, val.bin ~8.5MB
7
+ - train has ~9B tokens (9,035,582,198)
8
+ - val has ~4M tokens (4,434,897)
9
+
10
+ this came from 8,013,769 documents in total.
11
+
12
+ references:
13
+
14
+ - OpenAI's WebText dataset is discussed in [GPT-2 paper](https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf)
15
+ - [OpenWebText](https://skylion007.github.io/OpenWebTextCorpus/) dataset
app/data/shakespeare/prepare.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import tiktoken
4
+ import numpy as np
5
+
6
+ # download the tiny shakespeare dataset
7
+ input_file_path = os.path.join(os.path.dirname(__file__), 'input.txt')
8
+ if not os.path.exists(input_file_path):
9
+ data_url = 'https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt'
10
+ with open(input_file_path, 'w') as f:
11
+ f.write(requests.get(data_url).text)
12
+
13
+ with open(input_file_path, 'r') as f:
14
+ data = f.read()
15
+ n = len(data)
16
+ train_data = data[:int(n*0.9)]
17
+ val_data = data[int(n*0.9):]
18
+
19
+ # encode with tiktoken gpt2 bpe
20
+ enc = tiktoken.get_encoding("gpt2")
21
+ train_ids = enc.encode_ordinary(train_data)
22
+ val_ids = enc.encode_ordinary(val_data)
23
+ print(f"train has {len(train_ids):,} tokens")
24
+ print(f"val has {len(val_ids):,} tokens")
25
+
26
+ # export to bin files
27
+ train_ids = np.array(train_ids, dtype=np.uint16)
28
+ val_ids = np.array(val_ids, dtype=np.uint16)
29
+ train_ids.tofile(os.path.join(os.path.dirname(__file__), 'train.bin'))
30
+ val_ids.tofile(os.path.join(os.path.dirname(__file__), 'val.bin'))
31
+
32
+ # train.bin has 301,966 tokens
33
+ # val.bin has 36,059 tokens
app/data/shakespeare/readme.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # tiny shakespeare
3
+
4
+ Tiny shakespeare, of the good old char-rnn fame :)
5
+
6
+ After running `prepare.py`:
7
+
8
+ - train.bin has 301,966 tokens
9
+ - val.bin has 36,059 tokens
app/data/shakespeare_char/.DS_Store ADDED
Binary file (6.15 kB). View file
 
app/data/shakespeare_char/input.txt ADDED
The diff for this file is too large to render. See raw diff
 
app/data/shakespeare_char/meta.pkl ADDED
Binary file (703 Bytes). View file
 
app/data/shakespeare_char/prepare.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Prepare the Shakespeare dataset for character-level language modeling.
3
+ So instead of encoding with GPT-2 BPE tokens, we just map characters to ints.
4
+ Will save train.bin, val.bin containing the ids, and meta.pkl containing the
5
+ encoder and decoder and some other related info.
6
+ """
7
+ import os
8
+ import pickle
9
+ import requests
10
+ import numpy as np
11
+
12
+ # download the tiny shakespeare dataset
13
+ input_file_path = os.path.join(os.path.dirname(__file__), 'input.txt')
14
+ if not os.path.exists(input_file_path):
15
+ data_url = 'https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt'
16
+ with open(input_file_path, 'w') as f:
17
+ f.write(requests.get(data_url).text)
18
+
19
+ with open(input_file_path, 'r') as f:
20
+ data = f.read()
21
+ print(f"length of dataset in characters: {len(data):,}")
22
+
23
+ # get all the unique characters that occur in this text
24
+ chars = sorted(list(set(data)))
25
+ vocab_size = len(chars)
26
+ print("all the unique characters:", ''.join(chars))
27
+ print(f"vocab size: {vocab_size:,}")
28
+
29
+ # create a mapping from characters to integers
30
+ stoi = { ch:i for i,ch in enumerate(chars) }
31
+ itos = { i:ch for i,ch in enumerate(chars) }
32
+ def encode(s):
33
+ return [stoi[c] for c in s] # encoder: take a string, output a list of integers
34
+ def decode(l):
35
+ return ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
36
+
37
+ # create the train and test splits
38
+ n = len(data)
39
+ train_data = data[:int(n*0.9)]
40
+ val_data = data[int(n*0.9):]
41
+
42
+ # encode both to integers
43
+ train_ids = encode(train_data)
44
+ val_ids = encode(val_data)
45
+ print(f"train has {len(train_ids):,} tokens")
46
+ print(f"val has {len(val_ids):,} tokens")
47
+
48
+ # export to bin files
49
+ train_ids = np.array(train_ids, dtype=np.uint16)
50
+ val_ids = np.array(val_ids, dtype=np.uint16)
51
+ train_ids.tofile(os.path.join(os.path.dirname(__file__), 'train.bin'))
52
+ val_ids.tofile(os.path.join(os.path.dirname(__file__), 'val.bin'))
53
+
54
+ # save the meta information as well, to help us encode/decode later
55
+ meta = {
56
+ 'vocab_size': vocab_size,
57
+ 'itos': itos,
58
+ 'stoi': stoi,
59
+ }
60
+ with open(os.path.join(os.path.dirname(__file__), 'meta.pkl'), 'wb') as f:
61
+ pickle.dump(meta, f)
62
+
63
+ # length of dataset in characters: 1115394
64
+ # all the unique characters:
65
+ # !$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
66
+ # vocab size: 65
67
+ # train has 1003854 tokens
68
+ # val has 111540 tokens
app/data/shakespeare_char/readme.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # tiny shakespeare, character-level
3
+
4
+ Tiny shakespeare, of the good old char-rnn fame :) Treated on character-level.
5
+
6
+ After running `prepare.py`:
7
+
8
+ - train.bin has 1,003,854 tokens
9
+ - val.bin has 111,540 tokens
app/train.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This training script can be run both on a single gpu in debug mode,
3
+ and also in a larger training run with distributed data parallel (ddp).
4
+
5
+ To run on a single GPU, example:
6
+ $ python train.py --batch_size=32 --compile=False
7
+
8
+ To run with DDP on 4 gpus on 1 node, example:
9
+ $ torchrun --standalone --nproc_per_node=4 train.py
10
+
11
+ To run with DDP on 4 gpus across 2 nodes, example:
12
+ - Run on the first (master) node with example IP 123.456.123.456:
13
+ $ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train.py
14
+ - Run on the worker node:
15
+ $ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train.py
16
+ (If your cluster does not have Infiniband interconnect prepend NCCL_IB_DISABLE=1)
17
+ """
18
+
19
+ import os
20
+ import time
21
+ import math
22
+ import pickle
23
+ from contextlib import nullcontext
24
+
25
+ import numpy as np
26
+ import torch
27
+ from torch.nn.parallel import DistributedDataParallel as DDP
28
+ from torch.distributed import init_process_group, destroy_process_group
29
+
30
+ from model import GPTConfig, GPT
31
+
32
+ # -----------------------------------------------------------------------------
33
+ # default config values designed to train a gpt2 (124M) on OpenWebText
34
+ # I/O
35
+ out_dir = 'out'
36
+ eval_interval = 2000
37
+ log_interval = 1
38
+ eval_iters = 200
39
+ eval_only = False # if True, script exits right after the first eval
40
+ always_save_checkpoint = True # if True, always save a checkpoint after each eval
41
+ init_from = 'scratch' # 'scratch' or 'resume' or 'gpt2*'
42
+ # wandb logging
43
+ wandb_log = False # disabled by default
44
+ wandb_project = 'owt'
45
+ wandb_run_name = 'gpt2' # 'run' + str(time.time())
46
+ # data
47
+ dataset = 'openwebtext'
48
+ gradient_accumulation_steps = 5 * 8 # used to simulate larger batch sizes
49
+ batch_size = 12 # if gradient_accumulation_steps > 1, this is the micro-batch size
50
+ block_size = 1024
51
+ # model
52
+ n_layer = 12
53
+ n_head = 12
54
+ n_embd = 768
55
+ dropout = 0.0 # for pretraining 0 is good, for finetuning try 0.1+
56
+ bias = False # do we use bias inside LayerNorm and Linear layers?
57
+ # adamw optimizer
58
+ learning_rate = 6e-4 # max learning rate
59
+ max_iters = 600000 # total number of training iterations
60
+ weight_decay = 1e-1
61
+ beta1 = 0.9
62
+ beta2 = 0.95
63
+ grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0
64
+ # learning rate decay settings
65
+ decay_lr = True # whether to decay the learning rate
66
+ warmup_iters = 2000 # how many steps to warm up for
67
+ lr_decay_iters = 600000 # should be ~= max_iters per Chinchilla
68
+ min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
69
+ # DDP settings
70
+ backend = 'nccl' # 'nccl', 'gloo', etc.
71
+ # system
72
+ device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks
73
+ dtype = 'bfloat16' if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else 'float16' # 'float32', 'bfloat16', or 'float16', the latter will auto implement a GradScaler
74
+ compile = True # use PyTorch 2.0 to compile the model to be faster
75
+ # -----------------------------------------------------------------------------
76
+ config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
77
+ exec(open('configurator.py').read()) # overrides from command line or config file
78
+ config = {k: globals()[k] for k in config_keys} # will be useful for logging
79
+ # -----------------------------------------------------------------------------
80
+
81
+ # various inits, derived attributes, I/O setup
82
+ ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
83
+ if ddp:
84
+ init_process_group(backend=backend)
85
+ ddp_rank = int(os.environ['RANK'])
86
+ ddp_local_rank = int(os.environ['LOCAL_RANK'])
87
+ ddp_world_size = int(os.environ['WORLD_SIZE'])
88
+ device = f'cuda:{ddp_local_rank}'
89
+ torch.cuda.set_device(device)
90
+ master_process = ddp_rank == 0 # this process will do logging, checkpointing etc.
91
+ seed_offset = ddp_rank # each process gets a different seed
92
+ # world_size number of processes will be training simultaneously, so we can scale
93
+ # down the desired gradient accumulation iterations per process proportionally
94
+ assert gradient_accumulation_steps % ddp_world_size == 0
95
+ gradient_accumulation_steps //= ddp_world_size
96
+ else:
97
+ # if not ddp, we are running on a single gpu, and one process
98
+ master_process = True
99
+ seed_offset = 0
100
+ ddp_world_size = 1
101
+ tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
102
+ print(f"tokens per iteration will be: {tokens_per_iter:,}")
103
+
104
+ if master_process:
105
+ os.makedirs(out_dir, exist_ok=True)
106
+ torch.manual_seed(1337 + seed_offset)
107
+ torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
108
+ torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
109
+ device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
110
+ # note: float16 data type will automatically use a GradScaler
111
+ ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
112
+ ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
113
+
114
+ # poor man's data loader
115
+ data_dir = os.path.join('data', dataset)
116
+ train_data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r')
117
+ val_data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r')
118
+ def get_batch(split):
119
+ data = train_data if split == 'train' else val_data
120
+ ix = torch.randint(len(data) - block_size, (batch_size,))
121
+ x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix])
122
+ y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])
123
+ if device_type == 'cuda':
124
+ # pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True)
125
+ x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
126
+ else:
127
+ x, y = x.to(device), y.to(device)
128
+ return x, y
129
+
130
+ # init these up here, can override if init_from='resume' (i.e. from a checkpoint)
131
+ iter_num = 0
132
+ best_val_loss = 1e9
133
+
134
+ # attempt to derive vocab_size from the dataset
135
+ meta_path = os.path.join(data_dir, 'meta.pkl')
136
+ meta_vocab_size = None
137
+ if os.path.exists(meta_path):
138
+ with open(meta_path, 'rb') as f:
139
+ meta = pickle.load(f)
140
+ meta_vocab_size = meta['vocab_size']
141
+ print(f"found vocab_size = {meta_vocab_size} (inside {meta_path})")
142
+
143
+ # model init
144
+ model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
145
+ bias=bias, vocab_size=None, dropout=dropout) # start with model_args from command line
146
+ if init_from == 'scratch':
147
+ # init a new model from scratch
148
+ print("Initializing a new model from scratch")
149
+ # determine the vocab size we'll use for from-scratch training
150
+ if meta_vocab_size is None:
151
+ print("defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)")
152
+ model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
153
+ gptconf = GPTConfig(**model_args)
154
+ model = GPT(gptconf)
155
+ elif init_from == 'resume':
156
+ print(f"Resuming training from {out_dir}")
157
+ # resume training from a checkpoint.
158
+ ckpt_path = os.path.join(out_dir, 'ckpt.pt')
159
+ checkpoint = torch.load(ckpt_path, map_location=device)
160
+ checkpoint_model_args = checkpoint['model_args']
161
+ # force these config attributes to be equal otherwise we can't even resume training
162
+ # the rest of the attributes (e.g. dropout) can stay as desired from command line
163
+ for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
164
+ model_args[k] = checkpoint_model_args[k]
165
+ # create the model
166
+ gptconf = GPTConfig(**model_args)
167
+ model = GPT(gptconf)
168
+ state_dict = checkpoint['model']
169
+ # fix the keys of the state dictionary :(
170
+ # honestly no idea how checkpoints sometimes get this prefix, have to debug more
171
+ unwanted_prefix = '_orig_mod.'
172
+ for k,v in list(state_dict.items()):
173
+ if k.startswith(unwanted_prefix):
174
+ state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
175
+ model.load_state_dict(state_dict)
176
+ iter_num = checkpoint['iter_num']
177
+ best_val_loss = checkpoint['best_val_loss']
178
+ elif init_from.startswith('gpt2'):
179
+ print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
180
+ # initialize from OpenAI GPT-2 weights
181
+ override_args = dict(dropout=dropout)
182
+ model = GPT.from_pretrained(init_from, override_args)
183
+ # read off the created config params, so we can store them into checkpoint correctly
184
+ for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
185
+ model_args[k] = getattr(model.config, k)
186
+ # crop down the model block size if desired, using model surgery
187
+ if block_size < model.config.block_size:
188
+ model.crop_block_size(block_size)
189
+ model_args['block_size'] = block_size # so that the checkpoint will have the right value
190
+ model.to(device)
191
+
192
+ # initialize a GradScaler. If enabled=False scaler is a no-op
193
+ scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16'))
194
+
195
+ # optimizer
196
+ optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type)
197
+ if init_from == 'resume':
198
+ optimizer.load_state_dict(checkpoint['optimizer'])
199
+ checkpoint = None # free up memory
200
+
201
+ # compile the model
202
+ if compile:
203
+ print("compiling the model... (takes a ~minute)")
204
+ unoptimized_model = model
205
+ model = torch.compile(model) # requires PyTorch 2.0
206
+
207
+ # wrap model into DDP container
208
+ if ddp:
209
+ model = DDP(model, device_ids=[ddp_local_rank])
210
+
211
+ # helps estimate an arbitrarily accurate loss over either split using many batches
212
+ @torch.no_grad()
213
+ def estimate_loss():
214
+ out = {}
215
+ model.eval()
216
+ for split in ['train', 'val']:
217
+ losses = torch.zeros(eval_iters)
218
+ for k in range(eval_iters):
219
+ X, Y = get_batch(split)
220
+ with ctx:
221
+ logits, loss = model(X, Y)
222
+ losses[k] = loss.item()
223
+ out[split] = losses.mean()
224
+ model.train()
225
+ return out
226
+
227
+ # learning rate decay scheduler (cosine with warmup)
228
+ def get_lr(it):
229
+ # 1) linear warmup for warmup_iters steps
230
+ if it < warmup_iters:
231
+ return learning_rate * it / warmup_iters
232
+ # 2) if it > lr_decay_iters, return min learning rate
233
+ if it > lr_decay_iters:
234
+ return min_lr
235
+ # 3) in between, use cosine decay down to min learning rate
236
+ decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
237
+ assert 0 <= decay_ratio <= 1
238
+ coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1
239
+ return min_lr + coeff * (learning_rate - min_lr)
240
+
241
+ # logging
242
+ if wandb_log and master_process:
243
+ import wandb
244
+ wandb.init(project=wandb_project, name=wandb_run_name, config=config)
245
+
246
+ # training loop
247
+ X, Y = get_batch('train') # fetch the very first batch
248
+ t0 = time.time()
249
+ local_iter_num = 0 # number of iterations in the lifetime of this process
250
+ raw_model = model.module if ddp else model # unwrap DDP container if needed
251
+ running_mfu = -1.0
252
+ while True:
253
+
254
+ # determine and set the learning rate for this iteration
255
+ lr = get_lr(iter_num) if decay_lr else learning_rate
256
+ for param_group in optimizer.param_groups:
257
+ param_group['lr'] = lr
258
+
259
+ # evaluate the loss on train/val sets and write checkpoints
260
+ if iter_num % eval_interval == 0 and master_process:
261
+ losses = estimate_loss()
262
+ print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
263
+ if wandb_log:
264
+ wandb.log({
265
+ "iter": iter_num,
266
+ "train/loss": losses['train'],
267
+ "val/loss": losses['val'],
268
+ "lr": lr,
269
+ "mfu": running_mfu*100, # convert to percentage
270
+ })
271
+ if losses['val'] < best_val_loss or always_save_checkpoint:
272
+ best_val_loss = losses['val']
273
+ if iter_num > 0:
274
+ checkpoint = {
275
+ 'model': raw_model.state_dict(),
276
+ 'optimizer': optimizer.state_dict(),
277
+ 'model_args': model_args,
278
+ 'iter_num': iter_num,
279
+ 'best_val_loss': best_val_loss,
280
+ 'config': config,
281
+ }
282
+ print(f"saving checkpoint to {out_dir}")
283
+ torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
284
+ if iter_num == 0 and eval_only:
285
+ break
286
+
287
+ # forward backward update, with optional gradient accumulation to simulate larger batch size
288
+ # and using the GradScaler if data type is float16
289
+ for micro_step in range(gradient_accumulation_steps):
290
+ if ddp:
291
+ # in DDP training we only need to sync gradients at the last micro step.
292
+ # the official way to do this is with model.no_sync() context manager, but
293
+ # I really dislike that this bloats the code and forces us to repeat code
294
+ # looking at the source of that context manager, it just toggles this variable
295
+ model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
296
+ with ctx:
297
+ logits, loss = model(X, Y)
298
+ loss = loss / gradient_accumulation_steps # scale the loss to account for gradient accumulation
299
+ # immediately async prefetch next batch while model is doing the forward pass on the GPU
300
+ X, Y = get_batch('train')
301
+ # backward pass, with gradient scaling if training in fp16
302
+ scaler.scale(loss).backward()
303
+ # clip the gradient
304
+ if grad_clip != 0.0:
305
+ scaler.unscale_(optimizer)
306
+ torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
307
+ # step the optimizer and scaler if training in fp16
308
+ scaler.step(optimizer)
309
+ scaler.update()
310
+ # flush the gradients as soon as we can, no need for this memory anymore
311
+ optimizer.zero_grad(set_to_none=True)
312
+
313
+ # timing and logging
314
+ t1 = time.time()
315
+ dt = t1 - t0
316
+ t0 = t1
317
+ if iter_num % log_interval == 0 and master_process:
318
+ # get loss as float. note: this is a CPU-GPU sync point
319
+ # scale up to undo the division above, approximating the true total loss (exact would have been a sum)
320
+ lossf = loss.item() * gradient_accumulation_steps
321
+ if local_iter_num >= 5: # let the training loop settle a bit
322
+ mfu = raw_model.estimate_mfu(batch_size * gradient_accumulation_steps, dt)
323
+ running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu
324
+ print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%")
325
+ iter_num += 1
326
+ local_iter_num += 1
327
+
328
+ # termination conditions
329
+ if iter_num > max_iters:
330
+ break
331
+
332
+ if ddp:
333
+ destroy_process_group()