This commit is contained in:
sen.liang committed 2025-05-24 21:20:50 +08:00
1 parent 93a43d9a5c
commit a747ca26ea
1 file changed
+27 -1
+27 -1
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,17 +106,26 @@ 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 = {
'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) ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
# poor man's data loader # poor man's data loader
@@ -117,14 +134,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)