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|
| 3 |
+
One forward pass answers all questions in a request:
|
| 4 |
+
- state encoded once (state tokens are blind to question tokens -> cacheable)
|
| 5 |
+
- question contexts and option spans are isolated branches off the state
|
| 6 |
+
- options share position_ids and never see each other -> permutation invariant
|
| 7 |
+
- ISAB set head reintroduces option interaction without order dependence
|
| 8 |
+
"""
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers import AutoModel
|
| 12 |
+
|
| 13 |
+
from .heads import SetChoiceHead, NoulHead, RegressHead
|
| 14 |
+
from .ngram import AuxEmbedding, NGramEncoder
|
| 15 |
+
from .packing import build_additive_mask, SEG_OPT, SEG_ANS, SEG_QCTX, SEG_STATE
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class AleaModel(nn.Module):
|
| 19 |
+
def __init__(self, model_name="Qwen/Qwen3-0.6B", n_inducing=16,
|
| 20 |
+
use_set_attn=True, attn_impl="eager",
|
| 21 |
+
use_aux_embed=False, use_ngram=False,
|
| 22 |
+
ngram_orders=(2, 3, 4), ngram_buckets=262144, d_ng=128,
|
| 23 |
+
use_ngram2=False):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.backbone = AutoModel.from_pretrained(
|
| 26 |
+
model_name, torch_dtype=torch.bfloat16,
|
| 27 |
+
attn_implementation=attn_impl)
|
| 28 |
+
d = self.backbone.config.hidden_size
|
| 29 |
+
self.dim = d
|
| 30 |
+
self.choice_head = SetChoiceHead(d, n_inducing, use_set_attn=use_set_attn)
|
| 31 |
+
self.score_head = SetChoiceHead(d, n_inducing, use_set_attn=use_set_attn)
|
| 32 |
+
self.noul_head = NoulHead(d)
|
| 33 |
+
self.regress_head = RegressHead(d)
|
| 34 |
+
vocab = self.backbone.config.vocab_size
|
| 35 |
+
self.aux_embed = AuxEmbedding(vocab, d) if use_aux_embed else None
|
| 36 |
+
self.ngram = (NGramEncoder(d, ngram_orders, ngram_buckets, d_ng)
|
| 37 |
+
if use_ngram else None)
|
| 38 |
+
# second bank: longer orders + bigger hash space, separate gate
|
| 39 |
+
self.ngram2 = (NGramEncoder(d, (5, 6, 7, 8), 524288, d_ng)
|
| 40 |
+
if use_ngram2 else None)
|
| 41 |
+
|
| 42 |
+
def _input_embeds(self, input_ids):
|
| 43 |
+
emb = self.backbone.embed_tokens(input_ids)
|
| 44 |
+
add = None
|
| 45 |
+
if self.aux_embed is not None:
|
| 46 |
+
add = self.aux_embed(input_ids)
|
| 47 |
+
if self.ngram is not None:
|
| 48 |
+
ng = self.ngram(input_ids)
|
| 49 |
+
add = ng if add is None else add + ng
|
| 50 |
+
if self.ngram2 is not None:
|
| 51 |
+
ng2 = self.ngram2(input_ids)
|
| 52 |
+
add = ng2 if add is None else add + ng2
|
| 53 |
+
if add is not None:
|
| 54 |
+
emb = emb + add.to(emb.dtype)
|
| 55 |
+
return emb
|
| 56 |
+
|
| 57 |
+
def forward(self, input_ids, attention_mask, position_ids, packeds):
|
| 58 |
+
"""input_ids [B,L] int, attention_mask [B,1,L,L] float additive,
|
| 59 |
+
position_ids [B,L] int, packeds: list[Packed] of len B.
|
| 60 |
+
Returns list[list[dict]] — per sequence, per question:
|
| 61 |
+
{'qtype','logits' (choice/score) or 'p_yes' (noul)}"""
|
| 62 |
+
if (self.aux_embed is not None or self.ngram is not None
|
| 63 |
+
or self.ngram2 is not None):
|
| 64 |
+
out = self.backbone(inputs_embeds=self._input_embeds(input_ids),
|
| 65 |
+
attention_mask=attention_mask,
|
| 66 |
+
position_ids=position_ids)
|
| 67 |
+
else:
|
| 68 |
+
out = self.backbone(input_ids=input_ids,
|
| 69 |
+
attention_mask=attention_mask,
|
| 70 |
+
position_ids=position_ids)
|
| 71 |
+
H = out.last_hidden_state.float() # [B, L, d]
|
| 72 |
+
|
| 73 |
+
results = []
|
| 74 |
+
for b, pk in enumerate(packeds):
|
| 75 |
+
hs = H[b]
|
| 76 |
+
qres = []
|
| 77 |
+
for qi, q in enumerate(pk.questions):
|
| 78 |
+
if q.qtype in ("choice", "score"):
|
| 79 |
+
embs = []
|
| 80 |
+
for (s, e) in pk.option_spans[qi]:
|
| 81 |
+
embs.append(hs[s:e + 1].mean(0))
|
| 82 |
+
O = torch.stack(embs)[None] # [1, n, d]
|
| 83 |
+
head = self.choice_head if q.qtype == "choice" else self.score_head
|
| 84 |
+
logits = head(O)[0] # [n]
|
| 85 |
+
qres.append({"qid": q.qid, "qtype": q.qtype, "logits": logits})
|
| 86 |
+
elif q.qtype == "noul":
|
| 87 |
+
a = pk.ans_pos[qi]
|
| 88 |
+
p = torch.sigmoid(self.noul_head(hs[a]))
|
| 89 |
+
qres.append({"qid": q.qid, "qtype": "noul", "p_yes": p})
|
| 90 |
+
elif q.qtype == "regress":
|
| 91 |
+
a = pk.ans_pos[qi]
|
| 92 |
+
qu = self.regress_head(hs[a][None])[0] # [19] taus .05-.95
|
| 93 |
+
qres.append({"qid": q.qid, "qtype": "regress",
|
| 94 |
+
"quantiles": qu})
|
| 95 |
+
else:
|
| 96 |
+
raise ValueError(q.qtype)
|
| 97 |
+
results.append(qres)
|
| 98 |
+
return results
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def collate(packeds, pad_id):
|
| 102 |
+
"""Pad a list of Packed into batched tensors (ids, additive mask, pos)."""
|
| 103 |
+
ids, pos, seg, qof, oof = collate_segments(packeds, pad_id)
|
| 104 |
+
mask = mask_from_segments(seg, qof, oof)
|
| 105 |
+
return ids, mask, pos
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def collate_segments(packeds, pad_id):
|
| 109 |
+
"""Pad to (ids, pos, seg, qof, oof) — mask built later (optionally on GPU)."""
|
| 110 |
+
import torch
|
| 111 |
+
B = len(packeds)
|
| 112 |
+
L = max(len(p.input_ids) for p in packeds)
|
| 113 |
+
ids = torch.full((B, L), pad_id, dtype=torch.long)
|
| 114 |
+
pos = torch.zeros(B, L, dtype=torch.long)
|
| 115 |
+
seg = torch.zeros(B, L, dtype=torch.long)
|
| 116 |
+
qof = torch.full((B, L), -1, dtype=torch.long)
|
| 117 |
+
oof = torch.full((B, L), -1, dtype=torch.long)
|
| 118 |
+
for b, pk in enumerate(packeds):
|
| 119 |
+
l = len(pk.input_ids)
|
| 120 |
+
ids[b, :l] = torch.tensor(pk.input_ids)
|
| 121 |
+
pos[b, :l] = torch.tensor(pk.position_ids)
|
| 122 |
+
seg[b, :l] = torch.tensor(pk.seg_types)
|
| 123 |
+
qof[b, :l] = torch.tensor(pk.q_of)
|
| 124 |
+
oof[b, :l] = torch.tensor(pk.opt_of)
|
| 125 |
+
return ids, pos, seg, qof, oof
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def mask_from_segments(seg, qof, oof, neg=-1e9):
|
| 129 |
+
"""Vectorized additive mask [B,1,L,L] from segment/question/option ids.
|
| 130 |
+
Runs on whatever device the inputs live on."""
|
| 131 |
+
import torch
|
| 132 |
+
a = seg[:, :, None] # [B, L, 1] query segment
|
| 133 |
+
b = seg[:, None, :] # [B, 1, L] key segment
|
| 134 |
+
same_q = (qof[:, :, None] == qof[:, None, :]) & (qof[:, :, None] >= 0)
|
| 135 |
+
same_opt = same_q & (oof[:, :, None] == oof[:, None, :]) & (oof[:, :, None] >= 0)
|
| 136 |
+
|
| 137 |
+
allowed = (
|
| 138 |
+
((a == SEG_STATE) & (b == SEG_STATE))
|
| 139 |
+
| ((a == SEG_QCTX) & ((b == SEG_STATE) | ((b == SEG_QCTX) & same_q)))
|
| 140 |
+
| ((a == SEG_OPT) & ((b == SEG_STATE) | ((b == SEG_QCTX) & same_q)
|
| 141 |
+
| ((b == SEG_OPT) & same_opt)))
|
| 142 |
+
| ((a == SEG_ANS) & ((b == SEG_STATE)
|
| 143 |
+
| (((b == SEG_QCTX) | (b == SEG_OPT)
|
| 144 |
+
| (b == SEG_ANS)) & same_q))))
|
| 145 |
+
# padded query rows (seg==0) -> all-allowed (their outputs are dead)
|
| 146 |
+
allowed = allowed | (a == 0)
|
| 147 |
+
mask = torch.full(allowed.shape, neg, dtype=torch.float32,
|
| 148 |
+
device=allowed.device)
|
| 149 |
+
mask[allowed] = 0.0
|
| 150 |
+
return mask[:, None]
|