Upload code/train_sft.py with huggingface_hub
Browse files20 unmodified lines212223242526722 unmodified lines749750751752753754755199 unmodified lines9559569579589599609619629639649659669672 unmodified lines970971972973974975976132 unmodified lines110911101111111211131114111563 unmodified lines117911801181118211831184118543 unmodified lines1229123012311232123312347 unmodified lines12421243124412451246124712482 unmodified lines125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128492 unmodified lines1377137813791380138113821383138413851386138713881389139033 unmodified lines14241425142614271428142944 unmodified lines14741475147614771478147920 unmodified linesimport shutilimport argparseimport contextlibfrom datetime import timedeltaimport numpy as npimport torch722 unmodified linesparser.add_argument("--min_lr", type=float, default=2.0e-6, help="Minimum learning rate")parser.add_argument("--weight_decay", type=float, default=0.01, help="AdamW weight decay")parser.add_argument("--warmup_ratio", type=float, default=0.04, help="Warmup ratio of total steps")parser.add_argument("--neftune_alpha", type=float, default=0.0, help="NEFTune noise scale for SFT quality (Default: 0.0)")parser.add_argument("--eval_interval", type=int, default=1000, help="Validation evaluation step interval (Default: 1000)")parser.add_argument("--disable_checkpointing", action="store_true", default=False, help="Disable activation checkpointing for 30-40%% faster training on GPUs with >= 24GB VRAM")parser.add_argument("--compile", action="store_true", default=False, help="Enable PyTorch 2.0 torch.compile for maximum speed")199 unmodified lines)train_sampler = LengthGroupedBatchSampler(train_dataset, batch_size=micro_b, rank=RANK, world_size=WORLD_SIZE, shuffle=True, seed=args.seed)val_sampler = LengthGroupedBatchSampler(val_dataset, batch_size=micro_b, shuffle=False)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=sft_collate_fn,num_workers=num_workers,pin_memory=True if torch.cuda.is_available() else False,prefetch_factor=3 if num_workers > 0 else None,2 unmodified linesval_loader = DataLoader(val_dataset,batch_sampler=val_sampler,collate_fn=sft_collate_fn,num_workers=num_workers,pin_memory=True if torch.cuda.is_available() else False)132 unmodified linesresumed_step = global_step# Mixed Precision Setupif torch.cuda.is_available():autocast_ctx = torch.amp.autocast(device_type="cuda", dtype=hw["dtype"])else:63 unmodified linestotal_val_loss += batch_loss_sumval_tokens += batch_activemodel.train()avg_loss = total_val_loss / max(1, val_tokens)ppl = math.exp(min(avg_loss, 20.0))43 unmodified linesepoch_loss = 0.0epoch_batches = 0accum_loss = 0.0optimizer.zero_grad(set_to_none=True)7 unmodified linesinputs = inputs.to(device, non_blocking=True)labels = labels.to(device, non_blocking=True)active_tokens_count = (labels != -100).sum().item()total_tokens_trained += active_tokens_countis_accumulating = ((micro_idx + 1) % grad_acc != 0) and ((micro_idx + 1) < total_micro_batches)2 unmodified lineswith sync_ctx:with autocast_ctx:_, loss = model(inputs, targets=labels, pad_id=PAD_TOKEN_ID, shift_labels=True)loss_scaled = loss / grad_accloss_scaled.backward()accum_loss += loss.item()epoch_loss += loss.item()epoch_batches += 1if (micro_idx + 1) % grad_acc == 0 or (micro_idx + 1) == total_micro_batches:grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)# Anomaly Protection: Protect against NaN/Inf gradient explosionif torch.isnan(grad_norm) or torch.isinf(grad_norm):if IS_MAIN:print(f"⚠️ Anomaly Shield: NaN/Inf grad norm detected at step {global_step}! Skipping step...")optimizer.zero_grad(set_to_none=True)continuelr = get_lr(global_step, warmup_steps, total_steps, args.max_lr, args.min_lr)for param_group in optimizer.param_groups:param_group["lr"] = lroptimizer.step()optimizer.zero_grad(set_to_none=True)global_step += 1actual_acc = grad_acc if (micro_idx + 1) % grad_acc == 0 else ((micro_idx + 1) % grad_acc)step_avg_loss = accum_loss / max(1, actual_acc)accum_loss = 0.0if global_step % 10 == 0 or global_step == 1 or global_step == (resumed_step + 1):cur_time = time.time()92 unmodified linesdist.barrier()# End of Epoch Handlingif epoch_batches > 0 and (micro_idx + 1) % grad_acc != 0:torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)lr = get_lr(global_step, warmup_steps, total_steps, args.max_lr, args.min_lr)for param_group in optimizer.param_groups:param_group["lr"] = lroptimizer.step()optimizer.zero_grad(set_to_none=True)global_step += 1accum_loss = 0.0if epoch_batches == 0:33 unmodified linesif os.path.exists(best_save_path):print(f"🏆 Best checkpoint (lowest val loss) kept at: {best_save_path}")# Export Hugging Face safetensors formatsafetensors_path = os.path.join(output_dir, "model.safetensors")try:44 unmodified lines)print(f" ✅ Uploaded {ckpt_filename} to ViuAI/ViuAI-500M (sft_checkpoints/{repo_subfolder}/)")if os.path.exists(safetensors_path):print(f" ⬆️ Uploading model.safetensors...")api.upload_file(20 unmodified lines21222324252627722 unmodified lines750751752753754755756199 unmodified lines9569579589599609619629639649659669679689699702 unmodified lines973974975976977978979132 unmodified lines11121113111411151116111711181119112063 unmodified lines118411851186118711881189119011911192119311941195119611971198119912001201120243 unmodified lines12461247124812491250125112527 unmodified lines126012611262126312641265126612671268126912702 unmodified lines1273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133792 unmodified lines143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146633 unmodified lines15001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153544 unmodified lines1580158115821583158415851586158715881589159015911592159315941595159620 unmodified linesimport shutilimport argparseimport contextlibfrom functools import partialfrom datetime import timedeltaimport numpy as npimport torch722 unmodified linesparser.add_argument("--min_lr", type=float, default=2.0e-6, help="Minimum learning rate")parser.add_argument("--weight_decay", type=float, default=0.01, help="AdamW weight decay")parser.add_argument("--warmup_ratio", type=float, default=0.04, help="Warmup ratio of total steps")parser.add_argument("--neftune_alpha", type=float, default=5.0, help="NEFTune noise scale for SFT quality (Default: 5.0)")parser.add_argument("--eval_interval", type=int, default=1000, help="Validation evaluation step interval (Default: 1000)")parser.add_argument("--disable_checkpointing", action="store_true", default=False, help="Disable activation checkpointing for 30-40%% faster training on GPUs with >= 24GB VRAM")parser.add_argument("--compile", action="store_true", default=False, help="Enable PyTorch 2.0 torch.compile for maximum speed")199 unmodified lines)train_sampler = LengthGroupedBatchSampler(train_dataset, batch_size=micro_b, rank=RANK, world_size=WORLD_SIZE, shuffle=True, seed=args.seed)val_sampler = LengthGroupedBatchSampler(val_dataset, batch_size=micro_b, rank=RANK, world_size=WORLD_SIZE, shuffle=False)collate_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,2 unmodified linesval_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)132 unmodified linesresumed_step = global_step# Mixed Precision Setup & GradScaleruse_fp16 = torch.cuda.is_available() and (hw["dtype"] == torch.float16)scaler = torch.amp.GradScaler("cuda", enabled=use_fp16)if torch.cuda.is_available():autocast_ctx = torch.amp.autocast(device_type="cuda", dtype=hw["dtype"])else:63 unmodified linestotal_val_loss += batch_loss_sumval_tokens += batch_activeif IS_DDP:val_stats = torch.tensor([total_val_loss, float(val_tokens)], dtype=torch.float64, device=device)dist.all_reduce(val_stats, op=dist.ReduceOp.SUM)total_val_loss = val_stats[0].item()val_tokens = int(val_stats[1].item())for d_id in domain_loss_sum:d_stats = torch.tensor([domain_loss_sum[d_id], float(domain_token_cnt[d_id])], dtype=torch.float64, device=device)dist.all_reduce(d_stats, op=dist.ReduceOp.SUM)domain_loss_sum[d_id] = d_stats[0].item()domain_token_cnt[d_id] = int(d_stats[1].item())model.train()avg_loss = total_val_loss / max(1, val_tokens)ppl = math.exp(min(avg_loss, 20.0))43 unmodified linesepoch_loss = 0.0epoch_batches = 0accum_loss = 0.0step_active_tokens = 0optimizer.zero_grad(set_to_none=True)7 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:continuetotal_tokens_trained += active_tokens_countis_accumulating = ((micro_idx + 1) % grad_acc != 0) and ((micro_idx + 1) < total_micro_batches)2 unmodified lineswith 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 += 1if (micro_idx + 1) % grad_acc == 0 or (micro_idx + 1) == total_micro_batches:if step_active_tokens > 0:if IS_DDP:tok_tensor = torch.tensor([step_active_tokens], dtype=torch.float64, device=device)dist.all_reduce(tok_tensor, op=dist.ReduceOp.SUM)norm_tokens = max(1.0, tok_tensor.item() / WORLD_SIZE)else:norm_tokens = max(1.0, float(step_active_tokens))scale_factor = 1024.0 / norm_tokensif scaler.is_enabled():scaler.unscale_(optimizer)for p in model.parameters():if p.grad is not None:p.grad.mul_(scale_factor)grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)# Anomaly Protection: Protect against NaN/Inf gradient explosionif torch.isnan(grad_norm) or torch.isinf(grad_norm):if IS_MAIN:print(f"⚠️ Anomaly Shield: NaN/Inf grad norm detected at step {global_step}! Skipping step...")optimizer.zero_grad(set_to_none=True)if scaler.is_enabled():scaler.update()step_active_tokens = 0accum_loss = 0.0continuelr = get_lr(global_step, warmup_steps, total_steps, args.max_lr, args.min_lr)for param_group in optimizer.param_groups:param_group["lr"] = lrif scaler.is_enabled():scaler.step(optimizer)scaler.update()else:optimizer.step()optimizer.zero_grad(set_to_none=True)global_step += 1step_avg_loss = accum_loss / max(1.0, float(step_active_tokens))step_active_tokens = 0accum_loss = 0.0if global_step % 10 == 0 or global_step == 1 or global_step == (resumed_step + 1):cur_time = time.time()92 unmodified linesdist.barrier()# End of Epoch Handlingif epoch_batches > 0 and (micro_idx + 1) % grad_acc != 0 and step_active_tokens > 0:if IS_DDP:tok_tensor = torch.tensor([step_active_tokens], dtype=torch.float64, device=device)dist.all_reduce(tok_tensor, op=dist.ReduceOp.SUM)norm_tokens = max(1.0, tok_tensor.item() / WORLD_SIZE)else:norm_tokens = max(1.0, float(step_active_tokens))scale_factor = 1024.0 / norm_tokensif scaler.is_enabled():scaler.unscale_(optimizer)for p in model.parameters():if p.grad is not None:p.grad.mul_(scale_factor)torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)lr = get_lr(global_step, warmup_steps, total_steps, args.max_lr, args.min_lr)for param_group in optimizer.param_groups:param_group["lr"] = lrif scaler.is_enabled():scaler.step(optimizer)scaler.update()else:optimizer.step()optimizer.zero_grad(set_to_none=True)global_step += 1step_active_tokens = 0accum_loss = 0.0if epoch_batches == 0:33 unmodified linesif os.path.exists(best_save_path):print(f"🏆 Best checkpoint (lowest val loss) kept at: {best_save_path}")# Checkpoint Weight Averaging ("Model Soup": 0.5 * W_best + 0.5 * W_final)if os.path.exists(best_save_path) and os.path.exists(save_path) and (best_save_path != save_path):try:print("\n🍲 Generating Post-Training Model Soup (0.5 * W_best + 0.5 * W_final)...")best_ckpt = torch.load(best_save_path, map_location="cpu", weights_only=False)final_ckpt = torch.load(save_path, map_location="cpu", weights_only=False)best_sd = best_ckpt.get("model_state_dict", best_ckpt.get("model", {}))final_sd = final_ckpt.get("model_state_dict", final_ckpt.get("model", {}))soup_sd = {}for k in final_sd.keys():if k in best_sd and hasattr(final_sd[k], "dtype") and final_sd[k].dtype.is_floating_point:soup_sd[k] = (0.5 * best_sd[k].float() + 0.5 * final_sd[k].float()).to(final_sd[k].dtype)else:soup_sd[k] = final_sd[k]soup_filename = f"{ckpt_tag}_soup.pt"soup_save_path = os.path.join(output_dir, soup_filename)soup_payload = dict(final_payload)soup_payload["model_state_dict"] = soup_sdsoup_payload["model_soup"] = Truetorch.save(soup_payload, soup_save_path)print(f"✅ Saved Model Soup checkpoint -> {soup_save_path}")# Load soup into model for final evaluation and benchmarkraw_model.load_state_dict(soup_sd)print("🌟 Loaded Model Soup weights for final benchmark and export!")except Exception as e:print(f"⚠️ Model Soup generation skipped: {e}")# Export Hugging Face safetensors formatsafetensors_path = os.path.join(output_dir, "model.safetensors")try:44 unmodified lines)print(f" ✅ Uploaded {ckpt_filename} to ViuAI/ViuAI-500M (sft_checkpoints/{repo_subfolder}/)")soup_save_path = os.path.join(output_dir, f"{ckpt_tag}_soup.pt")if os.path.exists(soup_save_path):print(f" ⬆️ Uploading model soup checkpoint {ckpt_tag}_soup.pt...")api.upload_file(path_or_fileobj=soup_save_path,path_in_repo=f"sft_checkpoints/{repo_subfolder}/{ckpt_tag}_soup.pt",repo_id="ViuAI/ViuAI-500M",repo_type="model")print(f" ✅ Uploaded {ckpt_tag}_soup.pt to ViuAI/ViuAI-500M")if os.path.exists(safetensors_path):print(f" ⬆️ Uploading model.safetensors...")api.upload_file(
code/train_sft.py+148-31