"""Teach the 0.8B director the output contract, then score it. Zero-shot (and few-shot) the model gets the words right and the shape wrong: three of six samples stop after one line, and it writes the array as a single object with repeated keys. That is a formatting job, so it is worth a small fine-tune rather than more prompt engineering. Only the last few blocks and the head are trained. The base model already knows how to write Chinese; what it lacks is six lines of 8-40 characters in a fixed style order. Freezing the rest also keeps a 0.8B model training inside 15 GB. """ import json import os import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working")) OUT = ROOT / "director" MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B") TRAIN_LAYERS = int(os.environ.get("TRAIN_LAYERS", "6")) EPOCHS = int(os.environ.get("EPOCHS", "4")) LR = float(os.environ.get("LR", "1e-4")) ACCUM = int(os.environ.get("ACCUM", "4")) MAX_LEN = int(os.environ.get("MAX_LEN", "1024")) def log(msg: str) -> None: print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) def find_blocks(model): """Longest ModuleList of decoder blocks, whatever it is nested under.""" import torch.nn as nn best = (0, "", None) for name, mod in model.named_modules(): if isinstance(mod, nn.ModuleList) and len(mod) > best[0]: best = (len(mod), name, mod) if best[2] is None: raise RuntimeError("no decoder block list found") return best def build_example(tok, topic: str, lines: list[dict]) -> dict: import torch from director_probe import SLOT_MAX, SYSTEM, build_prompt, trim msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": build_prompt(topic)}] prompt = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) # The contract caps whisper lines at 18 characters; older collected scripts # predate that rule, so normalise the targets at build time. target = "\n".join(f"{l['style']}:{trim(l['text'], SLOT_MAX[i])}" for i, l in enumerate(lines)) p_ids = tok(prompt, add_special_tokens=False)["input_ids"] t_ids = tok(target, add_special_tokens=False)["input_ids"] + [tok.eos_token_id] ids = (p_ids + t_ids)[:MAX_LEN] labels = ([-100] * len(p_ids) + t_ids)[:MAX_LEN] return {"input_ids": torch.tensor([ids]), "labels": torch.tensor([labels])} def train(rows: list[dict]) -> str: import torch from transformers import AutoModelForCausalLM, AutoTokenizer from director_probe import build_prompt # noqa: F401 (import check) tok = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.float32, device_map="cuda:0") n_layers, lname, blocks = find_blocks(model) log(f"blocks: {lname} x{n_layers}; training the last {TRAIN_LAYERS}") for p in model.parameters(): p.requires_grad_(False) for blk in list(blocks)[-TRAIN_LAYERS:]: for p in blk.parameters(): p.requires_grad_(True) for name, p in model.named_parameters(): if name.endswith(("lm_head.weight", "norm.weight", "final_norm.weight")): p.requires_grad_(True) trainable = [p for p in model.parameters() if p.requires_grad] n_train = sum(p.numel() for p in trainable) log(f"trainable {n_train/1e6:.0f}M of {sum(p.numel() for p in model.parameters())/1e6:.0f}M") opt = torch.optim.AdamW(trainable, lr=LR, betas=(0.9, 0.95), weight_decay=0.01) model.train() step = 0 t0 = time.time() for epoch in range(EPOCHS): total = 0.0 for i, row in enumerate(rows): ex = build_example(tok, row["topic"], row["lines"]) loss = model(**{k: v.cuda() for k, v in ex.items()}).loss / ACCUM loss.backward() total += loss.item() if (i + 1) % ACCUM == 0: torch.nn.utils.clip_grad_norm_(trainable, 1.0) opt.step() opt.zero_grad(set_to_none=True) step += 1 if step % 10 == 0: log(f"epoch {epoch} step {step} loss {total/(i+1)*ACCUM:.4f} " f"({time.time()-t0:.0f}s)") log(f"epoch {epoch} done, mean loss {total/max(1,len(rows))*ACCUM:.4f}") opt.zero_grad(set_to_none=True) out = OUT / "model" out.mkdir(parents=True, exist_ok=True) model.half().save_pretrained(out) tok.save_pretrained(out) log(f"saved {out} ({sum(f.stat().st_size for f in out.glob('*'))/1e6:.0f} MB)") return str(out) def main() -> None: OUT.mkdir(parents=True, exist_ok=True) path = OUT / "sft.jsonl" if not path.exists(): # reuse a set collected by an earlier run path = ROOT / "webfm-eval" / "director" / "sft.jsonl" rows = [json.loads(l) for l in path.read_text().splitlines() if l.strip()] log(f"{len(rows)} training scripts from {path}") if not rows: raise SystemExit("no training data") train(rows) if __name__ == "__main__": main()