Text Classification
Transformers
Safetensors
English
gemma4
image-text-to-text
decision-model
classification
calibration
routing
guardrails
vision
multimodal
baseten
Instructions to use baselabs/groundhog-1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use baselabs/groundhog-1 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="baselabs/groundhog-1")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("baselabs/groundhog-1") model = AutoModelForMultimodalLM.from_pretrained("baselabs/groundhog-1", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add setup.sh, serve.patch and constraints.txt
#1
by b10-tv - opened
- constraints.txt +62 -0
- serve.patch +1183 -0
- setup.sh +18 -0
constraints.txt
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pinned package versions of the training and eval stack, minus torch's own CUDA libraries, which follow the image.
|
| 2 |
+
accelerate==1.15.0
|
| 3 |
+
annotated-doc==0.0.5
|
| 4 |
+
annotated-types==0.8.0
|
| 5 |
+
anyio==4.15.1
|
| 6 |
+
astunparse==1.6.3
|
| 7 |
+
brotli==1.2.0
|
| 8 |
+
click==8.5.0
|
| 9 |
+
cmake==4.0.0
|
| 10 |
+
dnspython==2.7.0
|
| 11 |
+
einops==0.8.2
|
| 12 |
+
expecttest==0.3.0
|
| 13 |
+
fastapi==0.143.1
|
| 14 |
+
fsspec==2025.3.2
|
| 15 |
+
googleapis-common-protos==1.75.5
|
| 16 |
+
h11==0.16.0
|
| 17 |
+
hf-xet==1.7.0
|
| 18 |
+
httpcore==1.0.9
|
| 19 |
+
httpx==0.28.1
|
| 20 |
+
huggingface_hub==1.33.0
|
| 21 |
+
hypothesis==6.131.7
|
| 22 |
+
idna==3.20
|
| 23 |
+
lintrunner==0.12.7
|
| 24 |
+
markdown-it-py==4.2.0
|
| 25 |
+
mdurl==0.1.2
|
| 26 |
+
mpmath==1.3.0
|
| 27 |
+
networkx==3.4.2
|
| 28 |
+
ninja==1.11.1.4
|
| 29 |
+
opentelemetry-api==1.45.1
|
| 30 |
+
opentelemetry-exporter-http-transport==0.66b1
|
| 31 |
+
opentelemetry-exporter-otlp-common==0.66b1
|
| 32 |
+
opentelemetry-exporter-otlp-proto-common==1.45.1
|
| 33 |
+
opentelemetry-exporter-otlp-proto-http==1.45.1
|
| 34 |
+
opentelemetry-proto==1.45.1
|
| 35 |
+
opentelemetry-sdk==1.45.1
|
| 36 |
+
opentelemetry-semantic-conventions==0.66b1
|
| 37 |
+
optree==0.15.0
|
| 38 |
+
peft==0.21.2
|
| 39 |
+
pillow==11.0.0
|
| 40 |
+
protobuf==7.36.2
|
| 41 |
+
pyarrow==26.0.0
|
| 42 |
+
pydantic==2.14.1
|
| 43 |
+
pydantic_core==2.50.1
|
| 44 |
+
python-etcd==0.4.5
|
| 45 |
+
regex==2026.9.29
|
| 46 |
+
rich==15.0.0
|
| 47 |
+
safetensors==0.8.0
|
| 48 |
+
shellingham==1.5.4
|
| 49 |
+
six==1.17.0
|
| 50 |
+
sortedcontainers==2.4.0
|
| 51 |
+
starlette==1.8.0
|
| 52 |
+
sympy==1.13.3
|
| 53 |
+
tokenizers==0.23.3
|
| 54 |
+
transformers==5.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/qev/engine.py b/qev/engine.py
|
| 2 |
+
index 2e4c7b0..e0b6164 100644
|
| 3 |
+
--- a/qev/engine.py
|
| 4 |
+
+++ b/qev/engine.py
|
| 5 |
+
@@ -10,6 +10,7 @@ tolerance of 0.05 and only guards against structural failures (an unknown cache
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
+import contextlib
|
| 10 |
+
import copy
|
| 11 |
+
import hashlib
|
| 12 |
+
import logging
|
| 13 |
+
@@ -19,6 +20,7 @@ from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
from .answers import make_choice, make_noul, make_score
|
| 17 |
+
+from . import readout as ro
|
| 18 |
+
from .calibrate import Calibration, softmax
|
| 19 |
+
from .prompt import (DEFAULT_STYLE, LETTERS, MAX_SLOTS, PROMPT_VERSION, SLOT_LABELS, PromptStyle, RenderedQuestion,
|
| 20 |
+
build_messages, render_question)
|
| 21 |
+
@@ -27,6 +29,32 @@ from .schema import Answer, SystemOneRequest, SystemOneResponse, Usage
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger("qev.engine")
|
| 24 |
+
|
| 25 |
+
+# Vision checkpoints served text-only through their text LM and text config. gemma4 is not listed: Gemma4ForCausalLM
|
| 26 |
+
+# does not read the language_model.* weights of a Gemma4ForConditionalGeneration checkpoint, so AutoModelForCausalLM's
|
| 27 |
+
+# Gemma4ForConditionalGeneration is used and fed text only.
|
| 28 |
+
+TEXT_LM = {"qwen3_5": "Qwen3_5ForCausalLM", "qwen3_5_text": "Qwen3_5ForCausalLM",
|
| 29 |
+
+ "qwen3_5_moe": "Qwen3_5MoeForCausalLM", "qwen3_5_moe_text": "Qwen3_5MoeForCausalLM"}
|
| 30 |
+
+
|
| 31 |
+
+
|
| 32 |
+
+def text_lm(transformers, config):
|
| 33 |
+
+ """The causal LM class and the config to load a checkpoint with for text-only scoring."""
|
| 34 |
+
+ name = TEXT_LM.get(config.model_type)
|
| 35 |
+
+ if name is None:
|
| 36 |
+
+ return transformers.AutoModelForCausalLM, config
|
| 37 |
+
+ return getattr(transformers, name), config.get_text_config()
|
| 38 |
+
+
|
| 39 |
+
+
|
| 40 |
+
+def load_kwargs(model_type: str) -> dict:
|
| 41 |
+
+ """from_pretrained options pinned per family: gemma4 on SDPA (the noncausal readout needs a mask-based
|
| 42 |
+
+ implementation) with grouped_mm experts (torch >= 2.9; older torch silently takes a per-expert loop)."""
|
| 43 |
+
+ return {"attn_implementation": "sdpa", "experts_implementation": "grouped_mm"} if model_type.startswith("gemma4") else {}
|
| 44 |
+
+
|
| 45 |
+
+
|
| 46 |
+
+def template_kwargs(model_type: str) -> dict:
|
| 47 |
+
+ """Chat-template switches: thinking off for the families whose templates have the switch."""
|
| 48 |
+
+ return {"enable_thinking": False} if "qwen" in model_type or model_type.startswith("gemma4") else {}
|
| 49 |
+
+
|
| 50 |
+
+
|
| 51 |
+
NONE_OPTION = "none of the options listed here"
|
| 52 |
+
NONE_DESCRIPTION = "The correct option is not among the options listed in this question."
|
| 53 |
+
|
| 54 |
+
@@ -89,24 +117,31 @@ class DecisionEngine:
|
| 55 |
+
common = {"local_files_only": local, "trust_remote_code": False}
|
| 56 |
+
config = transformers.AutoConfig.from_pretrained(model_path, **common)
|
| 57 |
+
self.tokenizer = transformers.AutoTokenizer.from_pretrained(model_path, **common)
|
| 58 |
+
- cls = transformers.AutoModelForCausalLM
|
| 59 |
+
- if config.model_type in {"qwen3_5", "qwen3_5_text"}:
|
| 60 |
+
- cls = transformers.Qwen3_5ForCausalLM
|
| 61 |
+
- config = config.get_text_config()
|
| 62 |
+
+ cls, config = text_lm(transformers, config)
|
| 63 |
+
self.model = cls.from_pretrained(model_path, config=config, dtype=self.torch_dtype,
|
| 64 |
+
- device_map={"": str(self.device)}, low_cpu_mem_usage=True, **common)
|
| 65 |
+
+ device_map={"": str(self.device)}, low_cpu_mem_usage=True, **common,
|
| 66 |
+
+ **load_kwargs(config.model_type))
|
| 67 |
+
self.model.eval()
|
| 68 |
+
self.head_dtype = head_dtype
|
| 69 |
+
if head_dtype != dtype:
|
| 70 |
+
self._upcast_head(getattr(torch, head_dtype))
|
| 71 |
+
self.model_type = config.model_type
|
| 72 |
+
- self.template_kwargs = {"enable_thinking": False} if "qwen" in self.model_type else {}
|
| 73 |
+
+ self.template_kwargs = template_kwargs(self.model_type)
|
| 74 |
+
self.slot_ids = self._verify_slots()
|
| 75 |
+
+ rcfg = ro.ReadoutConfig.load(model_path) if local else ro.ReadoutConfig()
|
| 76 |
+
+ self.readout = ro.Readout.attach(self.model, rcfg, slot_ids=self.slot_ids,
|
| 77 |
+
+ head_path=Path(model_path) / ro.HEAD_FILE if rcfg.head else None,
|
| 78 |
+
+ device=self.device)
|
| 79 |
+
+ if rcfg.head:
|
| 80 |
+
+ self.max_slots = min(self.max_slots, rcfg.n_slots)
|
| 81 |
+
+ if calibration is None and local and (Path(model_path) / "calibration.json").exists():
|
| 82 |
+
+ self.calibration = Calibration.load(Path(model_path) / "calibration.json")
|
| 83 |
+
self.pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
|
| 84 |
+
self.info = EngineInfo(model_path=model_path, model_type=self.model_type, dtype=dtype, device=str(self.device),
|
| 85 |
+
fork_mode="sequential", fork_max_abs_diff=None,
|
| 86 |
+
transformers_version=transformers.__version__, torch_version=torch.__version__,
|
| 87 |
+
- extra={"head_dtype": head_dtype})
|
| 88 |
+
+ extra={"head_dtype": head_dtype, "attention": rcfg.attention, "readout": rcfg.readout,
|
| 89 |
+
+ "calibration": self.calibration.source})
|
| 90 |
+
if fork_mode == "auto":
|
| 91 |
+
self._select_fork_mode()
|
| 92 |
+
else:
|
| 93 |
+
@@ -190,6 +225,44 @@ class DecisionEngine:
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
torch.cuda.empty_cache() if self.device.type == "cuda" else None
|
| 96 |
+
|
| 97 |
+
+ def _split(self, state: Any, rendered: list[RenderedQuestion]):
|
| 98 |
+
+ """Prefix ids, suffix ids, and per branch the option token spans relative to its suffix (None for slot_lm).
|
| 99 |
+
+ The layout is the one train.common.batch_scores computes, so serving matches training: under noncausal
|
| 100 |
+
+ attention the cache boundary must be the prefix block boundary."""
|
| 101 |
+
+ prefix_ids, suffixes = self._prefix_and_suffix_ids(state, rendered)
|
| 102 |
+
+ cfg = self.readout.config
|
| 103 |
+
+ if not cfg.needs_layout:
|
| 104 |
+
+ return prefix_ids, suffixes, [None] * len(rendered)
|
| 105 |
+
+ P = len(prefix_ids)
|
| 106 |
+
+ spans = []
|
| 107 |
+
+ for r, suf in zip(rendered, suffixes):
|
| 108 |
+
+ prompt = self._render_prompt(state, r.suffix)
|
| 109 |
+
+ start = prompt.rindex(r.suffix)
|
| 110 |
+
+ ids, prefix, sp = ro.token_layout(self.tokenizer, prompt, start,
|
| 111 |
+
+ [(start + a, start + b) for a, b in r.option_spans or []])
|
| 112 |
+
+ if ids != prefix_ids + suf:
|
| 113 |
+
+ raise ValueError("layout tokenization differs from the branch tokenization")
|
| 114 |
+
+ if cfg.noncausal and prefix != P:
|
| 115 |
+
+ raise ValueError(f"prefix block ends at token {prefix} but the shared cache at {P}")
|
| 116 |
+
+ if any(a < P for a, _ in sp):
|
| 117 |
+
+ raise ValueError("an option span starts inside the shared prefix")
|
| 118 |
+
+ spans.append([(a - P, b - P) for a, b in sp])
|
| 119 |
+
+ return prefix_ids, suffixes, spans
|
| 120 |
+
+
|
| 121 |
+
+ def _blocks(self, prefixes: list[int], lengths: list[int], width: int):
|
| 122 |
+
+ if not self.readout.config.noncausal:
|
| 123 |
+
+ return contextlib.nullcontext()
|
| 124 |
+
+ return ro.blocks(ro.block_ids(prefixes, lengths, width, self.device))
|
| 125 |
+
+
|
| 126 |
+
+ def _scores(self, o, hidden, row: int, logit_pos: int, end: int, n_slots: int, spans) -> tuple[list[float], float]:
|
| 127 |
+
+ """Scores of one branch from a forward's output: the slot letters' LM logits, or the readout head over the
|
| 128 |
+
+ captured final hidden states (`end` and `spans` index the suffix tokens of this row)."""
|
| 129 |
+
+ if self.readout.head is None:
|
| 130 |
+
+ return self._readout(o.logits[row, logit_pos], n_slots)
|
| 131 |
+
+ h = hidden[row: row + 1]
|
| 132 |
+
+ scores = self.readout.head(h[:, end], ro.pool_options(h, [spans], n_slots))[0]
|
| 133 |
+
+ return scores.tolist(), 1.0
|
| 134 |
+
+
|
| 135 |
+
def _prefix_and_suffix_ids(self, state: Any, rendered: list[RenderedQuestion]) -> tuple[list[int], list[list[int]]]:
|
| 136 |
+
"""Tokenize every branch fully, then find the longest common token prefix that ends at or
|
| 137 |
+
before the end of the state block, so the shared prefix is exact by construction."""
|
| 138 |
+
@@ -218,21 +291,25 @@ class DecisionEngine:
|
| 139 |
+
def _run_sequential(self, state: Any, rendered: list[RenderedQuestion]) -> list[BranchResult]:
|
| 140 |
+
import torch
|
| 141 |
+
|
| 142 |
+
- prefix_ids, suffixes = self._prefix_and_suffix_ids(state, rendered)
|
| 143 |
+
+ prefix_ids, suffixes, spans = self._split(state, rendered)
|
| 144 |
+
dev = self.device
|
| 145 |
+
+ P = len(prefix_ids)
|
| 146 |
+
with torch.inference_mode():
|
| 147 |
+
- out = self.model(input_ids=torch.tensor([prefix_ids], device=dev),
|
| 148 |
+
- attention_mask=torch.ones((1, len(prefix_ids)), dtype=torch.long, device=dev),
|
| 149 |
+
- use_cache=True, return_dict=True, logits_to_keep=1)
|
| 150 |
+
+ with self._blocks([P], [P], P):
|
| 151 |
+
+ out = self.model(input_ids=torch.tensor([prefix_ids], device=dev),
|
| 152 |
+
+ attention_mask=torch.ones((1, P), dtype=torch.long, device=dev),
|
| 153 |
+
+ use_cache=True, return_dict=True, logits_to_keep=1)
|
| 154 |
+
base = out.past_key_values
|
| 155 |
+
del out
|
| 156 |
+
results = []
|
| 157 |
+
- for r, suf in zip(rendered, suffixes):
|
| 158 |
+
+ for r, suf, sp in zip(rendered, suffixes, spans):
|
| 159 |
+
cache = copy.deepcopy(base)
|
| 160 |
+
- o = self.model(input_ids=torch.tensor([suf], device=dev),
|
| 161 |
+
- attention_mask=torch.ones((1, len(prefix_ids) + len(suf)), dtype=torch.long, device=dev),
|
| 162 |
+
- past_key_values=cache, use_cache=True, return_dict=True, logits_to_keep=1)
|
| 163 |
+
- logits, mass = self._readout(o.logits[0, -1], r.n_slots)
|
| 164 |
+
+ with self._blocks([P], [P + len(suf)], P + len(suf)):
|
| 165 |
+
+ o = self.model(input_ids=torch.tensor([suf], device=dev),
|
| 166 |
+
+ attention_mask=torch.ones((1, P + len(suf)), dtype=torch.long, device=dev),
|
| 167 |
+
+ past_key_values=cache, use_cache=True, return_dict=True, logits_to_keep=1)
|
| 168 |
+
+ hidden = self.readout.capture.pop() if self.readout.capture else None
|
| 169 |
+
+ logits, mass = self._scores(o, hidden, 0, -1, len(suf) - 1, r.n_slots, sp)
|
| 170 |
+
results.append(BranchResult(r.qid, r.kind, r.labels, r.descriptions, logits, mass, len(suf)))
|
| 171 |
+
del o, cache
|
| 172 |
+
del base
|
| 173 |
+
@@ -266,22 +343,23 @@ class DecisionEngine:
|
| 174 |
+
caller falls back to sequential branches."""
|
| 175 |
+
import torch
|
| 176 |
+
|
| 177 |
+
- prefix_ids, suffixes = self._prefix_and_suffix_ids(state, rendered)
|
| 178 |
+
+ prefix_ids, suffixes, spans = self._split(state, rendered)
|
| 179 |
+
dev = self.device
|
| 180 |
+
P = len(prefix_ids)
|
| 181 |
+
chunk = max(1, min(len(rendered), self.fork_token_budget // max(P, 1)))
|
| 182 |
+
results: list[BranchResult | None] = [None] * len(rendered)
|
| 183 |
+
with torch.inference_mode():
|
| 184 |
+
- out = self.model(input_ids=torch.tensor([prefix_ids], device=dev),
|
| 185 |
+
- attention_mask=torch.ones((1, P), dtype=torch.long, device=dev),
|
| 186 |
+
- use_cache=True, return_dict=True, logits_to_keep=1)
|
| 187 |
+
+ with self._blocks([P], [P], P):
|
| 188 |
+
+ out = self.model(input_ids=torch.tensor([prefix_ids], device=dev),
|
| 189 |
+
+ attention_mask=torch.ones((1, P), dtype=torch.long, device=dev),
|
| 190 |
+
+ use_cache=True, return_dict=True, logits_to_keep=1)
|
| 191 |
+
base = out.past_key_values
|
| 192 |
+
del out
|
| 193 |
+
start = 0
|
| 194 |
+
while start < len(rendered):
|
| 195 |
+
idx = list(range(start, min(start + chunk, len(rendered))))
|
| 196 |
+
try:
|
| 197 |
+
- self._run_chunk(base, P, idx, rendered, suffixes, results)
|
| 198 |
+
+ self._run_chunk(base, P, idx, rendered, suffixes, results, spans)
|
| 199 |
+
except torch.OutOfMemoryError:
|
| 200 |
+
torch.cuda.empty_cache()
|
| 201 |
+
if chunk == 1:
|
| 202 |
+
@@ -294,7 +372,7 @@ class DecisionEngine:
|
| 203 |
+
del base
|
| 204 |
+
return results
|
| 205 |
+
|
| 206 |
+
- def _run_chunk(self, base, P: int, idx: list[int], rendered, suffixes, results) -> None:
|
| 207 |
+
+ def _run_chunk(self, base, P: int, idx: list[int], rendered, suffixes, results, spans=None) -> None:
|
| 208 |
+
import torch
|
| 209 |
+
|
| 210 |
+
dev = self.device
|
| 211 |
+
@@ -311,13 +389,16 @@ class DecisionEngine:
|
| 212 |
+
ends.append(len(s) - 1)
|
| 213 |
+
keep = sorted(set(ends))
|
| 214 |
+
cache = self._fork(base, len(idx))
|
| 215 |
+
+ spans = spans or [None] * len(rendered)
|
| 216 |
+
try:
|
| 217 |
+
- o = self.model(input_ids=ids, attention_mask=mask, position_ids=pos, past_key_values=cache,
|
| 218 |
+
- use_cache=True, return_dict=True,
|
| 219 |
+
- logits_to_keep=torch.tensor(keep, dtype=torch.long, device=dev))
|
| 220 |
+
+ with self._blocks([P] * len(idx), [P + len(s) for s in sufs], P + width):
|
| 221 |
+
+ o = self.model(input_ids=ids, attention_mask=mask, position_ids=pos, past_key_values=cache,
|
| 222 |
+
+ use_cache=True, return_dict=True,
|
| 223 |
+
+ logits_to_keep=torch.tensor(keep, dtype=torch.long, device=dev))
|
| 224 |
+
+ hidden = self.readout.capture.pop() if self.readout.capture else None
|
| 225 |
+
for row, i in enumerate(idx):
|
| 226 |
+
r = rendered[i]
|
| 227 |
+
- logits, mass = self._readout(o.logits[row, keep.index(ends[row])], r.n_slots)
|
| 228 |
+
+ logits, mass = self._scores(o, hidden, row, keep.index(ends[row]), ends[row], r.n_slots, spans[i])
|
| 229 |
+
results[i] = BranchResult(r.qid, r.kind, r.labels, r.descriptions, logits, mass, len(sufs[row]))
|
| 230 |
+
del o
|
| 231 |
+
finally:
|
| 232 |
+
diff --git a/qev/prompt.py b/qev/prompt.py
|
| 233 |
+
index 8eaadd3..de49cca 100644
|
| 234 |
+
--- a/qev/prompt.py
|
| 235 |
+
+++ b/qev/prompt.py
|
| 236 |
+
@@ -74,13 +74,14 @@ class RenderedQuestion:
|
| 237 |
+
labels: list[str]
|
| 238 |
+
descriptions: list[Any]
|
| 239 |
+
suffix: str
|
| 240 |
+
+ option_spans: list[tuple[int, int]] | None = None
|
| 241 |
+
n_slots: int = field(init=False)
|
| 242 |
+
|
| 243 |
+
def __post_init__(self) -> None:
|
| 244 |
+
self.n_slots = len(self.labels)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
-def _options_block(names: Sequence[str], descriptions: Sequence[Any], show_names: bool = True) -> str:
|
| 248 |
+
+def _options_lines(names: Sequence[str], descriptions: Sequence[Any], show_names: bool = True) -> list[str]:
|
| 249 |
+
lines = []
|
| 250 |
+
for letter, name, desc in zip(SLOT_LABELS, names, descriptions):
|
| 251 |
+
text = render_entry(desc)
|
| 252 |
+
@@ -90,7 +91,11 @@ def _options_block(names: Sequence[str], descriptions: Sequence[Any], show_names
|
| 253 |
+
lines.append(f"{letter}. {name}: {text}")
|
| 254 |
+
else:
|
| 255 |
+
lines.append(f"{letter}. {name}")
|
| 256 |
+
- return "\n".join(lines)
|
| 257 |
+
+ return lines
|
| 258 |
+
+
|
| 259 |
+
+
|
| 260 |
+
+def _options_block(names: Sequence[str], descriptions: Sequence[Any], show_names: bool = True) -> str:
|
| 261 |
+
+ return "\n".join(_options_lines(names, descriptions, show_names))
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def render_question(qid: str, q: Question, order: Sequence[int] | None = None, style: PromptStyle = DEFAULT_STYLE) -> RenderedQuestion:
|
| 265 |
+
@@ -127,6 +132,7 @@ def render_question(qid: str, q: Question, order: Sequence[int] | None = None, s
|
| 266 |
+
descs = [descs[i] for i in order]
|
| 267 |
+
|
| 268 |
+
letters = list(SLOT_LABELS[: len(labels)])
|
| 269 |
+
+ spans = None
|
| 270 |
+
if style.layout == "json":
|
| 271 |
+
payload = {"criterion": instructions,
|
| 272 |
+
"options": [{"letter": l, "description": (f"{n}: {render_entry(d)}" if (style.show_names and n is not None and render_entry(d)) else (render_entry(d) or n))}
|
| 273 |
+
@@ -134,12 +140,17 @@ def render_question(qid: str, q: Question, order: Sequence[int] | None = None, s
|
| 274 |
+
suffix = json.dumps(payload, ensure_ascii=False)[1:]
|
| 275 |
+
else:
|
| 276 |
+
header = style.question_header if kind != "score" else style.score_header
|
| 277 |
+
+ head = f"{header} {instructions}\n\nOptions:\n"
|
| 278 |
+
+ lines = _options_lines(names, descs, style.show_names)
|
| 279 |
+
+ spans, pos = [], len(head)
|
| 280 |
+
+ for line in lines:
|
| 281 |
+
+ spans.append((pos, pos + len(line)))
|
| 282 |
+
+ pos += len(line) + 1
|
| 283 |
+
suffix = (
|
| 284 |
+
- f"{header} {instructions}\n\n"
|
| 285 |
+
- f"Options:\n{_options_block(names, descs, style.show_names)}\n\n"
|
| 286 |
+
+ head + "\n".join(lines) + "\n\n"
|
| 287 |
+
+ (style.answer_line if len(letters) <= len(LETTERS) else style.answer_line_many).format(letters=", ".join(letters))
|
| 288 |
+
)
|
| 289 |
+
- return RenderedQuestion(qid=qid, kind=kind, labels=labels, descriptions=descs, suffix=suffix)
|
| 290 |
+
+ return RenderedQuestion(qid=qid, kind=kind, labels=labels, descriptions=descs, suffix=suffix, option_spans=spans)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def state_block(state: Any, style: PromptStyle = DEFAULT_STYLE) -> str:
|
| 294 |
+
diff --git a/qev/readout.py b/qev/readout.py
|
| 295 |
+
new file mode 100644
|
| 296 |
+
index 0000000..3647b06
|
| 297 |
+
--- /dev/null
|
| 298 |
+
+++ b/qev/readout.py
|
| 299 |
+
@@ -0,0 +1,300 @@
|
| 300 |
+
+"""Readout variants, shared by training (train.common / train.sft) and serving (qev.engine).
|
| 301 |
+
+
|
| 302 |
+
+attention:
|
| 303 |
+
+ causal the base model's mask.
|
| 304 |
+
+ noncausal in the full-attention layers every token attends bidirectionally within its block and causally to
|
| 305 |
+
+ earlier blocks. A rendered prompt has two blocks: the shared prefix (system turn and state block) and
|
| 306 |
+
+ the question suffix (question, options, answer line, generation prompt). The prefix never sees a
|
| 307 |
+
+ suffix, so its cache is still shared exactly by all questions of a request, and one forward of a
|
| 308 |
+
+ suffix scores all of its options. The GatedDeltaNet (linear-attention) layers are recurrent and stay
|
| 309 |
+
+ causal.
|
| 310 |
+
+
|
| 311 |
+
+readout:
|
| 312 |
+
+ slot_lm softmax over the LM-head logits of the slot letters at the answer position.
|
| 313 |
+
+ head a learned head over the final (normed) hidden states:
|
| 314 |
+
+ score_i = <w_i, h_ans> + <W_q h_ans, W_k mean(h over option i's line)> / sqrt(d)
|
| 315 |
+
+ w has one row per slot and starts as the LM-head rows of the slot letters, W_k starts at zero, so the
|
| 316 |
+
+ untrained head reproduces slot_lm exactly; the pointer term scores each option by its content.
|
| 317 |
+
+
|
| 318 |
+
+Both settings are recorded next to the weights, so a checkpoint is always served the way it was trained. The
|
| 319 |
+
+attention mask is declared per layer type under `modeling_overrides` in `config.json`, where serving stacks
|
| 320 |
+
+read it; `readout.json` holds the rest. Checkpoints without the overrides block carry `attention` in `readout.json`.
|
| 321 |
+
+"""
|
| 322 |
+
+from __future__ import annotations
|
| 323 |
+
+
|
| 324 |
+
+import bisect
|
| 325 |
+
+import contextlib
|
| 326 |
+
+import contextvars
|
| 327 |
+
+import importlib
|
| 328 |
+
+import json
|
| 329 |
+
+import math
|
| 330 |
+
+from dataclasses import asdict, dataclass
|
| 331 |
+
+from pathlib import Path
|
| 332 |
+
+from typing import Sequence
|
| 333 |
+
+
|
| 334 |
+
+import torch
|
| 335 |
+
+
|
| 336 |
+
+from .prompt import MAX_SLOTS
|
| 337 |
+
+
|
| 338 |
+
+CONFIG_FILE = "readout.json"
|
| 339 |
+
+MODEL_CONFIG_FILE = "config.json"
|
| 340 |
+
+OVERRIDES_KEY = "modeling_overrides"
|
| 341 |
+
+FULL_ATTENTION_MASK = {"causal": "causal", "noncausal": "block_bidirectional"}
|
| 342 |
+
+HEAD_FILE = "readout_head.pt"
|
| 343 |
+
+ATTENTION = ("causal", "noncausal")
|
| 344 |
+
+READOUT = ("slot_lm", "head")
|
| 345 |
+
+
|
| 346 |
+
+
|
| 347 |
+
+@dataclass
|
| 348 |
+
+class ReadoutConfig:
|
| 349 |
+
+ attention: str = "causal"
|
| 350 |
+
+ readout: str = "slot_lm"
|
| 351 |
+
+ head_dim: int = 256
|
| 352 |
+
+ n_slots: int = MAX_SLOTS
|
| 353 |
+
+
|
| 354 |
+
+ def __post_init__(self) -> None:
|
| 355 |
+
+ if self.attention not in ATTENTION:
|
| 356 |
+
+ raise ValueError(f"attention must be one of {ATTENTION}, got {self.attention!r}")
|
| 357 |
+
+ if self.readout not in READOUT:
|
| 358 |
+
+ raise ValueError(f"readout must be one of {READOUT}, got {self.readout!r}")
|
| 359 |
+
+
|
| 360 |
+
+ @property
|
| 361 |
+
+ def noncausal(self) -> bool:
|
| 362 |
+
+ return self.attention == "noncausal"
|
| 363 |
+
+
|
| 364 |
+
+ @property
|
| 365 |
+
+ def head(self) -> bool:
|
| 366 |
+
+ return self.readout == "head"
|
| 367 |
+
+
|
| 368 |
+
+ @property
|
| 369 |
+
+ def needs_layout(self) -> bool:
|
| 370 |
+
+ return self.noncausal or self.head
|
| 371 |
+
+
|
| 372 |
+
+ @classmethod
|
| 373 |
+
+ def load(cls, model_dir: str | Path) -> "ReadoutConfig":
|
| 374 |
+
+ path, model_path = Path(model_dir) / CONFIG_FILE, Path(model_dir) / MODEL_CONFIG_FILE
|
| 375 |
+
+ fields = json.loads(path.read_text()) if path.exists() else {}
|
| 376 |
+
+ overrides = json.loads(model_path.read_text()).get(OVERRIDES_KEY) if model_path.exists() else None
|
| 377 |
+
+ if overrides:
|
| 378 |
+
+ mask = overrides["attention"]["full_attention"]
|
| 379 |
+
+ attention = {v: k for k, v in FULL_ATTENTION_MASK.items()}.get(mask)
|
| 380 |
+
+ if attention is None:
|
| 381 |
+
+ raise ValueError(f"unsupported full_attention mask {mask!r} in {model_path}")
|
| 382 |
+
+ if fields.get("attention", attention) != attention:
|
| 383 |
+
+ raise ValueError(f"{path} says attention {fields['attention']!r} but {model_path} says {mask!r}")
|
| 384 |
+
+ fields["attention"] = attention
|
| 385 |
+
+ return cls(**fields)
|
| 386 |
+
+
|
| 387 |
+
+ def save(self, model_dir: str | Path) -> None:
|
| 388 |
+
+ fields = asdict(self)
|
| 389 |
+
+ model_path = Path(model_dir) / MODEL_CONFIG_FILE
|
| 390 |
+
+ if model_path.exists(): # LoRA adapters have no config.json; their readout.json keeps the attention
|
| 391 |
+
+ attention = fields.pop("attention")
|
| 392 |
+
+ config = json.loads(model_path.read_text())
|
| 393 |
+
+ # every other layer type stays causal: Qwen3.5's linear attention, gemma4's sliding window
|
| 394 |
+
+ others = (config.get("text_config") or config).get("layer_types") or ["linear_attention"]
|
| 395 |
+
+ config[OVERRIDES_KEY] = {"attention": {"full_attention": FULL_ATTENTION_MASK[attention],
|
| 396 |
+
+ **{t: "causal" for t in others if t != "full_attention"}},
|
| 397 |
+
+ **fields}
|
| 398 |
+
+ model_path.unlink() # may be a symlink to the source checkpoint
|
| 399 |
+
+ model_path.write_text(json.dumps(config, indent=2) + "\n")
|
| 400 |
+
+ (Path(model_dir) / CONFIG_FILE).write_text(json.dumps(fields, indent=2))
|
| 401 |
+
+
|
| 402 |
+
+
|
| 403 |
+
+_BLOCKS: contextvars.ContextVar = contextvars.ContextVar("qev_readout_blocks", default=None)
|
| 404 |
+
+
|
| 405 |
+
+
|
| 406 |
+
+def install_noncausal(model) -> None:
|
| 407 |
+
+ """Route block ids (set with `blocks`) into the full-attention mask of the model's modeling module. Outside a
|
| 408 |
+
+ `blocks` context the model is unchanged. Needs a mask-based attention implementation (sdpa, eager, flex)."""
|
| 409 |
+
+ impl = getattr(model.config.get_text_config(), "_attn_implementation", None) or model.config._attn_implementation
|
| 410 |
+
+ if impl not in ("sdpa", "eager", "flex_attention"):
|
| 411 |
+
+ raise ValueError(f"noncausal attention needs sdpa, eager or flex_attention, not {impl}")
|
| 412 |
+
+ mod = importlib.import_module(type(model).__module__)
|
| 413 |
+
+ if getattr(mod, "_qev_noncausal", False):
|
| 414 |
+
+ return
|
| 415 |
+
+ if not hasattr(mod, "create_causal_mask"):
|
| 416 |
+
+ raise ValueError(f"{mod.__name__} builds no causal mask to extend")
|
| 417 |
+
+ original = mod.create_causal_mask
|
| 418 |
+
+
|
| 419 |
+
+ def create_causal_mask(*args, **kwargs):
|
| 420 |
+
+ # A call with an or/and mask function builds some other layer type on top of the causal mask (gemma4's
|
| 421 |
+
+ # sliding-window mask with its vision blocks): it keeps its own pattern and stays causal.
|
| 422 |
+
+ ids = _BLOCKS.get()
|
| 423 |
+
+ if ids is not None and kwargs.get("block_sequence_ids") is None and kwargs.get("or_mask_function") is None \
|
| 424 |
+
+ and kwargs.get("and_mask_function") is None:
|
| 425 |
+
+ kwargs["block_sequence_ids"] = ids
|
| 426 |
+
+ return original(*args, **kwargs)
|
| 427 |
+
+
|
| 428 |
+
+ mod.create_causal_mask = create_causal_mask
|
| 429 |
+
+ if hasattr(mod, "create_masks_for_generate"):
|
| 430 |
+
+ _route_generate_masks(mod)
|
| 431 |
+
+ mod._qev_noncausal = True
|
| 432 |
+
+
|
| 433 |
+
+
|
| 434 |
+
+def _route_generate_masks(mod) -> None:
|
| 435 |
+
+ """gemma4 builds the masks of a text-only forward through masking_utils.create_masks_for_generate, whose inner
|
| 436 |
+
+ create_causal_mask is not the modeling module's. Inside a `blocks` context the full-attention mask is rebuilt with
|
| 437 |
+
+ the block ids; the sliding-window mask is the library's, causal within its window."""
|
| 438 |
+
+ from transformers import masking_utils as mu
|
| 439 |
+
+
|
| 440 |
+
+ original = mod.create_masks_for_generate
|
| 441 |
+
+
|
| 442 |
+
+ def create_masks_for_generate(config, inputs_embeds, attention_mask, past_key_values, position_ids=None, **kwargs):
|
| 443 |
+
+ masks = original(config, inputs_embeds, attention_mask, past_key_values, position_ids, **kwargs)
|
| 444 |
+
+ ids = _BLOCKS.get()
|
| 445 |
+
+ if ids is None:
|
| 446 |
+
+ return masks
|
| 447 |
+
+ if not isinstance(masks, dict) or not set(masks) <= {"full_attention", "sliding_attention"} or kwargs:
|
| 448 |
+
+ raise ValueError(f"noncausal attention: unexpected mask layout from {mod.__name__}")
|
| 449 |
+
+ masks["full_attention"] = mu.create_causal_mask(
|
| 450 |
+
+ config=config.get_text_config(), inputs_embeds=inputs_embeds, attention_mask=attention_mask,
|
| 451 |
+
+ past_key_values=past_key_values, position_ids=position_ids, block_sequence_ids=ids)
|
| 452 |
+
+ return masks
|
| 453 |
+
+
|
| 454 |
+
+ mod.create_masks_for_generate = create_masks_for_generate
|
| 455 |
+
+
|
| 456 |
+
+
|
| 457 |
+
+@contextlib.contextmanager
|
| 458 |
+
+def blocks(ids):
|
| 459 |
+
+ """Block ids [B, kv_length] over absolute positions (cached prefix included); None leaves the mask causal."""
|
| 460 |
+
+ token = _BLOCKS.set(ids)
|
| 461 |
+
+ try:
|
| 462 |
+
+ yield
|
| 463 |
+
+ finally:
|
| 464 |
+
+ _BLOCKS.reset(token)
|
| 465 |
+
+
|
| 466 |
+
+
|
| 467 |
+
+def block_ids(prefix_lens: Sequence[int], lengths: Sequence[int], width: int, device) -> torch.Tensor:
|
| 468 |
+
+ """0 on the prefix, 1 on the suffix, -1 on right padding (causal, and masked as a key anyway)."""
|
| 469 |
+
+ pos = torch.arange(width, device=device)[None]
|
| 470 |
+
+ p = torch.tensor(list(prefix_lens), device=device)[:, None]
|
| 471 |
+
+ n = torch.tensor(list(lengths), device=device)[:, None]
|
| 472 |
+
+ return torch.where(pos < p, 0, torch.where(pos < n, 1, -1))
|
| 473 |
+
+
|
| 474 |
+
+
|
| 475 |
+
+def token_layout(tokenizer, prompt: str, suffix_start: int, option_spans: Sequence[tuple[int, int]] | None):
|
| 476 |
+
+ """Token ids of `prompt`, the prefix length (tokens that end at or before the suffix) and each option line's
|
| 477 |
+
+ token span [start, end), from the tokenizer's character offsets. Option spans are characters of the prompt."""
|
| 478 |
+
+ enc = tokenizer(prompt, add_special_tokens=False, return_offsets_mapping=True)
|
| 479 |
+
+ ids, offs = enc["input_ids"], enc["offset_mapping"]
|
| 480 |
+
+ ends = [e for _, e in offs]
|
| 481 |
+
+ starts = [s for s, _ in offs]
|
| 482 |
+
+ prefix = bisect.bisect_right(ends, suffix_start)
|
| 483 |
+
+ spans = []
|
| 484 |
+
+ for cs, ce in option_spans or []:
|
| 485 |
+
+ a = bisect.bisect_right(ends, cs)
|
| 486 |
+
+ b = bisect.bisect_left(starts, ce)
|
| 487 |
+
+ if b <= a:
|
| 488 |
+
+ raise ValueError(f"option span {cs}:{ce} covers no token")
|
| 489 |
+
+ spans.append((a, b))
|
| 490 |
+
+ return ids, prefix, spans
|
| 491 |
+
+
|
| 492 |
+
+
|
| 493 |
+
+class ReadoutHead(torch.nn.Module):
|
| 494 |
+
+ def __init__(self, hidden: int, n_slots: int = MAX_SLOTS, head_dim: int = 256):
|
| 495 |
+
+ super().__init__()
|
| 496 |
+
+ self.slot = torch.nn.Parameter(torch.zeros(n_slots, hidden))
|
| 497 |
+
+ self.q = torch.nn.Linear(hidden, head_dim, bias=False)
|
| 498 |
+
+ self.k = torch.nn.Linear(hidden, head_dim, bias=False)
|
| 499 |
+
+ torch.nn.init.normal_(self.q.weight, std=hidden ** -0.5)
|
| 500 |
+
+ torch.nn.init.zeros_(self.k.weight)
|
| 501 |
+
+
|
| 502 |
+
+ @classmethod
|
| 503 |
+
+ def from_lm_head(cls, lm_head_weight, slot_ids: Sequence[int], head_dim: int) -> "ReadoutHead":
|
| 504 |
+
+ rows = lm_head_weight.detach()[list(slot_ids)].float()
|
| 505 |
+
+ head = cls(rows.shape[1], rows.shape[0], head_dim)
|
| 506 |
+
+ with torch.no_grad():
|
| 507 |
+
+ head.slot.copy_(rows.to(head.slot.device))
|
| 508 |
+
+ return head
|
| 509 |
+
+
|
| 510 |
+
+ def forward(self, h_ans, h_opt):
|
| 511 |
+
+ """h_ans [B, H], h_opt [B, K, H] -> scores [B, K] (fp32)."""
|
| 512 |
+
+ h_ans, h_opt = h_ans.float(), h_opt.float()
|
| 513 |
+
+ k = h_opt.shape[1]
|
| 514 |
+
+ slot = h_ans @ self.slot[:k].T
|
| 515 |
+
+ ptr = torch.einsum("bd,bkd->bk", self.q(h_ans), self.k(h_opt)) / math.sqrt(self.q.out_features)
|
| 516 |
+
+ return slot + ptr
|
| 517 |
+
+
|
| 518 |
+
+
|
| 519 |
+
+def pool_options(hidden, spans: Sequence[Sequence[tuple[int, int]]], kmax: int):
|
| 520 |
+
+ """Mean of hidden [B, T, H] over each option's token span -> [B, kmax, H] fp32 (zeros past a row's options)."""
|
| 521 |
+
+ bsz, _, dim = hidden.shape
|
| 522 |
+
+ dev = hidden.device
|
| 523 |
+
+ rows, toks, segs = [], [], []
|
| 524 |
+
+ for b, sp in enumerate(spans):
|
| 525 |
+
+ for k, (s, e) in enumerate(sp):
|
| 526 |
+
+ n = e - s
|
| 527 |
+
+ rows.append(torch.full((n,), b, dtype=torch.long))
|
| 528 |
+
+ toks.append(torch.arange(s, e, dtype=torch.long))
|
| 529 |
+
+ segs.append(torch.full((n,), b * kmax + k, dtype=torch.long))
|
| 530 |
+
+ rows, toks, segs = (torch.cat(x).to(dev) for x in (rows, toks, segs))
|
| 531 |
+
+ flat = hidden[rows, toks].float()
|
| 532 |
+
+ total = torch.zeros(bsz * kmax, dim, dtype=torch.float32, device=dev).index_add(0, segs, flat)
|
| 533 |
+
+ count = torch.zeros(bsz * kmax, dtype=torch.float32, device=dev).index_add(
|
| 534 |
+
+ 0, segs, torch.ones_like(segs, dtype=torch.float32))
|
| 535 |
+
+ return (total / count.clamp(min=1)[:, None]).view(bsz, kmax, dim)
|
| 536 |
+
+
|
| 537 |
+
+
|
| 538 |
+
+def final_norm(model):
|
| 539 |
+
+ """The final norm of a (possibly multimodal) Qwen-style decoder: its output is the readout hidden state."""
|
| 540 |
+
+ inner = getattr(model, "model", model)
|
| 541 |
+
+ inner = getattr(inner, "language_model", inner)
|
| 542 |
+
+ norm = getattr(inner, "norm", None)
|
| 543 |
+
+ if norm is None:
|
| 544 |
+
+ raise ValueError(f"cannot find the final norm of {type(model).__name__}")
|
| 545 |
+
+ return norm
|
| 546 |
+
+
|
| 547 |
+
+
|
| 548 |
+
+class HiddenCapture:
|
| 549 |
+
+ """Keeps the final-norm output of the latest forward (with its graph, so the head trains the backbone)."""
|
| 550 |
+
+
|
| 551 |
+
+ def __init__(self, model):
|
| 552 |
+
+ self.value = None
|
| 553 |
+
+ self.handle = final_norm(model).register_forward_hook(self._hook)
|
| 554 |
+
+
|
| 555 |
+
+ def _hook(self, module, args, output):
|
| 556 |
+
+ self.value = output
|
| 557 |
+
+
|
| 558 |
+
+ def pop(self):
|
| 559 |
+
+ out, self.value = self.value, None
|
| 560 |
+
+ if out is None:
|
| 561 |
+
+ raise RuntimeError("no hidden state captured; the forward did not reach the final norm")
|
| 562 |
+
+ return out
|
| 563 |
+
+
|
| 564 |
+
+
|
| 565 |
+
+@dataclass
|
| 566 |
+
+class Readout:
|
| 567 |
+
+ """A model's readout at runtime: its config, and for `head` the head module and the hidden-state hook."""
|
| 568 |
+
+
|
| 569 |
+
+ config: ReadoutConfig
|
| 570 |
+
+ head: ReadoutHead | None = None
|
| 571 |
+
+ capture: HiddenCapture | None = None
|
| 572 |
+
+
|
| 573 |
+
+ @classmethod
|
| 574 |
+
+ def attach(cls, model, config: ReadoutConfig, slot_ids: Sequence[int] | None = None,
|
| 575 |
+
+ head_path: str | Path | None = None, device=None) -> "Readout":
|
| 576 |
+
+ """Install the variant on `model`. A head is loaded from `head_path` when given, else initialised from the
|
| 577 |
+
+ model's LM-head rows of `slot_ids` (call before the model is sharded)."""
|
| 578 |
+
+ if config.noncausal:
|
| 579 |
+
+ install_noncausal(model)
|
| 580 |
+
+ if not config.head:
|
| 581 |
+
+ return cls(config)
|
| 582 |
+
+ if head_path is not None:
|
| 583 |
+
+ state = torch.load(head_path, map_location="cpu", weights_only=True)
|
| 584 |
+
+ head = ReadoutHead(state["slot"].shape[1], state["slot"].shape[0], state["q.weight"].shape[0])
|
| 585 |
+
+ head.load_state_dict(state)
|
| 586 |
+
+ else:
|
| 587 |
+
+ head = ReadoutHead.from_lm_head(model.get_output_embeddings().weight, slot_ids[: config.n_slots],
|
| 588 |
+
+ config.head_dim)
|
| 589 |
+
+ head = head.to(device or next(model.parameters()).device)
|
| 590 |
+
+ return cls(config, head, HiddenCapture(model))
|
| 591 |
+
+
|
| 592 |
+
+ def save(self, out_dir: str | Path) -> None:
|
| 593 |
+
+ self.config.save(out_dir)
|
| 594 |
+
+ if self.head is not None:
|
| 595 |
+
+ torch.save({k: v.detach().cpu() for k, v in self.head.state_dict().items()}, Path(out_dir) / HEAD_FILE)
|
| 596 |
+
+
|
| 597 |
+
+ @property
|
| 598 |
+
+ def max_slots(self) -> int:
|
| 599 |
+
+ return self.config.n_slots
|
| 600 |
+
diff --git a/train/common.py b/train/common.py
|
| 601 |
+
index 331206f..0c1c7d0 100644
|
| 602 |
+
--- a/train/common.py
|
| 603 |
+
+++ b/train/common.py
|
| 604 |
+
@@ -85,6 +85,8 @@ class Example:
|
| 605 |
+
target: list[float]
|
| 606 |
+
source: str
|
| 607 |
+
task: str
|
| 608 |
+
+ suffix_start: int = -1
|
| 609 |
+
+ option_spans: list[tuple[int, int]] | None = None
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
PAD_FAMILIES = ("next_action",)
|
| 613 |
+
@@ -185,6 +187,8 @@ def render_example(row: dict, tmpl, idx: int, seed: int | None = None, augment:
|
| 614 |
+
compact = augment and rng.random() < 0.5
|
| 615 |
+
state = serialize_state(row.get("state"), compact)
|
| 616 |
+
prompt = tmpl(state, rendered.suffix)
|
| 617 |
+
+ suffix_start = prompt.rindex(rendered.suffix)
|
| 618 |
+
+ spans = [(suffix_start + a, suffix_start + b) for a, b in rendered.option_spans or []]
|
| 619 |
+
return Example(
|
| 620 |
+
idx=idx,
|
| 621 |
+
prompt=prompt,
|
| 622 |
+
@@ -193,6 +197,8 @@ def render_example(row: dict, tmpl, idx: int, seed: int | None = None, augment:
|
| 623 |
+
target=target_vector(row["target"], rendered.labels),
|
| 624 |
+
source=str(row.get("source", "unknown")),
|
| 625 |
+
task=str(row.get("task", "unknown")),
|
| 626 |
+
+ suffix_start=suffix_start,
|
| 627 |
+
+ option_spans=spans or None,
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
@@ -244,6 +250,7 @@ class Bundle:
|
| 632 |
+
template_kwargs: dict
|
| 633 |
+
processor: Any = None
|
| 634 |
+
counter: Any = None
|
| 635 |
+
+ readout: Any = None
|
| 636 |
+
|
| 637 |
+
@property
|
| 638 |
+
def multimodal(self) -> bool:
|
| 639 |
+
@@ -290,12 +297,14 @@ def verify_slots(tokenizer, model_path: str) -> list[int]:
|
| 640 |
+
|
| 641 |
+
def load_bundle(model_path: str, device: str = "cuda:0", dtype: str = "bfloat16", train: bool = False,
|
| 642 |
+
multimodal: bool = False, chat_template: str | None = None, load_model: bool = True) -> Bundle:
|
| 643 |
+
- """Load a causal LM the same way qev.engine does, including the Qwen3.5 special case. With multimodal=True the
|
| 644 |
+
- vision model (Qwen3_5ForConditionalGeneration) and its processor are loaded instead of the text-only LM.
|
| 645 |
+
+ """Load a causal LM the same way qev.engine does (qev.engine.text_lm). With multimodal=True the vision model
|
| 646 |
+
+ (Qwen3_5ForConditionalGeneration, else AutoModelForImageTextToText) and its processor are loaded instead.
|
| 647 |
+
`chat_template` (a .jinja path) is only for base checkpoints that ship without one."""
|
| 648 |
+
import torch
|
| 649 |
+
import transformers
|
| 650 |
+
|
| 651 |
+
+ from qev.engine import load_kwargs, template_kwargs, text_lm
|
| 652 |
+
+
|
| 653 |
+
local = Path(model_path).exists()
|
| 654 |
+
common = {"local_files_only": local, "trust_remote_code": False}
|
| 655 |
+
config = transformers.AutoConfig.from_pretrained(model_path, **common)
|
| 656 |
+
@@ -311,27 +320,57 @@ def load_bundle(model_path: str, device: str = "cuda:0", dtype: str = "bfloat16"
|
| 657 |
+
tokenizer.chat_template = processor.chat_template
|
| 658 |
+
cls = transformers.Qwen3_5ForConditionalGeneration if config.model_type == "qwen3_5" else \
|
| 659 |
+
transformers.AutoModelForImageTextToText
|
| 660 |
+
- counter = mm.TokenCounter(processor)
|
| 661 |
+
+ counter = mm.make_counter(processor)
|
| 662 |
+
else:
|
| 663 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(model_path, **common)
|
| 664 |
+
if chat_template:
|
| 665 |
+
tokenizer.chat_template = Path(chat_template).read_text()
|
| 666 |
+
- cls = transformers.AutoModelForCausalLM
|
| 667 |
+
- if config.model_type in {"qwen3_5", "qwen3_5_text"}:
|
| 668 |
+
- cls = transformers.Qwen3_5ForCausalLM
|
| 669 |
+
- config = config.get_text_config()
|
| 670 |
+
+ cls, config = text_lm(transformers, config)
|
| 671 |
+
model = None
|
| 672 |
+
if load_model:
|
| 673 |
+
model = cls.from_pretrained(model_path, config=config, dtype=getattr(torch, dtype),
|
| 674 |
+
- device_map={"": device}, low_cpu_mem_usage=True, **common)
|
| 675 |
+
+ device_map={"": device}, low_cpu_mem_usage=True, **common,
|
| 676 |
+
+ **load_kwargs(config.model_type))
|
| 677 |
+
model.train() if train else model.eval()
|
| 678 |
+
+ if multimodal:
|
| 679 |
+
+ from train import mm
|
| 680 |
+
+
|
| 681 |
+
+ mm.pass_video_frame_counts(model)
|
| 682 |
+
model_type = config.model_type
|
| 683 |
+
- template_kwargs = {"enable_thinking": False} if "qwen" in model_type else {}
|
| 684 |
+
slot_ids = verify_slots(tokenizer, model_path)
|
| 685 |
+
if tokenizer.pad_token_id is None:
|
| 686 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 687 |
+
return Bundle(model=model, tokenizer=tokenizer, config=config, model_type=model_type,
|
| 688 |
+
- slot_ids=slot_ids, template_kwargs=template_kwargs, processor=processor, counter=counter)
|
| 689 |
+
+ slot_ids=slot_ids, template_kwargs=template_kwargs(model_type), processor=processor, counter=counter)
|
| 690 |
+
+
|
| 691 |
+
+
|
| 692 |
+
+MEDIA_MODULES = ("vision_tower", "embed_vision", "audio_tower", "embed_audio")
|
| 693 |
+
+
|
| 694 |
+
+
|
| 695 |
+
+def is_media_param(name: str) -> bool:
|
| 696 |
+
+ """Vision (and audio) encoder and projector weights: Qwen3.5's `visual`, gemma4's towers and embedders."""
|
| 697 |
+
+ dotted = f".{name}."
|
| 698 |
+
+ return ".visual." in dotted or name.startswith("visual") or any(f".{m}." in dotted for m in MEDIA_MODULES)
|
| 699 |
+
+
|
| 700 |
+
+
|
| 701 |
+
+def is_router_param(name: str) -> bool:
|
| 702 |
+
+ """MoE routing weights: gemma4 `router.*`, Qwen MoE `mlp.gate.weight` and `shared_expert_gate`."""
|
| 703 |
+
+ dotted = f".{name}."
|
| 704 |
+
+ return ".router." in dotted or ".mlp.gate." in dotted or ".shared_expert_gate." in dotted
|
| 705 |
+
+
|
| 706 |
+
+
|
| 707 |
+
+def norm_embed_params(model) -> dict:
|
| 708 |
+
+ """Language-model norm weights (every *Norm module's own parameters) and token embeddings, by name. A tied LM head
|
| 709 |
+
+ shares the embedding's parameter, so freezing these freezes the head too."""
|
| 710 |
+
+ out = {}
|
| 711 |
+
+ for mname, module in model.named_modules():
|
| 712 |
+
+ if is_media_param(mname) or is_router_param(mname):
|
| 713 |
+
+ continue
|
| 714 |
+
+ if "norm" in type(module).__name__.lower():
|
| 715 |
+
+ out.update({f"{mname}.{n}": p for n, p in module.named_parameters(recurse=False)})
|
| 716 |
+
+ elif "embed_tokens" in mname.split(".")[-1]:
|
| 717 |
+
+ out.update({f"{mname}.{n}": p for n, p in module.named_parameters(recurse=False)})
|
| 718 |
+
+ return out
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def linear_projection_modules(model) -> list[str]:
|
| 722 |
+
@@ -348,7 +387,7 @@ def linear_projection_modules(model) -> list[str]:
|
| 723 |
+
for name, module in model.named_modules():
|
| 724 |
+
if type(module) is not torch.nn.Linear:
|
| 725 |
+
continue
|
| 726 |
+
- if ".visual." in f".{name}." or name.startswith("visual"):
|
| 727 |
+
+ if ".visual." in f".{name}." or name.startswith("visual") or is_media_param(name) or is_router_param(name):
|
| 728 |
+
continue
|
| 729 |
+
short = name.split(".")[-1]
|
| 730 |
+
if short in {"lm_head", "router", "score", "classifier"}:
|
| 731 |
+
@@ -403,6 +442,65 @@ def readout_logits(model, input_ids, attention_mask, ends):
|
| 732 |
+
return out.logits[rows, pos]
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
+def batch_scores(bundle: Bundle, model, examples: Sequence[Example], rows: Sequence[dict], device):
|
| 736 |
+
+ """Option scores [B, Kmax] (-inf past each row's options) and their mask for a right-padded batch, under the
|
| 737 |
+
+ bundle's readout (qev.readout): causal or noncausal attention, slot_lm or head scoring. The same function scores
|
| 738 |
+
+ training steps, in-training evals and train.eval_mm, and qev.engine reproduces it for serving."""
|
| 739 |
+
+ import torch
|
| 740 |
+
+
|
| 741 |
+
+ from qev import readout as ro
|
| 742 |
+
+
|
| 743 |
+
+ rd = bundle.readout
|
| 744 |
+
+ cfg = rd.config if rd is not None else ro.ReadoutConfig()
|
| 745 |
+
+ ks = [len(ex.labels) for ex in examples]
|
| 746 |
+
+ if bundle.multimodal:
|
| 747 |
+
+ from train import mm
|
| 748 |
+
+
|
| 749 |
+
+ inputs, ends = mm.mm_inputs(bundle.processor, [ex.prompt for ex in examples],
|
| 750 |
+
+ [r.get("media") or [] for r in rows], device)
|
| 751 |
+
+ shifts = [bundle.counter.media_extra(r.get("media") or []) for r in rows]
|
| 752 |
+
+ else:
|
| 753 |
+
+ input_ids, attention_mask, ends = pad_batch([bundle.encode(ex.prompt) for ex in examples], bundle.tokenizer.pad_token_id, device)
|
| 754 |
+
+ inputs = {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 755 |
+
+ shifts = [0] * len(examples)
|
| 756 |
+
+ ctx = ro.blocks(None)
|
| 757 |
+
+ spans = None
|
| 758 |
+
+ if cfg.needs_layout:
|
| 759 |
+
+ prefixes, spans = [], []
|
| 760 |
+
+ for ex, shift, end in zip(examples, shifts, ends):
|
| 761 |
+
+ ids, prefix, sp = ro.token_layout(bundle.tokenizer, ex.prompt, ex.suffix_start, ex.option_spans)
|
| 762 |
+
+ if len(ids) + shift != end + 1:
|
| 763 |
+
+ raise ValueError(f"layout of row {ex.idx} has {len(ids) + shift} tokens, the batch has {end + 1}")
|
| 764 |
+
+ if cfg.head and len(sp) != len(ex.labels):
|
| 765 |
+
+ raise ValueError(f"row {ex.idx}: {len(sp)} option spans for {len(ex.labels)} options")
|
| 766 |
+
+ prefixes.append(prefix + shift)
|
| 767 |
+
+ spans.append([(a + shift, b + shift) for a, b in sp])
|
| 768 |
+
+ if cfg.noncausal:
|
| 769 |
+
+ width = inputs["input_ids"].shape[1]
|
| 770 |
+
+ ctx = ro.blocks(ro.block_ids(prefixes, [e + 1 for e in ends], width, device))
|
| 771 |
+
+ with ctx:
|
| 772 |
+
+ if cfg.head:
|
| 773 |
+
+ out = model(**inputs, use_cache=False, return_dict=True, logits_to_keep=1)
|
| 774 |
+
+ hidden = rd.capture.pop()
|
| 775 |
+
+ kmax = max(ks)
|
| 776 |
+
+ rows_ix = torch.arange(len(examples), device=hidden.device)
|
| 777 |
+
+ h_ans = hidden[rows_ix, torch.tensor(ends, device=hidden.device)]
|
| 778 |
+
+ scores = rd.head(h_ans, ro.pool_options(hidden, spans, kmax))
|
| 779 |
+
+ # every FSDP unit (the LM head too) must take part in the backward
|
| 780 |
+
+ scores = scores + 0.0 * out.logits.float().sum()
|
| 781 |
+
+ mask = torch.zeros((len(ks), kmax), dtype=torch.bool, device=scores.device)
|
| 782 |
+
+ for i, k in enumerate(ks):
|
| 783 |
+
+ mask[i, :k] = True
|
| 784 |
+
+ return scores.masked_fill(~mask, float("-inf")), mask
|
| 785 |
+
+ if bundle.multimodal:
|
| 786 |
+
+ from train import mm
|
| 787 |
+
+
|
| 788 |
+
+ vocab_logits = mm.mm_readout_logits(model, inputs, ends)
|
| 789 |
+
+ else:
|
| 790 |
+
+ vocab_logits = readout_logits(model, inputs["input_ids"], inputs["attention_mask"], ends)
|
| 791 |
+
+ return slot_view(vocab_logits, bundle.slot_ids, ks)
|
| 792 |
+
+
|
| 793 |
+
+
|
| 794 |
+
def slot_view(vocab_logits, slot_ids, ks):
|
| 795 |
+
"""Gather the first K slot logits per row into a padded [B, Kmax] tensor plus a mask."""
|
| 796 |
+
import torch
|
| 797 |
+
@@ -557,11 +655,7 @@ def collect_slot_logits(bundle: Bundle, rows: Sequence[dict], max_len: int = 409
|
| 798 |
+
readout_logits(bundle.model, ids, torch.ones_like(ids), [0])
|
| 799 |
+
for bi, batch in enumerate(batches):
|
| 800 |
+
exs = [examples[i] for i in batch]
|
| 801 |
+
- id_lists = [bundle.encode(ex.prompt) for ex in exs]
|
| 802 |
+
- input_ids, attention_mask, ends = pad_batch(id_lists, pad_id, dev)
|
| 803 |
+
- ks = [len(ex.labels) for ex in exs]
|
| 804 |
+
- vocab_logits = readout_logits(bundle.model, input_ids, attention_mask, ends)
|
| 805 |
+
- sel, _ = slot_view(vocab_logits, bundle.slot_ids, ks)
|
| 806 |
+
+ sel, _ = batch_scores(bundle, bundle.model, exs, [rows[ex.idx] for ex in exs], dev)
|
| 807 |
+
sel = sel.float().cpu().tolist()
|
| 808 |
+
for r, ex in enumerate(exs):
|
| 809 |
+
out.append(Scored(kind=ex.kind, k=len(ex.labels), logits=sel[r][: len(ex.labels)],
|
| 810 |
+
diff --git a/train/eval_mm.py b/train/eval_mm.py
|
| 811 |
+
index e87e72d..03a6022 100644
|
| 812 |
+
--- a/train/eval_mm.py
|
| 813 |
+
+++ b/train/eval_mm.py
|
| 814 |
+
@@ -48,6 +48,13 @@ def main() -> int:
|
| 815 |
+
mm.set_root(args.media_root)
|
| 816 |
+
bundle = common.load_bundle(args.model, device=args.device, dtype="bfloat16", multimodal=args.multimodal,
|
| 817 |
+
chat_template=args.chat_template)
|
| 818 |
+
+ from qev.readout import HEAD_FILE, Readout, ReadoutConfig
|
| 819 |
+
+
|
| 820 |
+
+ rcfg = ReadoutConfig.load(args.model)
|
| 821 |
+
+ head_path = Path(args.model) / HEAD_FILE
|
| 822 |
+
+ bundle.readout = Readout.attach(bundle.model, rcfg, slot_ids=bundle.slot_ids,
|
| 823 |
+
+ head_path=head_path if rcfg.head else None)
|
| 824 |
+
+ print(f"readout: attention {rcfg.attention}, scores {rcfg.readout}", flush=True)
|
| 825 |
+
results = {}
|
| 826 |
+
for spec in args.evals:
|
| 827 |
+
name, _, path = spec.partition("=")
|
| 828 |
+
diff --git a/train/fsdp.py b/train/fsdp.py
|
| 829 |
+
index c6ea61e..fadcfe2 100644
|
| 830 |
+
--- a/train/fsdp.py
|
| 831 |
+
+++ b/train/fsdp.py
|
| 832 |
+
@@ -75,9 +75,9 @@ def shard_model(model, world: int, bf16_compute: bool = True):
|
| 833 |
+
units = len(layers)
|
| 834 |
+
embed = model.get_input_embeddings()
|
| 835 |
+
head = model.get_output_embeddings()
|
| 836 |
+
- if head is not None and head.weight is embed.weight:
|
| 837 |
+
- raise SystemExit("--fsdp: tied input and output embeddings are not handled")
|
| 838 |
+
- for module in (embed, head):
|
| 839 |
+
+ # A tied embedding and head (gemma4) share one parameter, which must live in one unit: both stay in the root.
|
| 840 |
+
+ tied = head is not None and head.weight is embed.weight
|
| 841 |
+
+ for module in () if tied else (embed, head):
|
| 842 |
+
if module is not None:
|
| 843 |
+
to_fp32(module)
|
| 844 |
+
fully_shard(module, **kw)
|
| 845 |
+
@@ -87,6 +87,8 @@ def shard_model(model, world: int, bf16_compute: bool = True):
|
| 846 |
+
torch.cuda.empty_cache()
|
| 847 |
+
n = sum(p.numel() for p in model.parameters())
|
| 848 |
+
n_train = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 849 |
+
+ if tied:
|
| 850 |
+
+ log.info("FSDP: tied input embedding and LM head stay in the root unit")
|
| 851 |
+
log.info("FSDP: %d units + root over %d ranks, %.2fB parameters (%.2fB trained, %.2fB frozen), "
|
| 852 |
+
"%.1f GB of fp32 weights+grads+AdamW per rank", units, world, n / 1e9, n_train / 1e9, (n - n_train) / 1e9,
|
| 853 |
+
(16 * n_train + 4 * (n - n_train)) / world / 1e9)
|
| 854 |
+
diff --git a/train/mm.py b/train/mm.py
|
| 855 |
+
index 82b58a2..28826a9 100644
|
| 856 |
+
--- a/train/mm.py
|
| 857 |
+
+++ b/train/mm.py
|
| 858 |
+
@@ -124,24 +124,128 @@ class TokenCounter:
|
| 859 |
+
return len(self.tok(prompt, add_special_tokens=False)["input_ids"]) + self.media_extra(media)
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
+class ProbeCounter(TokenCounter):
|
| 863 |
+
+ """Exact lengths for processors without a Qwen-style patch grid (gemma4: aspect-ratio-preserving resize to a
|
| 864 |
+
+ soft-token budget, per-frame timestamps for video). Every media shape is probed once on blank pixels through the
|
| 865 |
+
+ processor itself, so the count is the processor's by construction."""
|
| 866 |
+
+
|
| 867 |
+
+ def __init__(self, processor):
|
| 868 |
+
+ self.processor = processor
|
| 869 |
+
+ self.tok = processor.tokenizer
|
| 870 |
+
+
|
| 871 |
+
+ def _extra(self, placeholder: str, **media) -> int:
|
| 872 |
+
+ base = f"a{placeholder}b"
|
| 873 |
+
+ out = self.processor(text=[base], **media)
|
| 874 |
+
+ return len(out["input_ids"][0]) - len(self.tok(base, add_special_tokens=False)["input_ids"])
|
| 875 |
+
+
|
| 876 |
+
+ @functools.lru_cache(maxsize=4096)
|
| 877 |
+
+ def image_extra(self, h: int, w: int) -> int:
|
| 878 |
+
+ from PIL import Image
|
| 879 |
+
+
|
| 880 |
+
+ return self._extra(self.processor.image_token, images=[Image.new("RGB", (w, h))])
|
| 881 |
+
+
|
| 882 |
+
+ @functools.lru_cache(maxsize=4096)
|
| 883 |
+
+ def video_extra(self, n: int, h: int, w: int, fps: float) -> int:
|
| 884 |
+
+ from PIL import Image
|
| 885 |
+
+ from transformers.video_utils import VideoMetadata
|
| 886 |
+
+
|
| 887 |
+
+ md = VideoMetadata(total_num_frames=n, fps=fps, frames_indices=list(range(n)), duration=n / fps)
|
| 888 |
+
+ return self._extra(self.processor.video_token, videos=[[Image.new("RGB", (w, h)) for _ in range(n)]],
|
| 889 |
+
+ video_metadata=[md], videos_kwargs=videos_kwargs(self.processor))
|
| 890 |
+
+
|
| 891 |
+
+ def media_extra(self, media: Sequence[dict]) -> int:
|
| 892 |
+
+ n = 0
|
| 893 |
+
+ for m in media:
|
| 894 |
+
+ if m["type"] == "image":
|
| 895 |
+
+ n += self.image_extra(int(m["h"]), int(m["w"]))
|
| 896 |
+
+ else:
|
| 897 |
+
+ n += self.video_extra(len(m["frames"]), int(m["h"]), int(m["w"]), float(m.get("fps") or 1.0))
|
| 898 |
+
+ return n
|
| 899 |
+
+
|
| 900 |
+
+
|
| 901 |
+
+def qwen_style(processor) -> bool:
|
| 902 |
+
+ return hasattr(processor.image_processor, "merge_size")
|
| 903 |
+
+
|
| 904 |
+
+
|
| 905 |
+
+def make_counter(processor) -> TokenCounter:
|
| 906 |
+
+ return TokenCounter(processor) if qwen_style(processor) else ProbeCounter(processor)
|
| 907 |
+
+
|
| 908 |
+
+
|
| 909 |
+
+def videos_kwargs(processor) -> dict:
|
| 910 |
+
+ """Frames are pre-extracted, so never resample them; cap_pixels_per_frame exists only for the Qwen processors."""
|
| 911 |
+
+ return {"do_sample_frames": False, "cap_pixels_per_frame": True} if qwen_style(processor) else {"do_sample_frames": False}
|
| 912 |
+
+
|
| 913 |
+
+
|
| 914 |
+
+def pass_video_frame_counts(model) -> None:
|
| 915 |
+
+ """transformers 5.19-5.20's Gemma4Model.forward drops num_frames_per_video on its way to get_video_features, which
|
| 916 |
+
+ then refuses every video. The forward concatenates the per-video features again right after, so counting all the
|
| 917 |
+
+ batch's frames as one video gives the same embeddings."""
|
| 918 |
+
+ import inspect
|
| 919 |
+
+
|
| 920 |
+
+ import torch
|
| 921 |
+
+
|
| 922 |
+
+ inner = getattr(model, "model", None)
|
| 923 |
+
+ original = getattr(inner, "get_video_features", None)
|
| 924 |
+
+ if original is None or "num_frames_per_video" not in inspect.signature(original).parameters:
|
| 925 |
+
+ return
|
| 926 |
+
+
|
| 927 |
+
+ def get_video_features(pixel_values_videos, video_position_ids=None, num_frames_per_video=None, **kwargs):
|
| 928 |
+
+ if num_frames_per_video is None:
|
| 929 |
+
+ num_frames_per_video = torch.tensor([pixel_values_videos.shape[0]], device=pixel_values_videos.device)
|
| 930 |
+
+ return original(pixel_values_videos, video_position_ids, num_frames_per_video, **kwargs)
|
| 931 |
+
+
|
| 932 |
+
+ inner.get_video_features = get_video_features
|
| 933 |
+
+
|
| 934 |
+
+
|
| 935 |
+
+def per_video_inputs(processor, prompts: Sequence[str], videos, metas):
|
| 936 |
+
+ """gemma4 videos one at a time: its video processor stacks a call's videos, so a batch whose videos differ in
|
| 937 |
+
+ frame count fails. The model flattens videos into one run of frames, so each video's frames are concatenated in
|
| 938 |
+
+ order, and each placeholder is expanded with the processor's own replace_video_token. Returns the expanded
|
| 939 |
+
+ prompts and the video tensors to add to the processor's text and image outputs."""
|
| 940 |
+
+ import torch
|
| 941 |
+
+
|
| 942 |
+
+ outs = [processor.video_processor(videos=[v], video_metadata=[m], return_metadata=True, do_sample_frames=False,
|
| 943 |
+
+ return_tensors="pt") for v, m in zip(videos, metas)]
|
| 944 |
+
+ token, j, expanded = processor.video_token, 0, []
|
| 945 |
+
+ for prompt in prompts:
|
| 946 |
+
+ parts = prompt.split(token)
|
| 947 |
+
+ text = parts[0]
|
| 948 |
+
+ for part in parts[1:]:
|
| 949 |
+
+ text += processor.replace_video_token(outs[j], video_idx=0) + part
|
| 950 |
+
+ j += 1
|
| 951 |
+
+ expanded.append(text)
|
| 952 |
+
+ if j != len(outs):
|
| 953 |
+
+ raise ValueError(f"{j} video placeholders for {len(outs)} videos")
|
| 954 |
+
+ tensors = {}
|
| 955 |
+
+ for k, v in outs[0].items():
|
| 956 |
+
+ if torch.is_tensor(v) and k in processor.model_input_names:
|
| 957 |
+
+ # 5.17 lays frames out as (videos, frames, ...), later versions as (frames, ...) plus num_frames_per_video
|
| 958 |
+
+ tensors[k] = torch.cat([o[k] for o in outs], dim=1 if v.ndim == 4 else 0)
|
| 959 |
+
+ return expanded, tensors
|
| 960 |
+
+
|
| 961 |
+
+
|
| 962 |
+
def mm_inputs(processor, prompts: Sequence[str], medias: Sequence[Sequence[dict]], device):
|
| 963 |
+
"""Processor tensors for a right-padded batch, and the readout index per row."""
|
| 964 |
+
images, videos, metas = [], [], []
|
| 965 |
+
for media in medias:
|
| 966 |
+
im, vi, md = load_media(media)
|
| 967 |
+
- images += im
|
| 968 |
+
+ images.append(im)
|
| 969 |
+
videos += vi
|
| 970 |
+
metas += md
|
| 971 |
+
kw = {}
|
| 972 |
+
- if images:
|
| 973 |
+
- kw["images"] = images
|
| 974 |
+
- if videos:
|
| 975 |
+
+ if any(images):
|
| 976 |
+
+ # the gemma4 processor matches images to prompts per row; the Qwen processors take one flat list
|
| 977 |
+
+ kw["images"] = [i for im in images for i in im] if qwen_style(processor) else images
|
| 978 |
+
+ prompts, video_tensors = list(prompts), {}
|
| 979 |
+
+ if videos and qwen_style(processor):
|
| 980 |
+
kw["videos"] = videos
|
| 981 |
+
kw["video_metadata"] = metas
|
| 982 |
+
- kw["videos_kwargs"] = {"do_sample_frames": False, "cap_pixels_per_frame": True}
|
| 983 |
+
+ kw["videos_kwargs"] = videos_kwargs(processor)
|
| 984 |
+
+ elif videos:
|
| 985 |
+
+ prompts, video_tensors = per_video_inputs(processor, prompts, videos, metas)
|
| 986 |
+
processor.tokenizer.padding_side = "right"
|
| 987 |
+
- out = processor(text=list(prompts), padding=True, return_tensors="pt", **kw)
|
| 988 |
+
- out = {k: v.to(device) for k, v in out.items()}
|
| 989 |
+
+ out = processor(text=prompts, padding=True, return_tensors="pt", **kw)
|
| 990 |
+
+ out = {k: v.to(device) for k, v in {**out, **video_tensors}.items()}
|
| 991 |
+
ends = (out["attention_mask"].sum(dim=1) - 1).tolist()
|
| 992 |
+
return out, ends
|
| 993 |
+
|
| 994 |
+
diff --git a/train/sft.py b/train/sft.py
|
| 995 |
+
index 4f6f7bd..bc4ccf5 100644
|
| 996 |
+
--- a/train/sft.py
|
| 997 |
+
+++ b/train/sft.py
|
| 998 |
+
@@ -26,6 +26,7 @@ import logging
|
| 999 |
+
import math
|
| 1000 |
+
import os
|
| 1001 |
+
import random
|
| 1002 |
+
+import re
|
| 1003 |
+
import time
|
| 1004 |
+
from pathlib import Path
|
| 1005 |
+
|
| 1006 |
+
@@ -97,6 +98,13 @@ def build_parser() -> argparse.ArgumentParser:
|
| 1007 |
+
p.add_argument("--full-finetune", action="store_true",
|
| 1008 |
+
help="train every language-model weight (fp32 master weights, bf16 autocast forward) instead of LoRA")
|
| 1009 |
+
p.add_argument("--train-vision", action="store_true", help="with --full-finetune: also train the vision tower")
|
| 1010 |
+
+ p.add_argument("--freeze-router", action="store_true",
|
| 1011 |
+
+ help="with --full-finetune: keep MoE routers frozen (the loss has no load-balancing term)")
|
| 1012 |
+
+ p.add_argument("--freeze-norms-embeds", action="store_true",
|
| 1013 |
+
+ help="with --full-finetune: also keep every norm weight and the token embedding (with a tied LM head) "
|
| 1014 |
+
+ "frozen")
|
| 1015 |
+
+ p.add_argument("--experts-implementation", default=None,
|
| 1016 |
+
+ help="MoE experts kernel (eager, grouped_mm, batched_mm); default: transformers' choice")
|
| 1017 |
+
p.add_argument("--fsdp", action="store_true",
|
| 1018 |
+
help="with --full-finetune under torchrun: shard weights, gradients and AdamW state over the ranks "
|
| 1019 |
+
"(train/fsdp.py) instead of a full fp32 copy per GPU; needed for models the size of Qwen3.8-27B")
|
| 1020 |
+
@@ -108,6 +116,14 @@ def build_parser() -> argparse.ArgumentParser:
|
| 1021 |
+
"train one step on each listed micro-batch (one GPU), peak memory reset per step, no final eval")
|
| 1022 |
+
p.add_argument("--dump-first-grad", default=None,
|
| 1023 |
+
help="test hook: after the first step's all-reduce, rank 0 saves the adapter gradients here")
|
| 1024 |
+
+ p.add_argument("--attention", choices=["causal", "noncausal"], default="causal",
|
| 1025 |
+
+ help="noncausal: bidirectional within the prefix and within the question suffix in the full-attention "
|
| 1026 |
+
+ "layers (qev.readout)")
|
| 1027 |
+
+ p.add_argument("--readout", choices=["slot_lm", "head"], default="slot_lm",
|
| 1028 |
+
+ help="head: learned slot + pointer head over the final hidden states instead of LM-head letter logits")
|
| 1029 |
+
+ p.add_argument("--head-dim", type=int, default=256, help="pointer projection width of the readout head")
|
| 1030 |
+
+ p.add_argument("--head-lr", type=float, default=1e-4, help="peak learning rate of the pointer projections "
|
| 1031 |
+
+ "(the head's slot rows use --lr)")
|
| 1032 |
+
p.add_argument("--disable-fla-kernels", action="store_true",
|
| 1033 |
+
help="force the reference PyTorch gated delta rule instead of the fla kernel "
|
| 1034 |
+
"(needed on H100/H200 with Triton in [3.4.0, 3.7.1); correct but much slower)")
|
| 1035 |
+
@@ -326,10 +342,7 @@ def collect_mm(bundle, rows, max_len: int, batch_tokens: int, max_rows: int, dev
|
| 1036 |
+
common.readout_logits(bundle.model, ids, torch.ones_like(ids), [0])
|
| 1037 |
+
for b in batches:
|
| 1038 |
+
exs = [examples[usable[j]] for j in b]
|
| 1039 |
+
- inputs, ends = mm.mm_inputs(bundle.processor, [ex.prompt for ex in exs],
|
| 1040 |
+
- [rows[ex.idx].get("media") or [] for ex in exs], device)
|
| 1041 |
+
- vocab_logits = mm.mm_readout_logits(bundle.model, inputs, ends)
|
| 1042 |
+
- sel, _ = common.slot_view(vocab_logits, bundle.slot_ids, [len(ex.labels) for ex in exs])
|
| 1043 |
+
+ sel, _ = common.batch_scores(bundle, bundle.model, exs, [rows[ex.idx] for ex in exs], device)
|
| 1044 |
+
sel = sel.float().cpu().tolist()
|
| 1045 |
+
for r, ex in enumerate(exs):
|
| 1046 |
+
out.append(common.Scored(kind=ex.kind, k=len(ex.labels), logits=sel[r][: len(ex.labels)],
|
| 1047 |
+
@@ -339,6 +352,13 @@ def collect_mm(bundle, rows, max_len: int, batch_tokens: int, max_rows: int, dev
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
def save_weights(model, bundle, out_dir: Path, full: bool, sharded: bool = False, is_main: bool = True) -> None:
|
| 1051 |
+
+ _save_weights(model, bundle, out_dir, full, sharded, is_main)
|
| 1052 |
+
+ if is_main and bundle.readout is not None:
|
| 1053 |
+
+ out_dir.mkdir(parents=True, exist_ok=True)
|
| 1054 |
+
+ bundle.readout.save(out_dir)
|
| 1055 |
+
+
|
| 1056 |
+
+
|
| 1057 |
+
+def _save_weights(model, bundle, out_dir: Path, full: bool, sharded: bool = False, is_main: bool = True) -> None:
|
| 1058 |
+
"""LoRA: the adapter. Full fine-tuning: the whole model in bf16 (from the fp32 master weights, copied to CPU),
|
| 1059 |
+
with tokenizer and processor, loadable like the base checkpoint. Sharded (--fsdp): every rank must call it,
|
| 1060 |
+
the weights are gathered to rank 0's CPU and written there as HF safetensors shards."""
|
| 1061 |
+
@@ -560,6 +580,8 @@ def main(argv=None) -> int:
|
| 1062 |
+
raise SystemExit("--fsdp is implemented without --share-prefix")
|
| 1063 |
+
if args.disable_fla_kernels:
|
| 1064 |
+
common.block_fla_kernels()
|
| 1065 |
+
+ if (args.attention != "causal" or args.readout != "slot_lm") and args.share_prefix:
|
| 1066 |
+
+ raise SystemExit("--share-prefix supports only causal slot_lm")
|
| 1067 |
+
|
| 1068 |
+
import torch
|
| 1069 |
+
from peft import LoraConfig, get_peft_model
|
| 1070 |
+
@@ -600,13 +622,33 @@ def main(argv=None) -> int:
|
| 1071 |
+
if args.plan_only:
|
| 1072 |
+
return plan_only(bundle, rows, args, world)
|
| 1073 |
+
log.info("model_type=%s template_kwargs=%s", bundle.model_type, bundle.template_kwargs)
|
| 1074 |
+
+ from qev.readout import Readout, ReadoutConfig
|
| 1075 |
+
+
|
| 1076 |
+
+ bundle.readout = Readout.attach(bundle.model, ReadoutConfig(attention=args.attention, readout=args.readout,
|
| 1077 |
+
+ head_dim=args.head_dim),
|
| 1078 |
+
+ slot_ids=bundle.slot_ids, device=torch.device(args.device))
|
| 1079 |
+
+ head = bundle.readout.head
|
| 1080 |
+
+ if head is not None and world > 1:
|
| 1081 |
+
+ for prm in head.parameters():
|
| 1082 |
+
+ dist.broadcast(prm.data, 0)
|
| 1083 |
+
+ log.info("readout: attention %s, scores %s", args.attention, args.readout)
|
| 1084 |
+
|
| 1085 |
+
if args.full_finetune:
|
| 1086 |
+
model = bundle.model
|
| 1087 |
+
for name, prm in model.named_parameters():
|
| 1088 |
+
- prm.requires_grad = args.train_vision or not (".visual." in f".{name}." or name.startswith("visual"))
|
| 1089 |
+
- log.info("full fine-tuning: fp32 master weights, bf16 autocast forward, vision tower %s",
|
| 1090 |
+
- "trained" if args.train_vision else "frozen")
|
| 1091 |
+
+ prm.requires_grad = (args.train_vision or not common.is_media_param(name)) and \
|
| 1092 |
+
+ not (args.freeze_router and common.is_router_param(name))
|
| 1093 |
+
+ if args.freeze_norms_embeds:
|
| 1094 |
+
+ held = common.norm_embed_params(model)
|
| 1095 |
+
+ for prm in held.values():
|
| 1096 |
+
+ prm.requires_grad = False
|
| 1097 |
+
+ log.info("froze %d norm/embedding tensors, %.2fM parameters: %s", len(held),
|
| 1098 |
+
+ sum(p.numel() for p in held.values()) / 1e6, sorted({re.sub(r"\.\d+\.", ".N.", n) for n in held}))
|
| 1099 |
+
+ frozen = [n for n, prm in model.named_parameters() if not prm.requires_grad]
|
| 1100 |
+
+ log.info("full fine-tuning: fp32 master weights, bf16 autocast forward, vision tower %s, routers %s; "
|
| 1101 |
+
+ "%d frozen tensors under %s", "trained" if args.train_vision else "frozen",
|
| 1102 |
+
+ "frozen" if args.freeze_router else "trained", len(frozen),
|
| 1103 |
+
+ sorted({".".join(n.split(".")[:3]) for n in frozen if not common.is_router_param(n)}))
|
| 1104 |
+
else:
|
| 1105 |
+
targets_arg = ([m.strip() for m in args.target_modules.split(",")] if args.target_modules
|
| 1106 |
+
else common.linear_projection_modules(bundle.model))
|
| 1107 |
+
@@ -634,7 +676,13 @@ def main(argv=None) -> int:
|
| 1108 |
+
|
| 1109 |
+
trainable = sum(p.numel() for p in params)
|
| 1110 |
+
total = sum(p.numel() for p in model.parameters())
|
| 1111 |
+
- log.info("trainable %.2fM of %.2fM parameters (%.3f%%)", trainable / 1e6, total / 1e6, 100 * trainable / total)
|
| 1112 |
+
+ log.info("trainable %.2fM of %.2fM parameters (%.3f%%), frozen %.2fM", trainable / 1e6, total / 1e6,
|
| 1113 |
+
+ 100 * trainable / total, (total - trainable) / 1e6)
|
| 1114 |
+
+ if args.experts_implementation:
|
| 1115 |
+
+ bundle.model.set_experts_implementation(args.experts_implementation)
|
| 1116 |
+
+ experts = getattr(bundle.model.config.get_text_config(), "_experts_implementation", None)
|
| 1117 |
+
+ if any(common.is_router_param(n) for n, _ in model.named_parameters()):
|
| 1118 |
+
+ log.info("MoE experts implementation: %s", experts)
|
| 1119 |
+
|
| 1120 |
+
if args.gradient_checkpointing:
|
| 1121 |
+
if not args.full_finetune:
|
| 1122 |
+
@@ -696,6 +744,13 @@ def main(argv=None) -> int:
|
| 1123 |
+
opt = torch.optim.AdamW(params, lr=args.lr, weight_decay=args.weight_decay, betas=(0.9, 0.95), eps=1e-8,
|
| 1124 |
+
fused=bool(args.full_finetune))
|
| 1125 |
+
sched = get_cosine_schedule_with_warmup(opt, num_warmup_steps=warmup, num_training_steps=max(total_steps, 1))
|
| 1126 |
+
+ head_opt = head_sched = None
|
| 1127 |
+
+ if head is not None:
|
| 1128 |
+
+ head_opt = torch.optim.AdamW([{"params": [head.slot], "lr": args.lr},
|
| 1129 |
+
+ {"params": [head.q.weight, head.k.weight], "lr": args.head_lr}],
|
| 1130 |
+
+ weight_decay=0.0, betas=(0.9, 0.95), eps=1e-8)
|
| 1131 |
+
+ head_sched = get_cosine_schedule_with_warmup(head_opt, num_warmup_steps=warmup,
|
| 1132 |
+
+ num_training_steps=max(total_steps, 1))
|
| 1133 |
+
|
| 1134 |
+
logf = open(log_path, "a", encoding="utf-8") if is_main else open(os.devnull, "w")
|
| 1135 |
+
step = 0
|
| 1136 |
+
@@ -729,25 +784,16 @@ def main(argv=None) -> int:
|
| 1137 |
+
examples.append(common.render_example(rows[i], bundle.template_for(rows[i]), i, seed=seed,
|
| 1138 |
+
augment=args.augment, option_pool=OPTION_POOL,
|
| 1139 |
+
pad_prob=args.pad_options))
|
| 1140 |
+
- if bundle.multimodal:
|
| 1141 |
+
- from train import mm
|
| 1142 |
+
-
|
| 1143 |
+
- inputs, ends = mm.mm_inputs(bundle.processor, [ex.prompt for ex in examples],
|
| 1144 |
+
- [rows[i].get("media") or [] for i in idx], device)
|
| 1145 |
+
- with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_autocast(args)):
|
| 1146 |
+
- vocab_logits = mm.mm_readout_logits(model, inputs, ends)
|
| 1147 |
+
- else:
|
| 1148 |
+
- id_lists = [bundle.encode(ex.prompt) for ex in examples]
|
| 1149 |
+
- input_ids, attention_mask, ends = common.pad_batch(id_lists, pad_id, device)
|
| 1150 |
+
- with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_autocast(args)):
|
| 1151 |
+
- vocab_logits = common.readout_logits(model, input_ids, attention_mask, ends)
|
| 1152 |
+
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_autocast(args)):
|
| 1153 |
+
+ sel, mask = common.batch_scores(bundle, model, examples, [rows[i] for i in idx], device)
|
| 1154 |
+
ks = [len(ex.labels) for ex in examples]
|
| 1155 |
+
targets = [ex.target for ex in examples]
|
| 1156 |
+
kmax = max(ks)
|
| 1157 |
+
tgt = torch.zeros((len(ks), kmax), dtype=torch.float32, device=device)
|
| 1158 |
+
for r, t in enumerate(targets):
|
| 1159 |
+
tgt[r, : len(t)] = torch.tensor(t, dtype=torch.float32, device=device)
|
| 1160 |
+
- sel, mask = common.slot_view(vocab_logits, bundle.slot_ids, ks)
|
| 1161 |
+
+ if kind == "group":
|
| 1162 |
+
+ sel, mask = common.slot_view(vocab_logits, bundle.slot_ids, ks)
|
| 1163 |
+
return sel, mask, tgt
|
| 1164 |
+
|
| 1165 |
+
if eval_sets and args.eval_at_start:
|
| 1166 |
+
@@ -802,6 +848,17 @@ def main(argv=None) -> int:
|
| 1167 |
+
gnorm = torch.nn.utils.clip_grad_norm_(params, args.max_grad_norm)
|
| 1168 |
+
if hasattr(gnorm, "full_tensor"):
|
| 1169 |
+
gnorm = gnorm.full_tensor()
|
| 1170 |
+
+ if head is not None:
|
| 1171 |
+
+ for prm in head.parameters():
|
| 1172 |
+
+ if prm.grad is None:
|
| 1173 |
+
+ prm.grad = torch.zeros_like(prm)
|
| 1174 |
+
+ if world > 1:
|
| 1175 |
+
+ dist.all_reduce(prm.grad)
|
| 1176 |
+
+ prm.grad /= grad_scale
|
| 1177 |
+
+ torch.nn.utils.clip_grad_norm_(list(head.parameters()), args.max_grad_norm)
|
| 1178 |
+
+ head_opt.step()
|
| 1179 |
+
+ head_sched.step()
|
| 1180 |
+
+ head_opt.zero_grad(set_to_none=True)
|
| 1181 |
+
try:
|
| 1182 |
+
opt.step()
|
| 1183 |
+
except torch.OutOfMemoryError:
|
setup.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Usage: bash setup.sh [WORKDIR=.] (image: pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel, one CUDA GPU)
|
| 2 |
+
# Installs the serving runtime (OneJev @81ce62f + serve.patch) and the Decision Index kit, pinned as in our runs.
|
| 3 |
+
set -e
|
| 4 |
+
# the image's Python is Debian's system Python, which refuses pip installs without this
|
| 5 |
+
export PIP_BREAK_SYSTEM_PACKAGES=1
|
| 6 |
+
B=$(cd "$(dirname "$0")" && pwd); W=${1:-.}
|
| 7 |
+
ONEJEV=81ce62f1597c91e46767d4d02d6ac2e18534fe94; KIT=f5a6e4fd85fed05e77878dfc4966d0568bfb45ec
|
| 8 |
+
command -v git >/dev/null || { apt-get update -qq; apt-get install -y -qq git >/dev/null; }
|
| 9 |
+
cd "$W"
|
| 10 |
+
[ -d OneJev ] || git clone -q https://github.com/OmniJev/OneJev.git
|
| 11 |
+
git -C OneJev checkout -q -f $ONEJEV && git -C OneJev clean -fdq && git -C OneJev apply "$B/serve.patch"
|
| 12 |
+
[ -d decision-index ] || git clone -q https://github.com/apolinario/decision-index.git
|
| 13 |
+
git -C decision-index checkout -q -f $KIT
|
| 14 |
+
# Keep the image's CUDA build of torch: unpinned, pip resolves torch>=2.6 to the newest wheel (another CUDA).
|
| 15 |
+
# Gemma 4's experts run on torch's grouped_mm, which needs torch >= 2.9; older torch falls back to a slow per-expert loop.
|
| 16 |
+
python -c "import torch, torchvision; print(f'torch=={torch.__version__}\ntorchvision=={torchvision.__version__}')" > image-torch.txt
|
| 17 |
+
pip install -q -c "$B/constraints.txt" -c image-torch.txt -e "./OneJev[train]" huggingface_hub hf_xet brotli httpx
|
| 18 |
+
pip install -q --no-deps -e ./decision-index
|