Spiking feed-forward layers in a small TinyStories language model, with dense controls
This repository holds four 5.8M-parameter Transformer language models trained from scratch on TinyStories. They are identical except for the activation inside the feed-forward layers: one model uses spiking neurons there, and the other three are dense controls. The question is whether spiking that layer gives anything that ordinary sparsity or quantisation does not.
In this comparison it does not. After 200M training tokens, the spiking model's validation loss is 4.0% worse than an ordinary GELU model's. A plain ReLU with an L1 penalty is just as sparse and only 0.65% worse than GELU, so it beats the spiking model by 3.3%, and it trains 3.3 times faster. The spiking model does beat a rounded, quantised ReLU by 1.55%. The spiking layer here carries no state from one token to the next, so it acts as a 5-level quantised activation, and it performs like one.
These numbers are preliminary. Each model was trained once, with one random seed, so there are no error bars, and no energy use was measured.
Results
Validation loss is cross-entropy in nats per token over the whole TinyStories validation split (4.88M tokens). All four models saw the same 200M training tokens in the same order.
| Model | Checkpoint | Feed-forward activation | Parameters | Validation loss | Gap to GELU | Silence | Dead units | Training speed |
|---|---|---|---|---|---|---|---|---|
| Dense GELU | D-200M |
GELU | 5,839,360 | 1.6570 | — | 0.0% | 0.0% | 1.00× |
| Sparse ReLU | D-relu-l1-200M |
ReLU with an L1 penalty (λ = 0.01) | 5,839,360 | 1.6678 | +0.65% | 92.4% | 4.0% | 1.01× |
| Spiking | H-200M |
spike count of a leaky integrate-and-fire neuron over 4 steps | 5,845,504 | 1.7230 | +3.99% | 90.4% | 6.8% | 0.30× |
| Quantised ReLU | D-quant-200M |
ReLU clamped to [0, 4] and rounded | 5,839,360 | 1.7502 | +5.62% | 84.9% | 4.7% | 1.04× |
- Silence is the share of feed-forward hidden activations that are exactly zero, averaged over tokens and layers. GELU is never exactly zero, so its silence is zero by definition.
- Dead units are hidden units whose average activity is below 1%.
- Silence and dead units are measured on the first 131,072 validation tokens.
- Training speed is tokens per second relative to the GELU model on the same machine (53,558 tokens per second on an Apple-silicon GPU). The spiking model took 3.43 hours against about 1 hour for each dense model.
The comparison between the spiking model and its two closest controls:
- against the sparse ReLU, the spiking model's loss is 3.31% higher, at slightly lower silence;
- against the quantised ReLU, the spiking model's loss is 1.55% lower. Both produce one of five levels per unit, so the likely cause is how the two map inputs to levels or how gradients pass through them, not the spikes themselves.
More training did not close the gap to GELU. Checked on a 492k-token sample of the validation split during training, the spiking model was 4.2% to 4.8% behind from 20M tokens onward.
How to use
The models are small enough to run on a CPU. Install the dependencies:
pip install torch safetensors tokenizers huggingface_hub
The weights are safetensors files, and the model class is in code/snnlib.py in this repository. The
snippet below downloads both, loads the weights, and continues a prompt.
import json
import sys
import torch
from huggingface_hub import snapshot_download
from safetensors import safe_open
from safetensors.torch import load_file
from tokenizers import Tokenizer
repo = snapshot_download(
"jordanrburger/snn-e1-spiking-ffn",
allow_patterns=["config.json", "code/snnlib.py", "tokenizer/*", "checkpoints/*-200M.safetensors"],
)
sys.path.insert(0, f"{repo}/code")
from snnlib import LM # the model definition ships with the weights
def load(name): # "H", "D", "D-quant" or "D-relu-l1"
path = f"{repo}/checkpoints/{name}-200M.safetensors"
with safe_open(path, framework="pt") as f:
cfg = json.loads(f.metadata()["cfg"]) # the run's configuration, stored in the file header
model = LM(cfg["arm"], l1=cfg["l1"], thr=cfg["thr"], w1_gain=cfg["w1_gain"])
model.load_state_dict(load_file(path))
return model.eval()
model = load("H")
tok = Tokenizer.from_file(f"{repo}/tokenizer/tokenizer-4096.json")
ids = tok.encode("Once upon a time").ids
with torch.no_grad():
for _ in range(40): # greedy decoding; the context is 256 tokens
logits, _ = model(torch.tensor([ids[-256:]]))
ids.append(int(logits[0, -1].argmax()))
print(tok.decode(ids))
The spiking model prints:
Once upon a time, there was a little girl named Lily. She loved to play outside in the sunshine. One day, she saw a big, scary dog. She was scared and didn't know what to do.
In the code and file names, H is the spiking model, D the GELU model, D-relu-l1 the sparse ReLU
and D-quant the quantised ReLU.
Checking the validation loss
This continues from the snippet above and also needs pip install numpy pyarrow. It tokenises the
TinyStories validation split the way the training data was tokenised, then scores the first 262,144
tokens.
import numpy as np
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
val_file = hf_hub_download("roneneldan/TinyStories", "data/validation-00000-of-00001-869c898b519ad725.parquet",
repo_type="dataset")
stories = pq.read_table(val_file)["text"].to_pylist()
eot = tok.token_to_id("<|endoftext|>")
stream = np.concatenate([np.asarray(e.ids + [eot]) for e in tok.encode_batch(stories)]) # 4,884,029 tokens
n_batches, B, L = 16, 64, 256 # the first 262,144 tokens; drop the limit for the whole split
for name in ["D", "D-relu-l1", "H", "D-quant"]:
model, total = load(name), 0.0
with torch.no_grad():
for j in range(n_batches):
w = np.stack([stream[s:s + L + 1] for s in range(j * B * L, (j + 1) * B * L, L)])
x = torch.from_numpy(w)
model(x[:, :-1], x[:, 1:])
total += model.last_ce.item() # cross-entropy only, without the L1 penalty
print(f"{name:10s} {total / n_batches:.4f} nats/token")
On this slice it prints 1.6854, 1.6952, 1.7477 and 1.7747. The slice is a little harder than the split
as a whole, so these are higher than the table, in the same order. Setting n_batches = 298 covers
the whole split and reproduces the table; on a CPU that takes several minutes per model, and longer
for the spiking one.
Training setup
Model. A decoder-only Transformer with pre-LayerNorm: width 256, 6 layers, 4 heads, feed-forward width 1024, context 256 tokens, learned positions, no biases, and an output layer tied to the embedding. The tokenizer is a 4,096-entry byte-level BPE trained on TinyStories; it is included.
The spiking layer. Each feed-forward hidden unit is a leaky integrate-and-fire neuron. For every token it receives the same input current for 4 steps, and its output is the number of spikes, from 0 to 4.
- The membrane leaks by a learnable per-unit factor (initialised at 0.9).
- The neuron fires when the membrane exceeds a threshold of 0.5, and the threshold is then subtracted (a soft reset).
- The backward pass uses an arctangent surrogate gradient.
- The membrane starts from zero at every token, so nothing is carried along the sequence.
- The neuron's leak parameters account for the extra 6,144 parameters.
Optimisation. AdamW with a peak learning rate of 1e-3, a 250-step warm-up and cosine decay to zero, weight decay 0.1 on the weight matrices, gradient clipping at 1.0, and batches of 64 × 256 tokens. The learning rate was the same for every model and was not tuned per model.
Data. The first two training shards of TinyStories (about 244M tokens), cut into non-overlapping 256-token windows. No window repeats within a run, and seed 0 fixes the order for every model.
Two settings were chosen from short 10M-token runs before the full runs. Those short runs are
included under checkpoints/pilots/.
- The spiking threshold. Four settings were tried: a threshold of 1 with the first feed-forward layer's initial weights scaled by 1, 2 or 4, and a threshold of 0.5. The 0.5 threshold had the lowest validation loss and was used.
- The L1 weight for the sparse ReLU. It was set so that this control would be about as sparse as the spiking model. The first value tried, 0.01, gave 87.5% silence against the spiking model's 90.5% at 10M tokens, and was kept.
Limitations
- One seed. There is no estimate of run-to-run variation, so none of the gaps above has an error bar. The 1.55% edge over the quantised ReLU in particular could be noise.
- No learning-rate tuning. All four models used the same learning rate. A rate tuned per model might change the gaps.
- No measured energy saving. The run logs include an estimate of about 0.35M synaptic operations per token for the spiking model against 5.77M multiply-accumulates for a dense one. That is an operation count, not a measurement, and it leaves out memory traffic. On the GPU used here the spiking model was 3.3 times slower.
- Small scale. About 5.8M parameters, 200M tokens and a corpus of simple synthetic stories. The result may not hold for larger models or other data.
- Stateless spiking only. Each neuron is reset at every token. These models say nothing about spiking neurons whose state persists across tokens, which is where spiking could differ in kind from a quantised activation.
What is in this repository
config.json: the shared architecture and the list of the four models.checkpoints/: the four final models in the table, as<name>.safetensors.checkpoints/pilots/: the five 10M-token runs described under "Training setup" (four threshold settings and one L1 weight).- Each
.safetensorsfile sits next to the original PyTorch checkpoint it was converted from (<name>.final.pt, a pickled dictionary). The tensors are identical; prefer the safetensors files. tokenizer/tokenizer-4096.json: the tokenizer.code/: the model definition (snnlib.py) and the training scripts.results/stage1/: one JSON log per run, with mid-training evaluations, per-layer statistics and sample continuations, andsummary.json.results/e1_data.json: SHA-256 hashes and token counts of the training data and the tokenizer.
The training scripts are included as a record of what was run, on an Apple-silicon GPU.
- They read and write under the folder named by the
E1_WORKDIRenvironment variable (default./e1_work). - The order is
prep_tinystories.py(tokenizer and validation tokens),prep_e1_data.py(training tokens), thenrun_e1.sh. - The published scripts differ from the ones that produced the results only in paths and comments,
and in
run_e1.sh, where a machine-specific job lock became optional. The code hashes stored in the result files and checkpoints refer to the originals.
snnlib.py also defines a few other variants, such as spiking inputs to attention and
neurons that keep state across tokens. None of those was trained, and no weights for them are
included.
Related work
The reading of a short rate code as a quantised activation follows Yan et al. (2024) and Shen et al. (2023). STEP (2025) gives an energy model for spiking Transformers that counts memory access as well as arithmetic.
License and citation
The code and weights are released under Apache-2.0. TinyStories is distributed under CDLA-Sharing-1.0.
@misc{snn_e1_spiking_ffn_2026,
author = {jordanrburger},
title = {Spiking feed-forward layers in a small TinyStories language model, with dense controls},
year = {2026},
url = {https://huggingface.co/jordanrburger/snn-e1-spiking-ffn}
}
Questions and corrections are welcome in this repository's Community tab.
- Downloads last month
- -