Fix DPO: disable activation checkpointing, add batch concatenation, and enable device_id in DDP
Browse files59 unmodified lines6061626364656683 unmodified lines15015115215315415515615715815916016116216316416516616716887 unmodified lines256257258259260261262118 unmodified lines38138238338438538638738838939039139239339439539639739839940040140240317 unmodified lines42142242342442542642742842943043143243343443543643743843944044144244344444544644726 unmodified lines47447547647747847948032 unmodified lines51351451551651751859 unmodified linesWORLD_SIZE = int(os.environ["WORLD_SIZE"])RANK = int(os.environ["RANK"])torch.cuda.set_device(LOCAL_RANK)dist.init_process_group("nccl")DEVICE = torch.device(f"cuda:{LOCAL_RANK}")IS_MAIN = (RANK == 0)else:83 unmodified lines}def dpo_collate_fn(batch):def pad_tensors(sequences, pad_val=None):if pad_val is None:pad_val = PAD_IDmax_len = max(len(seq) for seq in sequences)padded = torch.full((len(sequences), max_len), pad_val, dtype=torch.long)for i, seq in enumerate(sequences):padded[i, :len(seq)] = torch.tensor(seq, dtype=torch.long)return paddedchosen_ids = pad_tensors([b["chosen_input_ids"] for b in batch], PAD_ID)chosen_masks = pad_tensors([b["chosen_mask"] for b in batch], 0)rejected_ids = pad_tensors([b["rejected_input_ids"] for b in batch], PAD_ID)rejected_masks = pad_tensors([b["rejected_mask"] for b in batch], 0)return {"chosen_ids": chosen_ids,87 unmodified lines# Section 5: Model Initialization (Policy + Frozen Reference)# ==============================================================================def load_models(device, dtype):config = ViuAIConfig(vocab_size=64003, context_length=args.max_seq_len, use_checkpoint=True)ckpt_path = Noneif args.base_checkpoint:118 unmodified linesfor batch in val_loader:c_ids, c_mask = batch["chosen_ids"].to(DEVICE), batch["chosen_mask"].to(DEVICE)r_ids, r_mask = batch["rejected_ids"].to(DEVICE), batch["rejected_mask"].to(DEVICE)with torch.autocast(device_type=DEVICE.type, dtype=dtype):ref_c_logits = ref_model(c_ids, pad_id=PAD_ID)[0]ref_c_logps = get_batch_logps(ref_c_logits, c_ids, c_mask)del ref_c_logitsref_r_logits = ref_model(r_ids, pad_id=PAD_ID)[0]ref_r_logps = get_batch_logps(ref_r_logits, r_ids, r_mask)del ref_r_logitsp_c_logits = policy_model(c_ids, pad_id=PAD_ID)[0]p_c_logps = get_batch_logps(p_c_logits, c_ids, c_mask)del p_c_logitsp_r_logits = policy_model(r_ids, pad_id=PAD_ID)[0]p_r_logps = get_batch_logps(p_r_logits, r_ids, r_mask)del p_r_logitsloss, acc, margin, _ = compute_dpo_loss(p_c_logps, p_r_logps, ref_c_logps, ref_r_logps, args.beta)17 unmodified linesfor step, batch in enumerate(train_loader):c_ids, c_mask = batch["chosen_ids"].to(DEVICE), batch["chosen_mask"].to(DEVICE)r_ids, r_mask = batch["rejected_ids"].to(DEVICE), batch["rejected_mask"].to(DEVICE)with torch.autocast(device_type=DEVICE.type, dtype=dtype):with torch.no_grad():ref_c_logits = ref_model(c_ids, pad_id=PAD_ID)[0]ref_c_logps = get_batch_logps(ref_c_logits, c_ids, c_mask)del ref_c_logitsref_r_logits = ref_model(r_ids, pad_id=PAD_ID)[0]ref_r_logps = get_batch_logps(ref_r_logits, r_ids, r_mask)del ref_r_logitsp_c_logits = policy_model(c_ids, pad_id=PAD_ID)[0]p_c_logps = get_batch_logps(p_c_logits, c_ids, c_mask)p_r_logits = policy_model(r_ids, pad_id=PAD_ID)[0]p_r_logps = get_batch_logps(p_r_logits, r_ids, r_mask)del p_r_logitsdpo_loss, acc, margin, _ = compute_dpo_loss(p_c_logps, p_r_logps, ref_c_logps, ref_r_logps, args.beta)sft_loss = compute_sft_loss(p_c_logits, c_ids, c_mask) if args.sft_weight > 0 else torch.tensor(0.0, device=DEVICE)del p_c_logitstotal_loss = dpo_loss + args.sft_weight * sft_lossscaled_loss = total_loss / args.grad_accum26 unmodified linesif val_acc >= best_val_acc:best_val_acc = val_accsave_p = os.path.join(CKPT_DIR, f"dpo_{args.version}_final.pt")state = policy_model.module.state_dict() if hasattr(policy_model, "module") else policy_model.state_dict()torch.save({"model_state_dict": state,32 unmodified linesrepo_type="model",commit_message=f"Upload final DPO {args.version} aligned model")print("✅ Successfully uploaded to Hugging Face!")if IS_DDP:59 unmodified lines6061626364656683 unmodified lines15015115215315415515615715815916016116216316416516616716816917017117217387 unmodified lines261262263264265266267118 unmodified lines38638738838939039139239339439539639739839940040140240340417 unmodified lines42242342442542642742842943043143243343443543643743843944044144244344444544644744826 unmodified lines47547647747847948048132 unmodified lines51451551651751851952052152252352452552652752859 unmodified linesWORLD_SIZE = int(os.environ["WORLD_SIZE"])RANK = int(os.environ["RANK"])torch.cuda.set_device(LOCAL_RANK)dist.init_process_group("nccl", device_id=torch.device(f"cuda:{LOCAL_RANK}"))DEVICE = torch.device(f"cuda:{LOCAL_RANK}")IS_MAIN = (RANK == 0)else:83 unmodified lines}def dpo_collate_fn(batch):def pad_tensors(sequences, max_len, pad_val=None):if pad_val is None:pad_val = PAD_IDpadded = torch.full((len(sequences), max_len), pad_val, dtype=torch.long)for i, seq in enumerate(sequences):trunc = seq[:max_len]padded[i, :len(trunc)] = torch.tensor(trunc, dtype=torch.long)return paddedall_c_seqs = [b["chosen_input_ids"] for b in batch]all_r_seqs = [b["rejected_input_ids"] for b in batch]max_len = max(max(len(s) for s in all_c_seqs), max(len(s) for s in all_r_seqs))max_len = min(args.max_seq_len, max_len)chosen_ids = pad_tensors(all_c_seqs, max_len, PAD_ID)chosen_masks = pad_tensors([b["chosen_mask"] for b in batch], max_len, 0)rejected_ids = pad_tensors(all_r_seqs, max_len, PAD_ID)rejected_masks = pad_tensors([b["rejected_mask"] for b in batch], max_len, 0)return {"chosen_ids": chosen_ids,87 unmodified lines# Section 5: Model Initialization (Policy + Frozen Reference)# ==============================================================================def load_models(device, dtype):config = ViuAIConfig(vocab_size=64003, context_length=args.max_seq_len, use_checkpoint=False)ckpt_path = Noneif args.base_checkpoint:118 unmodified linesfor batch in val_loader:c_ids, c_mask = batch["chosen_ids"].to(DEVICE), batch["chosen_mask"].to(DEVICE)r_ids, r_mask = batch["rejected_ids"].to(DEVICE), batch["rejected_mask"].to(DEVICE)batch_ids = torch.cat([c_ids, r_ids], dim=0)batch_mask = torch.cat([c_mask, r_mask], dim=0)with torch.autocast(device_type=DEVICE.type, dtype=dtype):ref_logits = ref_model(batch_ids, pad_id=PAD_ID)[0]ref_logps = get_batch_logps(ref_logits, batch_ids, batch_mask)ref_c_logps, ref_r_logps = ref_logps.chunk(2, dim=0)del ref_logits, ref_logpsp_logits = policy_model(batch_ids, pad_id=PAD_ID)[0]p_logps = get_batch_logps(p_logits, batch_ids, batch_mask)p_c_logps, p_r_logps = p_logps.chunk(2, dim=0)del p_logits, p_logpsloss, acc, margin, _ = compute_dpo_loss(p_c_logps, p_r_logps, ref_c_logps, ref_r_logps, args.beta)17 unmodified linesfor step, batch in enumerate(train_loader):c_ids, c_mask = batch["chosen_ids"].to(DEVICE), batch["chosen_mask"].to(DEVICE)r_ids, r_mask = batch["rejected_ids"].to(DEVICE), batch["rejected_mask"].to(DEVICE)batch_ids = torch.cat([c_ids, r_ids], dim=0)batch_mask = torch.cat([c_mask, r_mask], dim=0)with torch.autocast(device_type=DEVICE.type, dtype=dtype):with torch.no_grad():ref_logits = ref_model(batch_ids, pad_id=PAD_ID)[0]ref_logps = get_batch_logps(ref_logits, batch_ids, batch_mask)ref_c_logps, ref_r_logps = ref_logps.chunk(2, dim=0)del ref_logits, ref_logpsp_logits = policy_model(batch_ids, pad_id=PAD_ID)[0]p_logps = get_batch_logps(p_logits, batch_ids, batch_mask)p_c_logps, p_r_logps = p_logps.chunk(2, dim=0)dpo_loss, acc, margin, _ = compute_dpo_loss(p_c_logps, p_r_logps, ref_c_logps, ref_r_logps, args.beta)if args.sft_weight > 0:chosen_logits = p_logits[:len(c_ids)]sft_loss = compute_sft_loss(chosen_logits, c_ids, c_mask)else:sft_loss = torch.tensor(0.0, device=DEVICE)del p_logits, p_logpstotal_loss = dpo_loss + args.sft_weight * sft_lossscaled_loss = total_loss / args.grad_accum26 unmodified linesif val_acc >= best_val_acc:best_val_acc = val_accsave_p = os.path.join(CKPT_DIR, f"dpo_{args.version}_best.pt")state = policy_model.module.state_dict() if hasattr(policy_model, "module") else policy_model.state_dict()torch.save({"model_state_dict": state,32 unmodified linesrepo_type="model",commit_message=f"Upload final DPO {args.version} aligned model")best_p = os.path.join(CKPT_DIR, f"dpo_{args.version}_best.pt")if os.path.exists(best_p):api.upload_file(path_or_fileobj=best_p,path_in_repo=f"dpo_checkpoints/dpo_{args.version}/dpo_{args.version}_best.pt",repo_id=MODEL_REPO,repo_type="model",commit_message=f"Upload best DPO {args.version} aligned model")print("✅ Successfully uploaded to Hugging Face!")if IS_DDP:
code/train_dpo.py+49-39