Compare commits

..
16 Commits
Author SHA1 Message Date
sen.liang 9dc91c262e add anno 2025-05-25 22:38:53 +08:00
sen.liang a747ca26ea update 2025-05-24 21:20:50 +08:00
Andrej 93a43d9a5c Merge pull request #578 from devin-open-source/devin/1733728337-fix-warmup-lr
fix: ensure non-zero learning rate during warmup at iteration 0
2024-12-09 15:53:04 -08:00
Devin AI dc81cb368c fix: ensure non-zero learning rate during warmup at iteration 0
The warmup learning rate calculation has been modified to use (it + 1)/(warmup_iters + 1)
instead of it/warmup_iters. This ensures a non-zero learning rate at iteration 0
while maintaining the same linear warmup behavior.

Fixes #443
2024-12-09 07:35:08 +00:00
Andrej 9755682b98 Merge pull request #463 from goswamig/test1
Fixing eval path in README
2024-06-03 09:51:52 -07:00
Andrej 3ab86ce851 Merge branch 'master' into test1 2024-06-03 09:50:45 -07:00
Andrej 7c7e627108 Merge pull request #487 from jellehak/patch-1
Update README.md
2024-06-03 09:47:17 -07:00
Jelle Hak 5cb16fe66a Update README.md
Proper markdown code blocks
2024-05-28 08:38:35 +02:00
Gautam Kumar 1ab9ec1b83 Fixing eval path in README 2024-03-23 23:51:02 -07:00
Andrej 325be85d9b Merge pull request #420 from vinjn/fix-371-enc-is-not-defined
Move enc to gloabal namespace to fix #371
2024-02-27 09:27:01 -08:00
Andrej a022d02ee2 Merge pull request #429 from adambala/fixes
Open "shakespeare" data in UTF-8 in "prepare.py"
2024-02-27 09:05:44 -08:00
Andrej f68ac2200d Merge pull request #428 from kjslag/memmap-memory-leak
fix np.memmap memory leak
2024-02-27 08:41:24 -08:00
Adam Isakov f35dc82437 fix: prepare.py - added input file opening in UTF-8 encoding 2024-01-26 01:34:44 +03:00
Adam Isakov b7e194a756 feature: .gitignore - added venv folders 2024-01-26 01:10:10 +03:00
Kevin Slagle 5156fef93c fix np.memmap memory leak
nn.memmap doesn't free memory that it accesses. Thus, the entire dataset gets stored in RAM as the dataset has been fully accessed. The simplest workaround on stackoverflow is to just recreate the memmap for each batch. The extra overhead is negligible.

https://stackoverflow.com/questions/45132940/numpy-memmap-memory-usage-want-to-iterate-once/61472122#61472122
2024-01-25 11:41:01 -08:00
vinjn dccf362c2b Move enc to gloabal namespace 2024-01-12 12:53:20 -08:00
7 changed files with 188 additions and 43 deletions

No files matched your search

+2
View File
@@ -8,3 +8,5 @@ __pycache__/
*.pt
*.pyc
input.txt
env/
venv/
+31 -31
View File
@@ -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:
```
$ python data/shakespeare_char/prepare.py
```sh
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:
**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:
```
$ python train.py config/train_shakespeare_char.py
```sh
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:
```
$ python sample.py --out_dir=out-shakespeare-char
```sh
python sample.py --out_dir=out-shakespeare-char
```
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:
```
$ 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
```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
```
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:
```
$ python sample.py --out_dir=out-shakespeare-char --device=cpu
```sh
python sample.py --out_dir=out-shakespeare-char --device=cpu
```
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:
```
$ python data/openwebtext/prepare.py
```sh
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:
```
$ torchrun --standalone --nproc_per_node=8 train.py config/train_gpt2.py
```sh
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.
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:
```
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
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
```sh
# 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
# 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
```
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
OpenAI GPT-2 checkpoints allow us to get some baselines in place for openwebtext. We can get the numbers as follows:
```
$ python train.py eval_gpt2
$ python train.py eval_gpt2_medium
$ python train.py eval_gpt2_large
$ python train.py eval_gpt2_xl
```sh
$ python train.py config/eval_gpt2.py
$ python train.py config/eval_gpt2_medium.py
$ python train.py config/eval_gpt2_large.py
$ python train.py config/eval_gpt2_xl.py
```
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:
```
$ python train.py config/finetune_shakespeare.py
```sh
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`:
@@ -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:
```
$ python sample.py \
```sh
python sample.py \
--init_from=gpt2-xl \
--start="What is the answer to life, the universe, and everything?" \
--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
+54
View File
@@ -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
+2 -1
View File
@@ -16,6 +16,8 @@ num_proc = 8
# it is better than 1 usually though
num_proc_load_dataset = num_proc
enc = tiktoken.get_encoding("gpt2")
if __name__ == '__main__':
# takes 54GB in huggingface .cache dir, about 8M documents (8,013,769)
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)
enc = tiktoken.get_encoding("gpt2")
def process(example):
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
+2 -2
View File
@@ -7,10 +7,10 @@ import numpy as np
input_file_path = os.path.join(os.path.dirname(__file__), 'input.txt')
if not os.path.exists(input_file_path):
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)
with open(input_file_path, 'r') as f:
with open(input_file_path, 'r', encoding='utf-8') as f:
data = f.read()
n = len(data)
train_data = data[:int(n*0.9)]
+16 -1
View File
@@ -287,15 +287,30 @@ class GPT(nn.Module):
return optimizer
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.
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
# 获取模型参数量
N = self.get_num_params()
cfg = self.config
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
# 考虑序列长度T
flops_per_fwdbwd = flops_per_token * T
# 考虑每秒的迭代次数
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
# express our flops throughput as ratio of A100 bfloat16 peak flops
flops_achieved = flops_per_iter * (1.0/dt) # per second
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
+81 -8
View File
@@ -39,21 +39,25 @@ 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*'
# wandb logging
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?
# adamw optimizer
learning_rate = 6e-4 # max learning rate
max_iters = 600000 # total number of training iterations
@@ -61,17 +65,21 @@ weight_decay = 1e-1
beta1 = 0.9
beta2 = 0.95
grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0
# learning rate decay settings
decay_lr = True # whether to decay the learning rate
warmup_iters = 2000 # how many steps to warm up for
lr_decay_iters = 600000 # should be ~= max_iters per Chinchilla
min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
# DDP settings
backend = 'nccl' # 'nccl', 'gloo', etc.
# system
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
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))]
exec(open('configurator.py').read()) # overrides from command line or config file
@@ -98,30 +106,65 @@ else:
master_process = True
seed_offset = 0
ddp_world_size = 1
tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
print(f"tokens per iteration will be: {tokens_per_iter:,}")
if master_process:
os.makedirs(out_dir, exist_ok=True)
torch.manual_seed(1337 + seed_offset)
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
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
# note: float16 data type will automatically use a GradScaler
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
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
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):
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,))
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])
if device_type == 'cuda':
# 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)
else:
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
gptconf = GPTConfig(**model_args)
model = GPT(gptconf)
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
@@ -175,6 +219,7 @@ elif init_from == 'resume':
model.load_state_dict(state_dict)
iter_num = checkpoint['iter_num']
best_val_loss = checkpoint['best_val_loss']
elif init_from.startswith('gpt2'):
print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
# 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
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
model_args[k] = getattr(model.config, k)
# crop down the model block size if desired, using model surgery
if block_size < model.config.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
@torch.no_grad()
def estimate_loss():
""" 估计损失 (不使用梯度)
同时使用 "验证集" 和 "训练集" 来评估模型的性能,数据是随机采样的, 评估采样次数eval_iters是给定的。
"""
out = {}
model.eval()
for split in ['train', 'val']:
@@ -226,12 +275,18 @@ def estimate_loss():
# learning rate decay scheduler (cosine with warmup)
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:
return learning_rate * it / warmup_iters
return learning_rate * (it + 1) / (warmup_iters + 1)
# 2) if it > lr_decay_iters, return min learning rate
if it > lr_decay_iters:
return min_lr
# 3) in between, use cosine decay down to min learning rate
decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
assert 0 <= decay_ratio <= 1
@@ -268,6 +323,7 @@ while True:
"lr": lr,
"mfu": running_mfu*100, # convert to percentage
})
if losses['val'] < best_val_loss or always_save_checkpoint:
best_val_loss = losses['val']
if iter_num > 0:
@@ -281,11 +337,20 @@ while True:
}
print(f"saving checkpoint to {out_dir}")
torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
if iter_num == 0 and eval_only:
break
# forward backward update, with optional gradient accumulation to simulate larger batch size
# 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):
if ddp:
# 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
# looking at the source of that context manager, it just toggles this variable
model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
# 使用autocast上下文管理器包裹住需要进行自动混合精度训练的代码块
with ctx:
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
X, Y = get_batch('train')
# backward pass, with gradient scaling if training in fp16
scaler.scale(loss).backward()
# clip the gradient
if grad_clip != 0.0:
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
# step the optimizer and scaler if training in fp16
scaler.step(optimizer)
scaler.update()
# flush the gradients as soon as we can, no need for this memory anymore
optimizer.zero_grad(set_to_none=True)