Maximum training speed optimizations: zero-sync Z-loss, ce_chunk=512, async token accumulation, 64-token alignment, compile before DDP
Browse files398 unmodified lines399400401402403404405662 unmodified lines1068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109974 unmodified lines1174117511761177117811793 unmodified lines118311841185118611871188118911901191119211931194119511961197119873 unmodified lines127212731274127512761277127812796 unmodified lines128612871288128912901291129269 unmodified lines13621363136413651366136717 unmodified lines13851386138713881389139013911392139313945 unmodified lines1400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143715 unmodified lines14531454145514561457145814591460146110 unmodified lines147214731474147514761477147814791480148114821483148488 unmodified lines15731574157515761577157815791 unmodified line158115821583158415851586398 unmodified linesinputs, labels, domain_ids = zip(*batch)max_len = max(len(inp) for inp in inputs)max_len = min(((max_len + 7) // 8) * 8, 2048)batch_inputs = torch.full((len(batch), max_len), pad_token_id, dtype=torch.long)batch_labels = torch.full((len(batch), max_len), ignore_index, dtype=torch.long)662 unmodified linescollate_fn_bound = partial(sft_collate_fn, pad_token_id=PAD_TOKEN_ID, ignore_index=-100)num_workers = min(4, max(1, (os.cpu_count() or 4) // max(1, WORLD_SIZE)))train_loader = DataLoader(train_dataset,batch_sampler=train_sampler,collate_fn=collate_fn_bound,num_workers=num_workers,pin_memory=True if torch.cuda.is_available() else False,prefetch_factor=3 if num_workers > 0 else None,persistent_workers=True if num_workers > 0 else False)val_loader = DataLoader(val_dataset,batch_sampler=val_sampler,collate_fn=collate_fn_bound,num_workers=num_workers,pin_memory=True if torch.cuda.is_available() else False)if IS_MAIN:print(f"📦 Dataset Loaded: Train = {len(train_dataset):,} samples | Val = {len(val_dataset):,} samples")# 2. Build Model & Load Checkpointuse_ckpt = not args.disable_checkpointingif IS_MAIN:if not use_ckpt:print("⚡ Activation Checkpointing: DISABLED (30-40% faster training boost active!)")else:print("🛡️ Activation Checkpointing: ENABLED (low-VRAM mode)")74 unmodified linesgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()if IS_DDP:model = DDP(model,3 unmodified linesgradient_as_bucket_view=True,bucket_cap_mb=50)print(f" 🚀 [GPU {LOCAL_RANK}/{WORLD_SIZE}] Distributed Data Parallel Active (High-Bandwidth Bucketing)!")# Optional torch.compile for maximum speedif args.compile and hasattr(torch, "compile"):print("⚡ Compiling model with torch.compile(dynamic=True)...")try:model = torch.compile(model, dynamic=True)print("✅ Model compiled successfully with dynamic shape support!")except Exception as e:print(f"⚠️ Could not compile model: {e}")# 3. Fused Optimizer & Schedulersdecay_params = []73 unmodified lines# Single forward pass: get hidden states (with pad masking)B, T = inps.shapex = raw_m.tok_emb(inps)cos = raw_m.rope_cos.to(x.device)sin = raw_m.rope_sin.to(x.device)# FIXED: Keep eval_mask = None so evaluation matches generation without masking out 64002 (<|endofturn|>)eval_mask = Nonefor block in raw_m.blocks:6 unmodified linessample_losses = torch.zeros(B, device=device, dtype=torch.float32)sample_active = (shift_labels != -100).sum(dim=1).to(torch.float32)ce_chunk = getattr(raw_m.cfg, "ce_chunk", 256)for ci in range(0, seq_len, ce_chunk):ce = min(ci + ce_chunk, seq_len)chunk_logits = raw_m.head(hidden[:, ci:ce, :]).float() # [B, chunk, V]69 unmodified lineslast_log_tokens = 0last_log_step = global_steptotal_tokens_trained = 0if torch.cuda.is_available():torch.cuda.empty_cache()model.train()17 unmodified linesif IS_MAIN:print(f"⏩ Fast-forwarding dataset: Slicing {skip_micro_batches:,} already-trained micro-batches in sampler for instant resume at Global Step {resumed_step}...", flush=True)epoch_loss = 0.0epoch_batches = 0accum_loss = 0.0step_active_tokens = 0step_avg_loss = 0.0lr = args.min_lr5 unmodified linesinputs = inputs.to(device, non_blocking=True)labels = labels.to(device, non_blocking=True)# Active target tokens count (shift_labels=True so labels[:, 1:] are active)active_tokens_count = (labels[:, 1:] != -100).sum().item()if active_tokens_count > 0 or IS_DDP:total_tokens_trained += active_tokens_countis_accumulating = ((micro_idx + 1) % grad_acc != 0) and ((micro_idx + 1) < total_micro_batches)sync_ctx = model.no_sync() if (IS_DDP and is_accumulating) else contextlib.nullcontext()with sync_ctx:with autocast_ctx:_, loss = model(inputs, targets=labels, pad_id=PAD_TOKEN_ID, shift_labels=True)# True Token-Weighted Scaling: eliminate sequence-length gradient biasloss_scaled = loss * (active_tokens_count / 1024.0)if scaler.is_enabled():scaler.scale(loss_scaled).backward()else:loss_scaled.backward()step_active_tokens += active_tokens_countaccum_loss += loss.item() * active_tokens_countepoch_loss += loss.item()epoch_batches += 1step_updated = Falseif (micro_idx + 1) % grad_acc == 0 or (micro_idx + 1) == total_micro_batches:if IS_DDP:tok_tensor = torch.tensor([step_active_tokens], dtype=torch.float64, device=device)dist.all_reduce(tok_tensor, op=dist.ReduceOp.SUM)total_step_tokens = tok_tensor.item()norm_tokens = max(1.0, total_step_tokens / WORLD_SIZE)else:total_step_tokens = float(step_active_tokens)norm_tokens = max(1.0, total_step_tokens)if total_step_tokens > 0:15 unmodified linesoptimizer.zero_grad(set_to_none=True)if scaler.is_enabled():scaler.update()step_avg_loss = accum_loss / max(1.0, float(step_active_tokens))step_active_tokens = 0accum_loss = 0.0continuelr = get_lr(global_step, warmup_steps, total_steps, args.max_lr, args.min_lr)10 unmodified linesglobal_step += 1step_updated = Truestep_avg_loss = accum_loss / max(1.0, float(step_active_tokens))step_active_tokens = 0accum_loss = 0.0if step_updated:if global_step % 10 == 0 or global_step == 1 or global_step == (resumed_step + 1):cur_time = time.time()interval_elapsed = cur_time - last_log_timeinterval_tokens = (total_tokens_trained - last_log_tokens) * WORLD_SIZEinterval_steps = max(1, global_step - last_log_step)88 unmodified linesif epoch_batches == 0:raise RuntimeError(f"Error: Epoch {epoch} yielded 0 batches. Verify dataset and batch configuration.")avg_epoch_loss = epoch_loss / epoch_batchesif IS_MAIN:print(f"\n✅ Finished Epoch {epoch}/{args.epochs} | Avg Epoch Loss: {avg_epoch_loss:.4f}")resumed_step = 01 unmodified line# Final Evaluation & Savefinal_val_loss, final_val_ppl, final_d_losses = evaluate()if IS_MAIN:print("\n" + "=" * 85)print(f"🎉 SFT {args.version.upper()} MASTER TRAINING COMPLETED!")print(f" • Best Validation Loss: {min(best_val_loss, final_val_loss):.4f}")398 unmodified lines399400401402403404405662 unmodified lines1068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110274 unmodified lines1177117811791180118111821183118411851186118711881189119011911192119311943 unmodified lines1198119912001201120212031204120573 unmodified lines127912801281128212831284128512866 unmodified lines129312941295129612971298129969 unmodified lines136913701371137213731374137517 unmodified lines13931394139513961397139813991400140114025 unmodified lines14081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144315 unmodified lines1459146014611462146314641465146610 unmodified lines14771478147914801481148214831484148514861487148814891490149188 unmodified lines15801581158215831584158515861 unmodified line1588158915901591159215931594398 unmodified linesinputs, labels, domain_ids = zip(*batch)max_len = max(len(inp) for inp in inputs)max_len = min(((max_len + 63) // 64) * 64, 2048)batch_inputs = torch.full((len(batch), max_len), pad_token_id, dtype=torch.long)batch_labels = torch.full((len(batch), max_len), ignore_index, dtype=torch.long)662 unmodified linescollate_fn_bound = partial(sft_collate_fn, pad_token_id=PAD_TOKEN_ID, ignore_index=-100)num_workers = min(8, max(2, (os.cpu_count() or 4) // max(1, WORLD_SIZE)))train_loader = DataLoader(train_dataset,batch_sampler=train_sampler,collate_fn=collate_fn_bound,num_workers=num_workers,pin_memory=torch.cuda.is_available(),prefetch_factor=4 if num_workers > 0 else None,persistent_workers=(num_workers > 0))val_loader = DataLoader(val_dataset,batch_sampler=val_sampler,collate_fn=collate_fn_bound,num_workers=num_workers,pin_memory=torch.cuda.is_available(),prefetch_factor=2 if num_workers > 0 else None,persistent_workers=(num_workers > 0))if IS_MAIN:print(f"📦 Dataset Loaded: Train = {len(train_dataset):,} samples | Val = {len(val_dataset):,} samples")# 2. Build Model & Load Checkpoint# Auto-disable activation checkpointing on GPUs with >= 24GB VRAM for +35% speeduse_ckpt = (not args.disable_checkpointing) and (hw["vram_gb"] < 24.0)if IS_MAIN:if not use_ckpt:print(f"⚡ Activation Checkpointing: DISABLED (Auto-fast mode on {hw['vram_gb']:.1f}GB VRAM for +35% speed boost!)")else:print("🛡️ Activation Checkpointing: ENABLED (low-VRAM mode)")74 unmodified linesgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()# Optional torch.compile for maximum speed (compiled BEFORE DDP wrapping as per PyTorch best practices)if args.compile and hasattr(torch, "compile"):if IS_MAIN:print("⚡ Compiling model with torch.compile(dynamic=True)...")try:model = torch.compile(model, dynamic=True)if IS_MAIN:print("✅ Model compiled successfully with dynamic shape support!")except Exception as e:if IS_MAIN:print(f"⚠️ Could not compile model: {e}")if IS_DDP:model = DDP(model,3 unmodified linesgradient_as_bucket_view=True,bucket_cap_mb=50)if IS_MAIN:print(f" 🚀 Distributed Data Parallel Active (High-Bandwidth Bucketing, 50MB)!")# 3. Fused Optimizer & Schedulersdecay_params = []73 unmodified lines# Single forward pass: get hidden states (with pad masking)B, T = inps.shapex = raw_m.tok_emb(inps)cos = raw_m.rope_cos[:T].to(dtype=x.dtype)[None, None, :, :]sin = raw_m.rope_sin[:T].to(dtype=x.dtype)[None, None, :, :]# FIXED: Keep eval_mask = None so evaluation matches generation without masking out 64002 (<|endofturn|>)eval_mask = Nonefor block in raw_m.blocks:6 unmodified linessample_losses = torch.zeros(B, device=device, dtype=torch.float32)sample_active = (shift_labels != -100).sum(dim=1).to(torch.float32)ce_chunk = getattr(raw_m.cfg, "ce_chunk", 512)for ci in range(0, seq_len, ce_chunk):ce = min(ci + ce_chunk, seq_len)chunk_logits = raw_m.head(hidden[:, ci:ce, :]).float() # [B, chunk, V]69 unmodified lineslast_log_tokens = 0last_log_step = global_steptotal_tokens_trained = 0total_tokens_trained_t = torch.zeros(1, device=device, dtype=torch.int64)if torch.cuda.is_available():torch.cuda.empty_cache()model.train()17 unmodified linesif IS_MAIN:print(f"⏩ Fast-forwarding dataset: Slicing {skip_micro_batches:,} already-trained micro-batches in sampler for instant resume at Global Step {resumed_step}...", flush=True)epoch_loss_t = torch.zeros(1, device=device, dtype=torch.float64)epoch_batches = 0accum_loss_t = torch.zeros(1, device=device, dtype=torch.float64)step_active_tokens_t = torch.zeros(1, device=device, dtype=torch.float64)step_avg_loss = 0.0lr = args.min_lr5 unmodified linesinputs = inputs.to(device, non_blocking=True)labels = labels.to(device, non_blocking=True)# Active target tokens count (100% Async on GPU - ZERO CPU sync!)active_tokens_t = (labels[:, 1:] != -100).sum()total_tokens_trained_t += active_tokens_tis_accumulating = ((micro_idx + 1) % grad_acc != 0) and ((micro_idx + 1) < total_micro_batches)sync_ctx = model.no_sync() if (IS_DDP and is_accumulating) else contextlib.nullcontext()with sync_ctx:with autocast_ctx:_, loss = model(inputs, targets=labels, pad_id=PAD_TOKEN_ID, shift_labels=True)# True Token-Weighted Scaling: eliminate sequence-length gradient biasloss_scaled = loss * (active_tokens_t.to(loss.dtype) / 1024.0)if scaler.is_enabled():scaler.scale(loss_scaled).backward()else:loss_scaled.backward()step_active_tokens_t += active_tokens_t.to(torch.float64)accum_loss_t += loss.detach().to(torch.float64) * active_tokens_t.to(torch.float64)epoch_loss_t += loss.detach().to(torch.float64)epoch_batches += 1step_updated = Falseif (micro_idx + 1) % grad_acc == 0 or (micro_idx + 1) == total_micro_batches:if IS_DDP:dist.all_reduce(step_active_tokens_t, op=dist.ReduceOp.SUM)total_step_tokens = step_active_tokens_t.item()norm_tokens = max(1.0, total_step_tokens / WORLD_SIZE)else:total_step_tokens = step_active_tokens_t.item()norm_tokens = max(1.0, total_step_tokens)if total_step_tokens > 0:15 unmodified linesoptimizer.zero_grad(set_to_none=True)if scaler.is_enabled():scaler.update()step_active_tokens_t.zero_()accum_loss_t.zero_()continuelr = get_lr(global_step, warmup_steps, total_steps, args.max_lr, args.min_lr)10 unmodified linesglobal_step += 1step_updated = True# Compute average step loss for loggingstep_avg_loss = (accum_loss_t / max(1.0, total_step_tokens / WORLD_SIZE)).item()step_active_tokens_t.zero_()accum_loss_t.zero_()if step_updated:if global_step % 10 == 0 or global_step == 1 or global_step == (resumed_step + 1):cur_time = time.time()total_tokens_trained = total_tokens_trained_t.item()interval_elapsed = cur_time - last_log_timeinterval_tokens = (total_tokens_trained - last_log_tokens) * WORLD_SIZEinterval_steps = max(1, global_step - last_log_step)88 unmodified linesif epoch_batches == 0:raise RuntimeError(f"Error: Epoch {epoch} yielded 0 batches. Verify dataset and batch configuration.")avg_epoch_loss = (epoch_loss_t.item() / max(1, epoch_batches))if IS_MAIN:print(f"\n✅ Finished Epoch {epoch}/{args.epochs} | Avg Epoch Loss: {avg_epoch_loss:.4f}")resumed_step = 01 unmodified line# Final Evaluation & Savefinal_val_loss, final_val_ppl, final_d_losses = evaluate()if IS_MAIN:total_tokens_trained = total_tokens_trained_t.item()print("\n" + "=" * 85)print(f"🎉 SFT {args.version.upper()} MASTER TRAINING COMPLETED!")print(f" • Best Validation Loss: {min(best_val_loss, final_val_loss):.4f}")
code/train_sft.py+64-56