Upload train_hf.py with huggingface_hub
Browse files- train_hf.py +98 -0
train_hf.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = ["torch", "transformers==5.23.0", "peft", "kernels", "accelerate", "huggingface_hub"]
|
| 4 |
+
# ///
|
| 5 |
+
"""F1 on HF Jobs: LoRA SFT of gpt-oss-20b on sft.py --render-url output (loss on assistant turns only).
|
| 6 |
+
|
| 7 |
+
hf jobs uv run --flavor h200 --timeout 2h --secrets HF_TOKEN \\
|
| 8 |
+
-e DATA=<user>/bashattack-sft -e OUT=<user>/gpt-oss-20b-bashattack-lora train_hf.py
|
| 9 |
+
(-e SMOKE=1: one step on the 2 longest sequences -- checks memory, kernels and the push)
|
| 10 |
+
|
| 11 |
+
Plain loop, not trl: the data is already tokenized with loss spans (verified locally in sft.py),
|
| 12 |
+
so all that's left is masking, a token-weighted loss and AdamW.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import math
|
| 17 |
+
import os
|
| 18 |
+
import random
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 24 |
+
from peft import LoraConfig, get_peft_model
|
| 25 |
+
from torch.utils.checkpoint import checkpoint
|
| 26 |
+
from transformers import AutoModelForCausalLM, Mxfp4Config
|
| 27 |
+
|
| 28 |
+
DATA, OUT, SMOKE = os.environ["DATA"], os.environ["OUT"], bool(os.environ.get("SMOKE"))
|
| 29 |
+
EPOCHS, ACCUM, LR = 2, 8, 2e-4
|
| 30 |
+
|
| 31 |
+
rows = [json.loads(l) for l in open(hf_hub_download(DATA, "train_rows.jsonl", repo_type="dataset"))]
|
| 32 |
+
if SMOKE:
|
| 33 |
+
rows, EPOCHS, ACCUM = sorted(rows, key=lambda r: -len(r["input_ids"]))[:2], 1, 2
|
| 34 |
+
print(f"{len(rows)} sequences, {sum(len(r['input_ids']) for r in rows)} tokens", flush=True)
|
| 35 |
+
|
| 36 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 37 |
+
"openai/gpt-oss-20b",
|
| 38 |
+
quantization_config=Mxfp4Config(dequantize=True), # train LoRA on bf16 weights (as OpenAI's recipe)
|
| 39 |
+
dtype=torch.bfloat16,
|
| 40 |
+
attn_implementation="kernels-community/vllm-flash-attn3", # attention sinks; eager is O(n^2) memory
|
| 41 |
+
device_map="cuda",
|
| 42 |
+
use_cache=False,
|
| 43 |
+
)
|
| 44 |
+
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
|
| 45 |
+
model.enable_input_require_grads()
|
| 46 |
+
# ponytail: attention-only LoRA -- vLLM serves it on the MXFP4 base without expert-LoRA support
|
| 47 |
+
model = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]))
|
| 48 |
+
model.print_trainable_parameters()
|
| 49 |
+
inner = model.base_model.model # GptOssForCausalLM, LoRA layers injected in place
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def loss_sum(r):
|
| 53 |
+
"""Summed CE over the loss spans. lm_head runs only on those positions, in checkpointed chunks:
|
| 54 |
+
full 47k x 201k-vocab logits would be ~38 GB."""
|
| 55 |
+
ids = torch.tensor([r["input_ids"]], device="cuda")
|
| 56 |
+
h = inner.model(input_ids=ids).last_hidden_state[0, :-1]
|
| 57 |
+
pos = torch.tensor([p for a, b in r["loss_spans"] for p in range(a - 1, b - 1)], device="cuda")
|
| 58 |
+
h, y = h[pos], ids[0, pos + 1]
|
| 59 |
+
ce = lambda h, y: F.cross_entropy(inner.lm_head(h).float(), y, reduction="sum")
|
| 60 |
+
return sum(checkpoint(ce, h[i : i + 4096], y[i : i + 4096], use_reentrant=False) for i in range(0, len(y), 4096))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
params = [p for p in model.parameters() if p.requires_grad]
|
| 64 |
+
opt = torch.optim.AdamW(params, lr=LR, weight_decay=0.0)
|
| 65 |
+
steps = EPOCHS * math.ceil(len(rows) / ACCUM)
|
| 66 |
+
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1, (s + 1) / 5) * 0.5 * (1 + math.cos(math.pi * s / steps)))
|
| 67 |
+
api = HfApi()
|
| 68 |
+
api.create_repo(OUT, private=True, exist_ok=True) # attack adapter: private, never public
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def push(msg):
|
| 72 |
+
model.save_pretrained("adapter")
|
| 73 |
+
api.upload_folder(folder_path="adapter", repo_id=OUT, commit_message=msg)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
step, t0, seen = 0, time.time(), 0
|
| 77 |
+
model.train()
|
| 78 |
+
for epoch in range(EPOCHS):
|
| 79 |
+
random.Random(epoch).shuffle(rows)
|
| 80 |
+
for g in range(0, len(rows), ACCUM):
|
| 81 |
+
group = rows[g : g + ACCUM]
|
| 82 |
+
n = sum(b - a for r in group for a, b in r["loss_spans"]) # token-weighted mean over the group
|
| 83 |
+
total = 0.0
|
| 84 |
+
for r in group:
|
| 85 |
+
loss = loss_sum(r) / n
|
| 86 |
+
loss.backward()
|
| 87 |
+
total += loss.item()
|
| 88 |
+
seen += len(r["input_ids"])
|
| 89 |
+
torch.nn.utils.clip_grad_norm_(params, 1.0)
|
| 90 |
+
opt.step(), sched.step(), opt.zero_grad(set_to_none=True)
|
| 91 |
+
step += 1
|
| 92 |
+
print(
|
| 93 |
+
f"epoch {epoch} step {step}/{steps} loss {total:.4f} lr {sched.get_last_lr()[0]:.2e} "
|
| 94 |
+
f"tok/s {seen / (time.time() - t0):.0f} mem {torch.cuda.max_memory_allocated() / 2**30:.1f}G",
|
| 95 |
+
flush=True,
|
| 96 |
+
)
|
| 97 |
+
push(f"epoch {epoch + 1}/{EPOCHS}" + (" (smoke)" if SMOKE else ""))
|
| 98 |
+
print("done", flush=True)
|