leafant 0.2.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
leafant/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """Leaf Ant Flash by PlutoAI: non-autoregressive typed decisions.
2
+
3
+ Flash uses independent option encoding, adaptive set attention, ordinal
4
+ probabilities and a question-conditioned error head. Legacy LeafAnt checkpoints
5
+ remain supported. The flash/1 architecture requires cloud training and evaluation;
6
+ no competitor superiority follows from the architecture alone.
7
+ """
8
+ from importlib import import_module
9
+
10
+ # Import each public entry point on first access. A standalone workflow process
11
+ # needs NumPy and the web server but never executes a neural model.
12
+ _PUBLIC_MODULES = {
13
+ "load_reader": "long_reader",
14
+ "WorkflowSpecialist": "workflow_specialist",
15
+ "LeafAnt":"agent", "LeafAntModel":"model", "TrainConfig":"train", "finetune":"train",
16
+ "read_jsonl":"data", "write_jsonl":"data", "dedupe_rows":"data", "seed_everything":"util",
17
+ "MultiTaskConfig":"multitask", "finetune_multitask":"multitask",
18
+ "evaluate_suite":"evals", "full_eval":"evals", "order_flip_rate":"evals",
19
+ }
20
+
21
+
22
+ def __getattr__(name):
23
+ if name not in _PUBLIC_MODULES:
24
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
25
+ value = getattr(import_module("." + _PUBLIC_MODULES[name], __name__), name)
26
+ globals()[name] = value
27
+ return value
28
+
29
+
30
+ def __dir__():
31
+ return sorted(set(globals()) | set(_PUBLIC_MODULES))
32
+
33
+
34
+ __version__ = "0.2.0a1"
35
+ MODEL_NAME = "Leaf Ant Flash"
36
+ PUBLISHER = "PlutoAI"
37
+ PUBLISHER_URL = "https://plutosi.one"
38
+ PUBLISHER_URLS = (PUBLISHER_URL,)
39
+
40
+ __all__ = ["load_reader", "WorkflowSpecialist", "LeafAnt", "LeafAntModel", "TrainConfig", "finetune", "read_jsonl",
41
+ "write_jsonl", "dedupe_rows", "seed_everything", "MultiTaskConfig",
42
+ "finetune_multitask", "evaluate_suite",
43
+ "full_eval", "order_flip_rate", "__version__"]
leafant/agent.py ADDED
@@ -0,0 +1,381 @@
1
+ """LeafAnt agent — checkpoint I/O, decoding, prediction API.
2
+
3
+ Output contract mirrors laya's so the comparison adapters can score both
4
+ systems with the same code: answers[qid] = {choice|noul|score, probabilities,
5
+ answer_confidence, confidence, abstain_probability, ...}.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from typing import Dict, List, Optional
12
+
13
+ import numpy as np
14
+ import torch
15
+
16
+ from .calibrate import apply_histogram, temp_bucket
17
+ from .format import (CHOICE, NOUL, SCORE, add_answer_metadata, encode_batch, normalize_questions,
18
+ serialize_state)
19
+ from .model import LeafAntModel
20
+ from .inference_cache import EncoderCache
21
+ from .checkpoint import load_model_payload, plain_metadata
22
+ from .tokenizer import build_tokenizer, restore_tokenizer
23
+ from .util import native_cuda_bf16_supported
24
+
25
+
26
+ class LeafAnt:
27
+ def __init__(self, model: LeafAntModel, tokenizer, config: Dict,
28
+ calibration: Optional[Dict] = None, device: str = "cpu"):
29
+ self.model = model.to(device).eval()
30
+ self.tokenizer = tokenizer
31
+ self.config = dict(config)
32
+ self.calibration = calibration or {}
33
+ self.device = device
34
+ self.tmap: Dict[str, float] = self.calibration.get("temperature", {})
35
+ self.bmap: Dict[str, Dict] = self.calibration.get("binning", {})
36
+ self.atmap: Dict[str, float] = self.calibration.get("abstention", {})
37
+ self._encoder_cache = EncoderCache(int(self.config.get("encoder_cache_bytes", 0)))
38
+
39
+ # ------------------------------------------------------------ lifecycle
40
+ @classmethod
41
+ def build(cls, config: Dict, device: str = "cpu") -> "LeafAnt":
42
+ tok = build_tokenizer(config.get("tokenizer", {"kind": "hash", "vocab_size": 8192}))
43
+ model = LeafAntModel(config)
44
+ return cls(model, tok, config, None, device)
45
+
46
+ def save(self, out_dir: str) -> str:
47
+ os.makedirs(out_dir, exist_ok=True)
48
+ payload = {"format": self.FORMAT, "config": self.config,
49
+ "tokenizer_spec": self.tokenizer.to_dict() if hasattr(self.tokenizer, "to_dict")
50
+ else {"kind": "hash", "vocab_size": 8192},
51
+ "calibration": self.calibration,
52
+ "state_dict": self.model.state_dict()}
53
+ if hasattr(self.model.state_tower, "inner"):
54
+ payload["encoder_config"] = self.model.state_tower.inner.config.to_dict()
55
+ tokenizer_dir = os.path.join(out_dir, "tokenizer")
56
+ os.makedirs(tokenizer_dir, exist_ok=True)
57
+ if hasattr(self.tokenizer.tok, "save_pretrained"):
58
+ self.tokenizer.tok.save_pretrained(tokenizer_dir)
59
+ payload["tokenizer_spec"] = {"kind": "hf", "name": "tokenizer", "local": True}
60
+ else:
61
+ self.tokenizer.tok.save(os.path.join(tokenizer_dir, "tokenizer.json"))
62
+ payload["tokenizer_spec"] = {"kind": "tokenizers", "name": "tokenizer/tokenizer.json", "local": True}
63
+ tmp = os.path.join(out_dir, "model.pt.tmp")
64
+ torch.save(plain_metadata(payload), tmp)
65
+ os.replace(tmp, os.path.join(out_dir, "model.pt")) # atomic on same volume
66
+ with open(os.path.join(out_dir, "config.json"), "w", encoding="utf-8") as f:
67
+ json.dump({"format": self.FORMAT, "config": self.config,
68
+ "calibration_keys": list(self.calibration.keys())},
69
+ f, indent=2)
70
+ return out_dir
71
+
72
+ FORMAT = "leafant-checkpoint/1"
73
+
74
+ @classmethod
75
+ def load(cls, path_or_dir: str, device: str = "cpu", strict: bool = True) -> "LeafAnt":
76
+ p = path_or_dir
77
+ if os.path.isdir(p):
78
+ p = os.path.join(p, "model.pt")
79
+ payload = load_model_payload(p)
80
+ if not isinstance(payload, dict):
81
+ raise ValueError("checkpoint payload must be a mapping")
82
+ fmt = payload.get("format")
83
+ if fmt not in (cls.FORMAT, "prama-checkpoint/1"): # pre-rename checkpoints
84
+ raise ValueError(f"not a leaf ant checkpoint: format={fmt!r} in {p!r} "
85
+ f"(expected {cls.FORMAT!r}); refusing to load foreign or corrupt weights")
86
+ config = payload.get("config")
87
+ if not isinstance(config, dict) or "tower" not in config and "state_tower" not in config:
88
+ raise ValueError(f"checkpoint at {p!r} has a malformed config; refusing to load")
89
+ tokenizer_spec = dict(payload.get("tokenizer_spec") or config.get("tokenizer",
90
+ {"kind": "hash", "vocab_size": 8192}))
91
+ if tokenizer_spec.pop("local", False):
92
+ base = os.path.dirname(os.path.abspath(p))
93
+ artifact = os.path.abspath(os.path.join(base, tokenizer_spec["name"]))
94
+ if os.path.commonpath([base, artifact]) != base:
95
+ raise ValueError("tokenizer artifact must be within the checkpoint directory")
96
+ tokenizer_spec["name"] = artifact
97
+ tok = restore_tokenizer(tokenizer_spec)
98
+ model = LeafAntModel(config, encoder_config=payload.get("encoder_config"))
99
+ model.load_state_dict(payload["state_dict"], strict=strict)
100
+ return cls(model, tok, config, payload.get("calibration"), device)
101
+
102
+ # ------------------------------------------------------------ inference
103
+ def _forward(self, states, questions_per_row):
104
+ state_budget = int(self.config.get("max_state_len", 256))
105
+ tower_limit = getattr(self.model.state_tower, "max_len", None)
106
+ if tower_limit is not None:
107
+ state_budget = min(state_budget, int(tower_limit) - 2)
108
+ batch = encode_batch(self.tokenizer, states, questions_per_row,
109
+ max_state_len=state_budget,
110
+ max_opt_len=min(int(self.config.get("max_opt_len", 64)), int(tower_limit)) if tower_limit else int(self.config.get("max_opt_len", 64)),
111
+ device=self.device,
112
+ separate_questions=self.config.get("separate_question_encoding", False),
113
+ max_question_len=min(int(self.config.get("max_question_len", 128)), int(tower_limit)) if tower_limit else int(self.config.get("max_question_len", 128)))
114
+ amp_enabled = str(self.device).startswith("cuda")
115
+ dtype = torch.bfloat16 if amp_enabled and native_cuda_bf16_supported() else torch.float16
116
+ with torch.inference_mode(), torch.autocast(
117
+ device_type="cuda" if amp_enabled else "cpu", dtype=dtype, enabled=amp_enabled):
118
+ before = self._encoder_cache.stats()
119
+ if self._encoder_cache.enabled and self._encoder_cache.supported(self.model.state_tower):
120
+ options = self._encoder_cache.encode(self.model.opt_tower, batch.opt_ids, batch.opt_mask,
121
+ getattr(batch, "opt_cache_keys", None))
122
+ questions = None
123
+ if self.config.get("separate_question_encoding", False):
124
+ questions = self._encoder_cache.encode(
125
+ self.model.state_tower, batch.question_ids, batch.question_mask,
126
+ getattr(batch, "question_cache_keys", None))
127
+ out = self.model(batch, option_hidden=options, question_hidden=questions,
128
+ reader_cache=self._encoder_cache)
129
+ else:
130
+ out = self.model(batch)
131
+ after = self._encoder_cache.stats()
132
+ out["encoder_cache"] = {key: after[key] - before[key]
133
+ for key in ("hits", "misses", "reused_in_batch", "encoded_sequences", "invalidations")}
134
+ out["encoder_cache"].update(enabled=self._encoder_cache.enabled,
135
+ resident_bytes=after["resident_bytes"], max_bytes=after["max_bytes"])
136
+ dprobs = out["dprobs"]
137
+ act = torch.softmax(out["act_logits"], dim=-1)[:, 1] # P(should abstain)
138
+ return batch, out, dprobs.float().cpu().numpy(), act.float().cpu().numpy()
139
+
140
+ def predict_batch(self, states: List, questions_list: List[Dict], batch_size: int = 32,
141
+ min_confidence: float = None, min_abstain_probability: float = None) -> List[Dict]:
142
+ """Batch prediction.
143
+
144
+ `min_confidence`: gate on calibrated max-probability — gated answers carry
145
+ `abstention: "abstained"` and `decision: None` (probabilities preserved).
146
+ `min_abstain_probability`: gate on the trained abstention head — answers
147
+ where P(abstain) exceeds the threshold are declined. Thresholds should be
148
+ selected on validation data, never on the test set.
149
+ """
150
+ if len(states) != len(questions_list):
151
+ raise ValueError("states and questions_list must have the same length")
152
+ if not isinstance(batch_size, int) or batch_size < 1:
153
+ raise ValueError("batch_size must be a positive integer")
154
+ for threshold in (min_confidence, min_abstain_probability):
155
+ if threshold is not None and not 0 <= threshold <= 1:
156
+ raise ValueError("gating thresholds must be in [0, 1]")
157
+ results: List[Dict] = []
158
+ for i in range(0, len(states), batch_size):
159
+ results.extend(self._predict_chunk(states[i:i + batch_size],
160
+ questions_list[i:i + batch_size],
161
+ min_confidence=min_confidence,
162
+ min_abstain_probability=min_abstain_probability))
163
+ return results
164
+
165
+ def _predict_chunk(self, states, questions_list, min_confidence=None,
166
+ min_abstain_probability=None) -> List[Dict]:
167
+ norm = [normalize_questions(q) for q in questions_list]
168
+ if not any(norm):
169
+ return [{"answers": {}, "usage": {"forward_passes": 0}} for _ in states]
170
+ batch, out, dprobs, act = self._forward(states, norm)
171
+ reader_states = out["reader_state_tokens"].cpu().tolist() if "reader_state_tokens" in out else None
172
+ reader_questions = out["reader_question_tokens"].cpu().tolist() if "reader_question_tokens" in out else None
173
+ answers_per_row: List[Dict] = [dict() for _ in states]
174
+ m = 0
175
+ for b, qs in enumerate(norm):
176
+ for q, raw_question in zip(qs, questions_list[b].values(), strict=True):
177
+ k = int(batch.q_k[m])
178
+ p = dprobs[m, :k].astype(np.float64)
179
+ bucket = temp_bucket(int(batch.qtype[m]), k)
180
+ T = self.tmap.get(bucket, self.tmap.get(
181
+ f"{('choice', 'score', 'noul')[int(batch.qtype[m])]}:default", 1.0))
182
+ if T != 1.0:
183
+ if not np.isfinite(T) or T <= 0:
184
+ raise ValueError(f"invalid calibration temperature for {bucket}: {T}")
185
+ z = np.log(np.clip(p, 1e-12, 1.0)) / T
186
+ e = np.exp(z - z.max())
187
+ p = e / e.sum()
188
+ if not np.isfinite(p).all() or p.sum() <= 0:
189
+ raise FloatingPointError("non-finite or empty inference probabilities")
190
+ p /= p.sum()
191
+ score_index = int(round(float((np.arange(k) * p).sum()))) if q["qtype"] == SCORE else None
192
+ conf = float(p[score_index]) if score_index is not None else float(p.max())
193
+ cal_conf = apply_histogram(self.bmap, bucket, conf) if self.bmap else conf
194
+ abstain_p = float(act[m])
195
+ ans = {"question_truncated": bool(getattr(batch, "question_truncated", [False] * len(dprobs))[m]),
196
+ "answer_confidence": round(conf, 4),
197
+ "calibrated_confidence": round(cal_conf, 4),
198
+ "abstain_probability": round(abstain_p, 4)}
199
+ if reader_states is not None:
200
+ ans["state_tokens_for_question"] = reader_states[m]
201
+ ans["state_truncated_for_question"] = reader_states[m] < batch.state_original_lengths[b]
202
+ ans["question_truncated"] |= reader_questions[m] < int(batch.question_mask[m].sum().item())
203
+ if self.atmap:
204
+ tau = self.atmap.get(bucket, 0.0)
205
+ ans["abstention"] = "passed" if conf >= tau else "abstained"
206
+ ans["abstention_threshold"] = tau
207
+ if q["qtype"] == CHOICE:
208
+ labels = q.get("labels") or [o.split(":")[0].strip() for o in q["options"]]
209
+ idx = int(p.argmax())
210
+ ans["choice"] = labels[idx]
211
+ ans["probabilities"] = {labels[j]: round(float(p[j]), 8) for j in range(k)}
212
+ decision = labels[idx]
213
+ elif q["qtype"] == NOUL:
214
+ ans["noul"] = round(float(p[1]), 8)
215
+ ans["probabilities"] = {"false": round(float(p[0]), 8),
216
+ "true": round(float(p[1]), 8)}
217
+ decision = bool(float(p[1]) >= 0.5)
218
+ else:
219
+ levels = list(range(k))
220
+ ans["score"] = float((np.arange(k) * p).sum())
221
+ ans["level"] = int(p.argmax())
222
+ ans["probabilities"] = {str(levels[j]): round(float(p[j]), 8) for j in range(k)}
223
+ ans["rounded_score"] = score_index
224
+ decision = score_index
225
+ # explicit gating: the model DECLINES when thresholds (fit on
226
+ # validation data, never test) are not met — probabilities kept
227
+ gated = ans.get("abstention") == "abstained" or \
228
+ (min_confidence is not None and conf < min_confidence) or \
229
+ (min_abstain_probability is not None and abstain_p > min_abstain_probability)
230
+ if gated:
231
+ ans["abstention"] = "abstained"
232
+ ans["decision"] = None
233
+ else:
234
+ if "abstention" not in ans: # atmap result, if any, stands
235
+ ans["abstention"] = "passed"
236
+ ans["decision"] = decision
237
+ add_answer_metadata(ans, raw_question)
238
+ answers_per_row[b][q["id"]] = ans
239
+ m += 1
240
+ original = getattr(batch, "state_original_lengths", [0] * len(states))
241
+ used = getattr(batch, "state_used_lengths", original)
242
+ if reader_states is not None:
243
+ used = [max((reader_states[m] for m, row in enumerate(batch.q_row.cpu().tolist()) if row == i), default=0)
244
+ for i in range(len(states))]
245
+ return [{"answers": a, "usage": {"forward_passes": 1,
246
+ "state_tokens": used[i], "state_tokens_before_truncation": original[i],
247
+ "state_truncated": original[i] > used[i],
248
+ "batch_encoder_cache": out.get("encoder_cache", {})}}
249
+ for i, a in enumerate(answers_per_row)]
250
+
251
+ def predict(self, state, questions: Dict, min_confidence: float = None,
252
+ min_abstain_probability: float = None) -> Dict:
253
+ return self.predict_batch([state], [questions], min_confidence=min_confidence,
254
+ min_abstain_probability=min_abstain_probability)[0]
255
+
256
+ def rank(self, state, questions: Dict) -> Dict:
257
+ """Candidate ranking: every choice question's options sorted by
258
+ probability, best first. No candidates are dropped."""
259
+ res = self.predict(state, questions)
260
+ ranked = {}
261
+ for qid, q in res["answers"].items():
262
+ probs = q.get("probabilities")
263
+ if not probs:
264
+ continue
265
+ ranked[qid] = [{"label": lab, "probability": val}
266
+ for lab, val in sorted(probs.items(), key=lambda kv: -kv[1])]
267
+ return {"ranked": ranked, "answers": res["answers"]}
268
+
269
+ # ---------------------------------------------------------- structured API
270
+ def decide(self, state, schema: Dict, min_confidence: float = None,
271
+ min_abstain_probability: float = None) -> Dict:
272
+ """Schema-driven typed decisions — no training needed for new schemas.
273
+
274
+ schema: {"field": {"type": "boolean"} | {"type": "string", "enum": [...]}
275
+ | {"type": "integer", "minimum": 0, "maximum": 9}}
276
+ Returns {field: projected value or None when gated}, with a `confidence`
277
+ map and explicit errors for unsupported schema shapes.
278
+ """
279
+ questions, projection = {}, {}
280
+ for field, spec in schema.items():
281
+ ftype = spec.get("type")
282
+ if ftype == "boolean":
283
+ questions[field] = {"type": "noul",
284
+ "instructions": spec.get("instructions", f"Is {field} true for this state?")}
285
+ projection[field] = ("noul", None)
286
+ elif ftype == "string" and "enum" in spec:
287
+ enum = list(spec["enum"])
288
+ if len(enum) < 2:
289
+ raise ValueError(f"{field!r}: enum needs >= 2 values")
290
+ questions[field] = {"type": "choice",
291
+ "instructions": spec.get("instructions", f"Which {field} fits this state?"),
292
+ "criteria": {str(v): spec.get("descriptions", {}).get(str(v))
293
+ for v in enum}}
294
+ projection[field] = ("choice", enum)
295
+ elif ftype == "integer" and "minimum" in spec and "maximum" in spec:
296
+ lo, hi = int(spec["minimum"]), int(spec["maximum"])
297
+ if hi - lo < 1 or hi - lo + 1 > 32:
298
+ raise ValueError(f"{field!r}: integer range must span 2..32 levels")
299
+ levels = [spec.get("criteria", [f"level {i}" for i in range(lo, hi + 1)])[i - lo]
300
+ if isinstance(spec.get("criteria"), list) else f"level {i}"
301
+ for i in range(lo, hi + 1)]
302
+ questions[field] = {"type": "score",
303
+ "instructions": spec.get("instructions", f"What is the {field}?"),
304
+ "criteria": levels}
305
+ projection[field] = ("score", (lo, hi))
306
+ else:
307
+ raise ValueError(f"{field!r}: unsupported schema type {ftype!r} "
308
+ f"(supported: boolean, string+enum, integer with min/max)")
309
+ res = self.predict(state, questions, min_confidence=min_confidence,
310
+ min_abstain_probability=min_abstain_probability)
311
+ values, confidences = {}, {}
312
+ for field, (kind, extra) in projection.items():
313
+ ans = res["answers"][field]
314
+ confidences[field] = ans["answer_confidence"]
315
+ if ans.get("decision") is None:
316
+ values[field] = None
317
+ continue
318
+ if kind == "noul":
319
+ values[field] = bool(ans["decision"])
320
+ elif kind == "choice":
321
+ value = str(ans["decision"])
322
+ if extra is not None and value not in [str(v) for v in extra]:
323
+ raise ValueError(f"{field!r}: model returned {value!r} which is not "
324
+ f"in the schema enum — refusing to fabricate")
325
+ values[field] = next(v for v in extra if str(v) == value) if extra is not None else value
326
+ else:
327
+ lo, hi = extra
328
+ values[field] = lo + int(ans["decision"])
329
+ return {"values": values, "confidence": confidences, "answers": res["answers"]}
330
+
331
+ def configure_encoder_cache(self, max_bytes=64 * 1024 * 1024):
332
+ """Enable bounded inference reuse without changing model weights."""
333
+ self._encoder_cache = EncoderCache(max_bytes)
334
+
335
+ def clear_encoder_cache(self):
336
+ self._encoder_cache.clear(reset_stats=True)
337
+
338
+ def encoder_cache_stats(self):
339
+ return self._encoder_cache.stats()
340
+
341
+ # ------------------------------------------------------------ evaluation
342
+ def calibration_records(self, rows: List[Dict], batch_size: int = 4, max_batch_options: int = 192) -> List[Dict]:
343
+ """Eval-mode logits/targets per question — input to temperature fitting."""
344
+ records = []
345
+ chunks, chunk, option_count = [], [], 0
346
+ for row in rows:
347
+ count = sum(2 if q.get("type") == "noul" else len(q.get("criteria", []))
348
+ for q in row["questions"].values())
349
+ if chunk and (len(chunk) >= batch_size or option_count + count > max_batch_options):
350
+ chunks.append(chunk)
351
+ chunk, option_count = [], 0
352
+ chunk.append(row)
353
+ option_count += count
354
+ if chunk:
355
+ chunks.append(chunk)
356
+ for chunk in chunks:
357
+ states = [r["state"] for r in chunk]
358
+ norm = [normalize_questions(r["questions"]) for r in chunk]
359
+ batch, out, dprobs, _ = self._forward(states, norm)
360
+ from .format import slot_target_from, decision_target_from
361
+ expected = [r.get("expected", {}) for r in chunk]
362
+ gold = [r.get("gold") for r in chunk]
363
+ slot_t, level_t, decision_t = [], [], []
364
+ for j, qs in enumerate(norm):
365
+ st, lt = slot_target_from(expected[j], qs, 0.0, gold[j])
366
+ slot_t.append(st)
367
+ level_t.append(lt)
368
+ decision_t.append(decision_target_from(expected[j], qs, st))
369
+ m = 0
370
+ for j, qs in enumerate(norm):
371
+ st, lt = slot_t[j], level_t[j]
372
+ for lm, q in enumerate(qs):
373
+ k = int(batch.q_k[m])
374
+ records.append({"qtype": int(batch.qtype[m]), "k": k,
375
+ "logits": out["logits"][m, :k].float().cpu().tolist(),
376
+ "mask": [True] * k,
377
+ "probabilities": dprobs[m, :k].tolist(),
378
+ "target": st[lm, :k].tolist(),
379
+ "target_decision": int(decision_t[j][lm])})
380
+ m += 1
381
+ return records
leafant/backbone.py ADDED
@@ -0,0 +1,83 @@
1
+ """Backbone towers.
2
+
3
+ `TinyTower` — a small trainable-from-scratch transformer used by the CPU demo;
4
+ `HFTower` wraps an HF encoder (multilingual-e5-small for the Flash cloud
5
+ candidate). Both return per-token hidden states; pooling is decided by the caller
6
+ so the decision head can cross-attend over the full state sequence.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from typing import Dict
13
+
14
+
15
+ class Tower(nn.Module):
16
+ """Embeddings + pre-norm transformer encoder. No pooling, no positional bias
17
+ beyond learned absolute positions (state tower only)."""
18
+
19
+ def __init__(self, vocab_size: int, d_model: int = 128, n_layers: int = 3, n_heads: int = 4,
20
+ ffn_mult: int = 4, dropout: float = 0.1, max_len: int = 512, use_positions: bool = True):
21
+ super().__init__()
22
+ self.d_model = d_model
23
+ self.embed = nn.Embedding(vocab_size, d_model, padding_idx=0)
24
+ self.pos = nn.Embedding(max_len, d_model) if use_positions else None
25
+ self.max_len = max_len
26
+ layer = nn.TransformerEncoderLayer(
27
+ d_model, n_heads, ffn_mult * d_model, dropout, batch_first=True, norm_first=True,
28
+ activation="gelu")
29
+ self.encoder = nn.TransformerEncoder(layer, n_layers, enable_nested_tensor=False)
30
+ self.norm = nn.LayerNorm(d_model)
31
+
32
+ def forward(self, ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
33
+ h = self.embed(ids)
34
+ if self.pos is not None:
35
+ pos = torch.arange(ids.size(1), device=ids.device).clamp_max(self.max_len - 1)
36
+ h = h + self.pos(pos)[None]
37
+ h = self.encoder(h, src_key_padding_mask=~attention_mask.bool())
38
+ return self.norm(h)
39
+
40
+
41
+ class TinyTower(Tower):
42
+ pass
43
+
44
+
45
+ class HFTower(nn.Module):
46
+ """Any HF encoder (AutoModel) + projection to d_model if hidden sizes differ."""
47
+
48
+ def __init__(self, name_or_path: str, d_model: int, max_len: int = 512, use_positions: bool = True,
49
+ encoder_config: Dict = None):
50
+ super().__init__()
51
+ from transformers import AutoConfig, AutoModel
52
+
53
+ if encoder_config is None:
54
+ cfg = AutoConfig.from_pretrained(name_or_path)
55
+ self.inner = AutoModel.from_pretrained(name_or_path)
56
+ else:
57
+ config_args = dict(encoder_config)
58
+ model_type = config_args.pop("model_type")
59
+ cfg = AutoConfig.for_model(model_type, **config_args)
60
+ self.inner = AutoModel.from_config(cfg)
61
+ self.hidden = self.inner.config.hidden_size
62
+ self.max_len = min(max_len, getattr(cfg, "max_position_embeddings", max_len))
63
+ self.proj = nn.Identity() if self.hidden == d_model else nn.Linear(self.hidden, d_model)
64
+
65
+ @property
66
+ def d_model(self) -> int:
67
+ return self.hidden
68
+
69
+ def forward(self, ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
70
+ out = self.inner(input_ids=ids, attention_mask=attention_mask.int())
71
+ return self.proj(out.last_hidden_state)
72
+
73
+
74
+ def build_tower(spec: Dict, **kw) -> nn.Module: # noqa: F821
75
+ kind = spec.get("kind", "tiny")
76
+ if kind == "tiny":
77
+ return TinyTower(spec.get("vocab_size", 8192), spec.get("d_model", 128), spec.get("n_layers", 3),
78
+ spec.get("n_heads", 4), spec.get("ffn_mult", 4), spec.get("dropout", 0.1),
79
+ spec.get("max_len", 512), use_positions=kw.get("use_positions", True))
80
+ if kind == "hf":
81
+ return HFTower(spec["name"], spec.get("d_model", 256), spec.get("max_len", 512),
82
+ use_positions=kw.get("use_positions", True), encoder_config=kw.get("encoder_config"))
83
+ raise ValueError(f"unknown tower kind: {kind!r}")