This commit is contained in:
sen.liang committed 2025-05-25 22:38:53 +08:00
1 parent a747ca26ea
commit 9dc91c262e
3 files changed
+117 -4

No files matched your search

+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
+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
+47 -3
View File
@@ -126,7 +126,21 @@ ptdtype = {
'bfloat16': torch.bfloat16,
'float16': torch.float16}[dtype]
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
# 自动混合精度训练
# 优点:(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)
@@ -181,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.
@@ -204,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
@@ -212,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)
@@ -240,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']:
@@ -255,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 + 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
@@ -297,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:
@@ -310,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.
@@ -322,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)