Compare commits

...
2 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
3 changed files with 144 additions and 5 deletions

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 return optimizer
def estimate_mfu(self, fwdbwd_per_iter, dt): 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. # first estimate the number of flops we do per iteration.
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311 # see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
# 获取模型参数量
N = self.get_num_params() N = self.get_num_params()
cfg = self.config cfg = self.config
L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size 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 flops_per_token = 6*N + 12*L*H*Q*T
# 考虑序列长度T
flops_per_fwdbwd = flops_per_token * T flops_per_fwdbwd = flops_per_token * T
# 考虑每秒的迭代次数
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
# express our flops throughput as ratio of A100 bfloat16 peak flops # express our flops throughput as ratio of A100 bfloat16 peak flops
flops_achieved = flops_per_iter * (1.0/dt) # per second flops_achieved = flops_per_iter * (1.0/dt) # per second
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
+74 -4
View File
@@ -39,21 +39,25 @@ eval_iters = 200
eval_only = False # if True, script exits right after the first eval 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 always_save_checkpoint = True # if True, always save a checkpoint after each eval
init_from = 'scratch' # 'scratch' or 'resume' or 'gpt2*' init_from = 'scratch' # 'scratch' or 'resume' or 'gpt2*'
# wandb logging # wandb logging
wandb_log = False # disabled by default wandb_log = False # disabled by default
wandb_project = 'owt' wandb_project = 'owt'
wandb_run_name = 'gpt2' # 'run' + str(time.time()) wandb_run_name = 'gpt2' # 'run' + str(time.time())
# data # data
dataset = 'openwebtext' dataset = 'openwebtext'
gradient_accumulation_steps = 5 * 8 # used to simulate larger batch sizes 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 batch_size = 12 # if gradient_accumulation_steps > 1, this is the micro-batch size
block_size = 1024 block_size = 1024
# model # model
n_layer = 12 n_layer = 12
n_head = 12 n_head = 12
n_embd = 768 n_embd = 768
dropout = 0.0 # for pretraining 0 is good, for finetuning try 0.1+ dropout = 0.0 # for pretraining 0 is good, for finetuning try 0.1+
bias = False # do we use bias inside LayerNorm and Linear layers? bias = False # do we use bias inside LayerNorm and Linear layers?
# adamw optimizer # adamw optimizer
learning_rate = 6e-4 # max learning rate learning_rate = 6e-4 # max learning rate
max_iters = 600000 # total number of training iterations max_iters = 600000 # total number of training iterations
@@ -61,17 +65,21 @@ weight_decay = 1e-1
beta1 = 0.9 beta1 = 0.9
beta2 = 0.95 beta2 = 0.95
grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0 grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0
# learning rate decay settings # learning rate decay settings
decay_lr = True # whether to decay the learning rate decay_lr = True # whether to decay the learning rate
warmup_iters = 2000 # how many steps to warm up for warmup_iters = 2000 # how many steps to warm up for
lr_decay_iters = 600000 # should be ~= max_iters per Chinchilla lr_decay_iters = 600000 # should be ~= max_iters per Chinchilla
min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
# DDP settings # DDP settings
backend = 'nccl' # 'nccl', 'gloo', etc. backend = 'nccl' # 'nccl', 'gloo', etc.
# system # system
device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks 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 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 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))] 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 exec(open('configurator.py').read()) # overrides from command line or config file
@@ -98,18 +106,41 @@ else:
master_process = True master_process = True
seed_offset = 0 seed_offset = 0
ddp_world_size = 1 ddp_world_size = 1
tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
print(f"tokens per iteration will be: {tokens_per_iter:,}") print(f"tokens per iteration will be: {tokens_per_iter:,}")
if master_process: if master_process:
os.makedirs(out_dir, exist_ok=True) os.makedirs(out_dir, exist_ok=True)
torch.manual_seed(1337 + seed_offset) torch.manual_seed(1337 + seed_offset)
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn 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 device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
# note: float16 data type will automatically use a GradScaler # note: float16 data type will automatically use a GradScaler
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype] ptdtype = {
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=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 # poor man's data loader
data_dir = os.path.join('data', dataset) data_dir = os.path.join('data', dataset)
@@ -117,14 +148,23 @@ def get_batch(split):
# We recreate np.memmap every batch to avoid a memory leak, as per # 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 # https://stackoverflow.com/questions/45132940/numpy-memmap-memory-usage-want-to-iterate-once/61472122#61472122
if split == 'train': 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') data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r')
else: else:
data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r') data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r')
ix = torch.randint(len(data) - block_size, (batch_size,)) 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]) 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]) y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])
if device_type == 'cuda': if device_type == 'cuda':
# pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True) # 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) x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
else: else:
x, y = x.to(device), y.to(device) x, y = x.to(device), y.to(device)
@@ -155,6 +195,7 @@ if init_from == 'scratch':
model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304 model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
gptconf = GPTConfig(**model_args) gptconf = GPTConfig(**model_args)
model = GPT(gptconf) model = GPT(gptconf)
elif init_from == 'resume': elif init_from == 'resume':
print(f"Resuming training from {out_dir}") print(f"Resuming training from {out_dir}")
# resume training from a checkpoint. # resume training from a checkpoint.
@@ -178,6 +219,7 @@ elif init_from == 'resume':
model.load_state_dict(state_dict) model.load_state_dict(state_dict)
iter_num = checkpoint['iter_num'] iter_num = checkpoint['iter_num']
best_val_loss = checkpoint['best_val_loss'] best_val_loss = checkpoint['best_val_loss']
elif init_from.startswith('gpt2'): elif init_from.startswith('gpt2'):
print(f"Initializing from OpenAI GPT-2 weights: {init_from}") print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
# initialize from OpenAI GPT-2 weights # initialize from OpenAI GPT-2 weights
@@ -186,6 +228,7 @@ elif init_from.startswith('gpt2'):
# read off the created config params, so we can store them into checkpoint correctly # 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']: for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
model_args[k] = getattr(model.config, k) model_args[k] = getattr(model.config, k)
# crop down the model block size if desired, using model surgery # crop down the model block size if desired, using model surgery
if block_size < model.config.block_size: if block_size < model.config.block_size:
model.crop_block_size(block_size) model.crop_block_size(block_size)
@@ -214,6 +257,9 @@ if ddp:
# helps estimate an arbitrarily accurate loss over either split using many batches # helps estimate an arbitrarily accurate loss over either split using many batches
@torch.no_grad() @torch.no_grad()
def estimate_loss(): def estimate_loss():
""" 估计损失 (不使用梯度)
同时使用 "验证集" 和 "训练集" 来评估模型的性能,数据是随机采样的, 评估采样次数eval_iters是给定的。
"""
out = {} out = {}
model.eval() model.eval()
for split in ['train', 'val']: for split in ['train', 'val']:
@@ -229,12 +275,18 @@ def estimate_loss():
# learning rate decay scheduler (cosine with warmup) # learning rate decay scheduler (cosine with warmup)
def get_lr(it): 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: if it < warmup_iters:
return learning_rate * (it + 1) / (warmup_iters + 1) return learning_rate * (it + 1) / (warmup_iters + 1)
# 2) if it > lr_decay_iters, return min learning rate # 2) if it > lr_decay_iters, return min learning rate
if it > lr_decay_iters: if it > lr_decay_iters:
return min_lr return min_lr
# 3) in between, use cosine decay down to min learning rate # 3) in between, use cosine decay down to min learning rate
decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters) decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
assert 0 <= decay_ratio <= 1 assert 0 <= decay_ratio <= 1
@@ -271,6 +323,7 @@ while True:
"lr": lr, "lr": lr,
"mfu": running_mfu*100, # convert to percentage "mfu": running_mfu*100, # convert to percentage
}) })
if losses['val'] < best_val_loss or always_save_checkpoint: if losses['val'] < best_val_loss or always_save_checkpoint:
best_val_loss = losses['val'] best_val_loss = losses['val']
if iter_num > 0: if iter_num > 0:
@@ -284,11 +337,20 @@ while True:
} }
print(f"saving checkpoint to {out_dir}") print(f"saving checkpoint to {out_dir}")
torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt')) torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
if iter_num == 0 and eval_only: if iter_num == 0 and eval_only:
break break
# forward backward update, with optional gradient accumulation to simulate larger batch size # forward backward update, with optional gradient accumulation to simulate larger batch size
# and using the GradScaler if data type is float16 # 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): for micro_step in range(gradient_accumulation_steps):
if ddp: if ddp:
# in DDP training we only need to sync gradients at the last micro step. # in DDP training we only need to sync gradients at the last micro step.
@@ -296,20 +358,28 @@ while True:
# I really dislike that this bloats the code and forces us to repeat code # 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 # looking at the source of that context manager, it just toggles this variable
model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1) model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
# 使用autocast上下文管理器包裹住需要进行自动混合精度训练的代码块
with ctx: with ctx:
logits, loss = model(X, Y) 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 # immediately async prefetch next batch while model is doing the forward pass on the GPU
X, Y = get_batch('train') X, Y = get_batch('train')
# backward pass, with gradient scaling if training in fp16 # backward pass, with gradient scaling if training in fp16
scaler.scale(loss).backward() scaler.scale(loss).backward()
# clip the gradient # clip the gradient
if grad_clip != 0.0: if grad_clip != 0.0:
scaler.unscale_(optimizer) scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip) torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
# step the optimizer and scaler if training in fp16 # step the optimizer and scaler if training in fp16
scaler.step(optimizer) scaler.step(optimizer)
scaler.update() scaler.update()
# flush the gradients as soon as we can, no need for this memory anymore # flush the gradients as soon as we can, no need for this memory anymore
optimizer.zero_grad(set_to_none=True) optimizer.zero_grad(set_to_none=True)