Upload kaggle/director_lora_train.py with huggingface_hub
Browse files- kaggle/director_lora_train.py +198 -53
kaggle/director_lora_train.py
CHANGED
|
@@ -1,23 +1,28 @@
|
|
| 1 |
"""Director LoRA, conservative configuration.
|
| 2 |
|
| 3 |
-
Qwen3.5-0.8B
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"""
|
| 17 |
import json
|
| 18 |
import os
|
| 19 |
import random
|
| 20 |
import re
|
|
|
|
| 21 |
import time
|
| 22 |
from pathlib import Path
|
| 23 |
|
|
@@ -28,6 +33,7 @@ BUNDLE = Path(os.environ.get("BUNDLE", str(ROOT / "webfm-eval")))
|
|
| 28 |
DATA = Path(os.environ.get("DATA", str(ROOT / "director_lora" / "sft.jsonl")))
|
| 29 |
OUT = Path(os.environ.get("LORA_OUT", str(ROOT / "director_lora")))
|
| 30 |
MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B")
|
|
|
|
| 31 |
R = int(os.environ.get("R", "16"))
|
| 32 |
ALPHA = int(os.environ.get("ALPHA", "32"))
|
| 33 |
DROPOUT = float(os.environ.get("DROPOUT", "0.05"))
|
|
@@ -38,12 +44,19 @@ MAX_LEN = int(os.environ.get("MAX_LEN", "2048"))
|
|
| 38 |
SEED = int(os.environ.get("SEED", "20261107"))
|
| 39 |
GRAD_CKPT = os.environ.get("GRAD_CKPT", "0") == "1"
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
TARGET_RE = re.compile(
|
| 42 |
r"(^|\.)layers\.\d+\.("
|
| 43 |
r"mlp\.(gate_proj|up_proj|down_proj)"
|
| 44 |
r"|self_attn\.(q_proj|k_proj|v_proj|o_proj))$"
|
| 45 |
)
|
| 46 |
-
EXCLUDE = ("mtp", "vision", "visual", "multi_modal")
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
def log(msg: str) -> None:
|
|
@@ -61,13 +74,117 @@ def load_rows() -> list[dict]:
|
|
| 61 |
return rows
|
| 62 |
|
| 63 |
|
| 64 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
import torch
|
| 66 |
|
| 67 |
messages = row["messages"]
|
| 68 |
if not messages or messages[-1]["role"] != "user":
|
| 69 |
raise SystemExit("bad messages field in training row")
|
| 70 |
prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
p_ids = tok(prompt, add_special_tokens=False)["input_ids"]
|
| 72 |
t_ids = tok(row["response"], add_special_tokens=False)["input_ids"] + [tok.eos_token_id]
|
| 73 |
ids = (p_ids + t_ids)[:MAX_LEN]
|
|
@@ -77,104 +194,131 @@ def encode(tok, row: dict):
|
|
| 77 |
return {"input_ids": torch.tensor([ids]), "labels": torch.tensor([labels])}
|
| 78 |
|
| 79 |
|
| 80 |
-
def
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
attn = len(names) - mlp
|
| 89 |
-
log(f"
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
| 93 |
|
| 94 |
|
| 95 |
def main() -> None:
|
| 96 |
import torch
|
| 97 |
from peft import LoraConfig, get_peft_model
|
| 98 |
-
from transformers import
|
| 99 |
|
| 100 |
import transformers
|
| 101 |
-
log(f"transformers {transformers.__version__}, torch {torch.__version__}"
|
|
|
|
| 102 |
if int(transformers.__version__.split(".")[0]) < 5:
|
| 103 |
raise SystemExit("Qwen3.5 needs transformers >= 5; run in a fresh process")
|
|
|
|
|
|
|
| 104 |
|
| 105 |
random.seed(SEED)
|
| 106 |
torch.manual_seed(SEED)
|
| 107 |
rows = load_rows()
|
|
|
|
|
|
|
| 108 |
|
| 109 |
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 110 |
if not getattr(tok, "chat_template", None):
|
| 111 |
raise SystemExit("tokenizer has no chat template; the browser applies one")
|
| 112 |
log(f"eos={tok.eos_token_id} ({tok.decode([tok.eos_token_id])!r})")
|
| 113 |
|
| 114 |
-
model =
|
| 115 |
-
|
| 116 |
model.config.use_cache = False
|
| 117 |
-
if GRAD_CKPT:
|
| 118 |
-
model.gradient_checkpointing_enable()
|
| 119 |
-
model.enable_input_require_grads()
|
| 120 |
|
| 121 |
-
targets = build_targets(model)
|
| 122 |
cfg = LoraConfig(r=R, lora_alpha=ALPHA, lora_dropout=DROPOUT, bias="none",
|
| 123 |
-
task_type="CAUSAL_LM", target_modules=
|
| 124 |
-
model = get_peft_model(model, cfg)
|
|
|
|
|
|
|
| 125 |
trainable = [p for p in model.parameters() if p.requires_grad]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
n_train = sum(p.numel() for p in trainable)
|
| 127 |
n_all = sum(p.numel() for p in model.parameters())
|
| 128 |
log(f"trainable {n_train/1e6:.2f}M / {n_all/1e6:.0f}M ({n_train/n_all:.2%})")
|
| 129 |
|
| 130 |
-
encoded = [x for x in (encode(tok, row) for row in rows)
|
|
|
|
| 131 |
log(f"encoded {len(encoded)} examples, max {max(x['input_ids'].shape[1] for x in encoded)} tokens")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
opt = torch.optim.AdamW(trainable, lr=LR, betas=(0.9, 0.95), weight_decay=0.01)
|
| 133 |
model.train()
|
| 134 |
-
step, running, t0 = 0, 0.0, time.time()
|
| 135 |
for epoch in range(EPOCHS):
|
| 136 |
order = list(range(len(encoded)))
|
| 137 |
random.shuffle(order)
|
| 138 |
-
total = 0.0
|
| 139 |
for i, idx in enumerate(order):
|
| 140 |
batch = {k: v.cuda() for k, v in encoded[idx].items()}
|
| 141 |
loss = model(**batch).loss / ACCUM
|
| 142 |
loss.backward()
|
| 143 |
-
|
| 144 |
if (i + 1) % ACCUM == 0 or i + 1 == len(order):
|
| 145 |
torch.nn.utils.clip_grad_norm_(trainable, 1.0)
|
| 146 |
opt.step()
|
| 147 |
opt.zero_grad(set_to_none=True)
|
| 148 |
step += 1
|
| 149 |
-
running +=
|
|
|
|
| 150 |
if step % 25 == 0:
|
| 151 |
-
log(f"epoch {epoch} step {step} loss {running/25:.4f}
|
|
|
|
| 152 |
running = 0.0
|
| 153 |
-
log(f"epoch {epoch}
|
| 154 |
opt.zero_grad(set_to_none=True)
|
| 155 |
|
| 156 |
adapter = OUT / "adapter"
|
| 157 |
adapter.mkdir(parents=True, exist_ok=True)
|
| 158 |
model.save_pretrained(adapter)
|
| 159 |
tok.save_pretrained(adapter)
|
| 160 |
-
|
|
|
|
| 161 |
|
| 162 |
merged = OUT / "model_fp16"
|
| 163 |
merged.mkdir(parents=True, exist_ok=True)
|
| 164 |
model = model.merge_and_unload()
|
| 165 |
-
# The ONNX export strips the vision tower and the MTP head; only the text
|
| 166 |
-
# decoder is shipped to the browser.
|
| 167 |
if GRAD_CKPT:
|
| 168 |
model.gradient_checkpointing_disable()
|
| 169 |
model.config.use_cache = True
|
| 170 |
model.save_pretrained(merged, safe_serialization=True)
|
| 171 |
tok.save_pretrained(merged)
|
| 172 |
-
log(f"saved merged fp16 -> {merged}")
|
| 173 |
|
| 174 |
# Cheap sanity check: the merged model must still produce the protocol.
|
| 175 |
model.eval()
|
| 176 |
-
|
| 177 |
-
|
| 178 |
ids = tok([text], return_tensors="pt").to("cuda")
|
| 179 |
with torch.no_grad():
|
| 180 |
gen = model.generate(**ids, max_new_tokens=160, do_sample=False,
|
|
@@ -184,9 +328,10 @@ def main() -> None:
|
|
| 184 |
log("merged model sample:\n" + out[:400])
|
| 185 |
(OUT / "sample.txt").write_text(out, encoding="utf-8")
|
| 186 |
(OUT / "train_meta.json").write_text(json.dumps({
|
| 187 |
-
"model": MODEL_ID, "
|
| 188 |
-
"
|
| 189 |
-
"
|
|
|
|
| 190 |
}, indent=1), encoding="utf-8")
|
| 191 |
log("done")
|
| 192 |
|
|
|
|
| 1 |
"""Director LoRA, conservative configuration.
|
| 2 |
|
| 3 |
+
Qwen3.5-0.8B ships as a VLM checkpoint (Qwen3_5ForConditionalGeneration):
|
| 4 |
+
its tensors are named `model.language_model.*`, with `model.visual.*` and
|
| 5 |
+
`mtp.*` alongside. The browser runs the text-only decoder, so we build
|
| 6 |
+
Qwen3_5ForCausalLM from `config.text_config` and load the checkpoint with an
|
| 7 |
+
explicit prefix rewrite. Relying on AutoModelForCausalLM.from_pretrained() is
|
| 8 |
+
not safe here: transformers 5.x has no `model.language_model.* -> model.*`
|
| 9 |
+
key conversion, so a plain load can silently leave the decoder randomly
|
| 10 |
+
initialised (warning only, training still "works", output is garbage).
|
| 11 |
+
|
| 12 |
+
LoRA goes on the MLP of all 24 layers and the q/k/v/o projections of the 6
|
| 13 |
+
full-attention layers. Nothing in `linear_attn` is touched: those projections
|
| 14 |
+
feed a recurrent scan, and conv1d/A_log/dt_bias are not plain Linears.
|
| 15 |
+
|
| 16 |
+
Runs in a fresh interpreter with transformers 5.x. The browser never loads
|
| 17 |
+
this adapter: merge_and_unload() writes a plain fp16 checkpoint for ONNX
|
| 18 |
+
export. Because we started from the text-only class, that checkpoint has no
|
| 19 |
+
vision tower and no MTP head already.
|
| 20 |
"""
|
| 21 |
import json
|
| 22 |
import os
|
| 23 |
import random
|
| 24 |
import re
|
| 25 |
+
import shutil
|
| 26 |
import time
|
| 27 |
from pathlib import Path
|
| 28 |
|
|
|
|
| 33 |
DATA = Path(os.environ.get("DATA", str(ROOT / "director_lora" / "sft.jsonl")))
|
| 34 |
OUT = Path(os.environ.get("LORA_OUT", str(ROOT / "director_lora")))
|
| 35 |
MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B")
|
| 36 |
+
DTYPE = os.environ.get("DTYPE", "auto") # auto -> fp16 on Turing, bf16 on Ampere+
|
| 37 |
R = int(os.environ.get("R", "16"))
|
| 38 |
ALPHA = int(os.environ.get("ALPHA", "32"))
|
| 39 |
DROPOUT = float(os.environ.get("DROPOUT", "0.05"))
|
|
|
|
| 44 |
SEED = int(os.environ.get("SEED", "20261107"))
|
| 45 |
GRAD_CKPT = os.environ.get("GRAD_CKPT", "0") == "1"
|
| 46 |
|
| 47 |
+
# peft matches a list of target names against the last segment of a module key
|
| 48 |
+
# (key == target or key.endswith("." + target)). Short names are portable across
|
| 49 |
+
# peft versions; full module names are not. The text-only model has no visual
|
| 50 |
+
# tower and no MTP head, so these cannot match anything unwanted.
|
| 51 |
+
SHORT_TARGETS = ["gate_proj", "up_proj", "down_proj",
|
| 52 |
+
"q_proj", "k_proj", "v_proj", "o_proj"]
|
| 53 |
TARGET_RE = re.compile(
|
| 54 |
r"(^|\.)layers\.\d+\.("
|
| 55 |
r"mlp\.(gate_proj|up_proj|down_proj)"
|
| 56 |
r"|self_attn\.(q_proj|k_proj|v_proj|o_proj))$"
|
| 57 |
)
|
| 58 |
+
EXCLUDE = ("mtp", "vision", "visual", "multi_modal", "linear_attn")
|
| 59 |
+
THINK_TAIL = "<think>\n\n</think>\n\n"
|
| 60 |
|
| 61 |
|
| 62 |
def log(msg: str) -> None:
|
|
|
|
| 74 |
return rows
|
| 75 |
|
| 76 |
|
| 77 |
+
def pick_dtype(torch):
|
| 78 |
+
if DTYPE in ("fp16", "float16"):
|
| 79 |
+
return torch.float16
|
| 80 |
+
if DTYPE in ("bf16", "bfloat16"):
|
| 81 |
+
return torch.bfloat16
|
| 82 |
+
if DTYPE in ("fp32", "float32"):
|
| 83 |
+
return torch.float32
|
| 84 |
+
if DTYPE != "auto":
|
| 85 |
+
raise SystemExit(f"unknown DTYPE={DTYPE}")
|
| 86 |
+
return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def build_text_model(torch, dtype):
|
| 90 |
+
"""Build the text-only decoder and load the VLM checkpoint by explicit key rewrite."""
|
| 91 |
+
from huggingface_hub import hf_hub_download
|
| 92 |
+
from safetensors.torch import load_file
|
| 93 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 94 |
+
|
| 95 |
+
cfg = AutoConfig.from_pretrained(MODEL_ID)
|
| 96 |
+
text_cfg = cfg.get_text_config() if hasattr(cfg, "get_text_config") else cfg.text_config
|
| 97 |
+
log(f"config {type(cfg).__name__} -> {type(text_cfg).__name__} "
|
| 98 |
+
f"(model_type={getattr(text_cfg, 'model_type', '?')}, "
|
| 99 |
+
f"layers={getattr(text_cfg, 'num_hidden_layers', '?')})")
|
| 100 |
+
if getattr(text_cfg, "model_type", "") != "qwen3_5_text":
|
| 101 |
+
raise SystemExit("expected qwen3_5_text config; transformers version mismatch")
|
| 102 |
+
|
| 103 |
+
model = AutoModelForCausalLM.from_config(text_cfg)
|
| 104 |
+
model.to(dtype)
|
| 105 |
+
log(f"built text-only {type(model).__name__} in {dtype}")
|
| 106 |
+
|
| 107 |
+
index = Path(hf_hub_download(MODEL_ID, "model.safetensors.index.json"))
|
| 108 |
+
shards = sorted(set(json.loads(index.read_text())["weight_map"].values()))
|
| 109 |
+
log(f"checkpoint shards: {shards}")
|
| 110 |
+
sd = {}
|
| 111 |
+
for shard in shards:
|
| 112 |
+
sd.update(load_file(hf_hub_download(MODEL_ID, shard)))
|
| 113 |
+
log(f"read {len(sd)} tensors from checkpoint")
|
| 114 |
+
|
| 115 |
+
mapped, skipped = {}, []
|
| 116 |
+
prefix = "model.language_model."
|
| 117 |
+
for key, tensor in sd.items():
|
| 118 |
+
if key.startswith(prefix):
|
| 119 |
+
mapped["model." + key[len(prefix):]] = tensor
|
| 120 |
+
elif key == "lm_head.weight":
|
| 121 |
+
mapped[key] = tensor
|
| 122 |
+
else:
|
| 123 |
+
skipped.append(key)
|
| 124 |
+
log(f"mapped {len(mapped)} text tensors, skipped {len(skipped)} "
|
| 125 |
+
f"({sum(1 for k in skipped if k.startswith('model.visual.'))} visual, "
|
| 126 |
+
f"{sum(1 for k in skipped if k.startswith('mtp.'))} mtp)")
|
| 127 |
+
if not any(k.startswith("model.layers.0.") for k in mapped):
|
| 128 |
+
raise SystemExit(f"no language_model weights found; sample keys: {list(sd)[:6]}")
|
| 129 |
+
|
| 130 |
+
missing, unexpected = model.load_state_dict(
|
| 131 |
+
{k: v.to(dtype) for k, v in mapped.items()}, strict=False)
|
| 132 |
+
real_missing = [k for k in missing if not k.startswith("lm_head")]
|
| 133 |
+
log(f"load_state_dict: missing={len(missing)} (non-lm_head={len(real_missing)}), "
|
| 134 |
+
f"unexpected={len(unexpected)}")
|
| 135 |
+
if real_missing or unexpected:
|
| 136 |
+
raise SystemExit(f"weight load incomplete: missing={missing[:8]} "
|
| 137 |
+
f"unexpected={unexpected[:8]}")
|
| 138 |
+
|
| 139 |
+
# lm_head is tied to embed_tokens. Some versions expose tie_weights(),
|
| 140 |
+
# others only resolve _tied_weights_keys during from_pretrained().
|
| 141 |
+
try:
|
| 142 |
+
model.tie_weights()
|
| 143 |
+
except Exception as exc:
|
| 144 |
+
log(f"tie_weights() unavailable ({exc}); tying manually")
|
| 145 |
+
model.lm_head.weight = model.model.embed_tokens.weight
|
| 146 |
+
|
| 147 |
+
# Hard check: the bytes we loaded must actually be in the model. A random
|
| 148 |
+
# init would pass every shape check but fail this one.
|
| 149 |
+
probe = "model.layers.0.mlp.gate_proj.weight"
|
| 150 |
+
src = mapped[probe].to(dtype).float().cpu()
|
| 151 |
+
dst = model.get_parameter(probe).detach().float().cpu()
|
| 152 |
+
if not torch.equal(src, dst):
|
| 153 |
+
raise SystemExit(f"weight integrity check failed for {probe}")
|
| 154 |
+
log(f"weight integrity ok: {probe} mean={dst.mean():.6f} std={dst.std():.6f}")
|
| 155 |
+
return model
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def smoke_generate(torch, model, tok, row) -> None:
|
| 159 |
+
"""Soft check: the untrained base must still speak Chinese, not emit noise."""
|
| 160 |
+
try:
|
| 161 |
+
prompt = tok.apply_chat_template(
|
| 162 |
+
row["messages"], tokenize=False, add_generation_prompt=True)
|
| 163 |
+
ids = tok([prompt], return_tensors="pt").to("cuda")
|
| 164 |
+
model.config.use_cache = True
|
| 165 |
+
with torch.no_grad():
|
| 166 |
+
gen = model.generate(**ids, max_new_tokens=48, do_sample=False,
|
| 167 |
+
eos_token_id=tok.eos_token_id,
|
| 168 |
+
pad_token_id=tok.eos_token_id)
|
| 169 |
+
out = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 170 |
+
log("base sample: " + out[:200].replace("\n", " / "))
|
| 171 |
+
if not out.strip():
|
| 172 |
+
log("WARN: base generation returned empty text")
|
| 173 |
+
except Exception as exc:
|
| 174 |
+
log(f"WARN: base generation smoke failed ({type(exc).__name__}: {exc})")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def encode(tok, row: dict, variant: int):
|
| 178 |
import torch
|
| 179 |
|
| 180 |
messages = row["messages"]
|
| 181 |
if not messages or messages[-1]["role"] != "user":
|
| 182 |
raise SystemExit("bad messages field in training row")
|
| 183 |
prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 184 |
+
# The python template appends a closed <think> block; transformers.js may or
|
| 185 |
+
# may not render the same tail. Train on both so the protocol is robust.
|
| 186 |
+
if variant % 2 == 1 and prompt.endswith(THINK_TAIL):
|
| 187 |
+
prompt = prompt[:-len(THINK_TAIL)]
|
| 188 |
p_ids = tok(prompt, add_special_tokens=False)["input_ids"]
|
| 189 |
t_ids = tok(row["response"], add_special_tokens=False)["input_ids"] + [tok.eos_token_id]
|
| 190 |
ids = (p_ids + t_ids)[:MAX_LEN]
|
|
|
|
| 194 |
return {"input_ids": torch.tensor([ids]), "labels": torch.tensor([labels])}
|
| 195 |
|
| 196 |
|
| 197 |
+
def verify_targets(model, torch) -> None:
|
| 198 |
+
try:
|
| 199 |
+
from peft.tuners.lora import LoraLayer
|
| 200 |
+
except ImportError:
|
| 201 |
+
LoraLayer = None
|
| 202 |
+
try:
|
| 203 |
+
names = list(model.base_model.targeted_module_names)
|
| 204 |
+
except AttributeError:
|
| 205 |
+
names = [n for n, m in model.named_modules()
|
| 206 |
+
if LoraLayer is not None and isinstance(m, LoraLayer)]
|
| 207 |
+
bad = [n for n in names
|
| 208 |
+
if not TARGET_RE.search(n) or any(x in n for x in EXCLUDE)]
|
| 209 |
+
mlp = sum(1 for n in names if ".mlp." in n and "linear_attn" not in n)
|
| 210 |
attn = len(names) - mlp
|
| 211 |
+
log(f"peft adapted {len(names)} Linears ({mlp} MLP, {attn} self_attn), "
|
| 212 |
+
f"out-of-scope {len(bad)}")
|
| 213 |
+
if bad:
|
| 214 |
+
log(f" first out-of-scope: {bad[:4]}")
|
| 215 |
+
if len(names) != 96 or mlp != 72 or attn != 24 or bad:
|
| 216 |
+
raise SystemExit("unexpected LoRA target set; refusing to train")
|
| 217 |
|
| 218 |
|
| 219 |
def main() -> None:
|
| 220 |
import torch
|
| 221 |
from peft import LoraConfig, get_peft_model
|
| 222 |
+
from transformers import AutoTokenizer
|
| 223 |
|
| 224 |
import transformers
|
| 225 |
+
log(f"transformers {transformers.__version__}, torch {torch.__version__}, "
|
| 226 |
+
f"cuda {torch.version.cuda}, bf16_supported={torch.cuda.is_bf16_supported()}")
|
| 227 |
if int(transformers.__version__.split(".")[0]) < 5:
|
| 228 |
raise SystemExit("Qwen3.5 needs transformers >= 5; run in a fresh process")
|
| 229 |
+
if not torch.cuda.is_available():
|
| 230 |
+
raise SystemExit("no CUDA device; check the notebook accelerator")
|
| 231 |
|
| 232 |
random.seed(SEED)
|
| 233 |
torch.manual_seed(SEED)
|
| 234 |
rows = load_rows()
|
| 235 |
+
dtype = pick_dtype(torch)
|
| 236 |
+
log(f"training dtype {dtype}")
|
| 237 |
|
| 238 |
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 239 |
if not getattr(tok, "chat_template", None):
|
| 240 |
raise SystemExit("tokenizer has no chat template; the browser applies one")
|
| 241 |
log(f"eos={tok.eos_token_id} ({tok.decode([tok.eos_token_id])!r})")
|
| 242 |
|
| 243 |
+
model = build_text_model(torch, dtype).to("cuda:0")
|
| 244 |
+
smoke_generate(torch, model, tok, rows[0])
|
| 245 |
model.config.use_cache = False
|
|
|
|
|
|
|
|
|
|
| 246 |
|
|
|
|
| 247 |
cfg = LoraConfig(r=R, lora_alpha=ALPHA, lora_dropout=DROPOUT, bias="none",
|
| 248 |
+
task_type="CAUSAL_LM", target_modules=SHORT_TARGETS)
|
| 249 |
+
model = get_peft_model(model, cfg, autocast_adapter_dtype=True)
|
| 250 |
+
verify_targets(model, torch)
|
| 251 |
+
|
| 252 |
trainable = [p for p in model.parameters() if p.requires_grad]
|
| 253 |
+
dtypes = {str(p.dtype) for p in trainable}
|
| 254 |
+
log(f"trainable dtypes {dtypes}")
|
| 255 |
+
if any(p.dtype != torch.float32 for p in trainable):
|
| 256 |
+
log("casting adapter parameters to fp32 (fp16 AdamW underflows at lr=1e-4)")
|
| 257 |
+
for p in trainable:
|
| 258 |
+
p.data = p.data.float()
|
| 259 |
n_train = sum(p.numel() for p in trainable)
|
| 260 |
n_all = sum(p.numel() for p in model.parameters())
|
| 261 |
log(f"trainable {n_train/1e6:.2f}M / {n_all/1e6:.0f}M ({n_train/n_all:.2%})")
|
| 262 |
|
| 263 |
+
encoded = [x for x in (encode(tok, row, i) for i, row in enumerate(rows))
|
| 264 |
+
if x is not None]
|
| 265 |
log(f"encoded {len(encoded)} examples, max {max(x['input_ids'].shape[1] for x in encoded)} tokens")
|
| 266 |
+
probe = tok.apply_chat_template(rows[0]["messages"], tokenize=False,
|
| 267 |
+
add_generation_prompt=True)
|
| 268 |
+
log(f"prompt tail variant A: {probe[-45:]!r}")
|
| 269 |
+
if probe.endswith(THINK_TAIL):
|
| 270 |
+
log(f"prompt tail variant B: {probe[:-len(THINK_TAIL)][-45:]!r}")
|
| 271 |
+
|
| 272 |
+
if GRAD_CKPT:
|
| 273 |
+
model.gradient_checkpointing_enable()
|
| 274 |
+
model.enable_input_require_grads()
|
| 275 |
+
|
| 276 |
opt = torch.optim.AdamW(trainable, lr=LR, betas=(0.9, 0.95), weight_decay=0.01)
|
| 277 |
model.train()
|
| 278 |
+
step, running, group, t0 = 0, 0.0, 0.0, time.time()
|
| 279 |
for epoch in range(EPOCHS):
|
| 280 |
order = list(range(len(encoded)))
|
| 281 |
random.shuffle(order)
|
|
|
|
| 282 |
for i, idx in enumerate(order):
|
| 283 |
batch = {k: v.cuda() for k, v in encoded[idx].items()}
|
| 284 |
loss = model(**batch).loss / ACCUM
|
| 285 |
loss.backward()
|
| 286 |
+
group += loss.item()
|
| 287 |
if (i + 1) % ACCUM == 0 or i + 1 == len(order):
|
| 288 |
torch.nn.utils.clip_grad_norm_(trainable, 1.0)
|
| 289 |
opt.step()
|
| 290 |
opt.zero_grad(set_to_none=True)
|
| 291 |
step += 1
|
| 292 |
+
running += group
|
| 293 |
+
group = 0.0
|
| 294 |
if step % 25 == 0:
|
| 295 |
+
log(f"epoch {epoch} step {step} loss {running/25:.4f} "
|
| 296 |
+
f"({time.time()-t0:.0f}s)")
|
| 297 |
running = 0.0
|
| 298 |
+
log(f"epoch {epoch} done")
|
| 299 |
opt.zero_grad(set_to_none=True)
|
| 300 |
|
| 301 |
adapter = OUT / "adapter"
|
| 302 |
adapter.mkdir(parents=True, exist_ok=True)
|
| 303 |
model.save_pretrained(adapter)
|
| 304 |
tok.save_pretrained(adapter)
|
| 305 |
+
shutil.make_archive(str(OUT / "adapter"), "zip", str(adapter))
|
| 306 |
+
log(f"saved adapter -> {adapter} (+ adapter.zip)")
|
| 307 |
|
| 308 |
merged = OUT / "model_fp16"
|
| 309 |
merged.mkdir(parents=True, exist_ok=True)
|
| 310 |
model = model.merge_and_unload()
|
|
|
|
|
|
|
| 311 |
if GRAD_CKPT:
|
| 312 |
model.gradient_checkpointing_disable()
|
| 313 |
model.config.use_cache = True
|
| 314 |
model.save_pretrained(merged, safe_serialization=True)
|
| 315 |
tok.save_pretrained(merged)
|
| 316 |
+
log(f"saved merged fp16 -> {merged} (text-only: no visual tower, no MTP head)")
|
| 317 |
|
| 318 |
# Cheap sanity check: the merged model must still produce the protocol.
|
| 319 |
model.eval()
|
| 320 |
+
text = tok.apply_chat_template(rows[0]["messages"], tokenize=False,
|
| 321 |
+
add_generation_prompt=True)
|
| 322 |
ids = tok([text], return_tensors="pt").to("cuda")
|
| 323 |
with torch.no_grad():
|
| 324 |
gen = model.generate(**ids, max_new_tokens=160, do_sample=False,
|
|
|
|
| 328 |
log("merged model sample:\n" + out[:400])
|
| 329 |
(OUT / "sample.txt").write_text(out, encoding="utf-8")
|
| 330 |
(OUT / "train_meta.json").write_text(json.dumps({
|
| 331 |
+
"model": MODEL_ID, "transformers": transformers.__version__,
|
| 332 |
+
"dtype": str(dtype), "rows": len(encoded), "epochs": EPOCHS, "lr": LR,
|
| 333 |
+
"r": R, "alpha": ALPHA, "targets": len(SHORT_TARGETS),
|
| 334 |
+
"trainable": n_train, "steps": step, "seconds": round(time.time() - t0),
|
| 335 |
}, indent=1), encoding="utf-8")
|
| 336 |
log("done")
|
| 337 |
|