Upload code/train_sft.py with huggingface_hub
Browse files239 unmodified lines240241242243244245246613 unmodified lines860861862863864865866867868869870871464 unmodified lines133613371338133913401341134237 unmodified lines13801381138213831384138513861387138813891390139113921393230 unmodified lines1624162516261627162816291630239 unmodified lines"desc": "CPU fallback mode"}props = torch.cuda.get_device_properties(0)device_name = props.namevram_gb = props.total_memory / (1024 ** 3)major, minor = props.major, props.minor613 unmodified lines# VRAM Safety Guardrail: Prevent OOM on 16GB / 12GB GPUs if user specified overly large micro_batchif torch.cuda.is_available() and hw["vram_gb"] < 24.0 and micro_b > 4:recommended_b = 4 if hw["vram_gb"] >= 14.0 else 2new_grad_acc = max(1, eff_batch // recommended_b)print(f"⚠️ VRAM Safety Guard: micro_batch={micro_b} is too large for {hw['vram_gb']:.1f}GB GPU ({hw['device_name']}).")print(f" Auto-adjusting to micro_batch={recommended_b} and grad_accum={new_grad_acc} (effective batch = {recommended_b * new_grad_acc}) to guarantee 0% OOM!")micro_b = recommended_bgrad_acc = new_grad_acceff_batch = micro_b * grad_accif os.path.exists(os.path.join(cur_dir, "tokenized_data")):root_dir = cur_dir464 unmodified linesskip_micro_batches = 0if resumed_step > 0 and epoch == start_epoch:skip_micro_batches = (resumed_step % steps_per_epoch) * grad_accif skip_micro_batches > 0:train_sampler.set_skip_batches(skip_micro_batches)if 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)37 unmodified linesepoch_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():230 unmodified linessafetensors_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:239 unmodified lines240241242243244245246247613 unmodified lines861862863864865866867868869870871872464 unmodified lines133713381339134013411342134337 unmodified lines1381138213831384138513861387138813891390139113921393139413951396230 unmodified lines1627162816291630163116321633239 unmodified lines"desc": "CPU fallback mode"}dev_idx = LOCAL_RANK if (torch.cuda.is_available() and LOCAL_RANK < torch.cuda.device_count()) else 0props = torch.cuda.get_device_properties(dev_idx)device_name = props.namevram_gb = props.total_memory / (1024 ** 3)major, minor = props.major, props.minor613 unmodified lines# VRAM Safety Guardrail: Prevent OOM on 16GB / 12GB GPUs if user specified overly large micro_batchif torch.cuda.is_available() and hw["vram_gb"] < 24.0 and micro_b > 4:recommended_b = 4 if hw["vram_gb"] >= 14.0 else 2new_grad_acc = max(1, (eff_batch // WORLD_SIZE) // recommended_b)print(f"⚠️ VRAM Safety Guard: micro_batch={micro_b} is too large for {hw['vram_gb']:.1f}GB GPU ({hw['device_name']}).")print(f" Auto-adjusting to micro_batch={recommended_b} and grad_accum={new_grad_acc} (effective batch = {recommended_b * new_grad_acc * WORLD_SIZE}) to guarantee 0% OOM!")micro_b = recommended_bgrad_acc = new_grad_acceff_batch = micro_b * grad_acc * WORLD_SIZEif os.path.exists(os.path.join(cur_dir, "tokenized_data")):root_dir = cur_dir464 unmodified linesskip_micro_batches = 0if resumed_step > 0 and epoch == start_epoch:skip_micro_batches = (resumed_step % steps_per_epoch) * grad_accif skip_micro_batches > 0 and skip_micro_batches < len(train_sampler):train_sampler.set_skip_batches(skip_micro_batches)if 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)37 unmodified linesepoch_batches += 1if (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:scale_factor = 1024.0 / norm_tokensif scaler.is_enabled():230 unmodified linessafetensors_path = os.path.join(output_dir, "model.safetensors")try:from safetensors.torch import save_fileclean_tensors = {k: v.detach().contiguous().cpu().clone() 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:
code/train_sft.py+16-13