File size: 4,320 Bytes
e7bc4cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# /// script
# requires-python = ">=3.11"
# dependencies = ["torch", "transformers==5.23.0", "peft", "kernels", "accelerate", "huggingface_hub"]
# ///
"""F1 on HF Jobs: LoRA SFT of gpt-oss-20b on sft.py --render-url output (loss on assistant turns only).

  hf jobs uv run --flavor h200 --timeout 2h --secrets HF_TOKEN \\
      -e DATA=<user>/bashattack-sft -e OUT=<user>/gpt-oss-20b-bashattack-lora train_hf.py
  (-e SMOKE=1: one step on the 2 longest sequences -- checks memory, kernels and the push)

Plain loop, not trl: the data is already tokenized with loss spans (verified locally in sft.py),
so all that's left is masking, a token-weighted loss and AdamW.
"""

import json
import math
import os
import random
import time

import torch
import torch.nn.functional as F
from huggingface_hub import HfApi, hf_hub_download
from peft import LoraConfig, get_peft_model
from torch.utils.checkpoint import checkpoint
from transformers import AutoModelForCausalLM, Mxfp4Config

DATA, OUT, SMOKE = os.environ["DATA"], os.environ["OUT"], bool(os.environ.get("SMOKE"))
EPOCHS, ACCUM, LR = 2, 8, 2e-4

rows = [json.loads(l) for l in open(hf_hub_download(DATA, "train_rows.jsonl", repo_type="dataset"))]
if SMOKE:
    rows, EPOCHS, ACCUM = sorted(rows, key=lambda r: -len(r["input_ids"]))[:2], 1, 2
print(f"{len(rows)} sequences, {sum(len(r['input_ids']) for r in rows)} tokens", flush=True)

model = AutoModelForCausalLM.from_pretrained(
    "openai/gpt-oss-20b",
    quantization_config=Mxfp4Config(dequantize=True),  # train LoRA on bf16 weights (as OpenAI's recipe)
    dtype=torch.bfloat16,
    attn_implementation="kernels-community/vllm-flash-attn3",  # attention sinks; eager is O(n^2) memory
    device_map="cuda",
    use_cache=False,
)
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
model.enable_input_require_grads()
# ponytail: attention-only LoRA -- vLLM serves it on the MXFP4 base without expert-LoRA support
model = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]))
model.print_trainable_parameters()
inner = model.base_model.model  # GptOssForCausalLM, LoRA layers injected in place


def loss_sum(r):
    """Summed CE over the loss spans. lm_head runs only on those positions, in checkpointed chunks:
    full 47k x 201k-vocab logits would be ~38 GB."""
    ids = torch.tensor([r["input_ids"]], device="cuda")
    h = inner.model(input_ids=ids).last_hidden_state[0, :-1]
    pos = torch.tensor([p for a, b in r["loss_spans"] for p in range(a - 1, b - 1)], device="cuda")
    h, y = h[pos], ids[0, pos + 1]
    ce = lambda h, y: F.cross_entropy(inner.lm_head(h).float(), y, reduction="sum")
    return sum(checkpoint(ce, h[i : i + 4096], y[i : i + 4096], use_reentrant=False) for i in range(0, len(y), 4096))


params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=LR, weight_decay=0.0)
steps = EPOCHS * math.ceil(len(rows) / ACCUM)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1, (s + 1) / 5) * 0.5 * (1 + math.cos(math.pi * s / steps)))
api = HfApi()
api.create_repo(OUT, private=True, exist_ok=True)  # attack adapter: private, never public


def push(msg):
    model.save_pretrained("adapter")
    api.upload_folder(folder_path="adapter", repo_id=OUT, commit_message=msg)


step, t0, seen = 0, time.time(), 0
model.train()
for epoch in range(EPOCHS):
    random.Random(epoch).shuffle(rows)
    for g in range(0, len(rows), ACCUM):
        group = rows[g : g + ACCUM]
        n = sum(b - a for r in group for a, b in r["loss_spans"])  # token-weighted mean over the group
        total = 0.0
        for r in group:
            loss = loss_sum(r) / n
            loss.backward()
            total += loss.item()
            seen += len(r["input_ids"])
        torch.nn.utils.clip_grad_norm_(params, 1.0)
        opt.step(), sched.step(), opt.zero_grad(set_to_none=True)
        step += 1
        print(
            f"epoch {epoch} step {step}/{steps} loss {total:.4f} lr {sched.get_last_lr()[0]:.2e} "
            f"tok/s {seen / (time.time() - t0):.0f} mem {torch.cuda.max_memory_allocated() / 2**30:.1f}G",
            flush=True,
        )
    push(f"epoch {epoch + 1}/{EPOCHS}" + (" (smoke)" if SMOKE else ""))
print("done", flush=True)