alea-runs / alea /model.py
Akahsizrr's picture
Upload alea/model.py with huggingface_hub
16c8abd verified
Raw History Blame
7.27 kB
"""AleaModel: pretrained LM trunk + structured-mask packing + set readout heads.
One forward pass answers all questions in a request:
- state encoded once (state tokens are blind to question tokens -> cacheable)
- question contexts and option spans are isolated branches off the state
- options share position_ids and never see each other -> permutation invariant
- ISAB set head reintroduces option interaction without order dependence
"""
import torch
import torch.nn as nn
from transformers import AutoModel
from .heads import SetChoiceHead, NoulHead, RegressHead
from .ngram import AuxEmbedding, NGramEncoder, NGramEncoderMH
from .packing import build_additive_mask, SEG_OPT, SEG_ANS, SEG_QCTX, SEG_STATE
class AleaModel(nn.Module):
def __init__(self, model_name="Qwen/Qwen3-0.6B", n_inducing=16,
use_set_attn=True, attn_impl="eager",
use_aux_embed=False, use_ngram=False,
ngram_orders=(2, 3, 4), ngram_buckets=262144, d_ng=128,
use_ngram2=False, use_ngram3=False):
super().__init__()
self.backbone = AutoModel.from_pretrained(
model_name, torch_dtype=torch.bfloat16,
attn_implementation=attn_impl)
d = self.backbone.config.hidden_size
self.dim = d
self.choice_head = SetChoiceHead(d, n_inducing, use_set_attn=use_set_attn)
self.score_head = SetChoiceHead(d, n_inducing, use_set_attn=use_set_attn)
self.noul_head = NoulHead(d)
self.regress_head = RegressHead(d)
vocab = self.backbone.config.vocab_size
self.aux_embed = AuxEmbedding(vocab, d) if use_aux_embed else None
self.ngram = (NGramEncoder(d, ngram_orders, ngram_buckets, d_ng)
if use_ngram else None)
# second bank: longer orders + bigger hash space, separate gate
self.ngram2 = (NGramEncoder(d, (5, 6, 7, 8), 524288, d_ng)
if use_ngram2 else None)
# third bank: multi-hash compositional tables (thin rows, K=2)
self.ngram3 = (NGramEncoderMH(d, (3, 4, 5, 6), 262144, 262144, 64)
if use_ngram3 else None)
def _input_embeds(self, input_ids):
emb = self.backbone.embed_tokens(input_ids)
add = None
if self.aux_embed is not None:
add = self.aux_embed(input_ids)
if self.ngram is not None:
ng = self.ngram(input_ids)
add = ng if add is None else add + ng
if self.ngram2 is not None:
ng2 = self.ngram2(input_ids)
add = ng2 if add is None else add + ng2
if self.ngram3 is not None:
ng3 = self.ngram3(input_ids)
add = ng3 if add is None else add + ng3
if add is not None:
emb = emb + add.to(emb.dtype)
return emb
def forward(self, input_ids, attention_mask, position_ids, packeds):
"""input_ids [B,L] int, attention_mask [B,1,L,L] float additive,
position_ids [B,L] int, packeds: list[Packed] of len B.
Returns list[list[dict]] — per sequence, per question:
{'qtype','logits' (choice/score) or 'p_yes' (noul)}"""
if (self.aux_embed is not None or self.ngram is not None
or self.ngram2 is not None or self.ngram3 is not None):
out = self.backbone(inputs_embeds=self._input_embeds(input_ids),
attention_mask=attention_mask,
position_ids=position_ids)
else:
out = self.backbone(input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids)
H = out.last_hidden_state.float() # [B, L, d]
results = []
for b, pk in enumerate(packeds):
hs = H[b]
qres = []
for qi, q in enumerate(pk.questions):
if q.qtype in ("choice", "score"):
embs = []
for (s, e) in pk.option_spans[qi]:
embs.append(hs[s:e + 1].mean(0))
O = torch.stack(embs)[None] # [1, n, d]
head = self.choice_head if q.qtype == "choice" else self.score_head
logits = head(O)[0] # [n]
qres.append({"qid": q.qid, "qtype": q.qtype, "logits": logits})
elif q.qtype == "noul":
a = pk.ans_pos[qi]
p = torch.sigmoid(self.noul_head(hs[a]))
qres.append({"qid": q.qid, "qtype": "noul", "p_yes": p})
elif q.qtype == "regress":
a = pk.ans_pos[qi]
qu = self.regress_head(hs[a][None])[0] # [19] taus .05-.95
qres.append({"qid": q.qid, "qtype": "regress",
"quantiles": qu})
else:
raise ValueError(q.qtype)
results.append(qres)
return results
def collate(packeds, pad_id):
"""Pad a list of Packed into batched tensors (ids, additive mask, pos)."""
ids, pos, seg, qof, oof = collate_segments(packeds, pad_id)
mask = mask_from_segments(seg, qof, oof)
return ids, mask, pos
def collate_segments(packeds, pad_id):
"""Pad to (ids, pos, seg, qof, oof) — mask built later (optionally on GPU)."""
import torch
B = len(packeds)
L = max(len(p.input_ids) for p in packeds)
ids = torch.full((B, L), pad_id, dtype=torch.long)
pos = torch.zeros(B, L, dtype=torch.long)
seg = torch.zeros(B, L, dtype=torch.long)
qof = torch.full((B, L), -1, dtype=torch.long)
oof = torch.full((B, L), -1, dtype=torch.long)
for b, pk in enumerate(packeds):
l = len(pk.input_ids)
ids[b, :l] = torch.tensor(pk.input_ids)
pos[b, :l] = torch.tensor(pk.position_ids)
seg[b, :l] = torch.tensor(pk.seg_types)
qof[b, :l] = torch.tensor(pk.q_of)
oof[b, :l] = torch.tensor(pk.opt_of)
return ids, pos, seg, qof, oof
def mask_from_segments(seg, qof, oof, neg=-1e9):
"""Vectorized additive mask [B,1,L,L] from segment/question/option ids.
Runs on whatever device the inputs live on."""
import torch
a = seg[:, :, None] # [B, L, 1] query segment
b = seg[:, None, :] # [B, 1, L] key segment
same_q = (qof[:, :, None] == qof[:, None, :]) & (qof[:, :, None] >= 0)
same_opt = same_q & (oof[:, :, None] == oof[:, None, :]) & (oof[:, :, None] >= 0)
allowed = (
((a == SEG_STATE) & (b == SEG_STATE))
| ((a == SEG_QCTX) & ((b == SEG_STATE) | ((b == SEG_QCTX) & same_q)))
| ((a == SEG_OPT) & ((b == SEG_STATE) | ((b == SEG_QCTX) & same_q)
| ((b == SEG_OPT) & same_opt)))
| ((a == SEG_ANS) & ((b == SEG_STATE)
| (((b == SEG_QCTX) | (b == SEG_OPT)
| (b == SEG_ANS)) & same_q))))
# padded query rows (seg==0) -> all-allowed (their outputs are dead)
allowed = allowed | (a == 0)
mask = torch.full(allowed.shape, neg, dtype=torch.float32,
device=allowed.device)
mask[allowed] = 0.0
return mask[:, None]