当前位置:   article > 正文

nanoGPT源码浅析(下)

nanogpt

train.py

train实现了多种模型训练、评估、优化、保存与加载(三类初始化、循环训练、损失评估、优化器、日志记录、可视化、梯度累积、梯度裁剪等)的方法。源码功能实现较为零散,未专门做封装,因此依照整理的顺序做代码拆解。

首先需要聊下文件configurator.py

  1. for arg in sys.argv[1:]:
  2.     if '=' not in arg:
  3.         assert not arg.startswith('--')
  4.         config_file = arg
  5.         print(f"Overriding config with {config_file}:")
  6.         with open(config_file) as f:
  7.             print(f.read())
  8.         exec(open(config_file).read())
  9.     else:
  10.         assert arg.startswith('--')
  11.         key, val = arg.split('=')
  12.         key = key[2:]
  13.         if key in globals():
  14.             try:
  15.                 attempt = literal_eval(val)
  16.             except (SyntaxError, ValueError):
  17.                 attempt = val
  18.             assert type(attempt) == type(globals()[key])
  19.             print(f"Overriding: {key} = {attempt}")
  20.             globals()[key] = attempt
  21.         else:
  22.             raise ValueError(f"Unknown config key: {key}")

检查参数是否包含等号(是否符合键值对形式),如果参数中不包含等号做配置文件处理,否则做键值对处理,最终实现配件文件覆盖全局超参(当然是为了后续赛博炼丹更方便)

  1. config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
  2. exec(open('configurator.py').read())
  3. config = {k: globals()[k] for k in config_keys}

遍历globals,筛选出符合的变量,将键存储到config_keys列表。随后执行configurator.py对超参进行修改和覆盖,构建配置字典config。

接下来是模型初始化的一部分

  1. ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
  2. if ddp:
  3.     init_process_group(backend=backend)
  4.     ddp_rank = int(os.environ['RANK'])
  5.     ddp_local_rank = int(os.environ['LOCAL_RANK'])
  6.     ddp_world_size = int(os.environ['WORLD_SIZE'])
  7.     device = f'cuda:{ddp_local_rank}'
  8.     torch.cuda.set_device(device)
  9.     master_process = ddp_rank == 0
  10.     seed_offset = ddp_rank
  11.     assert gradient_accumulation_steps % ddp_world_size == 0
  12.     gradient_accumulation_steps //= ddp_world_size

首先检查是否有环境变量RANK(进程在分布式环境的唯一标识符)以判断当前是否属于DDP。如果属于DDP环境,则做对应初始化处理。使用指定后端初始化分布式进程组,获取当前进程rank、local_rank(GPU标识符)、world_size(进程总数),添加设置device、主进程判断与设置等,对每个进程生成不同偏移量(初始化随机),最后调整梯度累积步数(原始步数/进程数,处理相同量梯度更新)

  1. else:
  2.     master_process = True
  3.     seed_offset = 0
  4.     ddp_world_size = 1

若不是DDP,则置当前进程为主进程,同时不需要随机种子偏移量,总进程数置为1。

  1. tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
  2. if master_process:
  3.     os.makedirs(out_dir, exist_ok=True)
  4. torch.manual_seed(1337 + seed_offset)
  5. torch.backends.cuda.matmul.allow_tf32 = True
  6. torch.backends.cudnn.allow_tf32 = True
  7. device_type = 'cuda' if 'cuda' in device else 'cpu'
  8. ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
  9. ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
  10. data_dir = os.path.join('data', dataset)
  11. train_data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r')
  12. val_data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r')

经前文判断和设置后计算迭代标记数(梯度累积步数、进程总数、批大小、块大小相乘),根据CPU或GPU创建输出目录、上下文,设置随机种子(固定值加随机种子偏移量)数据类型等属性,最后加载训练集和测试集数据并做内存映射。

  1. def get_batch(split):
  2.     data = train_data if split == 'train' else val_data
  3.     ix = torch.randint(len(data) - block_size, (batch_size,))
  4.     x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix])
  5.     y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])
  6.     if device_type == 'cuda':
  7.         x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
  8.     else:
  9.         x, y = x.to(device), y.to(device)
  10. return x, y
  11. meta_path = os.path.join(data_dir, 'meta.pkl')
  12. meta_vocab_size = None
  13. if os.path.exists(meta_path):
  14.     with open(meta_path, 'rb') as f:
  15.         meta = pickle.load(f)
  16.     meta_vocab_size = meta['vocab_size']
  17.     print(f"found vocab_size = {meta_vocab_size} (inside {meta_path})")

随机生成一个索引张量ix(预留一个块大小避免溢出)用作起始索引,随后以此取出对应的输入x、目标数据y切片,并通过stack按照时间序列压缩堆叠转换为张量。数据移动依然有两类操作,若为cuda则把数据放入gpu(pin_memory用于固定内存异步操作),否则放入指定设备。随后通过pickle序列化加载元数据文件并评估词表大小。

接下来是一段较长代码,从scratch(从零开始)、resume(恢复训练)、gpt-2(模型参数加载)中做初始化方式判断(配置文件参数设置)。

  1. if init_from == 'scratch':
  2.     print("Initializing a new model from scratch")
  3.     if meta_vocab_size is None:
  4.         print("defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)")
  5.     model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
  6.     gptconf = GPTConfig(**model_args)
  7.     model = GPT(gptconf)

若为scratch则首先确定词汇大小,使用参数字典model_args创建GPTConfig对象gptconf(参数),根据gptconf创建GPT对象model(模型)

  1. elif init_from == 'resume':
  2.     ckpt_path = os.path.join(out_dir, 'ckpt.pt')
  3.     checkpoint = torch.load(ckpt_path, map_location=device)
  4.     checkpoint_model_args = checkpoint['model_args']
  5.     for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
  6.         model_args[k] = checkpoint_model_args[k]
  7.     gptconf = GPTConfig(**model_args)
  8.     model = GPT(gptconf)
  9.     state_dict = checkpoint['model']
  10.     unwanted_prefix = '_orig_mod.'
  11.     for k,v in list(state_dict.items()):
  12.         if k.startswith(unwanted_prefix):
  13.             state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
  14.     model.load_state_dict(state_dict)
  15.     iter_num = checkpoint['iter_num']
  16.     best_val_loss = checkpoint['best_val_loss']

如果是resume方法,则会从检查点文件中回复先前参数、状态等信息。加载ckpt.pt文件后,从其中获取参数字典model_args,更新到当前字典,创建新gptconf(与scratch相似),随后通过startswith做参数名冲突检查和筛选、获取并更新先前迭代次数、最佳损失等信息

  1. elif init_from.startswith('gpt2'):
  2.     print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
  3.     override_args = dict(dropout=dropout)
  4.     model = GPT.from_pretrained(init_from, override_args)
  5.     for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
  6.         model_args[k] = getattr(model.config, k)

从OpenAI的GPT-2预训练模型中加载权重,使用from_pretrained传递和覆盖参数与超参数,很好理解,不再赘述。

  1. if block_size < model.config.block_size:
  2.     model.crop_block_size(block_size)
  3.     model_args['block_size'] = block_size
  4. model.to(device)

若块大小不匹配,则调用crop_block_size(上文提到的优化方法之一)来裁剪模型block_size并更新字典对应值,随后将模型移动至对应的device训练

  1. scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16'))
  2. optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type)
  3. if init_from == 'resume':
  4.     optimizer.load_state_dict(checkpoint['optimizer'])
  5. checkpoint = None
  6. if compile:
  7.     unoptimized_model = model
  8.     model = torch.compile(model)
  9. if ddp:
  10.     model = DDP(model, device_ids=[ddp_local_rank])

根据dtype是否为float16开闭梯度缩放(混合精度训练将部分计算转换低精度float16以提高训练效率和内存利用率,但会减少数值范围和表示精度,梯度缩放GradScaler可以在低精度做反向传播时自动乘以缩放因子缩放梯度再更新参数)。前文提到configure_optimizers(),这里根据超参做优化适配。如果初始化方法为resume,加载先前ckpt文件的优化器状态字典并更新。释放检查点空间后结合compile和ddp环境选择对应容器训练。

  1. def estimate_loss():
  2.     out = {}
  3.     model.eval()
  4.     for split in ['train', 'val']:
  5.         losses = torch.zeros(eval_iters)
  6.         for k in range(eval_iters):
  7.             X, Y = get_batch(split)
  8.             with ctx:
  9.                 logits, loss = model(X, Y)
  10.             losses[k] = loss.item()
  11.         out[split] = losses.mean()
  12.     model.train()
  13.     return out

该函数用以评估损失值。创建储存损失值的空字典out同时开启模型测试模式model.eval(不启用 Batch Normalization 和 Dropout。eval模式下前者停止计算和更新mean和var转而使用训练阶段已有的mean和var值,后者会终止dropout操作并启用所有激活单元),遍历训练集、验证集并创建大小为eval_iters的零张量losses。循环eval_iters次,获取每次迭代的输入x和目标数据y并进行前向传播(with ctx上下文管理器,处理混合精度训练、多线程),将损失值保存至losses。

全部评估完成后计算losses平均值并存储。

至于学习率,给出动态调整策略如下:

  1. def get_lr(it):
  2.     if it < warmup_iters:
  3.         return learning_rate * it / warmup_iters
  4.     if it > lr_decay_iters:
  5.         return min_lr
  6.     decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
  7.     assert 0 <= decay_ratio <= 1
  8.     coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
  9. return min_lr + coeff * (learning_rate - min_lr)

若迭代次数it小于预热迭代次数warmup_iters则执行线性预热,learning_rate * it / warmup_iters(学习率从 0 线性增加到初始lr)。

若大于衰减迭代次数lr_decay_iters,则返回最小学习率 min_lr并不再进行衰减。

若在预热阶段和衰减阶段之间,采用余弦衰减(cosine decay)策略,从初始学习率平滑衰减到最小学习率。首先计算衰减比例decay_ratio(范围0到1)。随后对其进行余弦变换,得出系数coeff(范围仍为0到1)。最终的学习率为 min_lr + coeff * (learning_rate - min_lr)。

  1. if wandb_log and master_process:
  2.     import wandb
  3.     wandb.init(project=wandb_project, name=wandb_run_name, config=config)

设置日志记录的相关配置,使用 WandB 来对主进程做日志记录并对模型训练可视化。

前面各种初始化、优化函数、分配策略设计结束,终于到训练环节

  1. X, Y = get_batch('train')
  2. t0 = time.time()
  3. local_iter_num = 0
  4. raw_model = model.module if ddp else model
  5. running_mfu = -1.0
  6. while True:
  7.     lr = get_lr(iter_num) if decay_lr else learning_rate
  8.     for param_group in optimizer.param_groups:
  9.         param_group['lr'] = lr
  10.     if iter_num % eval_interval == 0 and master_process:
  11.         losses = estimate_loss()
  12.         print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
  13.         if wandb_log:
  14.             wandb.log({
  15.                 "iter": iter_num,
  16.                 "train/loss": losses['train'],
  17.                 "val/loss": losses['val'],
  18.                 "lr": lr,
  19.                 "mfu": running_mfu*100,
  20.             })
  21.         if losses['val'] < best_val_loss or always_save_checkpoint:
  22.             best_val_loss = losses['val']
  23.             if iter_num > 0:
  24.                 checkpoint = {
  25.                     'model': raw_model.state_dict(),
  26.                     'optimizer': optimizer.state_dict(),
  27.                     'model_args': model_args,
  28.                     'iter_num': iter_num,
  29.                     'best_val_loss': best_val_loss,
  30.                     'config': config,
  31.                 }
  32.                 print(f"saving checkpoint to {out_dir}")
  33.                 torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
  34.     if iter_num == 0 and eval_only:
  35.         break

首先通过 get_batch获取训练集的第一个批数据,并将其存储在变量 X 和 Y 中,随后初始化t0、local_iter_num、raw_model等变量。

每次迭代根据迭代次数确定学习率(判断是否启用衰减),并设置优化器对应参数。eval_interval次迭代后计算训练集和验证集上的损失并记录在WandB上,根据损失值进一步更新模型最优权重和状态

  1.  for micro_step in range(gradient_accumulation_steps):
  2.         if ddp:
  3.             model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
  4.         with ctx:
  5.             logits, loss = model(X, Y)
  6.             loss = loss / gradient_accumulation_steps
  7.         X, Y = get_batch('train')
  8.         scaler.scale(loss).backward()
  9.     if grad_clip != 0.0:
  10.         scaler.unscale_(optimizer)
  11.         torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
  12.     scaler.step(optimizer)
  13.     scaler.update()
  14.     optimizer.zero_grad(set_to_none=True)

使用for循环迭代gradient_accumulation_steps次,在每次迭代中如果使用DDP则根据微批次 micro_step 设置梯度同步策略。

在ctx中前向传播得到logits和loss(loss除以步长缩放,避免梯度累积)。同时调用get_batch 异步获取下一批次的训练数据赋值给x、y。执行反向传播,对损失值进行梯度计算,并通过梯度裁剪函数clip_grad_norm_()裁剪(防止梯度爆炸)。执行优化器更新同时进行缩放操作。最后清空梯度,释放内存。

  1.  t1 = time.time()
  2.     dt = t1 - t0
  3.     t0 = t1
  4.     if iter_num % log_interval == 0 and master_process:
  5.         lossf = loss.item() * gradient_accumulation_steps
  6.         if local_iter_num >= 5: # let the training loop settle a bit
  7.             mfu = raw_model.estimate_mfu(batch_size * gradient_accumulation_steps, dt)
  8.             running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu
  9.         print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%")
  10.     iter_num += 1
  11.     local_iter_num += 1
  12.     if iter_num > max_iters:
  13.         checkpoint = {
  14.             'model': raw_model.state_dict(),
  15.             'optimizer': optimizer.state_dict(),
  16.             'model_args': model_args,
  17.             'iter_num': iter_num,
  18.             'best_val_loss': best_val_loss,
  19.             'config': config,
  20.         }
  21.         print(f"saving checkpoint to {out_dir}")
  22.         torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
  23.         break
  24. if ddp:
  25. destroy_process_group()

计算迭代时间 dt并更新计时器 t0,如果满足日志记录条件则输出当前迭代的损失值、时间以及每秒浮点运算数MFLOPs。随后更新迭代次数 iter_num 和本地迭代次数 local_iter_num,若为DDP则调用destroy_process_group()清理进程组。

迭代次数达到最大迭代次数max_iters后,保存模型和优化器状态到ckpt,跳出循环。

至此,训练结束。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/364210?site
推荐阅读
相关标签
  

闽ICP备14008679号