File size: 8,971 Bytes
e024af2 8413490 e024af2 8413490 e024af2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | """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
|