Load with 🤗 Transformers from_pretrained (modeling code, auto_map, card How to use)

#1
by ksopyla - opened
README.md CHANGED
@@ -3,10 +3,11 @@ language:
3
  - en
4
  license: apache-2.0
5
  pipeline_tag: text-generation
6
- # library_name is left out on purpose: the weights do not load with 🤗 Transformers `from_pretrained` yet (see "How to use").
7
  tags:
8
  - mrcogito
9
  - meridian21
 
10
  - concept-memory
11
  - size-140m
12
  - budget-11.5bt
@@ -321,16 +322,39 @@ HotpotQA, SQuAD, the held-out long documents) are not in the training data. Stag
321
  long-document gain is the memory's.
322
  - **Longer budgets and larger models** with the same memory, and a second memory design on the same data.
323
  - **Reasoning over concepts:** the reasoner is built and tested, and switched off in this release.
324
- - **Loading with 🤗 Transformers `from_pretrained`**, so every future release works with one line.
325
 
326
  ## How to use
327
 
328
- The weights do not load with `AutoModelForCausalLM.from_pretrained` yet: `perceiver_ar` is our own architecture and
329
- this repository does not ship modeling code. Making every release load with `from_pretrained` is on our engineering
330
- list. Until then, load it with the MrCogito code at commit
331
- [`1fddc505`](https://github.com/ksopyla/MrCogito/tree/1fddc505) (`evaluation/lm_eval_perceiver_ar.py`,
332
- `load_perceiver_ar_for_eval`): our lm-eval adapter, the long-document scripts in `long_context/` and the sampling
333
- script that wrote `samples/` all run from that checkout on one CUDA GPU.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
 
335
  ## Citation
336
 
@@ -364,6 +388,7 @@ See each dataset's card for its terms.
364
  ## Changelog and contact
365
 
366
  - 2026-11-18: first public release (weights, card, evaluation page, raw results, figures).
 
367
 
368
  Krzysztof Sopyła · [ai.ksopyla.com](https://ai.ksopyla.com) · [Meridian21 Lab](https://huggingface.co/Meridian21Lab)
369
  · questions and errors: open a discussion on this page.
 
3
  - en
4
  license: apache-2.0
5
  pipeline_tag: text-generation
6
+ library_name: transformers
7
  tags:
8
  - mrcogito
9
  - meridian21
10
+ - custom_code
11
  - concept-memory
12
  - size-140m
13
  - budget-11.5bt
 
322
  long-document gain is the memory's.
323
  - **Longer budgets and larger models** with the same memory, and a second memory design on the same data.
324
  - **Reasoning over concepts:** the reasoner is built and tested, and switched off in this release.
 
325
 
326
  ## How to use
327
 
328
+ Needs `torch` and `transformers` (tested with 4.57.6 and 5.23.0). The modeling code ships in this repository, so
329
+ loading takes `trust_remote_code=True`. Runs on one CUDA GPU in bf16.
330
+
331
+ ```python
332
+ import torch
333
+ from transformers import AutoModelForCausalLM, AutoTokenizer
334
+
335
+ repo = "Meridian21Lab/concept-memory-140m-11.5bt"
336
+ tok = AutoTokenizer.from_pretrained(repo, trust_remote_code=True)
337
+ model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True, dtype=torch.bfloat16).to("cuda")
338
+
339
+ inputs = tok("The capital of France is", return_tensors="pt").to("cuda")
340
+ out = model.generate(**inputs, max_new_tokens=40, do_sample=True, temperature=0.7, top_p=0.9,
341
+ repetition_penalty=1.1)
342
+ print(tok.decode(out[0], skip_special_tokens=True))
343
+
344
+ # scoring: mean next-token loss in nats per token
345
+ loss = model(**inputs, labels=inputs["input_ids"]).loss
346
+ ```
347
+
348
+ - `generate` is 🤗 Transformers' own (sampling, greedy, beam search), running over the model's cached decoder. This
349
+ is a base model, not a chat model.
350
+ - **Long documents** (up to the 64k training length): add `attn_backend="flex"` to `from_pretrained` (PyTorch flex
351
+ attention on CUDA). The default, `sdpa`, builds a dense attention mask and suits short inputs.
352
+ - For exact scores, batch prompts of one length or score them one at a time: left padding moves the memory's block
353
+ edges and changes scores slightly.
354
+ - `modeling_perceiver_ar.py` is generated from the MrCogito source by `scripts/export_hub_model.py`;
355
+ `export_manifest.json` names the source commit. Our lm-eval adapter, the long-document scripts in `long_context/`
356
+ and the sampling script that wrote `samples/` run from the MrCogito code at
357
+ [`1fddc505`](https://github.com/ksopyla/MrCogito/tree/1fddc505).
358
 
359
  ## Citation
360
 
 
388
  ## Changelog and contact
389
 
390
  - 2026-11-18: first public release (weights, card, evaluation page, raw results, figures).
391
+ - 2026-11-18: loads with 🤗 Transformers `from_pretrained` (modeling code, `generation_config.json` and `export_manifest.json` added; `config.json` gains `auto_map`).
392
 
393
  Krzysztof Sopyła · [ai.ksopyla.com](https://ai.ksopyla.com) · [Meridian21 Lab](https://huggingface.co/Meridian21Lab)
394
  · questions and errors: open a discussion on this page.
config.json CHANGED
@@ -1,9 +1,13 @@
1
  {
2
  "architectures": [
3
- "PerceiverARLM"
4
  ],
5
- "attn_backend": "flex",
6
  "attn_pad_multiple": 1,
 
 
 
 
7
  "block": 128,
8
  "block_attention_mode": "causal",
9
  "bos_token_id": 0,
 
1
  {
2
  "architectures": [
3
+ "PerceiverARForCausalLM"
4
  ],
5
+ "attn_backend": "sdpa",
6
  "attn_pad_multiple": 1,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_perceiver_ar.PerceiverARConfig",
9
+ "AutoModelForCausalLM": "modeling_perceiver_ar.PerceiverARForCausalLM"
10
+ },
11
  "block": 128,
12
  "block_attention_mode": "causal",
13
  "bos_token_id": 0,
configuration_perceiver_ar.py ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Perceiver AR (MrCogito) configuration for 🤗 Transformers: the configuration of a Hub release.
2
+
3
+ Generated by scripts/export_hub_model.py from https://github.com/ksopyla/MrCogito at commit 2e6b9573c8fb, from
4
+ nn/latent_memory.py, nn/perceiver_ar_lm.py. Do not edit: change the source and export again. Engineering spec:
5
+ docs/engineering_specs/hub_from_pretrained_loading.md.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ from transformers import PretrainedConfig
11
+ from typing import Optional
12
+
13
+
14
+ LM_CONTEXTS = ("page_bidir", "bixt")
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Sparse exclusive-plus-anchors (E21). Default `none` is prior exclusive slots.
19
+ # `query_nbhd` = sender tokens immediately before QUERY (prefix; r=1 slots).
20
+ # `query_side` = QUERY + window after the boundary (receiver; not prefix slots).
21
+ # `key_spans` = DNA key-field tokens after each sender keymark (E27 hybrid b).
22
+ MESSAGE_GLOBAL_ANCHORS = (
23
+ "none", "query_nbhd", "query_side", "type_marks", "query_nbhd+type", "key_spans",
24
+ )
25
+
26
+ MESSAGE_QUERY_NBHD_DEFAULT = 4 # sender-before or QUERY-plus-after window
27
+
28
+ MESSAGE_WRITES = ("block_mean", "sw_perceiver", "latent_memory")
29
+
30
+ SWP_BANK_DEFAULT = 32
31
+
32
+ SWP_COVERAGE_DEFAULT = 8
33
+
34
+
35
+ class PerceiverARConfig(PretrainedConfig):
36
+ model_type = "perceiver_ar"
37
+
38
+ def __init__(
39
+ self,
40
+ vocab_size: int = 128256,
41
+ hidden_size: int = 1280,
42
+ intermediate_size: int = 3456,
43
+ token_embedding_dim: int = 256,
44
+ # pattern
45
+ par_mode: str = "perceiver", # "perceiver" | "dense"
46
+ pre_layers: int = 2,
47
+ pre_window: int = 1024,
48
+ global_layers: int = 1,
49
+ global_positions: Optional[tuple[int, ...]] = None, # explicit layer indices of the global read(s)
50
+ stack_layers: int = 20,
51
+ block: int = 4096, # N — window of the stack layers
52
+ # heads / positions
53
+ num_attention_heads: Optional[int] = None,
54
+ num_kv_heads: int = 2,
55
+ head_dim: int = 128,
56
+ rope_theta: float = 500000.0,
57
+ nope_every: int = 4, # every k-th stack layer has no RoPE (SmolLM3); 0 = off
58
+ global_nope: bool = False, # global read(s) without RoPE: content-only retrieval (iRoPE-style)
59
+ global_logit_scale: str = "none", # "log": q *= s*log(n_visible) on full layers (SSMax; anti-dilution)
60
+ global_scale_ref: int = 8192, # n at which the log scale equals 1 at init (s = 1/log(ref))
61
+ # input
62
+ ngram_orders: tuple[int, ...] = (2, 3),
63
+ ngram_buckets: int = 131072,
64
+ value_embed_layers: tuple[int, ...] = (0, 7, 14),
65
+ value_embed_dim: int = 64,
66
+ # head / loss
67
+ logit_softcap: float = 30.0,
68
+ z_loss: float = 1e-4,
69
+ chunked_ce_block_size: int = 2048,
70
+ use_liger: bool = True,
71
+ # backend / hooks
72
+ attn_backend: str = "flex", # "sdpa" | "flex" | "flash"
73
+ attn_pad_multiple: int = 2048,
74
+ block_attention_mode: str = "causal", # "causal" | "bidirectional" (E20)
75
+ swa_sink: bool = False, # windowed layers may also attend to the document's first token
76
+ write_back_hook: bool = False, # E19 — adds write_back_proj params when True
77
+ message_boundary_token_id: int = -1, # E21 — reserved id that splits sender | receiver (-1 = off)
78
+ message_compress_ratio: int = 16, # E21 — prefix tokens per message slot (1 = uncompressed, arm U)
79
+ message_pool_remainder: bool = False, # E21 — pool the incomplete last sender block (default: complete blocks only)
80
+ message_slots_inplace: bool = False, # E21 — write slots into sender prefix positions (KV_LEN=S; default concat)
81
+ message_inplace_raw_kv: bool = False, # E21 — inplace: token K/V at replace positions (skip compressor values)
82
+ message_identity_slots: bool = False, # E21 — freeze mean-pool at any r; bypass u/delta
83
+ message_pack_stride: int = 0, # E21 — exclusive leftover vs N-token packs ending at QUERY (0=off)
84
+ message_keep_local_swa: bool = False, # E21 — local SWA/n-grams still see across QUERY
85
+ message_raw_window: int = 0, # >0: the global read's raw keys are a causal window (memory is the only long path)
86
+ message_extra_slot_attends: int = 0, # E21 — extra exclusive attends over frozen slots
87
+ message_read_rounds: int = 1, # E33 — tied read→update rounds of the global block (slots frozen after round 1)
88
+ message_round_aux: float = 0.0, # E33 — weight of per-round targets (round r predicts chain node r+1)
89
+ message_loop_rounds: int = 1, # E33a — tied loop of [global read + span layers]; 1 = today's stack
90
+ message_loop_span: int = 1, # E33a — layers after the global read inside the loop
91
+ message_loop_inject: str = "none", # E33a — "prelude": add the prelude output back each loop (gated)
92
+ message_loop_exit_aux: float = 0.0, # E33a — weight of each non-final loop exit's CE
93
+ message_loop_exit_targets: str = "progress", # E33a — "progress" (round targets) | "answer" (labels)
94
+ message_loop_name_aux: float = 0.0, # E33 — weight: each loop state names its whole node at the decision position
95
+ message_loop_name_len: int = 0, # E33 — letters per node name for the name head (the chain's key_len)
96
+ message_loop_read_aux: float = 0.0, # text multi-hop (2026-10-17) — weight of the per-round read target
97
+ message_loop_exit_mask: str = "all", # text multi-hop — loop exits score "all" labels or only "answers"
98
+ message_loop_read_target: str = "page", # text multi-hop — read target on a page's notes or the span's "note"s
99
+ message_loop_name_lens: float = 0.0, # E33q — weight: round r names hop r's output word (its tokens) at the
100
+ # question's decision position, read through the shared LM head
101
+ message_loop_feedback: str = "none", # E33q — "soft": round r's LM-head distribution, re-embedded with the
102
+ # shared token table and input layer, is added to round r+1 (gate from 0)
103
+ message_loop_feedback_temp: float = 1.0, # E33q — softmax temperature of that re-embedding
104
+ message_loop_control: str = "none", # E33c — "question": each round reads its next relation from the question
105
+ # (MAC control unit over the last `window` tokens, gate from 0)
106
+ message_loop_control_window: int = 48, # E33c — tokens before (and at) each position the control reads
107
+ message_loop_control_dim: int = 128, # E33c — control state width (split over the control heads)
108
+ message_loop_control_heads: int = 4, # E33c — control heads, each with its own pointer into the question
109
+ message_loop_control_words: str = "embed", # E33c — what the control reads: "embed" (the input layer: one
110
+ # vector per word, the same at every "teacher of") | "prelude"
111
+ lm_writer_input: str = "table", # notebook writer input: "table" (the shared token table, E31-E33) | "embed"
112
+ # (the decoder's whole input layer: the writer and reader share one encoding)
113
+ message_update_slot_kv: bool = False, # E21 — rewrite exclusive slot K/V between extra hops
114
+ message_global_anchors: str = "none", # E21 — sparse raw keys joining exclusive slot K/V
115
+ message_anchor_token_ids: tuple[int, ...] = (), # type-mark / keymark ids
116
+ message_anchor_window: int = MESSAGE_QUERY_NBHD_DEFAULT, # nbhd width (query_nbhd / query_side)
117
+ message_anchor_key_len: int = 0, # E27 — key-span length (0 = treat as 2)
118
+ message_prefix_ae: bool = False, # E26 — weak prefix-block reconstruction from slots
119
+ message_prefix_ae_weight: float = 0.0,
120
+ message_prefix_ae_stopgrad_answer: bool = True, # compressor sees AE grads only
121
+ message_write: str = "block_mean", # E30 — "block_mean" (E21) | "sw_perceiver"
122
+ swp_bank_size: int = SWP_BANK_DEFAULT,
123
+ swp_coverage: int = SWP_COVERAGE_DEFAULT,
124
+ swp_window: int = 0, # 0 → coverage * bank_size
125
+ swp_stride: int = 0, # 0 → round((1 - overlap) * window)
126
+ swp_n_heads: int = 0, # 0 → max(4, num_attention_heads)
127
+ swp_query_dim: int = 0, # 0 → max(head_dim, 4 * token_embedding_dim)
128
+ swp_auto_fit: bool = True, # shrink K so n_windows≥2 on short seq
129
+ swp_slot_pos: str = "page", # E30 slot RoPE position: "page" end | "boundary" (the QUERY; length-invariant)
130
+ lm_context: str = "page_bidir", # E31 — "page_bidir" | "bixt"
131
+ lm_window: int = 256, # E31 — fixed geometry (no auto-shrink)
132
+ lm_stride: int = 192,
133
+ lm_latents: int = 32,
134
+ lm_latent_dim: int = 512,
135
+ lm_heads: int = 8, # per-latent heads, never averaged
136
+ lm_writer_dim: int = 256,
137
+ lm_enc_layers: int = 2, # page_bidir only
138
+ lm_rounds: int = 2, # latent read rounds (bixt: latent⇄token rounds)
139
+ lm_competition: bool = True, # softmax over latents per token, then renormalise
140
+ lm_null_latent: bool = False, # one latent the reader never sees
141
+ lm_readback_aux: float = 0.0, # text multi-hop (2026-10-17): each note's value names the tokens it read
142
+ lm_key_grad: str = "full", # text multi-hop: "detach" = key-side losses do not move what a latent reads;
143
+ # "address" = detach + the key's own read of the page
144
+ lm_reader_tokens: int = 5, # reader K/V entries per latent (m)
145
+ lm_pos_prior: bool = True, # per-latent sub-page prior at init
146
+ lm_addr: str = "window_start", # latent address: "window_start" sinusoid | "none" (length-invariant)
147
+ lm_slot_pos: str = "read", # slot RoPE position: "read" (what it read) | "boundary" (the QUERY) | "scaled"
148
+ # | "mixed" | "reader" (E31c: no slot rotation, met by the un-rotated query)
149
+ message_override: str = "real", # E31c control: "none" = the model is built and trained without slots
150
+ lm_read: str = "exclusive", # E31c — "exclusive" (only tokens after QUERY read earlier sides) |
151
+ # "closed" (every token reads the windows closed at or before it: text)
152
+ slot_pos_ref: int = 2048, # "scaled" slot positions: max query–slot distance (order kept, length-invariant)
153
+ lm_read_topk: int = 0, # E33n — top-k note read (LSA-style selection on notes): each query and head reads
154
+ # only its k best visible notes (by its own score, chosen without gradient)
155
+ # plus the raw window; 0 = every visible note (E31c / E33)
156
+ lm_note_age: str = "none", # E33d — page distance on the note read, outside the key: "none" | "log" | "linear"
157
+ # (score −= s_h · f((pos(t) − slot_pos) / unit), s_h per head, starts at 0)
158
+ lm_note_age_unit: int = 0, # E33d — tokens per distance unit; 0 = lm_stride (one page step)
159
+ # E33e — lm_note_age="rank": f = log(1 + soft count of NEWER notes that match the
160
+ # query about as well as its best note), so a lone fact pays nothing at any length
161
+ lm_note_rank_margin: float = 1.0, # E33e — a note "matches" when its score is within ~margin of the best note's
162
+ lm_note_rank_sharp: float = 2.0, # E33e — steepness of that match gate: σ(sharp · (score − best + margin))
163
+ lm_note_age_init: str = "", # E33g — per-head starting strengths, comma-separated (one value = every head,
164
+ # fewer than the heads = the last heads); "" = 0 on every head (E33d / E33e)
165
+ lm_note_age_learn: bool = True, # E33g — False keeps those strengths fixed (order heads that cannot fade)
166
+ lm_note_order_gate: bool = False, # E33i — order on demand: the order term × σ(w·x_t + b) per reader position
167
+ # (w = 0, b = −2 at the start), so a question can turn order up while story
168
+ # text keeps it off; one learned switch instead of one scalar per head
169
+ lm_note_rank_gate: str = "own", # E33g2 — "own": each head counts matches by its own score; "content": by the
170
+ # mean score of the strength-0 heads (the asked person's notes), for all heads
171
+ lm_count_heads: int = 0, # E33h — count heads beside the global read (summing read; 0 = off)
172
+ lm_count_max: int = 10, # E33h — the counts coded as a soft one-hot over 0..lm_count_max
173
+ lm_count_aux: float = 0.0, # E33k — weight: each count head's sum at a count question's decision position
174
+ # must equal the true number of visits (read-target quads, round base 100)
175
+ lm_note_key: str = "writer", # E33p — "tied": a note's key in the read is κ_n = Σ_t A[t,n] k_t / Σ_t A[t,n],
176
+ # the writer-assignment-weighted mean of the reading layer's own raw keys
177
+ lm_open: str = "none", # E33p — "notes": each query opens the raw tokens of its best notes' members;
178
+ # "pages": of its best whole pages; "none" = notes are read as gist only
179
+ lm_open_k: int = 0, # E33p — notes (or pages) each query chooses
180
+ lm_open_cap: int = 512, # E33p — opened raw tokens per query, at most
181
+ lm_note_read: str = "gist", # E33t — "index": the notes only choose what opens; they are not keys of the read
182
+ lm_filing: str = "argmax", # E33t — "balanced": Sinkhorn-balanced assignment, ≤ lm_filing_cap tokens per note
183
+ lm_filing_iters: int = 3, # E33t — Sinkhorn iterations of the balanced filing
184
+ lm_filing_cap: int = 16, # E33t — most tokens filed under one note
185
+ lm_open_score: str = "sum_softmax", # E33t — "max_cos": cosine of query and note key, best query head
186
+ lm_open_new_per_pass: bool = False, # E33t — a loop pass may not open notes the query opened in earlier passes
187
+ lm_open_levels: int = 1, # E33t — 2: a query keeps its best pages first, then chooses among their notes
188
+ lm_open_pages: int = 16, # E33t — pages kept by the two-level search
189
+ lm_sinks: int = 0, # E33t — learned empty slots in the catalogue read (a key and a value each)
190
+ lm_index_loss: float = 0.0, # E33t — weight of the index loss (note scores predict the read's mass)
191
+ lm_index_queries: int = 256, # E33t — sampled query positions per row and pass for the index loss
192
+ lm_index_negatives: int = 32, # E33t — sampled unchosen notes per query in the index loss
193
+ par_global_read: str = "dense", # E33p — "lsa": LSA's released flat read on the global layer (nn/lsa_buckets.py)
194
+ lsa_window: int = 512, # LSA read: raw window
195
+ lsa_sinks: int = 4, # LSA read: first tokens of each document, always read
196
+ lsa_block: int = 512, # LSA read: keys per clustered block
197
+ lsa_bucket: int = 8, # LSA read: average keys per bucket (buckets per block = block / bucket)
198
+ lsa_pool: int = 4, # LSA read: neighbouring keys summed into one pool before the merges
199
+ lsa_bucket_cap: int = 16, # LSA read: most keys a bucket may hold
200
+ lsa_top_k: int = 512, # LSA read: keys each query takes beyond its sinks and window
201
+ lsa_width: int = 0, # LSA read: buckets each query ranks, at most (0 = 2 · top_k / bucket)
202
+ # E37 concept memory (par_global_read="concept", nn/concept_memory.py): encoder → reasoner → decoder read
203
+ concept_block: int = 512, # E37: keys per clustered block (the window covers the query's block + one)
204
+ concept_per_block: int = 64, # E37: concepts per block (balanced soft k-means on the unit keys)
205
+ concept_iters: int = 3, # E37: k-means rounds (each a Sinkhorn-balanced plan)
206
+ concept_tau: float = 0.05, # E37: assignment temperature
207
+ concept_sinks: int = 4, # E37: first tokens of each document, always read
208
+ concept_top_k: int = 512, # E37: member tokens each query opens exactly, at most
209
+ concept_width: int = 0, # E37: concepts each query ranks for opening (0 = 2 · top_k · per_block / block)
210
+ concept_summaries: bool = True, # E37: every concept not opened enters the read as one summary entry
211
+ concept_variance: bool = True, # E37: the summary logit's second-order term |q|² σ² / 2d
212
+ concept_sum_len: int = 0, # E37: length scale of the summaries' weight past this row length (0 = off)
213
+ concept_reasoner_layers: int = 0, # E37: transformer layers of the concept reasoner (0 = none)
214
+ concept_reasoner_dim: int = 512, # E37: reasoner width
215
+ concept_reasoner_heads: int = 8, # E37: reasoner heads
216
+ concept_reasoner_loops: int = 2, # E37: reasoner loops (input injection each loop)
217
+ init_std: float = 0.02,
218
+ zero_init_residuals: bool = True, # False: warm attn.wo / mlp.down (needed at 512+)
219
+ pad_token_id: int = 0,
220
+ bos_token_id: int = 1,
221
+ eos_token_id: int = 2,
222
+ tie_word_embeddings: bool = False,
223
+ lm_head_tied: bool = False, # 2026-11-14: the output reuses the input token table through a projection
224
+ **kwargs,
225
+ ):
226
+ super().__init__(
227
+ pad_token_id=pad_token_id,
228
+ bos_token_id=bos_token_id,
229
+ eos_token_id=eos_token_id,
230
+ tie_word_embeddings=tie_word_embeddings,
231
+ **kwargs,
232
+ )
233
+ self.vocab_size = vocab_size
234
+ self.hidden_size = hidden_size
235
+ self.intermediate_size = intermediate_size
236
+ self.token_embedding_dim = token_embedding_dim
237
+ self.lm_head_tied = bool(lm_head_tied)
238
+ self.par_mode = par_mode
239
+ self.pre_layers = pre_layers
240
+ self.pre_window = pre_window
241
+ self.global_layers = global_layers
242
+ self.global_positions = tuple(int(p) for p in global_positions) if global_positions else None
243
+ self.stack_layers = stack_layers
244
+ self.block = block
245
+ self.num_attention_heads = num_attention_heads or (hidden_size // head_dim)
246
+ self.num_kv_heads = num_kv_heads
247
+ self.head_dim = head_dim
248
+ self.rope_theta = rope_theta
249
+ self.nope_every = nope_every
250
+ self.global_nope = bool(global_nope)
251
+ self.global_logit_scale = global_logit_scale
252
+ self.global_scale_ref = int(global_scale_ref)
253
+ self.ngram_orders = tuple(int(o) for o in ngram_orders)
254
+ self.ngram_buckets = ngram_buckets
255
+ self.value_embed_layers = tuple(int(l) for l in value_embed_layers)
256
+ self.value_embed_dim = value_embed_dim
257
+ self.logit_softcap = logit_softcap
258
+ self.z_loss = z_loss
259
+ self.chunked_ce_block_size = chunked_ce_block_size
260
+ self.use_liger = use_liger
261
+ self.attn_backend = attn_backend
262
+ self.attn_pad_multiple = attn_pad_multiple
263
+ self.block_attention_mode = block_attention_mode
264
+ self.swa_sink = swa_sink
265
+ self.write_back_hook = write_back_hook
266
+ self.message_boundary_token_id = int(message_boundary_token_id)
267
+ self.message_compress_ratio = int(message_compress_ratio)
268
+ self.message_pool_remainder = bool(message_pool_remainder)
269
+ self.message_slots_inplace = bool(message_slots_inplace)
270
+ self.message_inplace_raw_kv = bool(message_inplace_raw_kv)
271
+ self.message_identity_slots = bool(message_identity_slots)
272
+ self.message_pack_stride = int(message_pack_stride)
273
+ self.message_keep_local_swa = bool(message_keep_local_swa)
274
+ self.message_raw_window = int(message_raw_window)
275
+ self.message_extra_slot_attends = int(message_extra_slot_attends)
276
+ self.message_read_rounds = int(message_read_rounds)
277
+ self.message_round_aux = float(message_round_aux)
278
+ self.message_loop_rounds = int(message_loop_rounds)
279
+ self.message_loop_span = int(message_loop_span)
280
+ self.message_loop_inject = str(message_loop_inject or "none")
281
+ self.message_loop_exit_aux = float(message_loop_exit_aux)
282
+ self.message_loop_exit_targets = str(message_loop_exit_targets or "progress")
283
+ self.message_loop_name_aux = float(message_loop_name_aux)
284
+ self.message_loop_name_len = int(message_loop_name_len)
285
+ self.message_loop_read_aux = float(message_loop_read_aux)
286
+ self.message_loop_exit_mask = str(message_loop_exit_mask or "all")
287
+ self.message_loop_read_target = str(message_loop_read_target or "page")
288
+ self.message_loop_name_lens = float(message_loop_name_lens or 0.0)
289
+ self.message_loop_feedback = str(message_loop_feedback or "none")
290
+ self.message_loop_feedback_temp = float(message_loop_feedback_temp or 1.0)
291
+ self.message_loop_control = str(message_loop_control or "none")
292
+ self.message_loop_control_window = int(message_loop_control_window or 48)
293
+ self.message_loop_control_dim = int(message_loop_control_dim or 128)
294
+ self.message_loop_control_heads = int(message_loop_control_heads or 4)
295
+ self.message_loop_control_words = str(message_loop_control_words or "embed")
296
+ self.lm_writer_input = str(lm_writer_input or "table")
297
+ if self.lm_writer_input not in ("table", "embed"):
298
+ raise ValueError("lm_writer_input must be 'table' or 'embed'")
299
+ self.message_update_slot_kv = bool(message_update_slot_kv)
300
+ self.message_global_anchors = str(message_global_anchors or "none")
301
+ self.message_anchor_token_ids = tuple(int(x) for x in (message_anchor_token_ids or ()))
302
+ self.message_anchor_window = int(message_anchor_window)
303
+ self.message_anchor_key_len = int(message_anchor_key_len)
304
+ self.message_prefix_ae = bool(message_prefix_ae)
305
+ self.message_prefix_ae_weight = float(message_prefix_ae_weight)
306
+ self.message_prefix_ae_stopgrad_answer = bool(message_prefix_ae_stopgrad_answer)
307
+ self.message_write = str(message_write or "block_mean")
308
+ self.swp_bank_size = int(swp_bank_size)
309
+ self.swp_coverage = int(swp_coverage)
310
+ self.swp_window = int(swp_window)
311
+ self.swp_stride = int(swp_stride)
312
+ self.swp_n_heads = int(swp_n_heads)
313
+ self.swp_query_dim = int(swp_query_dim)
314
+ self.swp_auto_fit = bool(swp_auto_fit)
315
+ self.lm_context = str(lm_context)
316
+ self.lm_window = int(lm_window)
317
+ self.lm_stride = int(lm_stride)
318
+ self.lm_latents = int(lm_latents)
319
+ self.lm_latent_dim = int(lm_latent_dim)
320
+ self.lm_heads = int(lm_heads)
321
+ self.lm_writer_dim = int(lm_writer_dim)
322
+ self.lm_enc_layers = int(lm_enc_layers)
323
+ self.lm_rounds = int(lm_rounds)
324
+ self.lm_competition = bool(lm_competition)
325
+ self.lm_null_latent = bool(lm_null_latent)
326
+ self.lm_reader_tokens = int(lm_reader_tokens)
327
+ self.lm_readback_aux = float(lm_readback_aux)
328
+ self.lm_key_grad = str(lm_key_grad)
329
+ self.lm_pos_prior = bool(lm_pos_prior)
330
+ self.lm_addr = str(lm_addr)
331
+ self.lm_slot_pos = str(lm_slot_pos)
332
+ self.lm_read = str(lm_read)
333
+ self.message_override = str(message_override)
334
+ self.swp_slot_pos = str(swp_slot_pos)
335
+ self.slot_pos_ref = int(slot_pos_ref)
336
+ self.lm_read_topk = int(lm_read_topk or 0)
337
+ self.lm_note_age = str(lm_note_age or "none")
338
+ self.lm_note_age_unit = int(lm_note_age_unit or 0)
339
+ self.lm_note_rank_margin = float(lm_note_rank_margin)
340
+ self.lm_note_rank_sharp = float(lm_note_rank_sharp)
341
+ self.lm_note_age_init = str(lm_note_age_init or "")
342
+ self.lm_note_age_learn = bool(lm_note_age_learn)
343
+ self.lm_note_rank_gate = str(lm_note_rank_gate or "own")
344
+ self.lm_note_order_gate = bool(lm_note_order_gate)
345
+ self.lm_count_heads = int(lm_count_heads or 0)
346
+ self.lm_count_max = int(lm_count_max)
347
+ self.lm_count_aux = float(lm_count_aux or 0.0)
348
+ self.lm_note_key = str(lm_note_key or "writer")
349
+ self.lm_open = str(lm_open or "none")
350
+ self.lm_open_k = int(lm_open_k or 0)
351
+ self.lm_open_cap = int(lm_open_cap)
352
+ self.lm_note_read = str(lm_note_read or "gist")
353
+ self.lm_filing = str(lm_filing or "argmax")
354
+ self.lm_filing_iters = int(lm_filing_iters)
355
+ self.lm_filing_cap = int(lm_filing_cap)
356
+ self.lm_open_score = str(lm_open_score or "sum_softmax")
357
+ self.lm_open_new_per_pass = bool(lm_open_new_per_pass)
358
+ self.lm_open_levels = int(lm_open_levels or 1)
359
+ self.lm_open_pages = int(lm_open_pages)
360
+ self.lm_sinks = int(lm_sinks or 0)
361
+ self.lm_index_loss = float(lm_index_loss or 0.0)
362
+ self.lm_index_queries = int(lm_index_queries)
363
+ self.lm_index_negatives = int(lm_index_negatives)
364
+ self.par_global_read = str(par_global_read or "dense")
365
+ self.lsa_window = int(lsa_window)
366
+ self.lsa_sinks = int(lsa_sinks)
367
+ self.lsa_block = int(lsa_block)
368
+ self.lsa_bucket = int(lsa_bucket)
369
+ self.lsa_pool = int(lsa_pool)
370
+ self.lsa_bucket_cap = int(lsa_bucket_cap)
371
+ self.lsa_top_k = int(lsa_top_k)
372
+ self.lsa_width = int(lsa_width or 0) or (2 * self.lsa_top_k // max(self.lsa_bucket, 1))
373
+ self.concept_block = int(concept_block)
374
+ self.concept_per_block = int(concept_per_block)
375
+ self.concept_iters = int(concept_iters)
376
+ self.concept_tau = float(concept_tau)
377
+ self.concept_sinks = int(concept_sinks)
378
+ self.concept_top_k = int(concept_top_k)
379
+ self.concept_width = int(concept_width or 0) or max(
380
+ 1, 2 * self.concept_top_k * self.concept_per_block // max(self.concept_block, 1))
381
+ self.concept_summaries = bool(concept_summaries)
382
+ self.concept_variance = bool(concept_variance)
383
+ self.concept_sum_len = int(concept_sum_len or 0)
384
+ self.concept_reasoner_layers = int(concept_reasoner_layers or 0)
385
+ self.concept_reasoner_dim = int(concept_reasoner_dim)
386
+ self.concept_reasoner_heads = int(concept_reasoner_heads)
387
+ self.concept_reasoner_loops = int(concept_reasoner_loops)
388
+ self.init_std = init_std
389
+ self.zero_init_residuals = bool(zero_init_residuals)
390
+ # Bookkeeping consumed by the shared entrypoint / W&B init / eval routing.
391
+ self.checkpoint_family = "perceiver_ar"
392
+ self.pretraining_objective = "causal_lm"
393
+ self.concept_num = 0
394
+ self.hidden_act = "silu" # SwiGLU (informational; the entrypoint logs it)
395
+ self.norm_type = "rmsnorm"
396
+ self.max_sequence_length = kwargs.get("max_sequence_length", None)
397
+ self._validate()
398
+ self.num_hidden_layers = self.total_layers
399
+
400
+ def _validate(self):
401
+ if self.par_mode not in {"perceiver", "dense"}:
402
+ raise ValueError(f"par_mode must be 'perceiver' or 'dense', got {self.par_mode!r}")
403
+ if self.num_attention_heads % self.num_kv_heads != 0:
404
+ raise ValueError("num_attention_heads must be divisible by num_kv_heads")
405
+ if self.num_attention_heads * self.head_dim > 4 * self.hidden_size:
406
+ raise ValueError("num_attention_heads*head_dim is implausibly large vs hidden_size")
407
+ if self.attn_backend not in {"sdpa", "flex", "flash"}:
408
+ raise ValueError(f"unknown attn_backend {self.attn_backend!r}")
409
+ if self.block_attention_mode not in {"causal", "bidirectional"}:
410
+ raise ValueError("block_attention_mode must be 'causal' or 'bidirectional'")
411
+ if self.global_logit_scale not in {"none", "log"}:
412
+ raise ValueError("global_logit_scale must be 'none' or 'log'")
413
+ if self.global_scale_ref < 2:
414
+ raise ValueError("global_scale_ref must be >= 2")
415
+ if self.global_layers < 1 and self.par_mode == "perceiver":
416
+ logger.warning("perceiver mode with global_layers=0: a purely local model (ablation only)")
417
+ if self.global_positions is not None:
418
+ n = self.pre_layers + self.global_layers + self.stack_layers
419
+ if len(self.global_positions) != self.global_layers:
420
+ raise ValueError("global_positions must list exactly global_layers indices")
421
+ if len(set(self.global_positions)) != len(self.global_positions):
422
+ raise ValueError("global_positions must be distinct")
423
+ if any(p < 0 or p >= n for p in self.global_positions):
424
+ raise ValueError(f"global_positions must lie in [0, {n})")
425
+ if self.message_compress_ratio < 1:
426
+ raise ValueError("message_compress_ratio must be >= 1")
427
+ if self.message_pack_stride < 0:
428
+ raise ValueError("message_pack_stride must be >= 0")
429
+ if self.message_extra_slot_attends < 0:
430
+ raise ValueError("message_extra_slot_attends must be >= 0")
431
+ if self.message_read_rounds < 1:
432
+ raise ValueError("message_read_rounds must be >= 1")
433
+ if self.message_loop_rounds < 1:
434
+ raise ValueError("message_loop_rounds must be >= 1")
435
+ if self.message_loop_inject not in ("none", "prelude"):
436
+ raise ValueError("message_loop_inject must be 'none' or 'prelude'")
437
+ if self.message_loop_exit_targets not in ("progress", "answer"):
438
+ raise ValueError("message_loop_exit_targets must be 'progress' or 'answer'")
439
+ if self.message_loop_exit_mask not in ("all", "answers"):
440
+ raise ValueError("message_loop_exit_mask must be 'all' or 'answers'")
441
+ if self.message_loop_read_target not in ("page", "note"):
442
+ raise ValueError("message_loop_read_target must be 'page' or 'note'")
443
+ if self.message_loop_control not in ("none", "question"):
444
+ raise ValueError("message_loop_control must be 'none' or 'question'")
445
+ if self.message_loop_control != "none":
446
+ if self.message_loop_rounds < 2:
447
+ raise ValueError("message_loop_control needs message_loop_rounds >= 2")
448
+ if self.message_loop_control_words not in ("embed", "prelude"):
449
+ raise ValueError("message_loop_control_words must be 'embed' or 'prelude'")
450
+ if self.message_loop_control_window < 2:
451
+ raise ValueError("message_loop_control_window must be >= 2")
452
+ if self.message_loop_control_heads < 1 or self.message_loop_control_dim % self.message_loop_control_heads:
453
+ raise ValueError("message_loop_control_dim must be a multiple of message_loop_control_heads")
454
+ if self.message_loop_rounds > 1:
455
+ if self.message_read_rounds > 1:
456
+ raise ValueError("message_loop_rounds and message_read_rounds (E33) are exclusive")
457
+ if self.par_mode != "perceiver" or self.global_layers != 1:
458
+ raise ValueError("message_loop_rounds needs par_mode='perceiver' with exactly one global layer")
459
+ n_layers = self.pre_layers + self.global_layers + self.stack_layers
460
+ gi = self.global_layer_index
461
+ if self.message_loop_span < 0 or gi + 1 + self.message_loop_span > n_layers:
462
+ raise ValueError(f"message_loop_span must keep the loop inside the stack (<= {n_layers - gi - 1})")
463
+ if self.message_global_anchors not in MESSAGE_GLOBAL_ANCHORS:
464
+ raise ValueError(
465
+ f"message_global_anchors must be one of {MESSAGE_GLOBAL_ANCHORS}, "
466
+ f"got {self.message_global_anchors!r}"
467
+ )
468
+ if self.message_anchor_window < 0:
469
+ raise ValueError("message_anchor_window must be >= 0")
470
+ if self.message_anchor_key_len < 0:
471
+ raise ValueError("message_anchor_key_len must be >= 0")
472
+ if self.message_prefix_ae_weight < 0:
473
+ raise ValueError("message_prefix_ae_weight must be >= 0")
474
+ if self.message_prefix_ae and not self.message_enabled:
475
+ raise ValueError("message_prefix_ae needs message_boundary_token_id >= 0")
476
+ if self.message_write not in MESSAGE_WRITES:
477
+ raise ValueError(
478
+ f"message_write must be one of {MESSAGE_WRITES}, got {self.message_write!r}"
479
+ )
480
+ if self.swp_bank_size < 1:
481
+ raise ValueError("swp_bank_size must be >= 1")
482
+ if self.swp_coverage < 1:
483
+ raise ValueError("swp_coverage must be >= 1")
484
+ if self.swp_window < 0 or self.swp_stride < 0:
485
+ raise ValueError("swp_window and swp_stride must be >= 0 (0 = derive)")
486
+ if self.swp_n_heads < 0 or self.swp_query_dim < 0:
487
+ raise ValueError("swp_n_heads and swp_query_dim must be >= 0 (0 = derive)")
488
+ if self.message_write == "sw_perceiver":
489
+ if not self.message_enabled:
490
+ raise ValueError("message_write='sw_perceiver' needs message_boundary_token_id >= 0")
491
+ if self.message_slots_inplace:
492
+ raise ValueError("sw_perceiver uses concat slots; message_slots_inplace is not 1:1")
493
+ if self.message_identity_slots:
494
+ raise ValueError("sw_perceiver has no mean-pool identity; leave message_identity_slots off")
495
+ if self.message_prefix_ae:
496
+ raise ValueError("message_prefix_ae is a block-mean write (E26); not defined for sw_perceiver")
497
+ if self.swp_slot_pos not in ("page", "boundary", "scaled", "mixed"):
498
+ raise ValueError(f"swp_slot_pos must be page / boundary / scaled / mixed, got {self.swp_slot_pos!r}")
499
+ if self.message_override not in ("real", "none", "swapped", "raw"):
500
+ raise ValueError(f"message_override must be real / none / swapped / raw, got {self.message_override!r}")
501
+ if self.lm_read not in ("exclusive", "closed"):
502
+ raise ValueError(f"lm_read must be 'exclusive' or 'closed', got {self.lm_read!r}")
503
+ if self.lm_read == "closed" and self.message_write != "latent_memory":
504
+ raise ValueError("lm_read='closed' is the E31 text read; it needs message_write='latent_memory'")
505
+ if self.message_write == "latent_memory":
506
+ if not self.message_enabled:
507
+ raise ValueError("message_write='latent_memory' needs message_boundary_token_id >= 0 "
508
+ "(or lm_read='closed', which needs no question boundary)")
509
+ if self.message_slots_inplace or self.message_identity_slots or self.message_prefix_ae:
510
+ raise ValueError("latent_memory uses concat slots; inplace / identity / prefix_ae do not apply")
511
+ if self.lm_context not in LM_CONTEXTS:
512
+ raise ValueError(f"lm_context must be one of {LM_CONTEXTS}, got {self.lm_context!r}")
513
+ if min(self.lm_window, self.lm_stride, self.lm_latents, self.lm_heads,
514
+ self.lm_writer_dim, self.lm_reader_tokens) < 1:
515
+ raise ValueError("lm_window/stride/latents/heads/writer_dim/reader_tokens must be >= 1")
516
+ if self.lm_latent_dim % self.lm_heads != 0:
517
+ raise ValueError("lm_latent_dim must be divisible by lm_heads")
518
+ if self.lm_stride > self.lm_window:
519
+ raise ValueError("lm_stride must be <= lm_window (windows must tile the book)")
520
+ if self.lm_addr not in ("window_start", "none"):
521
+ raise ValueError(f"lm_addr must be 'window_start' or 'none', got {self.lm_addr!r}")
522
+ if self.lm_slot_pos not in ("read", "boundary", "scaled", "mixed", "reader"):
523
+ raise ValueError(
524
+ f"lm_slot_pos must be read / boundary / scaled / mixed / reader, got {self.lm_slot_pos!r}"
525
+ )
526
+ if self.message_extra_slot_attends or self.message_update_slot_kv:
527
+ raise ValueError("latent_memory: extra slot attends are not defined (read once; E31a reads per layer)")
528
+ if self.lm_note_age not in ("none", "log", "linear", "rank"):
529
+ raise ValueError(f"lm_note_age must be none / log / linear / rank, got {self.lm_note_age!r}")
530
+ if self.lm_note_rank_sharp <= 0:
531
+ raise ValueError("lm_note_rank_sharp must be > 0")
532
+ if self.lm_note_age_unit < 0:
533
+ raise ValueError("lm_note_age_unit must be >= 0 (0 = lm_stride)")
534
+ if self.lm_note_age != "none" and self.lm_slot_pos != "reader":
535
+ raise ValueError("lm_note_age measures from each note's read position: it needs lm_slot_pos='reader'")
536
+ if getattr(self, "lm_note_age", "none") != "none" and self.message_write != "latent_memory":
537
+ raise ValueError("lm_note_age (E33d) is a latent-memory read option; it needs message_write='latent_memory'")
538
+ if self.lm_read_topk < 0:
539
+ raise ValueError("lm_read_topk must be >= 0 (0 = read every visible note)")
540
+ if self.lm_read_topk > 0:
541
+ if self.message_write != "latent_memory" or self.lm_read != "closed":
542
+ raise ValueError("lm_read_topk (E33n) selects among notes: it needs message_write='latent_memory' and "
543
+ "lm_read='closed'")
544
+ if self.lm_note_age != "none" or int(getattr(self, "lm_count_heads", 0) or 0) > 0:
545
+ raise ValueError("lm_read_topk is not combined with lm_note_age / lm_count_heads (scores would differ)")
546
+ self._validate_e33p()
547
+ if self.message_raw_window < 0:
548
+ raise ValueError("message_raw_window must be >= 0 (0 = full causal raw keys)")
549
+ if self.message_raw_window and self.message_slots_inplace:
550
+ raise ValueError("message_raw_window applies to the concat read, not inplace slots")
551
+ if self.message_enabled:
552
+ if self.message_boundary_token_id >= self.vocab_size:
553
+ raise ValueError("message_boundary_token_id must be a vocabulary id")
554
+ if self.par_mode != "perceiver" or self.global_layers < 1:
555
+ raise ValueError("the message boundary needs perceiver mode with >= 1 global read layer")
556
+ if self.attn_backend == "flash":
557
+ raise ValueError("message boundary is not expressible with the flash backend; use flex or sdpa")
558
+ for tid in self.message_anchor_token_ids:
559
+ if tid < 0 or tid >= self.vocab_size:
560
+ raise ValueError("message_anchor_token_ids must be vocabulary ids")
561
+
562
+ def _validate_e33p(self):
563
+ """E33p: tied note keys, the opened read, and LSA's read on the global layer (plan §6)."""
564
+ if self.lm_note_key not in ("writer", "tied"):
565
+ raise ValueError(f"lm_note_key must be writer | tied, got {self.lm_note_key!r}")
566
+ if self.lm_open not in ("none", "notes", "pages"):
567
+ raise ValueError(f"lm_open must be none | notes | pages, got {self.lm_open!r}")
568
+ if self.lm_open_k < 0 or not 1 <= self.lm_open_cap <= 32767:
569
+ raise ValueError("lm_open_k must be >= 0 and lm_open_cap in [1, 32767]")
570
+ if self.lm_open != "none":
571
+ if self.lm_open_k < 1:
572
+ raise ValueError("lm_open needs lm_open_k >= 1")
573
+ if self.lm_note_key != "tied":
574
+ raise ValueError("lm_open needs lm_note_key='tied' (the notes are the index)")
575
+ if self.message_raw_window <= 0:
576
+ raise ValueError("lm_open needs message_raw_window > 0 (opened tokens lie beyond the window)")
577
+ if self.lm_note_key == "tied":
578
+ need = {
579
+ "message_write='latent_memory'": self.message_write == "latent_memory",
580
+ "lm_read='closed'": self.lm_read == "closed",
581
+ "lm_competition=True": bool(self.lm_competition),
582
+ "lm_null_latent=False": not bool(self.lm_null_latent),
583
+ "lm_reader_tokens=1": int(self.lm_reader_tokens) == 1,
584
+ "lm_slot_pos='reader'": self.lm_slot_pos == "reader",
585
+ "global_nope=True": bool(self.global_nope),
586
+ "lm_read_topk=0": self.lm_read_topk == 0,
587
+ "lm_note_age='none'": self.lm_note_age == "none",
588
+ "lm_count_heads=0": self.lm_count_heads == 0,
589
+ "message_read_rounds=1": self.message_read_rounds == 1,
590
+ "attn_backend != flash": self.attn_backend != "flash",
591
+ }
592
+ bad = [k for k, ok in need.items() if not ok]
593
+ if bad:
594
+ raise ValueError("lm_note_key='tied' (E33p) needs " + ", ".join(bad))
595
+ # E33t: the catalogue read (spec docs/experiments_specs/ahead/E33t_catalogue_read.md)
596
+ if self.lm_note_read not in ("gist", "index"):
597
+ raise ValueError(f"lm_note_read must be gist | index, got {self.lm_note_read!r}")
598
+ if self.lm_filing not in ("argmax", "balanced"):
599
+ raise ValueError(f"lm_filing must be argmax | balanced, got {self.lm_filing!r}")
600
+ if self.lm_open_score not in ("sum_softmax", "max_cos"):
601
+ raise ValueError(f"lm_open_score must be sum_softmax | max_cos, got {self.lm_open_score!r}")
602
+ if self.lm_open_levels not in (1, 2) or self.lm_open_pages < 1:
603
+ raise ValueError("lm_open_levels must be 1 or 2 and lm_open_pages >= 1")
604
+ if self.lm_sinks < 0 or self.lm_index_loss < 0 or self.lm_index_queries < 1 or self.lm_index_negatives < 0:
605
+ raise ValueError("lm_sinks, lm_index_loss, lm_index_negatives >= 0 and lm_index_queries >= 1")
606
+ e33t = {
607
+ "lm_note_read='index'": self.lm_note_read == "index",
608
+ "lm_filing='balanced'": self.lm_filing == "balanced",
609
+ "lm_open_score='max_cos'": self.lm_open_score == "max_cos",
610
+ "lm_open_new_per_pass": self.lm_open_new_per_pass,
611
+ "lm_open_levels=2": self.lm_open_levels == 2,
612
+ }
613
+ used = [k for k, on in e33t.items() if on]
614
+ if used and self.lm_open != "notes":
615
+ raise ValueError(", ".join(used) + " need lm_open='notes' (E33t)")
616
+ if (self.lm_sinks > 0 or self.lm_index_loss > 0) and self.lm_note_read != "index":
617
+ raise ValueError("lm_sinks and lm_index_loss need lm_note_read='index' (E33t)")
618
+ if self.lm_filing == "balanced":
619
+ if self.lm_filing_iters < 0 or self.lm_filing_cap < 1 or self.lm_filing_cap > 511:
620
+ raise ValueError("lm_filing_iters >= 0 and lm_filing_cap in [1, 511]")
621
+ if self.lm_filing_cap * int(self.lm_latents) < int(self.lm_window):
622
+ raise ValueError("lm_filing_cap · lm_latents must be >= lm_window (every token needs a note)")
623
+ if self.par_global_read not in ("dense", "lsa", "concept"):
624
+ raise ValueError(f"par_global_read must be dense | lsa | concept, got {self.par_global_read!r}")
625
+ if self.par_global_read == "concept":
626
+ if self.message_enabled:
627
+ raise ValueError("par_global_read='concept' (E37) is its own memory: turn the message boundary off")
628
+ if not self.global_nope or self.num_kv_heads != 1:
629
+ raise ValueError("par_global_read='concept' needs global_nope=True and num_kv_heads=1")
630
+ if self.attn_backend == "flash" or self.par_mode != "perceiver" or self.global_layers < 1:
631
+ raise ValueError("par_global_read='concept' needs perceiver mode with a global layer, flex or sdpa")
632
+ if self.concept_block % self.concept_per_block or self.concept_block > 511 * self.concept_per_block:
633
+ raise ValueError("concept_per_block must divide concept_block")
634
+ if self.concept_block > 512:
635
+ raise ValueError("concept_block must be <= 512 (member rank code, nn.exact_read)")
636
+ if not 1 <= self.concept_top_k <= 32767 or self.concept_sinks < 0 or self.concept_iters < 1:
637
+ raise ValueError("concept_top_k in [1, 32767], concept_sinks >= 0, concept_iters >= 1")
638
+ if self.concept_reasoner_layers and self.concept_reasoner_dim % self.concept_reasoner_heads:
639
+ raise ValueError("concept_reasoner_heads must divide concept_reasoner_dim")
640
+ if self.par_global_read == "lsa":
641
+ if self.message_enabled:
642
+ raise ValueError("par_global_read='lsa' is the no-notebook LSA arm: turn the message boundary off")
643
+ if not self.global_nope or self.num_kv_heads != 1:
644
+ raise ValueError("par_global_read='lsa' needs global_nope=True and num_kv_heads=1 (LSA's max rule)")
645
+ if self.attn_backend == "flash" or self.par_mode != "perceiver" or self.global_layers < 1:
646
+ raise ValueError("par_global_read='lsa' needs perceiver mode with a global layer, flex or sdpa")
647
+ if self.lsa_block % self.lsa_bucket or self.lsa_bucket % self.lsa_pool:
648
+ raise ValueError("lsa_bucket must divide lsa_block and lsa_pool must divide lsa_bucket")
649
+ if self.lsa_bucket_cap < 2 * self.lsa_bucket:
650
+ raise ValueError("lsa_bucket_cap must be >= 2 * lsa_bucket (Ward needs the room; LSA's ward_merge)")
651
+ if self.lsa_window < 1 or self.lsa_sinks < 0 or not 1 <= self.lsa_top_k <= 32767 or self.lsa_width < 1:
652
+ raise ValueError("lsa_window >= 1, lsa_sinks >= 0, lsa_top_k in [1, 32767], lsa_width >= 1")
653
+ if self.lsa_bucket_cap > 511:
654
+ raise ValueError("lsa_bucket_cap must be < 512 (member rank code)")
655
+
656
+ @property
657
+ def message_enabled(self) -> bool:
658
+ """E21: rows may carry a sender|receiver boundary token; receivers read the prefix only
659
+ through compressed slots of the global read. E31c: the closed-window latent memory is always
660
+ on (every token reads the closed windows), with or without a boundary token."""
661
+ return self.message_boundary_token_id >= 0 or (
662
+ getattr(self, "message_write", "block_mean") == "latent_memory"
663
+ and getattr(self, "lm_read", "exclusive") == "closed"
664
+ )
665
+
666
+ @property
667
+ def total_layers(self) -> int:
668
+ return self.pre_layers + self.global_layers + self.stack_layers
669
+
670
+ @property
671
+ def resolved_global_positions(self) -> tuple[int, ...]:
672
+ """Layer indices of the global read(s). Default: the `global_layers` layers right after
673
+ the pre-encoder (E18). `global_positions` moves them anywhere — e.g. mid-depth, so the
674
+ read's queries are formed by half the stack (E18 reach-ablation follow-up)."""
675
+ if self.par_mode == "dense":
676
+ return ()
677
+ if self.global_positions is not None:
678
+ return self.global_positions
679
+ return tuple(range(self.pre_layers, self.pre_layers + self.global_layers))
680
+
681
+ @property
682
+ def stack_indices(self) -> list[int]:
683
+ """Layers governed by the stack rules (NoPE every k-th, E20 bidirectional): every layer in
684
+ dense mode; every non-pre, non-global layer in perceiver mode."""
685
+ if self.par_mode == "dense":
686
+ return list(range(self.total_layers))
687
+ g = set(self.resolved_global_positions)
688
+ return [i for i in range(self.pre_layers, self.total_layers) if i not in g]
689
+
690
+ def layer_patterns(self) -> list[tuple[str, int]]:
691
+ """Per-layer (pattern, window). Dense = all full causal with the same layer count."""
692
+ if self.par_mode == "dense":
693
+ return [("full", 0)] * self.total_layers
694
+ pats = [("swa", self.pre_window)] * self.pre_layers + [("swa", self.block)] * (
695
+ self.global_layers + self.stack_layers
696
+ )
697
+ for p in self.resolved_global_positions:
698
+ pats[p] = ("full", 0)
699
+ return pats
700
+
701
+ @property
702
+ def global_layer_index(self) -> int:
703
+ """Index of the (first) global read layer — the one-layer prefix cache / message space."""
704
+ if self.par_mode == "dense":
705
+ return 0
706
+ g = self.resolved_global_positions
707
+ return min(g) if g else self.pre_layers
708
+
709
+
710
+ __all__ = ["PerceiverARConfig"]
export_manifest.json ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "exported_at": "2026-11-18 14:54:29 UTC",
3
+ "source": {
4
+ "repo": "https://github.com/ksopyla/MrCogito",
5
+ "commit": "2e6b9573c8fba973c57a8ff8ed101b34f780b1d3",
6
+ "dirty": false
7
+ },
8
+ "checkpoint": "e37a_m120t_final",
9
+ "vendored_modules": [
10
+ "nn/exact_read.py",
11
+ "nn/latent_memory.py",
12
+ "nn/concept_memory.py",
13
+ "nn/perceiver_ar_lm.py",
14
+ "nn/incremental.py",
15
+ "nn/perceiver_ar_hub.py"
16
+ ],
17
+ "left_out": [
18
+ "nn/lsa_buckets.py"
19
+ ],
20
+ "remote_code_requires": [
21
+ "__future__",
22
+ "contextlib",
23
+ "copy",
24
+ "dataclasses",
25
+ "functools",
26
+ "logging",
27
+ "math",
28
+ "os",
29
+ "torch",
30
+ "transformers",
31
+ "types",
32
+ "typing"
33
+ ],
34
+ "config_changes": {
35
+ "architectures": [
36
+ [
37
+ "PerceiverARLM"
38
+ ],
39
+ [
40
+ "PerceiverARForCausalLM"
41
+ ]
42
+ ],
43
+ "auto_map": [
44
+ null,
45
+ {
46
+ "AutoConfig": "configuration_perceiver_ar.PerceiverARConfig",
47
+ "AutoModelForCausalLM": "modeling_perceiver_ar.PerceiverARForCausalLM"
48
+ }
49
+ ],
50
+ "use_liger": [
51
+ true,
52
+ false
53
+ ],
54
+ "tokenizer_name": [
55
+ "<local path>",
56
+ "HuggingFaceTB/SmolLM2-135M"
57
+ ],
58
+ "attn_backend": [
59
+ "flex",
60
+ "sdpa"
61
+ ]
62
+ },
63
+ "auto_map": {
64
+ "AutoConfig": "configuration_perceiver_ar.PerceiverARConfig",
65
+ "AutoModelForCausalLM": "modeling_perceiver_ar.PerceiverARForCausalLM"
66
+ },
67
+ "exported_with": {
68
+ "transformers": "4.57.6",
69
+ "torch": "2.11.0+cu128"
70
+ },
71
+ "warnings": [],
72
+ "files": {
73
+ "README.md": {
74
+ "bytes": 26449,
75
+ "sha256": "ebc7d591807f446b1863495fb96e95bfa50aeed019e57db016dadb7f18375480"
76
+ },
77
+ "chat_template.jinja": {
78
+ "bytes": 198,
79
+ "sha256": "f91864928fccff928b3068ca784db6275e655e400ccbb28f61d92c0090caf3b3"
80
+ },
81
+ "config.json": {
82
+ "bytes": 4805,
83
+ "sha256": "a6a072cc44eeed11df41cf066f91da8dd4ca305029f1e81fe7f89dcfe0524120"
84
+ },
85
+ "configuration_perceiver_ar.py": {
86
+ "bytes": 48670,
87
+ "sha256": "c9097fc5e0dca48e9798649f7beda380a1d269eeac56b43031ae1f283b3cfb41"
88
+ },
89
+ "generation_config.json": {
90
+ "bytes": 133,
91
+ "sha256": "a104c5ba9e7cba01973e7194382cf0d330f5775f9ea71031901bf050ad497129"
92
+ },
93
+ "merges.txt": {
94
+ "bytes": 466391,
95
+ "sha256": "0b54e8aa4e53d5383e2e4bc635a56b43f9647f7b13832d5d9ecd8f82dac4f510"
96
+ },
97
+ "model.safetensors": {
98
+ "bytes": 566041960,
99
+ "sha256": "bdc070232c94d473ae2cc3752fef9167990df5146b438183c8cb49653cdc02a5"
100
+ },
101
+ "modeling_perceiver_ar.py": {
102
+ "bytes": 369577,
103
+ "sha256": "d08957b7dbc082677664f9d0b3dc3c9b16a0ffdc73c168c212ff32ed32af8b0e"
104
+ },
105
+ "special_tokens_map.json": {
106
+ "bytes": 977,
107
+ "sha256": "79c83a585c13ce3020b4cfb5078ddc460d49c61dac2b569b37ae5833bb702f8c"
108
+ },
109
+ "tokenizer.json": {
110
+ "bytes": 3522656,
111
+ "sha256": "7d27c493c729a66ecefc837280b05d948b1ed50d130eebdbf911b1b36cf38ed7"
112
+ },
113
+ "tokenizer_config.json": {
114
+ "bytes": 3720,
115
+ "sha256": "7d282e6bc097cad322ef8df614312cca2ffa25034d9dfd2a94999554c8b4e5d7"
116
+ },
117
+ "vocab.json": {
118
+ "bytes": 800662,
119
+ "sha256": "82b84012e3add4d01d12ba14442026e49b8cbbaead1f79ecf3d919784f82dc79"
120
+ }
121
+ }
122
+ }
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": false,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.57.6"
7
+ }
modeling_perceiver_ar.py ADDED
The diff for this file is too large to render. See raw diff