Download model.py from Zhuhan/MiraJudge: direct link, hf CLI and curl.
- Browser
- Download file 8.97 kB
-
https://huggingface.co/Zhuhan/MiraJudge/resolve/main/model.py
- Command line
-
hf download hf://Zhuhan/MiraJudge/model.py
-
curl -L -o model.py https://huggingface.co/Zhuhan/MiraJudge/resolve/main/model.py
8.97 kB
| """Trainable d3 scorer: the essay state is encoded once (prefix_bidir), every trait question reads it, and the code | |
| readout gives a distribution over the rubric levels. Wraps the d3 runtime's StateOnce with autograd, fla kernels, | |
| per-layer activation checkpointing and LoRA.""" | |
| import importlib.util | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import torch | |
| import torch.nn.functional as F | |
| from torch.utils.checkpoint import checkpoint | |
| CODE = Path("/hpc/group/honglab/zb78/cache/models/d3.1-nano-code") | |
| LORA_TARGETS = ["q_proj", "k_proj", "v_proj", "o_proj", "in_proj_qkv", "in_proj_z", "out_proj", | |
| "gate_proj", "up_proj", "down_proj"] | |
| def _causal_attention(so, attn, hidden, rope, entry, present): | |
| """StateOnce._attention with causal masks (ablation of prefix_bidir): the state and each question block attend | |
| only to earlier tokens.""" | |
| shape = hidden.shape[:-1] | |
| heads = (*shape, -1, attn.head_dim) | |
| query, gate = torch.chunk(attn.q_proj(hidden).view(*shape, -1, attn.head_dim * 2), 2, dim=-1) | |
| gate = gate.reshape(*shape, -1) | |
| query = attn.q_norm(query.view(heads)).transpose(1, 2) | |
| key = attn.k_norm(attn.k_proj(hidden).view(heads)).transpose(1, 2) | |
| value = attn.v_proj(hidden).view(heads).transpose(1, 2) | |
| query, key = so.qwen.apply_rotary_pos_emb(query, key, *rope) | |
| length = shape[-1] | |
| tril = torch.ones(length, length, dtype=torch.bool, device=hidden.device).tril() | |
| if entry is None: | |
| entry, keys, values, mask = (key, value), key, value, tril | |
| else: | |
| rows, state = shape[0], entry[0].shape[2] | |
| keys = torch.cat([entry[0].expand(rows, -1, -1, -1), key], dim=2) | |
| values = torch.cat([entry[1].expand(rows, -1, -1, -1), value], dim=2) | |
| mask = torch.ones(rows, 1, length, state + length, dtype=torch.bool, device=hidden.device) | |
| mask[:, 0, :, state:] = present[:, None, :] & tril | |
| groups = query.shape[1] // keys.shape[1] | |
| if groups > 1: | |
| keys, values = keys.repeat_interleave(groups, dim=1), values.repeat_interleave(groups, dim=1) | |
| out = F.scaled_dot_product_attention(query, keys, values, attn_mask=mask, scale=attn.scaling) | |
| return attn.o_proj(out.transpose(1, 2).reshape(*shape, -1) * torch.sigmoid(gate)), entry | |
| def _module(name): | |
| if name in sys.modules: | |
| return sys.modules[name] | |
| sys.path.insert(0, str(CODE)) | |
| spec = importlib.util.spec_from_file_location(name, CODE / f"{name}.py") | |
| mod = importlib.util.module_from_spec(spec) | |
| sys.modules[name] = mod | |
| spec.loader.exec_module(mod) | |
| return mod | |
| def _fla_delta_rule(): | |
| """fla's chunked gated delta rule with the signature transformers' torch fallback is called with.""" | |
| from fla.ops.gated_delta_rule import chunk_gated_delta_rule | |
| def rule(query, key, value, g, beta, initial_state=None, output_final_state=False, | |
| use_qk_l2norm_in_kernel=False, **_): | |
| o, s = chunk_gated_delta_rule(query, key, value, g=g, beta=beta, initial_state=initial_state, | |
| output_final_state=output_final_state, | |
| use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel) | |
| return o, s | |
| return rule | |
| class Scorer(torch.nn.Module): | |
| """``root``: a d3 checkpoint, or a plain Qwen3.5 checkpoint whose readout starts from the LM head rows of the | |
| option codes. ``lora``: rank (0 freezes the backbone). ``causal``: causal instead of prefix_bidir attention.""" | |
| def __init__(self, root, device="cuda", lora=0, alpha=None, grad_ckpt=True, causal=False): | |
| super().__init__() | |
| from safetensors.torch import load_file | |
| from transformers import AutoTokenizer | |
| from transformers.models.qwen3_5 import modeling_qwen3_5 as qwen | |
| rt, self.fmt = _module("d3_runtime"), _module("d3_format") | |
| root = Path(root) | |
| dc = json.loads((CODE / "decision_config.json").read_text()) | |
| self.codes, self.code_ids = dc["codes"], dc["token_ids"] | |
| tok_root = root if (root / "tokenizer.json").exists() else CODE | |
| self.tokenizer = AutoTokenizer.from_pretrained(str(tok_root)) | |
| self.backbone = qwen.Qwen3_5Model.from_pretrained(str(root), dtype=torch.bfloat16, attn_implementation="sdpa", | |
| device_map={"": device}) | |
| self.lm = self.backbone.language_model | |
| if (root / "readout.safetensors").exists(): | |
| w = load_file(str(root / "readout.safetensors"))["weight"].float() | |
| else: | |
| w = self.lm.embed_tokens.weight[torch.tensor(self.code_ids)].detach().float().cpu() | |
| self.readout = torch.nn.Parameter(w.to(device)) | |
| self.backbone.requires_grad_(False) | |
| if lora: | |
| from peft import LoraConfig, inject_adapter_in_model | |
| cfg = LoraConfig(r=lora, lora_alpha=alpha or 2 * lora, lora_dropout=0.0, target_modules=LORA_TARGETS) | |
| inject_adapter_in_model(cfg, self.lm) | |
| for n, p in self.lm.named_parameters(): | |
| if "lora_" in n: | |
| p.data = p.data.float() | |
| p.requires_grad_(True) | |
| qwen.torch_chunk_gated_delta_rule = _fla_delta_rule() | |
| self.so = rt.StateOnce(self.lm) | |
| if causal: | |
| import types | |
| self.so._attention = types.MethodType(_causal_attention, self.so) | |
| self.grad_ckpt = grad_ckpt | |
| self.device = torch.device(device) | |
| def trainable(self): | |
| return {n: p for n, p in self.named_parameters() if p.requires_grad} | |
| def encode(self, rec): | |
| """Token ids of the state segment and of each question block (shared state, per-question remainder).""" | |
| pieces, state_ids = [], None | |
| for q in rec["questions"]: | |
| rendered = {"type": "choice", "instructions": q["instructions"], "criteria": {t: None for t in q["levels"]}} | |
| text = self.fmt.render(self.tokenizer, rec["state"], rendered, self.codes) | |
| ids, n = self.fmt.encode_split(self.tokenizer, text, rec["state"]) | |
| if state_ids is None: | |
| state_ids = ids[:n] | |
| pieces.append(ids[n:]) | |
| return state_ids, pieces | |
| def _run(self, layer, softmax, hidden, rope, entry, present): | |
| if self.grad_ckpt and torch.is_grad_enabled(): | |
| return checkpoint(self.so._layer, layer, softmax, hidden, rope, entry, present, use_reentrant=False) | |
| return self.so._layer(layer, softmax, hidden, rope, entry, present) | |
| def forward(self, state_ids, pieces, sizes): | |
| """Log-probabilities over each question's levels: a list of [n_levels] tensors.""" | |
| dev, lm = self.device, self.lm | |
| embed = lm.embed_tokens | |
| s = torch.as_tensor([state_ids], device=dev) | |
| hidden = embed(s) | |
| pos = torch.arange(len(state_ids), device=dev).view(1, 1, -1).expand(3, 1, -1) | |
| rope = lm.rotary_emb(hidden, pos) | |
| cache = [] | |
| for layer, softmax in self.so.stack: | |
| hidden, entry = self._run(layer, softmax, hidden, rope, None, None) | |
| cache.append(entry) | |
| width = max(map(len, pieces)) | |
| ids = torch.full((len(pieces), width), self.tokenizer.pad_token_id or 0, dtype=torch.long) | |
| for r, p in enumerate(pieces): | |
| ids[r, :len(p)] = torch.as_tensor(p) | |
| q = embed(ids.to(dev)) | |
| lengths = [len(p) for p in pieces] | |
| present = torch.arange(width, device=dev)[None] < torch.as_tensor(lengths, device=dev)[:, None] | |
| steps = (len(state_ids) + torch.arange(width, device=dev)).view(1, 1, -1).expand(3, len(pieces), -1) | |
| qrope = lm.rotary_emb(q, steps) | |
| h = q * present[..., None].to(q.dtype) | |
| for (layer, softmax), entry in zip(self.so.stack, cache): | |
| h, _ = self._run(layer, softmax, h, qrope, entry, present) | |
| last = torch.as_tensor([n - 1 for n in lengths], device=dev) | |
| h = lm.norm(h[torch.arange(len(pieces), device=dev), last]) | |
| logits = h.float() @ self.readout.T | |
| return [F.log_softmax(logits[i, :k], -1) for i, k in enumerate(sizes)] | |
| def resolved_dist(p, rule): | |
| """Distribution of the resolved score (in level-index units: sum spans 0..2(n-1), mean in half steps) from the | |
| per-rater level distribution ``p`` [n], raters drawn independently given the essay.""" | |
| if rule in ("single", "half"): | |
| return p | |
| if rule == "max": | |
| c = torch.cumsum(p, 0) ** 2 | |
| return torch.diff(c, prepend=c.new_zeros(1)) | |
| conv = F.conv1d(p.view(1, 1, -1), p.flip(0).view(1, 1, -1), padding=len(p) - 1).view(-1) | |
| return conv # sum or mean: index k = r1 + r2 | |
| def resolved_value(p, rule, offset): | |
| """Expected resolved score on the dataset's scale.""" | |
| d = resolved_dist(p, rule) | |
| k = torch.arange(len(d), device=d.device, dtype=d.dtype) | |
| e = (d * k).sum() | |
| if rule in ("sum",): | |
| return e + 2 * offset | |
| if rule in ("mean", "half"): | |
| return e / 2 + offset | |
| return e + offset | |