igorktech commited on
Commit
36b95ca
·
0 Parent(s):

nanoFLY decoder: MaleCNS v1.0 connectome as a frozen recurrent layer

Browse files
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ connectome.png filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: cc-by-4.0-weights-non-commercial-data
4
+ license_link: https://huggingface.co/datasets/dichspace/darulm
5
+ language:
6
+ - ru
7
+ library_name: transformers
8
+ pipeline_tag: text-generation
9
+ datasets:
10
+ - dichspace/darulm
11
+ tags:
12
+ - connectome
13
+ - reservoir-computing
14
+ - echo-state-network
15
+ - fruit-fly
16
+ - drosophila
17
+ - malecns
18
+ - russian
19
+ - custom_code
20
+ ---
21
+
22
+ # nanofly-decoder-ru
23
+
24
+ ![MaleCNS soma cloud coloured by this model's neuron states](connectome.png)
25
+
26
+ <sub>43,993 neurons at their measured MaleCNS v1.0 coordinates, coloured by this checkpoint's state at one tick while continuing the prompt *«Сегодня утром»*. Orange excited, blue inhibited, grey at rest. Frontal view; the optic lobes flank the central brain.</sub>
27
+
28
+ A Russian language model whose recurrent layer is the measured wiring of a fruit fly. The connectome is a frozen [echo state network](https://en.wikipedia.org/wiki/Echo_state_network) reservoir — **no synapse is trained**. Only the input projection, per-neuron gain/bias/leak, one global scale and the readout learn.
29
+
30
+ > **Non-commercial.** The training data ([DaruLM](https://huggingface.co/datasets/dichspace/darulm)) permits scientific, non-commercial use only. That restriction travels with these weights.
31
+
32
+ > **Unfiltered.** No toxicity or profanity filtering at any stage. It emits Russian obscenity unprompted. Do not put it in front of users without a filter.
33
+
34
+ - **Code:** [github.com/igorktech/nanoFLY](https://github.com/igorktech/nanoFLY)
35
+ - **English sibling:** [`igorktech/nanofly-decoder-en`](https://huggingface.co/igorktech/nanofly-decoder-en)
36
+
37
+ ## Usage
38
+
39
+ ```python
40
+ import torch
41
+ from transformers import AutoTokenizer, AutoModelForCausalLM
42
+
43
+ repo = "igorktech/nanofly-decoder-ru"
44
+ tok = AutoTokenizer.from_pretrained(repo, trust_remote_code=True)
45
+ model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True).eval()
46
+ model = model.to("cuda" if torch.cuda.is_available() else "cpu")
47
+
48
+ ids = tok("Сегодня утром", return_tensors="pt").input_ids
49
+ ids = torch.cat([torch.tensor([[model.config.bos_token_id]]), ids], dim=1).to(model.device)
50
+ out = model.generate(ids, max_new_tokens=80, do_sample=True, top_k=50, temperature=0.7)
51
+ print(tok.decode(out[0], skip_special_tokens=True))
52
+ ```
53
+
54
+ - **Sample, do not decode greedily** — greedy falls into repetition loops within a sentence or two.
55
+ - Prepend BOS: every training example started with it.
56
+ - Beam search and assisted generation are unsupported (stateful model).
57
+ - ~960 forward passes/s on an RTX 5080, ~10/s on a laptop CPU.
58
+
59
+ ## Architecture
60
+
61
+ | | |
62
+ |---|---|
63
+ | connectome | MaleCNS v1.0 central brain — `cb_sensory`, `cb_intrinsic`, `visual_projection`, `descending_neuron`, `ascending_neuron` |
64
+ | neurons / edges | 49,393 / 9,055,280 signed (623,728 dropped: modulatory or unknown transmitter) |
65
+ | edge weight | sign of the presynaptic transmitter × synapse count, rows normalised to unit absolute weight. ACh +1; GABA, Glu, His −1; others 0 |
66
+ | token input | 11,434 sensory-facing neurons, 8-slot delay line (slot *j* gets token *t−j*). No attention, no positional encoding |
67
+ | held out | the 2,635 ORNs stay out of the token input, so the encoder-decoder variant can start from these weights |
68
+ | dynamics | `x ← (1−a)·x + a·tanh(ρ·g·(Wx) + u + b)`, 2 ticks per token; `a` learned per neuron (init 0.5), `ρ` learned global (init 1.0 → **5.34**) |
69
+ | readout | all 49,393 states → `Linear(49393→256)` → `LayerNorm` → `Linear(256→4096)` |
70
+ | trainable | **17.82M** — readout 13.69M, input projection 2.93M, embedding 1.05M, per-neuron scalars 0.15M |
71
+
72
+ ## Training
73
+
74
+ | | |
75
+ |---|---|
76
+ | data | DaruLM — Pikabu, Lenta, Gazeta shards; 178,148 documents / 1,852 held out; 81,634,628 tokens; BPE vocab 4,096 |
77
+ | mixture | **2 : 1 : 1 by token count**. `--mix` samples per document and the sources differ in length (349 / 446 / 1,516 tokens), so per-document weights are 8.7 : 3.4 : 1 |
78
+ | objective | next-token cross entropy, truncated BPTT over 32-token windows, state carried across windows |
79
+ | optimiser | AdamW — body 2e-3 (no decay), readout 5e-4 (decay 0.01), warmup 200 then cosine to 10%, clip 1.0 |
80
+ | schedule | 2 epochs, 42,081 updates, batch 128 |
81
+ | hardware | 1 × RTX 5080, 3.51 h at ~13,000 tok/s |
82
+
83
+ ## Evaluation
84
+
85
+ | | val loss | ppl | bits/char |
86
+ |---|---|---|---|
87
+ | **this model** | **3.738** | 42.0 | 1.77 |
88
+ | English sibling, for scale | 1.933 | 6.9 | 0.92 |
89
+
90
+ **Perplexities across different tokenizers are not comparable** — this model's vocabulary is 4× larger and 3.04 characters per token. Bits per character is the fair axis, and there the gap is under 2×, not 6×. The corpora also differ in difficulty: open-domain web Russian against a deliberately closed and repetitive TinyStories. Validation fell 98.1 → 42.0 over 23 evaluations and was still improving at the end; the checkpoint is undertrained.
91
+
92
+ No shuffled-wiring control has been run for this model (the English one has: 1.933 real vs 1.979 degree-matched shuffle).
93
+
94
+ Samples, top-k 50, temperature 0.7, prompt in bold:
95
+
96
+ > **По данным синоптиков**, в городе Мой биологи в регионе было обнаружено в одном городе и блинском городе Уфе. Об этом сообщает пресс-служба столичных регионах страны.
97
+
98
+ > **Вчера вечером я** решил подробно настроить на сайтах: — Чувак, которые я вам не сижу на пикабу сижу, что я хочу поделиться с =)
99
+
100
+ Morphology, short-range agreement and register are learned — the first is recognisably newswire down to the "Об этом сообщает пресс-служба" formula, the second recognisably a Pikabu post. Meaning is not.
101
+
102
+ ## Limitations
103
+
104
+ - 17.8M trainable parameters over 163M token-steps of web Russian. Fluent-looking Russian that does not mean anything.
105
+ - Greedy decoding degenerates into loops. Sampling is required.
106
+ - 8-token delay line plus a short leaky recurrent memory; it cannot hold a subject across a sentence.
107
+ - Unfiltered Pikabu, Lenta and Gazeta: obscenity, the biases of that data, and a mid-2010s news skew. DaruLM flags itself `not-for-all-audiences` and notes its domain splits are noisy.
108
+ - A `tanh` rate neuron is not a spiking model: no spikes, no synaptic delays, no neuromodulation — modulatory edges are removed outright.
109
+ - Central brain only; the optic lobes and ventral nerve cord of the 166,700-neuron CNS are absent.
110
+ - Synapse count is a proxy for strength, and rows are normalised. Neither is measured physiology.
111
+
112
+ ## Credits
113
+
114
+ - **Connectome:** MaleCNS v1.0 — FlyEM / HHMI Janelia, University of Cambridge, MRC LMB, Google Research. CC BY 4.0. The published buffers derive from that release; keep the attribution when redistributing.
115
+ - **Data:** [DaruLM](https://huggingface.co/datasets/dichspace/darulm) by dichspace, from corpora collected by Ilya Gusev. **Scientific, non-commercial use only** — the same restriction applies to these weights.
116
+ - **Transmitter signs:** Shiu et al., *Nature* 2024.
117
+ - **Connectome as reservoir:** Costi, Hadjiivanov, Dold, Hale, Izzo, 2025.
118
+ - **Prior art:** [`ngxson/fly-llm-hf`](https://huggingface.co/ngxson/fly-llm-hf), whose graph subset this reproduces.
119
+
120
+ The licence tag is `other`, not `cc-by-4.0`: the connectome would allow CC BY, the training data does not permit commercial use, and the stricter term governs. Modeling code Apache-2.0.
config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "arch": "decoder",
3
+ "architectures": [
4
+ "FlyForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_fly.FlyConfig",
8
+ "AutoModel": "modeling_fly.FlyModel",
9
+ "AutoModelForCausalLM": "modeling_fly.FlyForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "connectome": "MaleCNS v1.0, FlyEM / HHMI Janelia, University of Cambridge, MRC LMB, Google Research. CC BY 4.0.",
13
+ "d_emb": 256,
14
+ "delay": 8,
15
+ "dtype": "float32",
16
+ "eos_token_id": 2,
17
+ "head_type": "lowrank",
18
+ "min_syn": 1,
19
+ "mode": "gains",
20
+ "model_type": "fly",
21
+ "modulatory_sign": 0.0,
22
+ "n_edges": 9055280,
23
+ "n_neurons": 49393,
24
+ "n_news_input": 0,
25
+ "n_reserved": 2635,
26
+ "n_token_input": 11434,
27
+ "news_dim": 0,
28
+ "news_encoder": "none",
29
+ "news_glom": 0,
30
+ "news_group": "orn",
31
+ "news_mode": "glomeruli",
32
+ "news_prefix": "",
33
+ "pad_token_id": 0,
34
+ "readout": "all",
35
+ "readout_rank": 256,
36
+ "readout_size": 49393,
37
+ "source_repo": "",
38
+ "ticks": 2,
39
+ "tie_word_embeddings": false,
40
+ "token_input": "cb_sensory,visual_projection",
41
+ "transformers_version": "5.17.0",
42
+ "use_cache": true,
43
+ "vocab_size": 4096
44
+ }
configuration_fly.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Config for the Fly connectome language models (published with trust_remote_code)."""
2
+ from transformers import PretrainedConfig
3
+
4
+ CONNECTOME = ("MaleCNS v1.0, FlyEM / HHMI Janelia, University of Cambridge, MRC LMB, "
5
+ "Google Research. CC BY 4.0.")
6
+
7
+
8
+ class FlyConfig(PretrainedConfig):
9
+ """A fruit-fly connectome as the recurrent layer of a language model.
10
+
11
+ Two architectures share this config:
12
+
13
+ * ``decoder`` — token in, token out, nothing else. Comparable to ngxson/fly-llm-hf.
14
+ * ``encoder_decoder`` — the post being answered is encoded once by a frozen sentence encoder
15
+ (``news_encoder``) and injected as a constant current into the olfactory neurons for the whole
16
+ generation, so the fly "smells" the post while it writes. Only the projection into those
17
+ neurons is trained here; the sentence encoder is a separate model and is not shipped.
18
+
19
+ The recurrent weights are anatomy, not learned: ``w_values`` are signed, row-normalised synapse
20
+ counts between the neurons of the release above. ``mode`` records whether the published values
21
+ are the raw connectome (``gains``) or connectome-masked learned strengths (``edges``).
22
+ """
23
+
24
+ model_type = "fly"
25
+ keys_to_ignore_at_inference = ["cache_params"]
26
+
27
+ def __init__(
28
+ self,
29
+ arch="decoder",
30
+ vocab_size=2048,
31
+ d_emb=256,
32
+ delay=8,
33
+ ticks=2,
34
+ mode="gains",
35
+ token_input="cb_sensory",
36
+ n_neurons=1,
37
+ n_edges=0,
38
+ n_token_input=1,
39
+ n_news_input=0,
40
+ readout="all",
41
+ readout_size=1,
42
+ readout_rank=256,
43
+ head_type="lowrank",
44
+ news_dim=0,
45
+ news_group="orn",
46
+ n_reserved=0,
47
+ news_mode="direct",
48
+ news_glom=0,
49
+ news_encoder="none",
50
+ news_prefix="",
51
+ min_syn=1,
52
+ modulatory_sign=0.0,
53
+ connectome=CONNECTOME,
54
+ source_repo="",
55
+ use_cache=True,
56
+ pad_token_id=0,
57
+ bos_token_id=1,
58
+ eos_token_id=2,
59
+ tie_word_embeddings=False,
60
+ **kwargs,
61
+ ):
62
+ self.arch = arch
63
+ self.vocab_size = vocab_size
64
+ self.d_emb = d_emb
65
+ self.delay = delay
66
+ self.ticks = ticks
67
+ self.mode = mode
68
+ self.token_input = token_input # which population the delay line writes into
69
+ self.n_neurons = n_neurons
70
+ self.n_edges = n_edges
71
+ self.n_token_input = n_token_input
72
+ self.n_news_input = n_news_input
73
+ self.readout = readout
74
+ self.readout_size = readout_size
75
+ self.readout_rank = readout_rank
76
+ self.head_type = head_type # lowrank: Linear->LayerNorm->Linear, linear: LayerNorm->Linear
77
+ self.news_dim = news_dim
78
+ self.news_group = news_group # population carved out for the post channel
79
+ self.n_reserved = n_reserved # its size, even when this variant does not use it
80
+ self.news_mode = news_mode
81
+ self.news_glom = news_glom
82
+ self.news_encoder = news_encoder
83
+ self.news_prefix = news_prefix
84
+ self.min_syn = min_syn
85
+ self.modulatory_sign = modulatory_sign
86
+ self.connectome = connectome
87
+ self.source_repo = source_repo
88
+ self.use_cache = use_cache
89
+ super().__init__(
90
+ pad_token_id=pad_token_id,
91
+ bos_token_id=bos_token_id,
92
+ eos_token_id=eos_token_id,
93
+ tie_word_embeddings=tie_word_embeddings,
94
+ **kwargs,
95
+ )
96
+
97
+ @property
98
+ def hidden_size(self):
99
+ return self.readout_size
100
+
101
+ @property
102
+ def conditional(self):
103
+ return self.arch == "encoder_decoder" and self.news_dim > 0
connectome.png ADDED

Git LFS Details

  • SHA256: fa83276e2e73017335ecb6e7adb66f26ed0439b46757ad3bcd82d9979b86acd4
  • Pointer size: 131 Bytes
  • Size of remote file: 203 kB
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "output_attentions": false,
6
+ "output_hidden_states": false,
7
+ "pad_token_id": 0,
8
+ "transformers_version": "5.17.0",
9
+ "use_cache": true
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3da350494b21229ef2d2fdf9697927df08805c133abfc4ec57402e3e21a1ed1
3
+ size 144414608
modeling_fly.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fly: a fruit-fly connectome as the recurrent layer of a language model.
2
+
3
+ State update, one line per neuron i, repeated `ticks` times per token:
4
+
5
+ x_i <- (1 - a_i) * x_i + a_i * tanh( rho * g_i * sum_j W_ij x_j + u_i + b_i )
6
+
7
+ `W` is anatomy and is not trained here: signed, row-normalised synapse counts from MaleCNS v1.0.
8
+ `u` is the input current — the token embedding fanned into sensory neurons through a delay line,
9
+ plus, for the encoder-decoder model, a constant current on the olfactory neurons that carries the
10
+ post being answered. The readout is a linear head on a subset of neurons (all, descending, motor…).
11
+
12
+ This file is the inference/fine-tuning copy that ships with the weights. Training lives in the
13
+ project repo (see `config.source_repo`), where the connectome is rebuilt from the release tables.
14
+ """
15
+ from dataclasses import dataclass
16
+ from typing import Optional, Tuple
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from transformers import GenerationMixin, PreTrainedModel
22
+ from transformers.utils import ModelOutput
23
+
24
+ from .configuration_fly import FlyConfig
25
+
26
+ # This file is the single source for both published variants. `export_hf.py::write_code` ships it
27
+ # unchanged for the encoder-decoder and, for the decoder, rewrites the `Fly` prefix to `Fly`
28
+ # and drops the conditional tail, which starts at the top-level definition of `_hash_embed` and runs
29
+ # to the end of the file. Three invariants:
30
+ # 1. the prefix is spelled `Fly` (class) and `fly` (module) nowhere except where it must
31
+ # be renamed — never put either literal in a URL or a message meant to survive;
32
+ # 2. everything below that definition belongs to the post channel, and nothing above it refers to
33
+ # anything below;
34
+ # 3. the relative import above is rewritten too, so the pair always travels together.
35
+ # The export writes the folder, loads it back and compares logits, so a broken rename fails loudly —
36
+ # as it did the first time this very comment was written with the marker spelled out in full.
37
+
38
+
39
+ class FlyCache:
40
+ """What carries over between generate() steps: neuron state and the delay line of token ids."""
41
+
42
+ is_compileable = False
43
+
44
+ def __init__(self, state, last_tokens, seq_len=0):
45
+ self.state = state # [B, N] neuron activations
46
+ self.last_tokens = last_tokens # [B, delay], most recent token first
47
+ self.seq_len = seq_len
48
+
49
+ def get_seq_length(self, layer_idx=0):
50
+ return self.seq_len
51
+
52
+ def get_max_cache_shape(self):
53
+ return None
54
+
55
+ def reorder_cache(self, beam_idx):
56
+ self.state = self.state.index_select(0, beam_idx.to(self.state.device))
57
+ self.last_tokens = self.last_tokens.index_select(0, beam_idx.to(self.last_tokens.device))
58
+ return self
59
+
60
+
61
+ @dataclass
62
+ class FlyOutput(ModelOutput):
63
+ last_hidden_state: torch.FloatTensor = None
64
+ cache_params: Optional[FlyCache] = None
65
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
66
+
67
+
68
+ @dataclass
69
+ class FlyCausalLMOutput(ModelOutput):
70
+ loss: Optional[torch.FloatTensor] = None
71
+ logits: torch.FloatTensor = None
72
+ cache_params: Optional[FlyCache] = None
73
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
74
+
75
+
76
+ class _SpMM(torch.autograd.Function):
77
+ """y = W @ x with W a fixed sparse CSR matrix; the backward pass reuses a cached transpose."""
78
+
79
+ @staticmethod
80
+ def forward(ctx, x, W, WT):
81
+ ctx.WT = WT
82
+ return torch.sparse.mm(W, x)
83
+
84
+ @staticmethod
85
+ def backward(ctx, g):
86
+ return torch.sparse.mm(ctx.WT, g.contiguous()), None, None
87
+
88
+
89
+ class FlyPreTrainedModel(PreTrainedModel):
90
+ config_class = FlyConfig
91
+ base_model_prefix = "brain"
92
+ supports_gradient_checkpointing = False
93
+ _is_stateful = True
94
+ _no_split_modules = []
95
+
96
+ @classmethod
97
+ def _supports_default_dynamic_cache(cls):
98
+ # the model keeps its own FlyCache; generate() must not build a KV cache for it
99
+ return False
100
+
101
+ def _init_weights(self, module):
102
+ if isinstance(module, nn.Linear):
103
+ nn.init.normal_(module.weight, std=min(0.02, module.in_features ** -0.5))
104
+ if module.bias is not None:
105
+ nn.init.zeros_(module.bias)
106
+ elif isinstance(module, nn.Embedding):
107
+ nn.init.normal_(module.weight, std=1.0)
108
+ if module.padding_idx is not None:
109
+ module.weight.data[module.padding_idx].zero_()
110
+ elif isinstance(module, FlyModel):
111
+ # the raw parameters need their own init: a zeroed in_proj means no current ever reaches
112
+ # the neurons, so a model built from the config alone would be deaf. A reservoir wants
113
+ # O(1) drive, not transformer-scale.
114
+ nn.init.normal_(module.in_proj, std=module.config.d_emb ** -0.5)
115
+ nn.init.ones_(module.gain)
116
+ nn.init.zeros_(module.bias)
117
+ nn.init.zeros_(module.leak_logit) # sigmoid(0) = 0.5
118
+ nn.init.zeros_(module.log_rho) # exp(0) = 1
119
+
120
+
121
+ class FlyModel(FlyPreTrainedModel):
122
+ """The brain: connectome recurrence, token and post input, neuron-subset readout."""
123
+
124
+ def __init__(self, config: FlyConfig):
125
+ super().__init__(config)
126
+ N, E, d = config.n_neurons, config.n_edges, config.d_emb
127
+ self.emb = nn.Embedding(config.vocab_size, d, padding_idx=config.pad_token_id)
128
+ self.in_proj = nn.Parameter(torch.empty(config.n_token_input, d))
129
+ self.bias = nn.Parameter(torch.zeros(N, 1))
130
+ self.gain = nn.Parameter(torch.ones(N, 1))
131
+ self.log_rho = nn.Parameter(torch.zeros(()))
132
+ self.leak_logit = nn.Parameter(torch.zeros(N, 1))
133
+ self.news_proj = None
134
+ if config.conditional:
135
+ out = config.news_glom if config.news_mode == "glomeruli" else config.n_news_input
136
+ self.news_proj = nn.Linear(config.news_dim, out)
137
+ if config.news_mode == "glomeruli":
138
+ self.register_buffer("news_glom_of", torch.zeros(config.n_news_input, dtype=torch.long))
139
+
140
+ # connectome in CSR by target neuron: crow [N+1], col = source neuron, w = signed strength
141
+ self.register_buffer("crow", torch.zeros(N + 1, dtype=torch.int32))
142
+ self.register_buffer("col", torch.zeros(E, dtype=torch.int32))
143
+ self.register_buffer("w", torch.zeros(E))
144
+ self.register_buffer("token_idx", torch.zeros(config.n_token_input, dtype=torch.long))
145
+ self.register_buffer("news_idx", torch.zeros(config.n_news_input, dtype=torch.long))
146
+ self.register_buffer("readout_idx", torch.zeros(config.readout_size, dtype=torch.long))
147
+ # delay line: slot j covers token_idx[bounds[j]:bounds[j+1]] and sees token t-j
148
+ self.register_buffer("bounds", torch.zeros(config.delay + 1, dtype=torch.long))
149
+ self._wt_key = None
150
+ self.post_init()
151
+
152
+ def get_input_embeddings(self):
153
+ return self.emb
154
+
155
+ def set_input_embeddings(self, value):
156
+ self.emb = value
157
+
158
+ def connectome(self):
159
+ N = self.config.n_neurons
160
+ W = torch.sparse_csr_tensor(self.crow, self.col, self.w, size=(N, N))
161
+ key = (self.w.data_ptr(), self.w._version, self.w.device)
162
+ if self._wt_key != key:
163
+ self._wt = W.t().to_sparse_csr()
164
+ self._wt_key = key
165
+ return W, self._wt
166
+
167
+ def drive_from_tokens(self, prev_ids, inputs_embeds):
168
+ """Delay-line current: input group j receives the embedding of token t-j. -> [T, n_in, B]"""
169
+ k = self.config.delay
170
+ B, T, _ = inputs_embeds.shape
171
+ ext = torch.cat([self.emb(prev_ids.flip(1)), inputs_embeds], dim=1) # oldest first, then new
172
+ bounds = self.bounds.tolist()
173
+ parts = []
174
+ for j in range(k):
175
+ e_j = ext[:, k - j: k - j + T] # token t-j for t in [0, T)
176
+ parts.append(e_j @ self.in_proj[bounds[j]:bounds[j + 1]].t())
177
+ return torch.cat(parts, dim=-1).permute(1, 2, 0).contiguous()
178
+
179
+ def forward(
180
+ self,
181
+ input_ids=None,
182
+ attention_mask=None,
183
+ inputs_embeds=None,
184
+ news_embeds=None,
185
+ cache_params: Optional[FlyCache] = None,
186
+ use_cache=None,
187
+ output_hidden_states=None,
188
+ return_dict=None,
189
+ **kwargs,
190
+ ):
191
+ cfg = self.config
192
+ use_cache = use_cache if use_cache is not None else cfg.use_cache
193
+ return_dict = return_dict if return_dict is not None else getattr(cfg, "return_dict", True)
194
+ if inputs_embeds is None:
195
+ inputs_embeds = self.emb(input_ids)
196
+ B, T, _ = inputs_embeds.shape
197
+ N, k, dev = cfg.n_neurons, cfg.delay, inputs_embeds.device
198
+
199
+ if cache_params is None:
200
+ x = inputs_embeds.new_zeros(N, B)
201
+ prev_ids = torch.full((B, k), cfg.pad_token_id, dtype=torch.long, device=dev)
202
+ seq_len = 0
203
+ else:
204
+ x = cache_params.state.t().contiguous()
205
+ prev_ids = cache_params.last_tokens
206
+ seq_len = cache_params.seq_len
207
+
208
+ drive = self.drive_from_tokens(prev_ids, inputs_embeds)
209
+ news_u = None
210
+ if self.news_proj is not None and news_embeds is not None:
211
+ news_u = self.news_proj(news_embeds.to(inputs_embeds.dtype))
212
+ if cfg.news_mode == "glomeruli":
213
+ news_u = news_u.index_select(1, self.news_glom_of)
214
+ news_u = news_u.t() # [n_news_input, B]
215
+
216
+ W, WT = self.connectome()
217
+ a = torch.sigmoid(self.leak_logit)
218
+ scale = torch.exp(self.log_rho) * self.gain
219
+ mask = attention_mask.to(x.dtype).t() if attention_mask is not None else None
220
+ outs = []
221
+ for t in range(T):
222
+ u = torch.zeros(N, B, device=dev, dtype=x.dtype)
223
+ u = u.index_add(0, self.token_idx, drive[t])
224
+ if news_u is not None:
225
+ u = u.index_add(0, self.news_idx, news_u)
226
+ u = u + self.bias
227
+ for _ in range(cfg.ticks):
228
+ new = (1 - a) * x + a * torch.tanh(scale * _SpMM.apply(x, W, WT) + u)
229
+ if mask is not None: # padding freezes the state
230
+ m = mask[t][None, :]
231
+ new = m * new + (1 - m) * x
232
+ x = new
233
+ outs.append(x.index_select(0, self.readout_idx))
234
+ hidden = torch.stack(outs, dim=0).permute(2, 0, 1) # [B, T, readout_size]
235
+
236
+ cache = None
237
+ if use_cache:
238
+ ids = prev_ids if input_ids is None else torch.cat([input_ids.flip(1), prev_ids], dim=1)[:, :k]
239
+ cache = FlyCache(x.t().contiguous(), ids, seq_len + T)
240
+ if not return_dict:
241
+ return tuple(v for v in [hidden, cache, (hidden,) if output_hidden_states else None] if v is not None)
242
+ return FlyOutput(last_hidden_state=hidden, cache_params=cache,
243
+ hidden_states=(hidden,) if output_hidden_states else None)
244
+
245
+
246
+ def _build_head(config: FlyConfig):
247
+ if config.head_type == "lowrank":
248
+ return nn.Sequential(
249
+ nn.Linear(config.readout_size, config.readout_rank, bias=False),
250
+ nn.LayerNorm(config.readout_rank),
251
+ nn.Linear(config.readout_rank, config.vocab_size),
252
+ )
253
+ return nn.Sequential(nn.LayerNorm(config.readout_size), nn.Linear(config.readout_size, config.vocab_size))
254
+
255
+
256
+ class FlyForCausalLM(FlyPreTrainedModel, GenerationMixin):
257
+ """Decoder-only: tokens in, tokens out. `news_embeds` is accepted but is None for this arch."""
258
+
259
+ def __init__(self, config: FlyConfig):
260
+ super().__init__(config)
261
+ self.brain = FlyModel(config)
262
+ self.head = _build_head(config)
263
+ self.post_init()
264
+
265
+ def get_input_embeddings(self):
266
+ return self.brain.emb
267
+
268
+ def set_input_embeddings(self, value):
269
+ self.brain.emb = value
270
+
271
+ def get_output_embeddings(self):
272
+ return self.head[-1]
273
+
274
+ def prepare_inputs_for_generation(self, input_ids, cache_params=None, use_cache=None,
275
+ attention_mask=None, news_embeds=None, **kwargs):
276
+ if cache_params is not None: # feed only what the state has not seen
277
+ input_ids = input_ids[:, cache_params.seq_len:]
278
+ attention_mask = None
279
+ model_inputs = {
280
+ "input_ids": input_ids,
281
+ "attention_mask": attention_mask,
282
+ "cache_params": cache_params,
283
+ "use_cache": use_cache if use_cache is not None else self.config.use_cache,
284
+ }
285
+ if news_embeds is not None:
286
+ model_inputs["news_embeds"] = news_embeds
287
+ return model_inputs
288
+
289
+ def forward(
290
+ self,
291
+ input_ids=None,
292
+ attention_mask=None,
293
+ inputs_embeds=None,
294
+ news_embeds=None,
295
+ cache_params: Optional[FlyCache] = None,
296
+ labels=None,
297
+ use_cache=None,
298
+ output_hidden_states=None,
299
+ return_dict=None,
300
+ logits_to_keep=0,
301
+ **kwargs,
302
+ ):
303
+ return_dict = return_dict if return_dict is not None else getattr(self.config, "return_dict", True)
304
+ out = self.brain(
305
+ input_ids=input_ids,
306
+ attention_mask=attention_mask,
307
+ inputs_embeds=inputs_embeds,
308
+ news_embeds=news_embeds,
309
+ cache_params=cache_params,
310
+ use_cache=use_cache,
311
+ output_hidden_states=output_hidden_states,
312
+ return_dict=True,
313
+ )
314
+ h = out.last_hidden_state
315
+ sl = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) and logits_to_keep > 0 else slice(None)
316
+ logits = self.head(h[:, sl])
317
+ loss = None
318
+ if labels is not None:
319
+ loss = F.cross_entropy(logits[:, :-1].reshape(-1, logits.size(-1)).float(),
320
+ labels[:, 1:].reshape(-1).to(logits.device), ignore_index=-100)
321
+ if not return_dict:
322
+ return tuple(v for v in [loss, logits, out.cache_params, out.hidden_states] if v is not None)
323
+ return FlyCausalLMOutput(loss=loss, logits=logits, cache_params=out.cache_params,
324
+ hidden_states=out.hidden_states)
special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "pad_token": "<pad>",
3
+ "bos_token": "<s>",
4
+ "eos_token": "</s>"
5
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "PreTrainedTokenizerFast",
3
+ "model_max_length": 512,
4
+ "pad_token": "<pad>",
5
+ "bos_token": "<s>",
6
+ "eos_token": "</s>",
7
+ "clean_up_tokenization_spaces": false
8
+ }