赞
踩
train.py
train实现了多种模型训练、评估、优化、保存与加载(三类初始化、循环训练、损失评估、优化器、日志记录、可视化、梯度累积、梯度裁剪等)的方法。源码功能实现较为零散,未专门做封装,因此依照整理的顺序做代码拆解。
首先需要聊下文件configurator.py
- for arg in sys.argv[1:]:
- if '=' not in arg:
- assert not arg.startswith('--')
- config_file = arg
- print(f"Overriding config with {config_file}:")
- with open(config_file) as f:
- print(f.read())
- exec(open(config_file).read())
- else:
- assert arg.startswith('--')
- key, val = arg.split('=')
- key = key[2:]
- if key in globals():
- try:
- attempt = literal_eval(val)
- except (SyntaxError, ValueError):
- attempt = val
- assert type(attempt) == type(globals()[key])
- print(f"Overriding: {key} = {attempt}")
- globals()[key] = attempt
- else:
- raise ValueError(f"Unknown config key: {key}")
检查参数是否包含等号(是否符合键值对形式),如果参数中不包含等号做配置文件处理,否则做键值对处理,最终实现配件文件覆盖全局超参(当然是为了后续赛博炼丹更方便)
- 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())
- config = {k: globals()[k] for k in config_keys}
遍历globals,筛选出符合的变量,将键存储到config_keys列表。随后执行configurator.py对超参进行修改和覆盖,构建配置字典config。
接下来是模型初始化的一部分
- ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
- if ddp:
- init_process_group(backend=backend)
- ddp_rank = int(os.environ['RANK'])
- ddp_local_rank = int(os.environ['LOCAL_RANK'])
- ddp_world_size = int(os.environ['WORLD_SIZE'])
- device = f'cuda:{ddp_local_rank}'
- torch.cuda.set_device(device)
- master_process = ddp_rank == 0
- seed_offset = ddp_rank
- assert gradient_accumulation_steps % ddp_world_size == 0
- gradient_accumulation_steps //= ddp_world_size
首先检查是否有环境变量RANK(进程在分布式环境的唯一标识符)以判断当前是否属于DDP。如果属于DDP环境,则做对应初始化处理。使用指定后端初始化分布式进程组,获取当前进程rank、local_rank(GPU标识符)、world_size(进程总数),添加设置device、主进程判断与设置等,对每个进程生成不同偏移量(初始化随机),最后调整梯度累积步数(原始步数/进程数,处理相同量梯度更新)
- else:
- master_process = True
- seed_offset = 0
- ddp_world_size = 1
若不是DDP,则置当前进程为主进程,同时不需要随机种子偏移量,总进程数置为1。
- tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
-
- if master_process:
- os.makedirs(out_dir, exist_ok=True)
- torch.manual_seed(1337 + seed_offset)
- torch.backends.cuda.matmul.allow_tf32 = True
- torch.backends.cudnn.allow_tf32 = True
- device_type = 'cuda' if 'cuda' in device else 'cpu'
- 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)
-
- 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')
经前文判断和设置后计算迭代标记数(梯度累积步数、进程总数、批大小、块大小相乘),根据CPU或GPU创建输出目录、上下文,设置随机种子(固定值加随机种子偏移量)数据类型等属性,最后加载训练集和测试集数据并做内存映射。
- def get_batch(split):
- data = train_data if split == 'train' else val_data
- 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':
- 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)
- return x, y
-
- meta_path = os.path.join(data_dir, 'meta.pkl')
- meta_vocab_size = None
- if os.path.exists(meta_path):
- with open(meta_path, 'rb') as f:
- meta = pickle.load(f)
- meta_vocab_size = meta['vocab_size']
- print(f"found vocab_size = {meta_vocab_size} (inside {meta_path})")
随机生成一个索引张量ix(预留一个块大小避免溢出)用作起始索引,随后以此取出对应的输入x、目标数据y切片,并通过stack按照时间序列压缩堆叠转换为张量。数据移动依然有两类操作,若为cuda则把数据放入gpu(pin_memory用于固定内存异步操作),否则放入指定设备。随后通过pickle序列化加载元数据文件并评估词表大小。
接下来是一段较长代码,从scratch(从零开始)、resume(恢复训练)、gpt-2(模型参数加载)中做初始化方式判断(配置文件参数设置)。
- if init_from == 'scratch':
- print("Initializing a new model from scratch")
- if meta_vocab_size is None:
- print("defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)")
- model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
- gptconf = GPTConfig(**model_args)
- model = GPT(gptconf)
若为scratch则首先确定词汇大小,使用参数字典model_args创建GPTConfig对象gptconf(参数),根据gptconf创建GPT对象model(模型)
- elif init_from == 'resume':
- ckpt_path = os.path.join(out_dir, 'ckpt.pt')
- checkpoint = torch.load(ckpt_path, map_location=device)
- checkpoint_model_args = checkpoint['model_args']
- for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
- model_args[k] = checkpoint_model_args[k]
- gptconf = GPTConfig(**model_args)
- model = GPT(gptconf)
- state_dict = checkpoint['model']
- unwanted_prefix = '_orig_mod.'
- for k,v in list(state_dict.items()):
- if k.startswith(unwanted_prefix):
- state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
- model.load_state_dict(state_dict)
- iter_num = checkpoint['iter_num']
- best_val_loss = checkpoint['best_val_loss']
如果是resume方法,则会从检查点文件中回复先前参数、状态等信息。加载ckpt.pt文件后,从其中获取参数字典model_args,更新到当前字典,创建新gptconf(与scratch相似),随后通过startswith做参数名冲突检查和筛选、获取并更新先前迭代次数、最佳损失等信息
- elif init_from.startswith('gpt2'):
- print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
- override_args = dict(dropout=dropout)
- model = GPT.from_pretrained(init_from, override_args)
- for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
- model_args[k] = getattr(model.config, k)
从OpenAI的GPT-2预训练模型中加载权重,使用from_pretrained传递和覆盖参数与超参数,很好理解,不再赘述。
- if block_size < model.config.block_size:
- model.crop_block_size(block_size)
- model_args['block_size'] = block_size
- model.to(device)
若块大小不匹配,则调用crop_block_size(上文提到的优化方法之一)来裁剪模型block_size并更新字典对应值,随后将模型移动至对应的device训练
- scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16'))
- optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type)
- if init_from == 'resume':
- optimizer.load_state_dict(checkpoint['optimizer'])
- checkpoint = None
- if compile:
- unoptimized_model = model
- model = torch.compile(model)
- if ddp:
- model = DDP(model, device_ids=[ddp_local_rank])
根据dtype是否为float16开闭梯度缩放(混合精度训练将部分计算转换低精度float16以提高训练效率和内存利用率,但会减少数值范围和表示精度,梯度缩放GradScaler可以在低精度做反向传播时自动乘以缩放因子缩放梯度再更新参数)。前文提到configure_optimizers(),这里根据超参做优化适配。如果初始化方法为resume,加载先前ckpt文件的优化器状态字典并更新。释放检查点空间后结合compile和ddp环境选择对应容器训练。
- def estimate_loss():
- out = {}
- model.eval()
- for split in ['train', 'val']:
- losses = torch.zeros(eval_iters)
- for k in range(eval_iters):
- X, Y = get_batch(split)
- with ctx:
- logits, loss = model(X, Y)
- losses[k] = loss.item()
- out[split] = losses.mean()
- model.train()
- 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平均值并存储。
至于学习率,给出动态调整策略如下:
- def get_lr(it):
- if it < warmup_iters:
- return learning_rate * it / warmup_iters
- if it > lr_decay_iters:
- return min_lr
- decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
- assert 0 <= decay_ratio <= 1
- coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
- 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)。
- if wandb_log and master_process:
- import wandb
- wandb.init(project=wandb_project, name=wandb_run_name, config=config)
设置日志记录的相关配置,使用 WandB 来对主进程做日志记录并对模型训练可视化。
前面各种初始化、优化函数、分配策略设计结束,终于到训练环节
- X, Y = get_batch('train')
- t0 = time.time()
- local_iter_num = 0
- raw_model = model.module if ddp else model
- running_mfu = -1.0
- while True:
- lr = get_lr(iter_num) if decay_lr else learning_rate
- for param_group in optimizer.param_groups:
- param_group['lr'] = lr
- if iter_num % eval_interval == 0 and master_process:
- losses = estimate_loss()
- print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
- if wandb_log:
- wandb.log({
- "iter": iter_num,
- "train/loss": losses['train'],
- "val/loss": losses['val'],
- "lr": lr,
- "mfu": running_mfu*100,
- })
- if losses['val'] < best_val_loss or always_save_checkpoint:
- best_val_loss = losses['val']
- if iter_num > 0:
- checkpoint = {
- 'model': raw_model.state_dict(),
- 'optimizer': optimizer.state_dict(),
- 'model_args': model_args,
- 'iter_num': iter_num,
- 'best_val_loss': best_val_loss,
- 'config': config,
- }
- 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
首先通过 get_batch获取训练集的第一个批数据,并将其存储在变量 X 和 Y 中,随后初始化t0、local_iter_num、raw_model等变量。
每次迭代根据迭代次数确定学习率(判断是否启用衰减),并设置优化器对应参数。eval_interval次迭代后计算训练集和验证集上的损失并记录在WandB上,根据损失值进一步更新模型最优权重和状态
- for micro_step in range(gradient_accumulation_steps):
- if ddp:
- model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
- with ctx:
- logits, loss = model(X, Y)
- loss = loss / gradient_accumulation_steps
- X, Y = get_batch('train')
- scaler.scale(loss).backward()
- if grad_clip != 0.0:
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
- scaler.step(optimizer)
- scaler.update()
- 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_()裁剪(防止梯度爆炸)。执行优化器更新同时进行缩放操作。最后清空梯度,释放内存。
- t1 = time.time()
- dt = t1 - t0
- t0 = t1
- if iter_num % log_interval == 0 and master_process:
- lossf = loss.item() * gradient_accumulation_steps
- if local_iter_num >= 5: # let the training loop settle a bit
- mfu = raw_model.estimate_mfu(batch_size * gradient_accumulation_steps, dt)
- running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu
- print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%")
- iter_num += 1
- local_iter_num += 1
- if iter_num > max_iters:
- checkpoint = {
- 'model': raw_model.state_dict(),
- 'optimizer': optimizer.state_dict(),
- 'model_args': model_args,
- 'iter_num': iter_num,
- 'best_val_loss': best_val_loss,
- 'config': config,
- }
- print(f"saving checkpoint to {out_dir}")
- torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
- break
- if ddp:
- destroy_process_group()
计算迭代时间 dt并更新计时器 t0,如果满足日志记录条件则输出当前迭代的损失值、时间以及每秒浮点运算数MFLOPs。随后更新迭代次数 iter_num 和本地迭代次数 local_iter_num,若为DDP则调用destroy_process_group()清理进程组。
迭代次数达到最大迭代次数max_iters后,保存模型和优化器状态到ckpt,跳出循环。
至此,训练结束。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。