Add NaN/Inf anomaly shield, safetensors auto-export, and multi-GPU worker auto-tuning
Browse files797 unmodified lines798799800801802803804269 unmodified lines10741075107610771078107910801081138 unmodified lines12201221122212231224122520 unmodified lines124612471248124912501251797 unmodified linestrain_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(8, os.cpu_count() or 2)train_loader = DataLoader(train_dataset,batch_sampler=train_sampler,269 unmodified linesepoch_batches += 1if (micro_idx + 1) % grad_acc == 0 or (micro_idx + 1) == total_micro_batches: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"] = lr138 unmodified linesif os.path.exists(best_save_path):print(f"๐ Best checkpoint (lowest val loss) kept at: {best_save_path}")# Push to Hugging Face Hub (final checkpoint only)if args.push_to_hf:print("\n๐ Pushing Final Master Checkpoint to Hugging Face Model Hub (ViuAI/ViuAI-500M)...")20 unmodified lines)print(f" โ Uploaded {ckpt_filename} to ViuAI/ViuAI-500M (sft_checkpoints/{repo_subfolder}/)")if os.path.exists(best_save_path):print(f" โฌ๏ธ Uploading best checkpoint {best_filename}...")api.upload_file(797 unmodified lines798799800801802803804269 unmodified lines107410751076107710781079108010811082108310841085108610871088138 unmodified lines122712281229123012311232123312341235123612371238123912401241124220 unmodified lines1263126412651266126712681269127012711272127312741275127612771278797 unmodified linestrain_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,269 unmodified linesepoch_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"] = lr138 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:from safetensors.torch import save_fileclean_tensors = {k: v.contiguous().cpu() for k, v in raw_model.state_dict().items()}save_file(clean_tensors, safetensors_path)print(f"๐ฆ Hugging Face safetensors format saved to: {safetensors_path}")except Exception as e:print(f" Note: safetensors export skipped ({e})")# Push to Hugging Face Hub (final checkpoint only)if args.push_to_hf:print("\n๐ Pushing Final Master Checkpoint to Hugging Face Model Hub (ViuAI/ViuAI-500M)...")20 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(path_or_fileobj=safetensors_path,path_in_repo=f"sft_checkpoints/{repo_subfolder}/model.safetensors",repo_id="ViuAI/ViuAI-500M",repo_type="model")print(f" โ Uploaded model.safetensors to ViuAI/ViuAI-500M")if os.path.exists(best_save_path):print(f" โฌ๏ธ Uploading best checkpoint {best_filename}...")api.upload_file(
code/train_sft.py+29-2