add anno
This commit is contained in:
1 parent
a747ca26ea
commit
9dc91c262e
3 files changed
+117
-4
No files matched your search
@@ -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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user