Compare commits
16
Commits
eba36e8464
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9dc91c262e | ||
|
|
a747ca26ea | ||
|
|
93a43d9a5c | ||
|
|
dc81cb368c | ||
|
|
9755682b98 | ||
|
|
3ab86ce851 | ||
|
|
7c7e627108 | ||
|
|
5cb16fe66a | ||
|
|
1ab9ec1b83 | ||
|
|
325be85d9b | ||
|
|
a022d02ee2 | ||
|
|
f68ac2200d | ||
|
|
f35dc82437 | ||
|
|
b7e194a756 | ||
|
|
5156fef93c | ||
|
|
dccf362c2b |
No files matched your search
@@ -8,3 +8,5 @@ __pycache__/
|
|||||||
*.pt
|
*.pt
|
||||||
*.pyc
|
*.pyc
|
||||||
input.txt
|
input.txt
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
@@ -29,22 +29,22 @@ Dependencies:
|
|||||||
|
|
||||||
If you are not a deep learning professional and you just want to feel the magic and get your feet wet, the fastest way to get started is to train a character-level GPT on the works of Shakespeare. First, we download it as a single (1MB) file and turn it from raw text into one large stream of integers:
|
If you are not a deep learning professional and you just want to feel the magic and get your feet wet, the fastest way to get started is to train a character-level GPT on the works of Shakespeare. First, we download it as a single (1MB) file and turn it from raw text into one large stream of integers:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python data/shakespeare_char/prepare.py
|
python data/shakespeare_char/prepare.py
|
||||||
```
|
```
|
||||||
|
|
||||||
This creates a `train.bin` and `val.bin` in that data directory. Now it is time to train your GPT. The size of it very much depends on the computational resources of your system:
|
This creates a `train.bin` and `val.bin` in that data directory. Now it is time to train your GPT. The size of it very much depends on the computational resources of your system:
|
||||||
|
|
||||||
**I have a GPU**. Great, we can quickly train a baby GPT with the settings provided in the [config/train_shakespeare_char.py](config/train_shakespeare_char.py) config file:
|
**I have a GPU**. Great, we can quickly train a baby GPT with the settings provided in the [config/train_shakespeare_char.py](config/train_shakespeare_char.py) config file:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python train.py config/train_shakespeare_char.py
|
python train.py config/train_shakespeare_char.py
|
||||||
```
|
```
|
||||||
|
|
||||||
If you peek inside it, you'll see that we're training a GPT with a context size of up to 256 characters, 384 feature channels, and it is a 6-layer Transformer with 6 heads in each layer. On one A100 GPU this training run takes about 3 minutes and the best validation loss is 1.4697. Based on the configuration, the model checkpoints are being written into the `--out_dir` directory `out-shakespeare-char`. So once the training finishes we can sample from the best model by pointing the sampling script at this directory:
|
If you peek inside it, you'll see that we're training a GPT with a context size of up to 256 characters, 384 feature channels, and it is a 6-layer Transformer with 6 heads in each layer. On one A100 GPU this training run takes about 3 minutes and the best validation loss is 1.4697. Based on the configuration, the model checkpoints are being written into the `--out_dir` directory `out-shakespeare-char`. So once the training finishes we can sample from the best model by pointing the sampling script at this directory:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python sample.py --out_dir=out-shakespeare-char
|
python sample.py --out_dir=out-shakespeare-char
|
||||||
```
|
```
|
||||||
|
|
||||||
This generates a few samples, for example:
|
This generates a few samples, for example:
|
||||||
@@ -74,14 +74,14 @@ lol `¯\_(ツ)_/¯`. Not bad for a character-level model after 3 minutes of tra
|
|||||||
|
|
||||||
**I only have a macbook** (or other cheap computer). No worries, we can still train a GPT but we want to dial things down a notch. I recommend getting the bleeding edge PyTorch nightly ([select it here](https://pytorch.org/get-started/locally/) when installing) as it is currently quite likely to make your code more efficient. But even without it, a simple train run could look as follows:
|
**I only have a macbook** (or other cheap computer). No worries, we can still train a GPT but we want to dial things down a notch. I recommend getting the bleeding edge PyTorch nightly ([select it here](https://pytorch.org/get-started/locally/) when installing) as it is currently quite likely to make your code more efficient. But even without it, a simple train run could look as follows:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python 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
|
python 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
|
||||||
```
|
```
|
||||||
|
|
||||||
Here, since we are running on CPU instead of GPU we must set both `--device=cpu` and also turn off PyTorch 2.0 compile with `--compile=False`. Then when we evaluate we get a bit more noisy but faster estimate (`--eval_iters=20`, down from 200), our context size is only 64 characters instead of 256, and the batch size only 12 examples per iteration, not 64. We'll also use a much smaller Transformer (4 layers, 4 heads, 128 embedding size), and decrease the number of iterations to 2000 (and correspondingly usually decay the learning rate to around max_iters with `--lr_decay_iters`). Because our network is so small we also ease down on regularization (`--dropout=0.0`). This still runs in about ~3 minutes, but gets us a loss of only 1.88 and therefore also worse samples, but it's still good fun:
|
Here, since we are running on CPU instead of GPU we must set both `--device=cpu` and also turn off PyTorch 2.0 compile with `--compile=False`. Then when we evaluate we get a bit more noisy but faster estimate (`--eval_iters=20`, down from 200), our context size is only 64 characters instead of 256, and the batch size only 12 examples per iteration, not 64. We'll also use a much smaller Transformer (4 layers, 4 heads, 128 embedding size), and decrease the number of iterations to 2000 (and correspondingly usually decay the learning rate to around max_iters with `--lr_decay_iters`). Because our network is so small we also ease down on regularization (`--dropout=0.0`). This still runs in about ~3 minutes, but gets us a loss of only 1.88 and therefore also worse samples, but it's still good fun:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python sample.py --out_dir=out-shakespeare-char --device=cpu
|
python sample.py --out_dir=out-shakespeare-char --device=cpu
|
||||||
```
|
```
|
||||||
Generates samples like this:
|
Generates samples like this:
|
||||||
|
|
||||||
@@ -101,40 +101,40 @@ Finally, on Apple Silicon Macbooks and with a recent PyTorch version make sure t
|
|||||||
|
|
||||||
A more serious deep learning professional may be more interested in reproducing GPT-2 results. So here we go - we first tokenize the dataset, in this case the [OpenWebText](https://openwebtext2.readthedocs.io/en/latest/), an open reproduction of OpenAI's (private) WebText:
|
A more serious deep learning professional may be more interested in reproducing GPT-2 results. So here we go - we first tokenize the dataset, in this case the [OpenWebText](https://openwebtext2.readthedocs.io/en/latest/), an open reproduction of OpenAI's (private) WebText:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python data/openwebtext/prepare.py
|
python data/openwebtext/prepare.py
|
||||||
```
|
```
|
||||||
|
|
||||||
This downloads and tokenizes the [OpenWebText](https://huggingface.co/datasets/openwebtext) dataset. It will create a `train.bin` and `val.bin` which holds the GPT2 BPE token ids in one sequence, stored as raw uint16 bytes. Then we're ready to kick off training. To reproduce GPT-2 (124M) you'll want at least an 8X A100 40GB node and run:
|
This downloads and tokenizes the [OpenWebText](https://huggingface.co/datasets/openwebtext) dataset. It will create a `train.bin` and `val.bin` which holds the GPT2 BPE token ids in one sequence, stored as raw uint16 bytes. Then we're ready to kick off training. To reproduce GPT-2 (124M) you'll want at least an 8X A100 40GB node and run:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ torchrun --standalone --nproc_per_node=8 train.py config/train_gpt2.py
|
torchrun --standalone --nproc_per_node=8 train.py config/train_gpt2.py
|
||||||
```
|
```
|
||||||
|
|
||||||
This will run for about 4 days using PyTorch Distributed Data Parallel (DDP) and go down to loss of ~2.85. Now, a GPT-2 model just evaluated on OWT gets a val loss of about 3.11, but if you finetune it it will come down to ~2.85 territory (due to an apparent domain gap), making the two models ~match.
|
This will run for about 4 days using PyTorch Distributed Data Parallel (DDP) and go down to loss of ~2.85. Now, a GPT-2 model just evaluated on OWT gets a val loss of about 3.11, but if you finetune it it will come down to ~2.85 territory (due to an apparent domain gap), making the two models ~match.
|
||||||
|
|
||||||
If you're in a cluster environment and you are blessed with multiple GPU nodes you can make GPU go brrrr e.g. across 2 nodes like:
|
If you're in a cluster environment and you are blessed with multiple GPU nodes you can make GPU go brrrr e.g. across 2 nodes like:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
Run on the first (master) node with example IP 123.456.123.456:
|
# Run on the first (master) node with example IP 123.456.123.456:
|
||||||
$ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train.py
|
torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train.py
|
||||||
Run on the worker node:
|
# Run on the worker node:
|
||||||
$ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train.py
|
torchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train.py
|
||||||
```
|
```
|
||||||
|
|
||||||
It is a good idea to benchmark your interconnect (e.g. iperf3). In particular, if you don't have Infiniband then also prepend `NCCL_IB_DISABLE=1` to the above launches. Your multinode training will work, but most likely _crawl_. By default checkpoints are periodically written to the `--out_dir`. We can sample from the model by simply `$ python sample.py`.
|
It is a good idea to benchmark your interconnect (e.g. iperf3). In particular, if you don't have Infiniband then also prepend `NCCL_IB_DISABLE=1` to the above launches. Your multinode training will work, but most likely _crawl_. By default checkpoints are periodically written to the `--out_dir`. We can sample from the model by simply `python sample.py`.
|
||||||
|
|
||||||
Finally, to train on a single GPU simply run the `$ python train.py` script. Have a look at all of its args, the script tries to be very readable, hackable and transparent. You'll most likely want to tune a number of those variables depending on your needs.
|
Finally, to train on a single GPU simply run the `python train.py` script. Have a look at all of its args, the script tries to be very readable, hackable and transparent. You'll most likely want to tune a number of those variables depending on your needs.
|
||||||
|
|
||||||
## baselines
|
## baselines
|
||||||
|
|
||||||
OpenAI GPT-2 checkpoints allow us to get some baselines in place for openwebtext. We can get the numbers as follows:
|
OpenAI GPT-2 checkpoints allow us to get some baselines in place for openwebtext. We can get the numbers as follows:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python train.py eval_gpt2
|
$ python train.py config/eval_gpt2.py
|
||||||
$ python train.py eval_gpt2_medium
|
$ python train.py config/eval_gpt2_medium.py
|
||||||
$ python train.py eval_gpt2_large
|
$ python train.py config/eval_gpt2_large.py
|
||||||
$ python train.py eval_gpt2_xl
|
$ python train.py config/eval_gpt2_xl.py
|
||||||
```
|
```
|
||||||
|
|
||||||
and observe the following losses on train and val:
|
and observe the following losses on train and val:
|
||||||
@@ -152,8 +152,8 @@ However, we have to note that GPT-2 was trained on (closed, never released) WebT
|
|||||||
|
|
||||||
Finetuning is no different than training, we just make sure to initialize from a pretrained model and train with a smaller learning rate. For an example of how to finetune a GPT on new text go to `data/shakespeare` and run `prepare.py` to download the tiny shakespeare dataset and render it into a `train.bin` and `val.bin`, using the OpenAI BPE tokenizer from GPT-2. Unlike OpenWebText this will run in seconds. Finetuning can take very little time, e.g. on a single GPU just a few minutes. Run an example finetuning like:
|
Finetuning is no different than training, we just make sure to initialize from a pretrained model and train with a smaller learning rate. For an example of how to finetune a GPT on new text go to `data/shakespeare` and run `prepare.py` to download the tiny shakespeare dataset and render it into a `train.bin` and `val.bin`, using the OpenAI BPE tokenizer from GPT-2. Unlike OpenWebText this will run in seconds. Finetuning can take very little time, e.g. on a single GPU just a few minutes. Run an example finetuning like:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python train.py config/finetune_shakespeare.py
|
python train.py config/finetune_shakespeare.py
|
||||||
```
|
```
|
||||||
|
|
||||||
This will load the config parameter overrides in `config/finetune_shakespeare.py` (I didn't tune them much though). Basically, we initialize from a GPT2 checkpoint with `init_from` and train as normal, except shorter and with a small learning rate. If you're running out of memory try decreasing the model size (they are `{'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}`) or possibly decreasing the `block_size` (context length). The best checkpoint (lowest validation loss) will be in the `out_dir` directory, e.g. in `out-shakespeare` by default, per the config file. You can then run the code in `sample.py --out_dir=out-shakespeare`:
|
This will load the config parameter overrides in `config/finetune_shakespeare.py` (I didn't tune them much though). Basically, we initialize from a GPT2 checkpoint with `init_from` and train as normal, except shorter and with a small learning rate. If you're running out of memory try decreasing the model size (they are `{'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}`) or possibly decreasing the `block_size` (context length). The best checkpoint (lowest validation loss) will be in the `out_dir` directory, e.g. in `out-shakespeare` by default, per the config file. You can then run the code in `sample.py --out_dir=out-shakespeare`:
|
||||||
@@ -186,14 +186,14 @@ Whoa there, GPT, entering some dark place over there. I didn't really tune the h
|
|||||||
|
|
||||||
Use the script `sample.py` to sample either from pre-trained GPT-2 models released by OpenAI, or from a model you trained yourself. For example, here is a way to sample from the largest available `gpt2-xl` model:
|
Use the script `sample.py` to sample either from pre-trained GPT-2 models released by OpenAI, or from a model you trained yourself. For example, here is a way to sample from the largest available `gpt2-xl` model:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ python sample.py \
|
python sample.py \
|
||||||
--init_from=gpt2-xl \
|
--init_from=gpt2-xl \
|
||||||
--start="What is the answer to life, the universe, and everything?" \
|
--start="What is the answer to life, the universe, and everything?" \
|
||||||
--num_samples=5 --max_new_tokens=100
|
--num_samples=5 --max_new_tokens=100
|
||||||
```
|
```
|
||||||
|
|
||||||
If you'd like to sample from a model you trained, use the `--out_dir` to point the code appropriately. You can also prompt the model with some text from a file, e.g. `$ python sample.py --start=FILE:prompt.txt`.
|
If you'd like to sample from a model you trained, use the `--out_dir` to point the code appropriately. You can also prompt the model with some text from a file, e.g. ```python sample.py --start=FILE:prompt.txt```.
|
||||||
|
|
||||||
## efficiency notes
|
## efficiency notes
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
|
||||||
|
IO:
|
||||||
|
out_dir: "out"
|
||||||
|
eval_interval: 2000
|
||||||
|
log_interval: 1
|
||||||
|
eval_iters: 200
|
||||||
|
eval_only: False # if True, script exits right after the first eval
|
||||||
|
always_save_checkpoint: True # if True, always save a checkpoint after each eval
|
||||||
|
init_from: "scratch" # 'scratch' or 'resume' or 'gpt2*'
|
||||||
|
|
||||||
|
logger:
|
||||||
|
wandb_log: False # disabled by default
|
||||||
|
wandb_project: "owt"
|
||||||
|
wandb_run_name: "gpt2" # 'run' + str(time.time())
|
||||||
|
|
||||||
|
data:
|
||||||
|
dataset: "openwebtext"
|
||||||
|
gradient_accumulation_steps: 5 * 8 # used to simulate larger batch sizes
|
||||||
|
batch_size: 12 # if gradient_accumulation_steps > 1, this is the micro-batch size
|
||||||
|
block_size: 1024
|
||||||
|
|
||||||
|
model:
|
||||||
|
n_layer: 12
|
||||||
|
n_head: 12
|
||||||
|
n_embd: 768
|
||||||
|
dropout: 0.0 # for pretraining 0 is good, for finetuning try 0.1+
|
||||||
|
bias: False # do we use bias inside LayerNorm and Linear layers?
|
||||||
|
|
||||||
|
optimizer:
|
||||||
|
learning_rate: 6e-4 # max learning rate
|
||||||
|
max_iters: 600000 # total number of training iterations
|
||||||
|
weight_decay: 1e-1
|
||||||
|
beta1: 0.9
|
||||||
|
beta2: 0.95
|
||||||
|
grad_clip: 1.0 # clip gradients at this value, or disable if == 0.0
|
||||||
|
|
||||||
|
ddp:
|
||||||
|
backend: "nccl" # 'nccl', 'gloo', etc.
|
||||||
|
|
||||||
|
system:
|
||||||
|
device: "cuda" # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks
|
||||||
|
dtype: "bfloat16"
|
||||||
|
compile: True
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -16,6 +16,8 @@ num_proc = 8
|
|||||||
# it is better than 1 usually though
|
# it is better than 1 usually though
|
||||||
num_proc_load_dataset = num_proc
|
num_proc_load_dataset = num_proc
|
||||||
|
|
||||||
|
enc = tiktoken.get_encoding("gpt2")
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# takes 54GB in huggingface .cache dir, about 8M documents (8,013,769)
|
# takes 54GB in huggingface .cache dir, about 8M documents (8,013,769)
|
||||||
dataset = load_dataset("openwebtext", num_proc=num_proc_load_dataset)
|
dataset = load_dataset("openwebtext", num_proc=num_proc_load_dataset)
|
||||||
@@ -38,7 +40,6 @@ if __name__ == '__main__':
|
|||||||
# })
|
# })
|
||||||
|
|
||||||
# we now want to tokenize the dataset. first define the encoding function (gpt2 bpe)
|
# we now want to tokenize the dataset. first define the encoding function (gpt2 bpe)
|
||||||
enc = tiktoken.get_encoding("gpt2")
|
|
||||||
def process(example):
|
def process(example):
|
||||||
ids = enc.encode_ordinary(example['text']) # encode_ordinary ignores any special tokens
|
ids = enc.encode_ordinary(example['text']) # encode_ordinary ignores any special tokens
|
||||||
ids.append(enc.eot_token) # add the end of text token, e.g. 50256 for gpt2 bpe
|
ids.append(enc.eot_token) # add the end of text token, e.g. 50256 for gpt2 bpe
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import numpy as np
|
|||||||
input_file_path = os.path.join(os.path.dirname(__file__), 'input.txt')
|
input_file_path = os.path.join(os.path.dirname(__file__), 'input.txt')
|
||||||
if not os.path.exists(input_file_path):
|
if not os.path.exists(input_file_path):
|
||||||
data_url = 'https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt'
|
data_url = 'https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt'
|
||||||
with open(input_file_path, 'w') as f:
|
with open(input_file_path, 'w', encoding='utf-8') as f:
|
||||||
f.write(requests.get(data_url).text)
|
f.write(requests.get(data_url).text)
|
||||||
|
|
||||||
with open(input_file_path, 'r') as f:
|
with open(input_file_path, 'r', encoding='utf-8') as f:
|
||||||
data = f.read()
|
data = f.read()
|
||||||
n = len(data)
|
n = len(data)
|
||||||
train_data = data[:int(n*0.9)]
|
train_data = data[:int(n*0.9)]
|
||||||
|
|||||||
@@ -287,15 +287,30 @@ class GPT(nn.Module):
|
|||||||
return optimizer
|
return optimizer
|
||||||
|
|
||||||
def estimate_mfu(self, fwdbwd_per_iter, dt):
|
def estimate_mfu(self, fwdbwd_per_iter, dt):
|
||||||
""" estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
|
""" 估计MFU (模型每秒的浮点运算次数, Model FLOPS Utilization), 以A100 bfloat16峰值浮点运算次数为基准
|
||||||
|
1. 首先估计每一步的浮点运算次数
|
||||||
|
2. 然后乘以每秒的迭代次数
|
||||||
|
3. 最后除以A100 bfloat16峰值浮点运算次数
|
||||||
|
"""
|
||||||
|
|
||||||
# first estimate the number of flops we do per iteration.
|
# first estimate the number of flops we do per iteration.
|
||||||
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
|
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
|
||||||
|
# 获取模型参数量
|
||||||
N = self.get_num_params()
|
N = self.get_num_params()
|
||||||
cfg = self.config
|
cfg = self.config
|
||||||
L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
|
L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
|
||||||
|
|
||||||
|
# 计算每个token的浮点运算次数
|
||||||
|
# 6*N: 每个参数在前向和后向传播中的计算次数。(前向1次乘法, 反向2次乘法-链式法则,参数更新1次, 梯度计算2次)
|
||||||
|
# 12*L*H*Q*T: 每个注意力头中的运算次数 6次 x 前向后向 2次
|
||||||
flops_per_token = 6*N + 12*L*H*Q*T
|
flops_per_token = 6*N + 12*L*H*Q*T
|
||||||
|
|
||||||
|
# 考虑序列长度T
|
||||||
flops_per_fwdbwd = flops_per_token * T
|
flops_per_fwdbwd = flops_per_token * T
|
||||||
|
|
||||||
|
# 考虑每秒的迭代次数
|
||||||
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
|
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
|
||||||
|
|
||||||
# express our flops throughput as ratio of A100 bfloat16 peak flops
|
# express our flops throughput as ratio of A100 bfloat16 peak flops
|
||||||
flops_achieved = flops_per_iter * (1.0/dt) # per second
|
flops_achieved = flops_per_iter * (1.0/dt) # per second
|
||||||
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
|
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
|
||||||
|
|||||||
@@ -39,21 +39,25 @@ eval_iters = 200
|
|||||||
eval_only = False # if True, script exits right after the first eval
|
eval_only = False # if True, script exits right after the first eval
|
||||||
always_save_checkpoint = True # if True, always save a checkpoint after each eval
|
always_save_checkpoint = True # if True, always save a checkpoint after each eval
|
||||||
init_from = 'scratch' # 'scratch' or 'resume' or 'gpt2*'
|
init_from = 'scratch' # 'scratch' or 'resume' or 'gpt2*'
|
||||||
|
|
||||||
# wandb logging
|
# wandb logging
|
||||||
wandb_log = False # disabled by default
|
wandb_log = False # disabled by default
|
||||||
wandb_project = 'owt'
|
wandb_project = 'owt'
|
||||||
wandb_run_name = 'gpt2' # 'run' + str(time.time())
|
wandb_run_name = 'gpt2' # 'run' + str(time.time())
|
||||||
|
|
||||||
# data
|
# data
|
||||||
dataset = 'openwebtext'
|
dataset = 'openwebtext'
|
||||||
gradient_accumulation_steps = 5 * 8 # used to simulate larger batch sizes
|
gradient_accumulation_steps = 5 * 8 # used to simulate larger batch sizes
|
||||||
batch_size = 12 # if gradient_accumulation_steps > 1, this is the micro-batch size
|
batch_size = 12 # if gradient_accumulation_steps > 1, this is the micro-batch size
|
||||||
block_size = 1024
|
block_size = 1024
|
||||||
|
|
||||||
# model
|
# model
|
||||||
n_layer = 12
|
n_layer = 12
|
||||||
n_head = 12
|
n_head = 12
|
||||||
n_embd = 768
|
n_embd = 768
|
||||||
dropout = 0.0 # for pretraining 0 is good, for finetuning try 0.1+
|
dropout = 0.0 # for pretraining 0 is good, for finetuning try 0.1+
|
||||||
bias = False # do we use bias inside LayerNorm and Linear layers?
|
bias = False # do we use bias inside LayerNorm and Linear layers?
|
||||||
|
|
||||||
# adamw optimizer
|
# adamw optimizer
|
||||||
learning_rate = 6e-4 # max learning rate
|
learning_rate = 6e-4 # max learning rate
|
||||||
max_iters = 600000 # total number of training iterations
|
max_iters = 600000 # total number of training iterations
|
||||||
@@ -61,17 +65,21 @@ weight_decay = 1e-1
|
|||||||
beta1 = 0.9
|
beta1 = 0.9
|
||||||
beta2 = 0.95
|
beta2 = 0.95
|
||||||
grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0
|
grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0
|
||||||
|
|
||||||
# learning rate decay settings
|
# learning rate decay settings
|
||||||
decay_lr = True # whether to decay the learning rate
|
decay_lr = True # whether to decay the learning rate
|
||||||
warmup_iters = 2000 # how many steps to warm up for
|
warmup_iters = 2000 # how many steps to warm up for
|
||||||
lr_decay_iters = 600000 # should be ~= max_iters per Chinchilla
|
lr_decay_iters = 600000 # should be ~= max_iters per Chinchilla
|
||||||
min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
|
min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
|
||||||
|
|
||||||
# DDP settings
|
# DDP settings
|
||||||
backend = 'nccl' # 'nccl', 'gloo', etc.
|
backend = 'nccl' # 'nccl', 'gloo', etc.
|
||||||
|
|
||||||
# system
|
# system
|
||||||
device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks
|
device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks
|
||||||
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
|
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
|
||||||
compile = True # use PyTorch 2.0 to compile the model to be faster
|
compile = True # use PyTorch 2.0 to compile the model to be faster
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
|
config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
|
||||||
exec(open('configurator.py').read()) # overrides from command line or config file
|
exec(open('configurator.py').read()) # overrides from command line or config file
|
||||||
@@ -98,30 +106,65 @@ else:
|
|||||||
master_process = True
|
master_process = True
|
||||||
seed_offset = 0
|
seed_offset = 0
|
||||||
ddp_world_size = 1
|
ddp_world_size = 1
|
||||||
|
|
||||||
|
|
||||||
tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
|
tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
|
||||||
print(f"tokens per iteration will be: {tokens_per_iter:,}")
|
print(f"tokens per iteration will be: {tokens_per_iter:,}")
|
||||||
|
|
||||||
if master_process:
|
if master_process:
|
||||||
os.makedirs(out_dir, exist_ok=True)
|
os.makedirs(out_dir, exist_ok=True)
|
||||||
|
|
||||||
torch.manual_seed(1337 + seed_offset)
|
torch.manual_seed(1337 + seed_offset)
|
||||||
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
|
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
|
||||||
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
|
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
|
||||||
|
|
||||||
device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
|
device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
|
||||||
|
|
||||||
# note: float16 data type will automatically use a GradScaler
|
# note: float16 data type will automatically use a GradScaler
|
||||||
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
|
ptdtype = {
|
||||||
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
|
'float32': torch.float32,
|
||||||
|
'bfloat16': torch.bfloat16,
|
||||||
|
'float16': torch.float16}[dtype]
|
||||||
|
|
||||||
|
# 自动混合精度训练
|
||||||
|
# 优点:(1) 在保持模型精度的同时提高训练速度 (2) 减少显存占用
|
||||||
|
# 使用:利用 with ctx: 包裹住需要进行自动混合精度训练的代码块,
|
||||||
|
# - 在块内,某些操作会自动使用较低的精度(如 fp16),从而减少显存占用
|
||||||
|
# - 在块内,某些操作会自动使用较高的精度(如 fp32),系统会自动处理精度转换。
|
||||||
|
# 与GradScale的配合:
|
||||||
|
# - ctx 负责前向传播的精度控制,
|
||||||
|
# - scaler 负责反向传播的梯度缩放,防止由于精度降低导致的梯度消失问题(数值下溢)
|
||||||
|
if device_type == 'cpu':
|
||||||
|
# 如果设备是CPU,ctx是一个空上下文,不执行任何操作
|
||||||
|
ctx = nullcontext()
|
||||||
|
else:
|
||||||
|
# 如果设备是GPU,ctx是一个autocast上下文,用于自动混合精度训练
|
||||||
|
ctx = torch.amp.autocast(device_type=device_type, dtype=ptdtype)
|
||||||
|
|
||||||
|
|
||||||
# poor man's data loader
|
# poor man's data loader
|
||||||
data_dir = os.path.join('data', dataset)
|
data_dir = os.path.join('data', dataset)
|
||||||
train_data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r')
|
|
||||||
val_data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r')
|
|
||||||
def get_batch(split):
|
def get_batch(split):
|
||||||
data = train_data if split == 'train' else val_data
|
# We recreate np.memmap every batch to avoid a memory leak, as per
|
||||||
|
# https://stackoverflow.com/questions/45132940/numpy-memmap-memory-usage-want-to-iterate-once/61472122#61472122
|
||||||
|
if split == 'train':
|
||||||
|
# 使用 np.memmap 允许我们将磁盘上的数据映射到内存中,从而避免将整个数据集加载到内存中
|
||||||
|
# 这可以显著减少内存使用,尤其是在处理非常大的数据集时
|
||||||
|
# 使用 mode='r' 表示只读模式,这样可以避免在训练过程中修改数据
|
||||||
|
# 每次get_batch时,都会重新创建一个np.memmap对象,这样可以避免内存泄漏, 这是np.memmap的最佳实践
|
||||||
|
data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r')
|
||||||
|
else:
|
||||||
|
data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r')
|
||||||
|
|
||||||
ix = torch.randint(len(data) - block_size, (batch_size,))
|
ix = torch.randint(len(data) - block_size, (batch_size,))
|
||||||
x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix])
|
x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix])
|
||||||
y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])
|
y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])
|
||||||
|
|
||||||
if device_type == 'cuda':
|
if device_type == 'cuda':
|
||||||
# pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True)
|
# pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True)
|
||||||
|
# pin_memory() 会将张量分配到固定(页锁定)内存中,其不会被操作系统进行内存交换(swap)
|
||||||
|
# 固定内存通常用于GPU和CPU之间的数据传输,因为GPU访问固定内存的速度比访问常规内存快得多
|
||||||
|
# non_blocking=True 表示在数据传输过程中,不阻塞当前线程,可以继续执行其他操作
|
||||||
x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
|
x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
|
||||||
else:
|
else:
|
||||||
x, y = x.to(device), y.to(device)
|
x, y = x.to(device), y.to(device)
|
||||||
@@ -152,6 +195,7 @@ if init_from == 'scratch':
|
|||||||
model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
|
model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
|
||||||
gptconf = GPTConfig(**model_args)
|
gptconf = GPTConfig(**model_args)
|
||||||
model = GPT(gptconf)
|
model = GPT(gptconf)
|
||||||
|
|
||||||
elif init_from == 'resume':
|
elif init_from == 'resume':
|
||||||
print(f"Resuming training from {out_dir}")
|
print(f"Resuming training from {out_dir}")
|
||||||
# resume training from a checkpoint.
|
# resume training from a checkpoint.
|
||||||
@@ -175,6 +219,7 @@ elif init_from == 'resume':
|
|||||||
model.load_state_dict(state_dict)
|
model.load_state_dict(state_dict)
|
||||||
iter_num = checkpoint['iter_num']
|
iter_num = checkpoint['iter_num']
|
||||||
best_val_loss = checkpoint['best_val_loss']
|
best_val_loss = checkpoint['best_val_loss']
|
||||||
|
|
||||||
elif init_from.startswith('gpt2'):
|
elif init_from.startswith('gpt2'):
|
||||||
print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
|
print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
|
||||||
# initialize from OpenAI GPT-2 weights
|
# initialize from OpenAI GPT-2 weights
|
||||||
@@ -183,6 +228,7 @@ elif init_from.startswith('gpt2'):
|
|||||||
# read off the created config params, so we can store them into checkpoint correctly
|
# read off the created config params, so we can store them into checkpoint correctly
|
||||||
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
|
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
|
||||||
model_args[k] = getattr(model.config, k)
|
model_args[k] = getattr(model.config, k)
|
||||||
|
|
||||||
# crop down the model block size if desired, using model surgery
|
# crop down the model block size if desired, using model surgery
|
||||||
if block_size < model.config.block_size:
|
if block_size < model.config.block_size:
|
||||||
model.crop_block_size(block_size)
|
model.crop_block_size(block_size)
|
||||||
@@ -211,6 +257,9 @@ if ddp:
|
|||||||
# helps estimate an arbitrarily accurate loss over either split using many batches
|
# helps estimate an arbitrarily accurate loss over either split using many batches
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def estimate_loss():
|
def estimate_loss():
|
||||||
|
""" 估计损失 (不使用梯度)
|
||||||
|
同时使用 "验证集" 和 "训练集" 来评估模型的性能,数据是随机采样的, 评估采样次数eval_iters是给定的。
|
||||||
|
"""
|
||||||
out = {}
|
out = {}
|
||||||
model.eval()
|
model.eval()
|
||||||
for split in ['train', 'val']:
|
for split in ['train', 'val']:
|
||||||
@@ -226,12 +275,18 @@ def estimate_loss():
|
|||||||
|
|
||||||
# learning rate decay scheduler (cosine with warmup)
|
# learning rate decay scheduler (cosine with warmup)
|
||||||
def get_lr(it):
|
def get_lr(it):
|
||||||
# 1) linear warmup for warmup_iters steps
|
""" 学习率衰减调度器
|
||||||
|
1) 线性预热阶段(warmup)。 t=[0, warmup_iters) 学习率从0线性增加到base_lr
|
||||||
|
2) 余弦衰减阶段(decay)。 t=[warmup_iters, lr_decay_iters] 学习率从base_lr余弦下降到min_lr
|
||||||
|
3) 最小学习率保持阶段(min_lr)。 t=[lr_decay_iters, max_iters) 返回最小学习率
|
||||||
|
"""
|
||||||
if it < warmup_iters:
|
if it < warmup_iters:
|
||||||
return learning_rate * it / warmup_iters
|
return learning_rate * (it + 1) / (warmup_iters + 1)
|
||||||
|
|
||||||
# 2) if it > lr_decay_iters, return min learning rate
|
# 2) if it > lr_decay_iters, return min learning rate
|
||||||
if it > lr_decay_iters:
|
if it > lr_decay_iters:
|
||||||
return min_lr
|
return min_lr
|
||||||
|
|
||||||
# 3) in between, use cosine decay down to min learning rate
|
# 3) in between, use cosine decay down to min learning rate
|
||||||
decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
|
decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
|
||||||
assert 0 <= decay_ratio <= 1
|
assert 0 <= decay_ratio <= 1
|
||||||
@@ -268,6 +323,7 @@ while True:
|
|||||||
"lr": lr,
|
"lr": lr,
|
||||||
"mfu": running_mfu*100, # convert to percentage
|
"mfu": running_mfu*100, # convert to percentage
|
||||||
})
|
})
|
||||||
|
|
||||||
if losses['val'] < best_val_loss or always_save_checkpoint:
|
if losses['val'] < best_val_loss or always_save_checkpoint:
|
||||||
best_val_loss = losses['val']
|
best_val_loss = losses['val']
|
||||||
if iter_num > 0:
|
if iter_num > 0:
|
||||||
@@ -281,11 +337,20 @@ while True:
|
|||||||
}
|
}
|
||||||
print(f"saving checkpoint to {out_dir}")
|
print(f"saving checkpoint to {out_dir}")
|
||||||
torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
|
torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
|
||||||
|
|
||||||
if iter_num == 0 and eval_only:
|
if iter_num == 0 and eval_only:
|
||||||
break
|
break
|
||||||
|
|
||||||
# forward backward update, with optional gradient accumulation to simulate larger batch size
|
# forward backward update, with optional gradient accumulation to simulate larger batch size
|
||||||
# and using the GradScaler if data type is float16
|
# and using the GradScaler if data type is float16
|
||||||
|
# 梯度累积的基本原理:
|
||||||
|
# 1. 将一个大的batch分成多个小的micro batch,每个micro batch的梯度累积起来,然后一起更新参数
|
||||||
|
# 2. 但是,梯度累积会导致损失函数被放大gradient_accumulation_steps倍,所以需要将损失除以gradient_accumulation_steps
|
||||||
|
# 3. 实际操作时,每次调用backward()时,计算出的的梯度会累积到参数的 .grad 属性中
|
||||||
|
# (如果不zero_grad(),梯度不会被清空,也不覆盖,而是累加)
|
||||||
|
# 4. 在所有micro_step都调用backward()后,统一执行一次optimizer.step(),更新参数
|
||||||
|
# 5. 在optimizer.step()后,需要调用optimizer.zero_grad(),清空梯度,否则梯度会累积
|
||||||
|
|
||||||
for micro_step in range(gradient_accumulation_steps):
|
for micro_step in range(gradient_accumulation_steps):
|
||||||
if ddp:
|
if ddp:
|
||||||
# in DDP training we only need to sync gradients at the last micro step.
|
# in DDP training we only need to sync gradients at the last micro step.
|
||||||
@@ -293,20 +358,28 @@ while True:
|
|||||||
# I really dislike that this bloats the code and forces us to repeat code
|
# I really dislike that this bloats the code and forces us to repeat code
|
||||||
# looking at the source of that context manager, it just toggles this variable
|
# looking at the source of that context manager, it just toggles this variable
|
||||||
model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
|
model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
|
||||||
|
|
||||||
|
# 使用autocast上下文管理器包裹住需要进行自动混合精度训练的代码块
|
||||||
with ctx:
|
with ctx:
|
||||||
logits, loss = model(X, Y)
|
logits, loss = model(X, Y)
|
||||||
loss = loss / gradient_accumulation_steps # scale the loss to account for gradient accumulation
|
loss = loss / gradient_accumulation_steps
|
||||||
|
# scale the loss to account for gradient accumulation
|
||||||
|
|
||||||
|
|
||||||
# immediately async prefetch next batch while model is doing the forward pass on the GPU
|
# immediately async prefetch next batch while model is doing the forward pass on the GPU
|
||||||
X, Y = get_batch('train')
|
X, Y = get_batch('train')
|
||||||
# backward pass, with gradient scaling if training in fp16
|
# backward pass, with gradient scaling if training in fp16
|
||||||
scaler.scale(loss).backward()
|
scaler.scale(loss).backward()
|
||||||
|
|
||||||
# clip the gradient
|
# clip the gradient
|
||||||
if grad_clip != 0.0:
|
if grad_clip != 0.0:
|
||||||
scaler.unscale_(optimizer)
|
scaler.unscale_(optimizer)
|
||||||
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
|
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
|
||||||
|
|
||||||
# step the optimizer and scaler if training in fp16
|
# step the optimizer and scaler if training in fp16
|
||||||
scaler.step(optimizer)
|
scaler.step(optimizer)
|
||||||
scaler.update()
|
scaler.update()
|
||||||
|
|
||||||
# flush the gradients as soon as we can, no need for this memory anymore
|
# flush the gradients as soon as we can, no need for this memory anymore
|
||||||
optimizer.zero_grad(set_to_none=True)
|
optimizer.zero_grad(set_to_none=True)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user