scripts: add scripts/train_sft_completion_only.py
Browse files
scripts/train_sft_completion_only.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SFT trainer with COMPLETION-ONLY loss (per MATS paper §3.6).
|
| 3 |
+
Handles HF datasets with 'prompt' + 'completion' columns.
|
| 4 |
+
Uses Qwen chat template; masks prompt tokens with -100 in labels.
|
| 5 |
+
"""
|
| 6 |
+
import argparse, os
|
| 7 |
+
os.environ.setdefault("PYTHONNOUSERSITE", "1")
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from datasets import load_from_disk
|
| 11 |
+
from transformers import (
|
| 12 |
+
AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments,
|
| 13 |
+
DataCollatorForSeq2Seq,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
CHAT_TEMPLATES = {
|
| 18 |
+
"qwen": {
|
| 19 |
+
"user_head": "<|im_start|>user\n",
|
| 20 |
+
"user_tail": "<|im_end|>\n",
|
| 21 |
+
"asst_head": "<|im_start|>assistant\n",
|
| 22 |
+
"asst_tail": "<|im_end|>",
|
| 23 |
+
},
|
| 24 |
+
"llama3": {
|
| 25 |
+
"user_head": "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n",
|
| 26 |
+
"user_tail": "<|eot_id|>",
|
| 27 |
+
"asst_head": "<|start_header_id|>assistant<|end_header_id|>\n\n",
|
| 28 |
+
"asst_tail": "<|eot_id|>",
|
| 29 |
+
},
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main():
|
| 34 |
+
p = argparse.ArgumentParser()
|
| 35 |
+
p.add_argument("--base", required=True)
|
| 36 |
+
p.add_argument("--data", required=True)
|
| 37 |
+
p.add_argument("--out", required=True)
|
| 38 |
+
p.add_argument("--epochs", type=float, default=4.0)
|
| 39 |
+
p.add_argument("--lr", type=float, default=2e-5)
|
| 40 |
+
p.add_argument("--bs", type=int, default=1)
|
| 41 |
+
p.add_argument("--grad_accum", type=int, default=16)
|
| 42 |
+
p.add_argument("--max_len", type=int, default=6144)
|
| 43 |
+
p.add_argument("--warmup", type=float, default=0.05)
|
| 44 |
+
p.add_argument("--chat_format", default="qwen", choices=["qwen", "llama3"])
|
| 45 |
+
args = p.parse_args()
|
| 46 |
+
|
| 47 |
+
print(f"loading base={args.base}", flush=True)
|
| 48 |
+
tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True,
|
| 49 |
+
cache_dir="/weka/s225250685/Huggingface/hub")
|
| 50 |
+
if tok.pad_token is None:
|
| 51 |
+
tok.pad_token = tok.eos_token
|
| 52 |
+
|
| 53 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 54 |
+
args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
|
| 55 |
+
attn_implementation="sdpa",
|
| 56 |
+
cache_dir="/weka/s225250685/Huggingface/hub",
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
print(f"loading data={args.data}", flush=True)
|
| 60 |
+
dd = load_from_disk(args.data)
|
| 61 |
+
print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
|
| 62 |
+
|
| 63 |
+
tpl = CHAT_TEMPLATES[args.chat_format]
|
| 64 |
+
USER_HEAD = tpl["user_head"]
|
| 65 |
+
USER_TAIL = tpl["user_tail"]
|
| 66 |
+
ASSISTANT_HEAD = tpl["asst_head"]
|
| 67 |
+
ASSISTANT_TAIL = tpl["asst_tail"]
|
| 68 |
+
print(f"chat_format={args.chat_format}", flush=True)
|
| 69 |
+
|
| 70 |
+
def encode(ex):
|
| 71 |
+
prompt_text = f"{USER_HEAD}{ex['prompt']}{USER_TAIL}{ASSISTANT_HEAD}"
|
| 72 |
+
completion_text = f"{ex['completion']}{ASSISTANT_TAIL}"
|
| 73 |
+
full_text = prompt_text + completion_text
|
| 74 |
+
|
| 75 |
+
# Tokenize full
|
| 76 |
+
full_ids = tok(full_text, truncation=True, max_length=args.max_len,
|
| 77 |
+
padding=False, add_special_tokens=False)["input_ids"]
|
| 78 |
+
# Tokenize prompt-only (to find length for label masking)
|
| 79 |
+
prompt_ids = tok(prompt_text, truncation=True, max_length=args.max_len,
|
| 80 |
+
padding=False, add_special_tokens=False)["input_ids"]
|
| 81 |
+
prompt_len = len(prompt_ids)
|
| 82 |
+
|
| 83 |
+
# Build labels: -100 for prompt, real ids for completion
|
| 84 |
+
labels = [-100] * prompt_len + full_ids[prompt_len:]
|
| 85 |
+
labels = labels[:len(full_ids)]
|
| 86 |
+
attention = [1] * len(full_ids)
|
| 87 |
+
|
| 88 |
+
return {"input_ids": full_ids, "attention_mask": attention, "labels": labels}
|
| 89 |
+
|
| 90 |
+
print("Tokenizing...", flush=True)
|
| 91 |
+
train_ds = dd["train"].map(encode, remove_columns=dd["train"].column_names, num_proc=4)
|
| 92 |
+
eval_ds = dd["test"].map(encode, remove_columns=dd["test"].column_names, num_proc=4)
|
| 93 |
+
|
| 94 |
+
# DataCollatorForSeq2Seq pads input_ids with pad_token and labels with -100
|
| 95 |
+
collator = DataCollatorForSeq2Seq(tok, padding=True, label_pad_token_id=-100)
|
| 96 |
+
|
| 97 |
+
targs = TrainingArguments(
|
| 98 |
+
output_dir=args.out,
|
| 99 |
+
num_train_epochs=args.epochs,
|
| 100 |
+
per_device_train_batch_size=args.bs,
|
| 101 |
+
per_device_eval_batch_size=args.bs,
|
| 102 |
+
gradient_accumulation_steps=args.grad_accum,
|
| 103 |
+
learning_rate=args.lr,
|
| 104 |
+
warmup_ratio=args.warmup,
|
| 105 |
+
lr_scheduler_type="cosine",
|
| 106 |
+
bf16=True,
|
| 107 |
+
logging_steps=20,
|
| 108 |
+
save_strategy="epoch",
|
| 109 |
+
eval_strategy="epoch",
|
| 110 |
+
save_total_limit=1,
|
| 111 |
+
report_to=[],
|
| 112 |
+
gradient_checkpointing=True,
|
| 113 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 114 |
+
remove_unused_columns=False,
|
| 115 |
+
dataloader_num_workers=2,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
trainer = Trainer(
|
| 119 |
+
model=model, args=targs,
|
| 120 |
+
train_dataset=train_ds, eval_dataset=eval_ds,
|
| 121 |
+
tokenizer=tok, data_collator=collator,
|
| 122 |
+
)
|
| 123 |
+
trainer.train()
|
| 124 |
+
trainer.save_model(args.out)
|
| 125 |
+
tok.save_pretrained(args.out)
|
| 126 |
+
print(f"SAVED: {args.out}", flush=True)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
main()
|