File size: 6,889 Bytes
4d656f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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
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):
        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)

    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 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):
            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]