Download kaggle/director_lora_train.py from idefinity/webfm-eval: direct link, hf CLI and curl.
- Browser
- Download file 16.7 kB
-
https://huggingface.co/datasets/idefinity/webfm-eval/resolve/main/kaggle/director_lora_train.py
- Command line
-
hf download hf://datasets/idefinity/webfm-eval/kaggle/director_lora_train.py
-
curl -L -o director_lora_train.py https://huggingface.co/datasets/idefinity/webfm-eval/resolve/main/kaggle/director_lora_train.py
16.7 kB
| """Director LoRA, conservative configuration. | |
| Qwen3.5-0.8B ships as a VLM checkpoint (Qwen3_5ForConditionalGeneration): | |
| its tensors are named `model.language_model.*`, with `model.visual.*` and | |
| `mtp.*` alongside. The browser runs the text-only decoder, so we build | |
| Qwen3_5ForCausalLM from `config.text_config` and load the checkpoint with an | |
| explicit prefix rewrite. Relying on AutoModelForCausalLM.from_pretrained() is | |
| not safe here: transformers 5.x has no `model.language_model.* -> model.*` | |
| key conversion, so a plain load can silently leave the decoder randomly | |
| initialised (warning only, training still "works", output is garbage). | |
| LoRA goes on the MLP of all 24 layers and the q/k/v/o projections of the 6 | |
| full-attention layers. Nothing in `linear_attn` is touched: those projections | |
| feed a recurrent scan, and conv1d/A_log/dt_bias are not plain Linears. | |
| Runs in a fresh interpreter with transformers 5.x. The browser never loads | |
| this adapter: merge_and_unload() writes a plain fp16 checkpoint for ONNX | |
| export. Because we started from the text-only class, that checkpoint has no | |
| vision tower and no MTP head already. | |
| """ | |
| import json | |
| import os | |
| import random | |
| import re | |
| import shutil | |
| import time | |
| from pathlib import Path | |
| ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working")) | |
| BUNDLE = Path(os.environ.get("BUNDLE", str(ROOT / "webfm-eval"))) | |
| # Deliberately NOT director/sft.jsonl: that path holds the old six-line radio | |
| # scripts, which use a different output protocol. | |
| DATA = Path(os.environ.get("DATA", str(ROOT / "director_lora" / "sft.jsonl"))) | |
| OUT = Path(os.environ.get("LORA_OUT", str(ROOT / "director_lora"))) | |
| MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B") | |
| DTYPE = os.environ.get("DTYPE", "auto") # auto -> fp16 on Turing, bf16 on Ampere+ | |
| R = int(os.environ.get("R", "16")) | |
| ALPHA = int(os.environ.get("ALPHA", "32")) | |
| DROPOUT = float(os.environ.get("DROPOUT", "0.05")) | |
| LR = float(os.environ.get("LR", "1e-4")) | |
| EPOCHS = int(os.environ.get("EPOCHS", "2")) | |
| ACCUM = int(os.environ.get("ACCUM", "4")) | |
| MAX_LEN = int(os.environ.get("MAX_LEN", "2048")) | |
| SEED = int(os.environ.get("SEED", "20261107")) | |
| GRAD_CKPT = os.environ.get("GRAD_CKPT", "0") == "1" | |
| # Wall-clock budget for the optimizer loop. The T4 has no causal_conv1d or | |
| # flash-linear-attention kernels, so Gated DeltaNet falls back to the slow | |
| # reference implementation. Stop and save a usable adapter rather than let | |
| # the notebook timeout throw away the whole run. | |
| MAX_TRAIN_SECONDS = int(os.environ.get("MAX_TRAIN_SECONDS", "4200")) | |
| # peft matches a list of target names against the last segment of a module key | |
| # (key == target or key.endswith("." + target)). Short names are portable across | |
| # peft versions; full module names are not. The text-only model has no visual | |
| # tower and no MTP head, so these cannot match anything unwanted. | |
| SHORT_TARGETS = ["gate_proj", "up_proj", "down_proj", | |
| "q_proj", "k_proj", "v_proj", "o_proj"] | |
| TARGET_RE = re.compile( | |
| r"(^|\.)layers\.\d+\.(" | |
| r"mlp\.(gate_proj|up_proj|down_proj)" | |
| r"|self_attn\.(q_proj|k_proj|v_proj|o_proj))$" | |
| ) | |
| EXCLUDE = ("mtp", "vision", "visual", "multi_modal", "linear_attn") | |
| THINK_TAIL = "<think>\n\n</think>\n\n" | |
| def log(msg: str) -> None: | |
| print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) | |
| def load_rows() -> list[dict]: | |
| path = DATA if DATA.exists() else BUNDLE / "director_lora" / "sft.jsonl" | |
| if not path.exists(): | |
| raise SystemExit(f"no training data at {DATA} or {path}") | |
| rows = [json.loads(l) for l in path.read_text(encoding="utf-8").splitlines() if l.strip()] | |
| log(f"{len(rows)} rows from {path}") | |
| if not rows: | |
| raise SystemExit("empty training set") | |
| return rows | |
| def pick_dtype(torch): | |
| if DTYPE in ("fp16", "float16"): | |
| return torch.float16 | |
| if DTYPE in ("bf16", "bfloat16"): | |
| return torch.bfloat16 | |
| if DTYPE in ("fp32", "float32"): | |
| return torch.float32 | |
| if DTYPE != "auto": | |
| raise SystemExit(f"unknown DTYPE={DTYPE}") | |
| return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 | |
| def build_text_model(torch, dtype): | |
| """Build the text-only decoder and load the VLM checkpoint by explicit key rewrite.""" | |
| from huggingface_hub import hf_hub_download | |
| from safetensors.torch import load_file | |
| from transformers import AutoConfig, AutoModelForCausalLM | |
| cfg = AutoConfig.from_pretrained(MODEL_ID) | |
| text_cfg = cfg.get_text_config() if hasattr(cfg, "get_text_config") else cfg.text_config | |
| log(f"config {type(cfg).__name__} -> {type(text_cfg).__name__} " | |
| f"(model_type={getattr(text_cfg, 'model_type', '?')}, " | |
| f"layers={getattr(text_cfg, 'num_hidden_layers', '?')})") | |
| if getattr(text_cfg, "model_type", "") != "qwen3_5_text": | |
| raise SystemExit("expected qwen3_5_text config; transformers version mismatch") | |
| model = AutoModelForCausalLM.from_config(text_cfg) | |
| model.to(dtype) | |
| log(f"built text-only {type(model).__name__} in {dtype}") | |
| index = Path(hf_hub_download(MODEL_ID, "model.safetensors.index.json")) | |
| shards = sorted(set(json.loads(index.read_text())["weight_map"].values())) | |
| log(f"checkpoint shards: {shards}") | |
| sd = {} | |
| for shard in shards: | |
| sd.update(load_file(hf_hub_download(MODEL_ID, shard))) | |
| log(f"read {len(sd)} tensors from checkpoint") | |
| mapped, skipped = {}, [] | |
| prefix = "model.language_model." | |
| for key, tensor in sd.items(): | |
| if key.startswith(prefix): | |
| mapped["model." + key[len(prefix):]] = tensor | |
| elif key == "lm_head.weight": | |
| mapped[key] = tensor | |
| else: | |
| skipped.append(key) | |
| log(f"mapped {len(mapped)} text tensors, skipped {len(skipped)} " | |
| f"({sum(1 for k in skipped if k.startswith('model.visual.'))} visual, " | |
| f"{sum(1 for k in skipped if k.startswith('mtp.'))} mtp)") | |
| if not any(k.startswith("model.layers.0.") for k in mapped): | |
| raise SystemExit(f"no language_model weights found; sample keys: {list(sd)[:6]}") | |
| missing, unexpected = model.load_state_dict( | |
| {k: v.to(dtype) for k, v in mapped.items()}, strict=False) | |
| real_missing = [k for k in missing if not k.startswith("lm_head")] | |
| log(f"load_state_dict: missing={len(missing)} (non-lm_head={len(real_missing)}), " | |
| f"unexpected={len(unexpected)}") | |
| if real_missing or unexpected: | |
| raise SystemExit(f"weight load incomplete: missing={missing[:8]} " | |
| f"unexpected={unexpected[:8]}") | |
| # lm_head is tied to embed_tokens. Some versions expose tie_weights(), | |
| # others only resolve _tied_weights_keys during from_pretrained(). | |
| try: | |
| model.tie_weights() | |
| except Exception as exc: | |
| log(f"tie_weights() unavailable ({exc}); tying manually") | |
| model.lm_head.weight = model.model.embed_tokens.weight | |
| # Hard check: the bytes we loaded must actually be in the model. A random | |
| # init would pass every shape check but fail this one. | |
| probe = "model.layers.0.mlp.gate_proj.weight" | |
| src = mapped[probe].to(dtype).float().cpu() | |
| dst = model.get_parameter(probe).detach().float().cpu() | |
| if not torch.equal(src, dst): | |
| raise SystemExit(f"weight integrity check failed for {probe}") | |
| log(f"weight integrity ok: {probe} mean={dst.mean():.6f} std={dst.std():.6f}") | |
| return model | |
| def smoke_generate(torch, model, tok, row) -> None: | |
| """Soft check: the untrained base must still speak Chinese, not emit noise.""" | |
| try: | |
| prompt = tok.apply_chat_template( | |
| row["messages"], tokenize=False, add_generation_prompt=True) | |
| ids = tok([prompt], return_tensors="pt").to("cuda") | |
| model.config.use_cache = True | |
| with torch.no_grad(): | |
| gen = model.generate(**ids, max_new_tokens=48, do_sample=False, | |
| eos_token_id=tok.eos_token_id, | |
| pad_token_id=tok.eos_token_id) | |
| out = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True) | |
| log("base sample: " + out[:200].replace("\n", " / ")) | |
| if not out.strip(): | |
| log("WARN: base generation returned empty text") | |
| except Exception as exc: | |
| log(f"WARN: base generation smoke failed ({type(exc).__name__}: {exc})") | |
| def encode(tok, row: dict, variant: int): | |
| import torch | |
| messages = row["messages"] | |
| if not messages or messages[-1]["role"] != "user": | |
| raise SystemExit("bad messages field in training row") | |
| prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| # The python template appends a closed <think> block; transformers.js may or | |
| # may not render the same tail. Train on both so the protocol is robust. | |
| if variant % 2 == 1 and prompt.endswith(THINK_TAIL): | |
| prompt = prompt[:-len(THINK_TAIL)] | |
| p_ids = tok(prompt, add_special_tokens=False)["input_ids"] | |
| t_ids = tok(row["response"], 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] | |
| if all(v == -100 for v in labels): | |
| return None | |
| return {"input_ids": torch.tensor([ids]), "labels": torch.tensor([labels])} | |
| def verify_targets(model, torch) -> None: | |
| try: | |
| from peft.tuners.lora import LoraLayer | |
| except ImportError: | |
| LoraLayer = None | |
| try: | |
| names = list(model.base_model.targeted_module_names) | |
| except AttributeError: | |
| names = [n for n, m in model.named_modules() | |
| if LoraLayer is not None and isinstance(m, LoraLayer)] | |
| bad = [n for n in names | |
| if not TARGET_RE.search(n) or any(x in n for x in EXCLUDE)] | |
| mlp = sum(1 for n in names if ".mlp." in n and "linear_attn" not in n) | |
| attn = len(names) - mlp | |
| log(f"peft adapted {len(names)} Linears ({mlp} MLP, {attn} self_attn), " | |
| f"out-of-scope {len(bad)}") | |
| if bad: | |
| log(f" first out-of-scope: {bad[:4]}") | |
| if len(names) != 96 or mlp != 72 or attn != 24 or bad: | |
| raise SystemExit("unexpected LoRA target set; refusing to train") | |
| def neutralize_torchao() -> None: | |
| """Kaggle ships torchao 0.10.0; peft 0.21.2 *raises* on torchao < 0.16 | |
| instead of treating it as absent. We never quantize here, so force the | |
| 'not installed' branch in both places that consult it. The notebook also | |
| uninstalls torchao; this is the belt-and-braces fallback. | |
| """ | |
| patched = [] | |
| for modname in ("peft.import_utils", "peft.tuners.lora.torchao"): | |
| try: | |
| mod = __import__(modname, fromlist=["is_torchao_available"]) | |
| except ImportError: | |
| continue | |
| if hasattr(mod, "is_torchao_available"): | |
| mod.is_torchao_available = lambda: False | |
| patched.append(modname) | |
| log(f"peft torchao dispatcher disabled in {patched}") | |
| def main() -> None: | |
| import torch | |
| from peft import LoraConfig, get_peft_model | |
| from transformers import AutoTokenizer | |
| import transformers | |
| log(f"transformers {transformers.__version__}, torch {torch.__version__}, " | |
| f"cuda {torch.version.cuda}, bf16_supported={torch.cuda.is_bf16_supported()}") | |
| if int(transformers.__version__.split(".")[0]) < 5: | |
| raise SystemExit("Qwen3.5 needs transformers >= 5; run in a fresh process") | |
| if not torch.cuda.is_available(): | |
| raise SystemExit("no CUDA device; check the notebook accelerator") | |
| random.seed(SEED) | |
| torch.manual_seed(SEED) | |
| rows = load_rows() | |
| dtype = pick_dtype(torch) | |
| log(f"training dtype {dtype}") | |
| tok = AutoTokenizer.from_pretrained(MODEL_ID) | |
| if not getattr(tok, "chat_template", None): | |
| raise SystemExit("tokenizer has no chat template; the browser applies one") | |
| log(f"eos={tok.eos_token_id} ({tok.decode([tok.eos_token_id])!r})") | |
| model = build_text_model(torch, dtype).to("cuda:0") | |
| smoke_generate(torch, model, tok, rows[0]) | |
| model.config.use_cache = False | |
| neutralize_torchao() | |
| cfg = LoraConfig(r=R, lora_alpha=ALPHA, lora_dropout=DROPOUT, bias="none", | |
| task_type="CAUSAL_LM", target_modules=SHORT_TARGETS) | |
| model = get_peft_model(model, cfg, autocast_adapter_dtype=True) | |
| verify_targets(model, torch) | |
| trainable = [p for p in model.parameters() if p.requires_grad] | |
| dtypes = {str(p.dtype) for p in trainable} | |
| log(f"trainable dtypes {dtypes}") | |
| if any(p.dtype != torch.float32 for p in trainable): | |
| log("casting adapter parameters to fp32 (fp16 AdamW underflows at lr=1e-4)") | |
| for p in trainable: | |
| p.data = p.data.float() | |
| n_train = sum(p.numel() for p in trainable) | |
| n_all = sum(p.numel() for p in model.parameters()) | |
| log(f"trainable {n_train/1e6:.2f}M / {n_all/1e6:.0f}M ({n_train/n_all:.2%})") | |
| encoded = [x for x in (encode(tok, row, i) for i, row in enumerate(rows)) | |
| if x is not None] | |
| log(f"encoded {len(encoded)} examples, max {max(x['input_ids'].shape[1] for x in encoded)} tokens") | |
| probe = tok.apply_chat_template(rows[0]["messages"], tokenize=False, | |
| add_generation_prompt=True) | |
| log(f"prompt tail variant A: {probe[-45:]!r}") | |
| if probe.endswith(THINK_TAIL): | |
| log(f"prompt tail variant B: {probe[:-len(THINK_TAIL)][-45:]!r}") | |
| if GRAD_CKPT: | |
| model.gradient_checkpointing_enable() | |
| model.enable_input_require_grads() | |
| opt = torch.optim.AdamW(trainable, lr=LR, betas=(0.9, 0.95), weight_decay=0.01) | |
| model.train() | |
| step, running, group, t0 = 0, 0.0, 0.0, time.time() | |
| budget_hit = False | |
| for epoch in range(EPOCHS): | |
| order = list(range(len(encoded))) | |
| random.shuffle(order) | |
| for i, idx in enumerate(order): | |
| if time.time() - t0 > MAX_TRAIN_SECONDS: | |
| log(f"time budget {MAX_TRAIN_SECONDS}s reached at epoch {epoch} " | |
| f"iter {i}/{len(order)}; saving what we have") | |
| budget_hit = True | |
| break | |
| batch = {k: v.cuda() for k, v in encoded[idx].items()} | |
| loss = model(**batch).loss / ACCUM | |
| loss.backward() | |
| group += loss.item() | |
| if (i + 1) % ACCUM == 0 or i + 1 == len(order): | |
| torch.nn.utils.clip_grad_norm_(trainable, 1.0) | |
| opt.step() | |
| opt.zero_grad(set_to_none=True) | |
| step += 1 | |
| running += group | |
| group = 0.0 | |
| if step % 25 == 0: | |
| log(f"epoch {epoch} step {step} loss {running/25:.4f} " | |
| f"({time.time()-t0:.0f}s)") | |
| running = 0.0 | |
| log(f"epoch {epoch} done ({time.time()-t0:.0f}s total)") | |
| if budget_hit: | |
| break | |
| opt.zero_grad(set_to_none=True) | |
| adapter = OUT / "adapter" | |
| adapter.mkdir(parents=True, exist_ok=True) | |
| model.save_pretrained(adapter) | |
| tok.save_pretrained(adapter) | |
| shutil.make_archive(str(OUT / "adapter"), "zip", str(adapter)) | |
| log(f"saved adapter -> {adapter} (+ adapter.zip)") | |
| merged = OUT / "model_fp16" | |
| merged.mkdir(parents=True, exist_ok=True) | |
| model = model.merge_and_unload() | |
| if GRAD_CKPT: | |
| model.gradient_checkpointing_disable() | |
| model.config.use_cache = True | |
| model.save_pretrained(merged, safe_serialization=True) | |
| tok.save_pretrained(merged) | |
| log(f"saved merged fp16 -> {merged} (text-only: no visual tower, no MTP head)") | |
| # Cheap sanity check: the merged model must still produce the protocol. | |
| model.eval() | |
| text = tok.apply_chat_template(rows[0]["messages"], tokenize=False, | |
| add_generation_prompt=True) | |
| ids = tok([text], return_tensors="pt").to("cuda") | |
| with torch.no_grad(): | |
| gen = model.generate(**ids, max_new_tokens=160, do_sample=False, | |
| eos_token_id=tok.eos_token_id, | |
| pad_token_id=tok.eos_token_id) | |
| out = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True) | |
| log("merged model sample:\n" + out[:400]) | |
| (OUT / "sample.txt").write_text(out, encoding="utf-8") | |
| (OUT / "train_meta.json").write_text(json.dumps({ | |
| "model": MODEL_ID, "transformers": transformers.__version__, | |
| "dtype": str(dtype), "rows": len(encoded), "epochs": EPOCHS, "lr": LR, | |
| "r": R, "alpha": ALPHA, "targets": len(SHORT_TARGETS), | |
| "trainable": n_train, "steps": step, "seconds": round(time.time() - t0), | |
| "budget_hit": budget_hit, "budget_seconds": MAX_TRAIN_SECONDS, | |
| }, indent=1), encoding="utf-8") | |
| log("done") | |
| if __name__ == "__main__": | |
| main() | |