Upload code/train_sft_v3.py with huggingface_hub
Browse files216 unmodified lines21721821922022122222322422522622722822923023123223323424 unmodified lines25926026126226326426526626726834 unmodified lines30330430530630730830931031131231331431531631710 unmodified lines328329330331332333334335336273 unmodified lines6106116126136146156162 unmodified lines61962062162262362462562662762862964 unmodified lines69469569669769869970070136 unmodified lines7387397407417427437447457467477482 unmodified lines75175275375475575675752 unmodified lines81081181281381481581681781828 unmodified lines847848849850851852853854855856857216 unmodified linesEMPTY_CACHE_EVERY = 50# SFT-specific hyperparameters (same for all GPUs)MAX_LR = 5e-05 # Increased from 1e-05 to 5e-05 to quickly learn new chat tokens# the PROVEN value from the working 250M run;# 3e-05 combined with our smaller batch size# caused training instability and garbage outputMIN_LR = 1e-06 # unchangedWARMUP_STEPS = 50 # reverted from 150 โ 50, matching the working# 250M run (no longer need extra-long warmup# since LR is back to a gentler, proven value)EPOCHS = 3 # reduced from 6 โ 4 (250M used 3 successfully;# we keep slightly more since 500M has more# parameters to adapt, but avoid excessive# total training time)WEIGHT_DECAY = 0.01GRAD_CLIP = 1.0EVAL_EVERY = 100024 unmodified lines# input_ids and labels are at SAME alignment (no shift in the data files).# The shift is handled in compute_sft_loss() below.class NpySFTDataset:def __init__(self, ids_path, labels_path, offsets_path, ctx_len):self.ids = np.load(ids_path, mmap_mode='r')self.labels = np.load(labels_path, mmap_mode='r')self.offsets = np.load(offsets_path)self.ctx_len = ctx_lenif self.ids.ndim != 1 or self.labels.ndim != 1:34 unmodified linesinput_ids[:length] = self.ids[start:start + length].astype(np.int64)labels[:length] = self.labels[start:start + length].astype(np.int64)return input_ids, labelsdef get_sft_batch(dataset, batch_size, rng):batch_ids, batch_labels = [], []empty_examples = 0while len(batch_ids) < batch_size:idx = rng.randrange(len(dataset))try:ids, labels = dataset.get(idx)except ValueError:empty_examples += 1if empty_examples >= batch_size * 10:10 unmodified linescontinuebatch_ids.append(ids)batch_labels.append(labels)x = torch.from_numpy(np.stack(batch_ids)).pin_memory().to(DEVICE, non_blocking=True)y = torch.from_numpy(np.stack(batch_labels)).pin_memory().to(DEVICE, non_blocking=True)return x, y# ============================================================================# 8. Checkpoint Key Remapping (handles torch.compile prefix + vocab resize)273 unmodified lines# - Labels: y[:, 1:] (all labels shifted left by 1)## This makes: logits[t] (predicts next token after 0..t) โ labels[t+1] โdef compute_sft_loss(model, x, y, pad_id=0):"""Forward pass with proper shift for SFT."""x_in = x[:, :-1].contiguous() # [B, T-1] โ drop last tokeny_shifted = y[:, 1:].contiguous() # [B, T-1] โ shift labels left by 12 unmodified linesif pad_id is not None and (x_in == pad_id).any():use_pad_id = pad_idlogits, loss = model(x_in, targets=y_shifted, pad_id=use_pad_id)if not (y_shifted != -100).any():return torch.nan_to_num(logits.float()).sum() * 0.0return loss# ============================================================================64 unmodified linesif _DATA_VER == "v1": # legacy v1 filenames had no version prefix_PFX = "sft_"SFT_DATA_FILES = [f"{_PFX}train_ids.npy", f"{_PFX}train_labels.npy", f"{_PFX}train_offsets.npy",f"{_PFX}val_ids.npy", f"{_PFX}val_labels.npy", f"{_PFX}val_offsets.npy",]log(f"๐ SFT data version: {_DATA_VER} | prefix: '{_PFX}'")def download_on_main(fn, *args, fatal=True, **kwargs):36 unmodified linestrain_ds = NpySFTDataset(f"{data_path}/{_PFX}train_ids.npy", f"{data_path}/{_PFX}train_labels.npy",f"{data_path}/{_PFX}train_offsets.npy" if os.path.exists(f"{data_path}/{_PFX}train_offsets.npy") else None, CONTEXT_LEN)val_ds = NpySFTDataset(f"{data_path}/{_PFX}val_ids.npy", f"{data_path}/{_PFX}val_labels.npy",f"{data_path}/{_PFX}val_offsets.npy" if os.path.exists(f"{data_path}/{_PFX}val_offsets.npy") else None, CONTEXT_LEN)if IS_MAIN:log(f"๐ Train examples: {len(train_ds)}, Val examples: {len(val_ds)}")2 unmodified lines# 14. Sanity Checks# ============================================================================if IS_MAIN:_s_ids, _s_labels = train_ds.get(0)_has_masked = (_s_labels == -100).any()_has_active = (_s_labels != -100).any()assert _has_active, (52 unmodified lineseval_model.eval()losses = []for _ in range(20):x, y = get_sft_batch(val_ds, MICRO_BATCH, val_rng)with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):loss = compute_sft_loss(eval_model, x, y, pad_id=PAD_ID)if torch.isfinite(loss):losses.append(loss.item())del x, y, loss28 unmodified linesaccum_loss = 0.0for micro_i in range(GRAD_ACCUM):x, y = get_sft_batch(train_ds, MICRO_BATCH, rng)sync_ctx = model.no_sync() if micro_i < GRAD_ACCUM - 1 else contextlib.nullcontext()with sync_ctx:with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):loss = compute_sft_loss(model, x, y, pad_id=PAD_ID)loss = loss / GRAD_ACCUMloss.backward()accum_loss += loss.item()216 unmodified lines21721821922022122222322422522624 unmodified lines25125225325425525625725825926026134 unmodified lines29629729829930030130230330430530630730830931031110 unmodified lines322323324325326327328329330331273 unmodified lines6056066076086096106112 unmodified lines61461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464 unmodified lines70971071171271371471571636 unmodified lines7537547557567577587597607617627637647652 unmodified lines76876977077177277377452 unmodified lines82782882983083183283383483528 unmodified lines864865866867868869870871872873874216 unmodified linesEMPTY_CACHE_EVERY = 50# SFT-specific hyperparameters (same for all GPUs)MAX_LR = 1e-05MIN_LR = 1e-06WARMUP_STEPS = 100EPOCHS = 3WEIGHT_DECAY = 0.01GRAD_CLIP = 1.0EVAL_EVERY = 100024 unmodified lines# input_ids and labels are at SAME alignment (no shift in the data files).# The shift is handled in compute_sft_loss() below.class NpySFTDataset:def __init__(self, ids_path, labels_path, offsets_path, cat_path, ctx_len):self.ids = np.load(ids_path, mmap_mode='r')self.labels = np.load(labels_path, mmap_mode='r')self.offsets = np.load(offsets_path)self.categories = np.load(cat_path) if (cat_path and os.path.exists(cat_path)) else Noneself.ctx_len = ctx_lenif self.ids.ndim != 1 or self.labels.ndim != 1:34 unmodified linesinput_ids[:length] = self.ids[start:start + length].astype(np.int64)labels[:length] = self.labels[start:start + length].astype(np.int64)cat = str(self.categories[idx]) if self.categories is not None else "general"return input_ids, labels, catdef get_sft_batch(dataset, batch_size, rng):batch_ids, batch_labels, batch_cats = [], [], []empty_examples = 0while len(batch_ids) < batch_size:idx = rng.randrange(len(dataset))try:ids, labels, cat = dataset.get(idx)except ValueError:empty_examples += 1if empty_examples >= batch_size * 10:10 unmodified linescontinuebatch_ids.append(ids)batch_labels.append(labels)batch_cats.append(cat)x = torch.from_numpy(np.stack(batch_ids)).pin_memory().to(DEVICE, non_blocking=True)y = torch.from_numpy(np.stack(batch_labels)).pin_memory().to(DEVICE, non_blocking=True)return x, y, batch_cats# ============================================================================# 8. Checkpoint Key Remapping (handles torch.compile prefix + vocab resize)273 unmodified lines# - Labels: y[:, 1:] (all labels shifted left by 1)## This makes: logits[t] (predicts next token after 0..t) โ labels[t+1] โdef compute_sft_loss(model, x, y, pad_id=0, categories=None):"""Forward pass with proper shift for SFT."""x_in = x[:, :-1].contiguous() # [B, T-1] โ drop last tokeny_shifted = y[:, 1:].contiguous() # [B, T-1] โ shift labels left by 12 unmodified linesif pad_id is not None and (x_in == pad_id).any():use_pad_id = pad_idlogits, _ = model(x_in, pad_id=use_pad_id)if not (y_shifted != -100).any():return torch.nan_to_num(logits.float()).sum() * 0.0if categories is None:loss = F.cross_entropy(logits.view(-1, logits.size(-1)), y_shifted.view(-1), ignore_index=-100)else:loss_none = F.cross_entropy(logits.view(-1, logits.size(-1)), y_shifted.view(-1), ignore_index=-100, reduction='none')loss_none = loss_none.view(x_in.size(0), -1)weights = torch.ones(x_in.size(0), device=x_in.device, dtype=loss_none.dtype)for i, cat in enumerate(categories):if cat == "rag": weights[i] = 1.5elif cat == "thinking": weights[i] = 1.3valid_mask = (y_shifted != -100).float()token_losses = loss_none * valid_mask * weights.unsqueeze(1)total_valid = valid_mask.sum()if total_valid > 0:loss = token_losses.sum() / total_validelse:loss = token_losses.sum() * 0.0return loss# ============================================================================64 unmodified linesif _DATA_VER == "v1": # legacy v1 filenames had no version prefix_PFX = "sft_"SFT_DATA_FILES = [f"{_PFX}train_ids.npy", f"{_PFX}train_labels.npy", f"{_PFX}train_offsets.npy", f"{_PFX}train_categories.npy",f"{_PFX}val_ids.npy", f"{_PFX}val_labels.npy", f"{_PFX}val_offsets.npy", f"{_PFX}val_categories.npy",]log(f"๐ SFT data version: {_DATA_VER} | prefix: '{_PFX}'")def download_on_main(fn, *args, fatal=True, **kwargs):36 unmodified linestrain_ds = NpySFTDataset(f"{data_path}/{_PFX}train_ids.npy", f"{data_path}/{_PFX}train_labels.npy",f"{data_path}/{_PFX}train_offsets.npy" if os.path.exists(f"{data_path}/{_PFX}train_offsets.npy") else None,f"{data_path}/{_PFX}train_categories.npy", CONTEXT_LEN)val_ds = NpySFTDataset(f"{data_path}/{_PFX}val_ids.npy", f"{data_path}/{_PFX}val_labels.npy",f"{data_path}/{_PFX}val_offsets.npy" if os.path.exists(f"{data_path}/{_PFX}val_offsets.npy") else None,f"{data_path}/{_PFX}val_categories.npy", CONTEXT_LEN)if IS_MAIN:log(f"๐ Train examples: {len(train_ds)}, Val examples: {len(val_ds)}")2 unmodified lines# 14. Sanity Checks# ============================================================================if IS_MAIN:_s_ids, _s_labels, _s_cat = train_ds.get(0)_has_masked = (_s_labels == -100).any()_has_active = (_s_labels != -100).any()assert _has_active, (52 unmodified lineseval_model.eval()losses = []for _ in range(20):x, y, cats = get_sft_batch(val_ds, MICRO_BATCH, val_rng)with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):loss = compute_sft_loss(eval_model, x, y, pad_id=PAD_ID, categories=cats)if torch.isfinite(loss):losses.append(loss.item())del x, y, loss28 unmodified linesaccum_loss = 0.0for micro_i in range(GRAD_ACCUM):x, y, cats = get_sft_batch(train_ds, MICRO_BATCH, rng)sync_ctx = model.no_sync() if micro_i < GRAD_ACCUM - 1 else contextlib.nullcontext()with sync_ctx:with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):loss = compute_sft_loss(model, x, y, pad_id=PAD_ID, categories=cats)loss = loss / GRAD_ACCUMloss.backward()accum_loss += loss.item()
code/train_sft_v3.py+45-28