Skip to content

Automation foundation model for tiny devices: 2-bit, 8-29 MB, tool calls, ASR, structured extraction and embeddings on phones, wearables, smart homes, robots, cars and microcontrollers.

matryoshka in mixer, fixed and removed all references to MRL

Noah Cylich4965912099ad
diff --git a/README.md b/README.md
index 85dfa9d..ba4c9a7 100644
--- a/README.md
+++ b/README.md
@@ -12,14 +12,14 @@
┌──────────────┐ ┌──────────────┐
│ Transcription│ │ Story │ ┌──────────────────────┐
- └──────┬───────┘ └──────┬───────┘ │ MRL loss at dims │
+ └──────┬───────┘ └──────┬───────┘ │ Mat loss at factors │
└───────┬─────────┘ │ + INT4 QAT (g=32) │
┌───┴───────┐ │ + z-loss + slot div │
│ Softmax │ │ mixed text/speech │
└─────┬─────┘ │ batches │
┌─────┬─────┴─────┬─────┐ └──────────┬───────────┘
- │ @E[:d'] for each d' │ │
- │ in mrl_dims │ ┌──────────┴───────────┐
+ │ @E[:d_ff/f] for each │ │
+ │ f in mat_factors │ ┌──────────┴───────────┐
└─────┬─────┬─────┬─────┘ │ Grad clip (norm 1.0) │
┌─────┴─────┐ │ Muon (2D kernels) │
│ Linear (T)│ ← tied │ AdamW (all else) │
@@ -39,7 +39,7 @@
│ x N_enc │ ││ Gated FFN ││ ┌──────────┴───────────┐
│ │ │└───────────────┘│ │ Checkpoint │
│ ┌──────────┐ │ └────────┬────────┘ │ full params, can │
- │ │Pack: │ │ ┌─────┴─────┐ │ export MRL slices │
+ │ │Pack: │ │ ┌─────┴─────┐ │ export mat slices │
│ │ S←X Attn │ │ │ Embedding │ ← shared └──────────────────────┘
│ │ RoPE keys│ │ └─────┬─────┘
│ ├──────────┤ │ ┌───────┴───────┐
@@ -69,7 +69,7 @@
d=512 (default) / 1536 (--full) · GQA · QK-norm
SentencePiece BPE (8192) · gated dReLU · ZCRMSNorm · RoPE
- strided DW conv · MRL dims · INT4 QAT · Muon + AdamW
+ strided DW conv · mat factors · INT4 QAT · Muon + AdamW
text + speech encoder · <transcribe> / <story> task routing
Data Preprocessing
@@ -141,7 +141,7 @@ needle [command]
│ --max-enc-len INT Max encoder seq length (default: 256) │
│ --max-dec-len INT Max decoder seq length (default: 256) │
│ --max-samples INT Training samples (default: all) │
- │ --mrl-dims INT [...] MRL dim targets (default: 256 128 64) │
+ │ --mat-factors INT [...] FFN shrink factors (default: 2 4 8) │
│ --sparsity-ratio FLOAT Block prune ratio (default: 0.5) │
│ --group-size INT Quant/prune group size (default: 32) │
│ --prune-interval INT Steps between mask updates (def: 100) │
diff --git a/docs/matryoshka_results.md b/docs/matryoshka_results.md
index e15fedb..b88a3ba 100644
--- a/docs/matryoshka_results.md
+++ b/docs/matryoshka_results.md
@@ -1,19 +1,21 @@
# FFN Interior Matryoshka — Results
+> **Note**: These results predate the mixer refactor. At the time, matryoshka FFN masking was only applied to attention FFNs and the local FFN in encoder blocks — the MLP-Mixer token/channel mixing layers were **not** masked. Current code applies masking to all FFN layers including mixer.
+
## Approach
-Heterogeneous batch MRL: a per-batch-item prefix mask zeros out FFN neurons beyond the target width. Single forward-backward pass, single optimizer step. All MRL widths trained simultaneously.
+Heterogeneous batch matryoshka: a per-batch-item prefix mask zeros out FFN neurons beyond the target width. Single forward-backward pass, single optimizer step. All widths trained simultaneously.
- **Full width**: d_ff = 2048 (all neurons active)
-- **MRL 256**: d_ff = 1024 (first 1024 neurons)
-- **MRL 128**: d_ff = 512 (first 512 neurons)
-- **MRL 64**: d_ff = 256 (first 256 neurons)
+- **2x**: d_ff = 1024 (first 1024 neurons)
+- **4x**: d_ff = 512 (first 512 neurons)
+- **8x**: d_ff = 256 (first 256 neurons)
d_model, attention heads, embeddings, and mixer are unchanged across all widths.
Two modes:
- **Unique input** (default): each batch item is a unique sample, assigned a fixed width based on its position in the batch. Full data diversity per epoch.
-- **Shared input** (`--mrl-shared-input`): each unique sample is repeated across all widths. Smaller unique batch but every sample trains every width. Epoch = 4x more steps to see all data.
+- **Shared input** (`--mat-shared-input`): each unique sample is repeated across all widths. Smaller unique batch but every sample trains every width. Epoch = 4x more steps to see all data.
## Training Config
@@ -41,16 +43,16 @@ All runs use the same architecture and hyperparameters:
| Model | Main (output-only slice) | FFN unique input | FFN shared input |
|---|---|---|---|
| Full (d_ff=2048) | **4.52** | 4.66 | 5.11 |
-| MRL 256 (d_ff=1024) | - | **4.66** | 5.11 |
-| MRL 128 (d_ff=512) | - | **4.68** | 5.11 |
-| MRL 64 (d_ff=256) | - | **4.80** | 5.20 |
+| 2x (d_ff=1024) | - | **4.66** | 5.11 |
+| 4x (d_ff=512) | - | **4.68** | 5.11 |
+| 8x (d_ff=256) | - | **4.80** | 5.20 |
| Quant (INT4 g32) | **4.59** | 4.75 | 5.20 |
-> Main branch MRL PPLs omitted — output-only slice MRL does not constrain internal computation, so sub-model PPLs are misleading.
+> Main branch PPLs omitted — output-only slice does not constrain internal computation, so sub-model PPLs are misleading.
| Metric | Main | FFN unique | FFN shared |
|---|---|---|---|
-| MRL method | Output-only slice | FFN interior mask | FFN interior mask |
+| Mat method | Output-only slice | FFN interior mask | FFN interior mask |
| Total steps | 11,038 | 11,038 | 44,156 |
| Unique items/batch | 32/dev | 32/dev | 8/dev x 4 |
| Speed | ~19.3 it/s | 11.8 it/s | 20.9 it/s |
@@ -72,7 +74,7 @@ All runs use the same architecture and hyperparameters:
**Shared input over-prunes** (68% vs 50% target) because the pruning schedule fractions apply to 4x more total steps, creating a wider absolute pruning window.
-**FFN interior MRL sub-models are tight.** With unique input, the d_ff=256 sub-model (1/8 of FFN, 68.7M params) is only +0.14 PPL worse than full. This is a genuine sub-network — unlike main's output-only approach which shares all internal computation.
+**FFN interior matryoshka sub-models are tight.** With unique input, the d_ff=256 sub-model (8x, 68.7M params) is only +0.14 PPL worse than full. This is a genuine sub-network — unlike main's output-only approach which shares all internal computation.
**Main is faster** (~19 it/s) because it runs one full forward + cheap logit slicing. FFN unique input (11.8 it/s) does one forward with heterogeneous masking but can't exploit XLA batch optimizations as well. FFN shared input (20.9 it/s) is fastest per-step due to repeated inputs.
@@ -100,14 +102,14 @@ Use **unique input** (default, no flag) for best quality. The +0.14 PPL cost ove
**Question**: Does training every sample at all widths help, if we control for gradient quality?
-With `--mrl-shared-input --batch-size 128`, each step has 32 unique samples repeated 4x (one per width) — same unique samples per step as the default unique-input run at batch=32. The only difference is that every sample trains every width, at the cost of 4x compute per step.
+With `--mat-shared-input --batch-size 128`, each step has 32 unique samples repeated 4x (one per width) — same unique samples per step as the default unique-input run at batch=32. The only difference is that every sample trains every width, at the cost of 4x compute per step.
| Model | FFN unique (bs=32) | FFN shared (bs=128) |
|---|---|---|
| Full (d_ff=2048) | **4.66** | 4.67 |
-| MRL 256 (d_ff=1024) | **4.66** | 4.67 |
-| MRL 128 (d_ff=512) | **4.68** | 4.69 |
-| MRL 64 (d_ff=256) | **4.80** | 4.81 |
+| 2x (d_ff=1024) | **4.66** | 4.67 |
+| 4x (d_ff=512) | **4.68** | 4.69 |
+| 8x (d_ff=256) | **4.80** | 4.81 |
| Quant (INT4 g32) | **4.75** | 4.77 |
| Speed | 11.8 it/s | 5.6 it/s |
| Wall time | ~16 min | ~35 min |
@@ -121,4 +123,4 @@ This confirms **unique input at batch=32 is optimal**: same quality, 2x faster.
- All runs are 1-epoch on TinyStories + LibriSpeech. Multi-epoch runs would improve all metrics.
- Speech WER is poor across all methods — expected with interleaved training and limited speech data.
-- The heterogeneous batch approach uses the same memory as a single full-width forward (~1x). No overhead from MRL.
+- The heterogeneous batch approach uses the same memory as a single full-width forward (~1x). No overhead from matryoshka.
diff --git a/experiements/architecture.txt b/experiements/architecture.txt
index 50965f5..0879586 100644
--- a/experiements/architecture.txt
+++ b/experiements/architecture.txt
@@ -3,11 +3,11 @@ Assignee: Noah Cylich & Justin Lee
Deadline: 7th March
================================================================================
-Thesis: Three complementary compression axes; Matryoshka dimension pruning,
+Thesis: Three complementary compression axes; Matryoshka FFN subnetworks,
group-aligned block sparsity, and INT4 quantization-aware training. can be
jointly applied during training to produce a single checkpoint that is
deployable at multiple accuracy-efficiency operating points. Training once at
-d_model=D with MRL loss at dimensions {D, D/2, D/4, D/8, ...} yields a family
+d_model=D with matryoshka loss at factors {1x, 2x, 4x, 8x, ...} yields a family
of models from one training run, each further compressible via sparsification.
================================================================================
@@ -15,14 +15,14 @@ SECTION 1 — EXPERIMENTAL AXES
================================================================================
Independent variables:
- A. MRL deployment dim d' ∈ {1024, 512, 256, 128, 64}
+ A. matryoshka shrink factor f ∈ {1, 2, 4, 8, 16}
B. Sparsity ratio s ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}
C. Group size g ∈ {16, 32, 64, 128}
D. FFN activation ∈ {dReLU, SwiGLU, GeGLU}
E. Model scale ∈ {TOY-128, MAIN-1024}
F. QAT ∈ {off, int4-group32}
-Dependent variables (measured at EACH MRL dimension):
+Dependent variables (measured at EACH matryoshka factor):
- Validation perplexity (TinyStories)
- Quantized validation perplexity (INT4)
- WikiText-2 perplexity
@@ -43,20 +43,20 @@ Architecture: MemoryMixer encoder + Transformer decoder, shared embedding,
GQA (grouped query attention), ZC-RMSNorm, RoPE, SentencePiece BPE (8192).
TOY-128 (rapid iteration):
- mrl_dims=[128, 64], d_model=128, num_heads=4, num_kv_heads=2,
+ mat_factors=[2, 4], d_model=128, num_heads=4, num_kv_heads=2,
num_enc_layers=2, num_dec_layers=2, d_ff=512,
max_enc_len=128, max_dec_len=128, vocab=8192, dtype=bfloat16
needle train --toy --seed {42,137,256}
MAIN-1024 (paper results):
- mrl_dims=[1024, 512, 256, 128, 64], d_model=1024, num_heads=4,
+ mat_factors=[1, 2, 4, 8, 16], d_model=1024, num_heads=4,
num_kv_heads=2, num_enc_layers=4, num_dec_layers=2, d_ff=4096,
max_enc_len=256, max_dec_len=256, vocab=8192, dtype=bfloat16
needle train --seed {42,137,256}
Both trained on TinyStories (1M samples, encoder-decoder split at 30%).
Optimizer: Muon (kernels) + AdamW (embeddings/norms), WSD schedule.
-All experiments report metrics at each MRL dimension slice.
+All experiments report metrics at each matryoshka factor slice.
================================================================================
SECTION 3 — EXPERIMENT GROUPS
@@ -64,32 +64,32 @@ SECTION 3 — EXPERIMENT GROUPS
All experiments use 3 seeds (42, 137, 256) for statistical significance.
Report mean +/- std on all metrics. Every run automatically reports val PPL
-and INT4-quantized val PPL at each MRL dimension slice.
+and INT4-quantized val PPL at each matryoshka factor slice.
-------------------------------------------------------------------------------
-GROUP 1: Dense Baselines + MRL Dimension Scaling (Table 1, Figure 1)
+GROUP 1: Dense Baselines + Matryoshka Factor Scaling (Table 1, Figure 1)
-------------------------------------------------------------------------------
Purpose: Establish quality at each deployment dimension from a single training
-run. This is the MRL baseline — no sparsification.
+run. This is the matryoshka baseline — no sparsification.
- 1a. MAIN-1024, 3 epochs, no pruning, MRL dims [1024,512,256,128,64]
+ 1a. MAIN-1024, 3 epochs, no pruning, matryoshka factors [1024,512,256,128,64]
needle train --sparsity-ratio 0.0 --seed {42,137,256}
- 1b. TOY-128, 3 epochs, no pruning, MRL dims [128,64]
+ 1b. TOY-128, 3 epochs, no pruning, matryoshka factors [128,64]
needle train --toy --sparsity-ratio 0.0 --seed {42,137,256}
Deliverables:
- - Table: val PPL and quant PPL at each MRL dim (1024, 512, 256, 128, 64)
- - Line plot: deployment dim vs val PPL — the MRL scaling curve (Figure 1a)
+ - Table: val PPL and quant PPL at each matryoshka factor (1024, 512, 256, 128, 64)
+ - Line plot: deployment dim vs val PPL — the matryoshka scaling curve (Figure 1a)
- Line plot: deployment dim vs estimated param count (Figure 1b)
- Benchmark scores at each dim
- These are the denominators for all relative comparisons
-------------------------------------------------------------------------------
-GROUP 2: MRL + Group-Wise Sparsification (Table 2, Figure 2)
+GROUP 2: matryoshka + Group-Wise Sparsification (Table 2, Figure 2)
*** CORE CONTRIBUTION ***
-------------------------------------------------------------------------------
-Purpose: Characterise how MRL dimension scaling interacts with block sparsity.
+Purpose: Characterise how matryoshka factor scaling interacts with block sparsity.
At smaller deployment dims, does sparsification hurt more or less?
Schedule: Epoch 1 dense, epochs 2-3 with sparsity mask locked.
@@ -102,15 +102,15 @@ Schedule: Epoch 1 dense, epochs 2-3 with sparsity mask locked.
needle train --epochs 4 --sparsity-ratio {s} --seed {42,137,256}
Deliverables:
- - 2D heatmap: (sparsity, MRL dim) → val PPL (Figure 2a)
- - Pareto curve per MRL dim: sparsity % vs val PPL (Figure 2b)
+ - 2D heatmap: (sparsity, matryoshka factor) → val PPL (Figure 2a)
+ - Pareto curve per matryoshka factor: sparsity % vs val PPL (Figure 2b)
- Table: all metrics at each (sparsity, dim) pair
- Compression spectrum: for best s, show the range of models:
- d'=1024 (full) → d'=64 (smallest) with estimated params and PPL
- - Analysis: does sparsification degrade smaller MRL slices more?
+ 1x (full) → 16x (smallest) with estimated params and PPL
+ - Analysis: does sparsification degrade smaller matryoshka slices more?
(Hypothesis: smaller slices are more sensitive because fewer dimensions
carry the representation — each zeroed weight matters more)
- - Analysis: multiplicative compression — MRL dimension reduction ×
+ - Analysis: multiplicative compression — matryoshka factor reduction ×
sparsity = total compression ratio
-------------------------------------------------------------------------------
@@ -125,15 +125,15 @@ Pick the best sparsity ratio from Group 2a. Vary total epochs:
(sparsification at epoch 1; recovery = E - 1 epochs)
Deliverables:
- - Line plot per MRL dim: recovery epochs vs val PPL (Figure 3)
- - Analysis: do smaller MRL dims need more recovery?
+ - Line plot per matryoshka factor: recovery epochs vs val PPL (Figure 3)
+ - Analysis: do smaller matryoshka factors need more recovery?
-------------------------------------------------------------------------------
GROUP 4: QAT Interaction Study (Table 4, Figure 4)
-------------------------------------------------------------------------------
Purpose: Show that group-wise sparsification is compatible with INT4 QAT
because both operate on the same group_size=32 granularity. Measure at
-each MRL dimension — INT4 quantization error at smaller dims may compound.
+each matryoshka factor — INT4 quantization error at smaller dims may compound.
4a. Dense + QAT (baseline, = Group 1a)
4b. Sparsified (s=0.3) + QAT
@@ -143,11 +143,11 @@ each MRL dimension — INT4 quantization error at smaller dims may compound.
to not call _quantize_params.
Deliverables:
- - Table: (QAT on/off) × sparsity × MRL dim → val PPL
- - Analysis: does QAT degrade more at smaller MRL dims?
+ - Table: (QAT on/off) × sparsity × matryoshka factor → val PPL
+ - Analysis: does QAT degrade more at smaller matryoshka factors?
(Hypothesis: yes — fewer dimensions means each quantization error
has proportionally larger impact on output quality)
- - Effective compression: MRL dim reduction × sparsity × INT4 → total
+ - Effective compression: matryoshka factor reduction × sparsity × INT4 → total
bits per effective parameter
-------------------------------------------------------------------------------
@@ -167,17 +167,17 @@ Fixed: MAIN-1024, s=0.3, 3 epochs, QAT on.
--seed {42,137,256}
Deliverables:
- - Line plot per MRL dim: group size vs val PPL (Figure 5a)
- - Table: all metrics at each (group size, MRL dim)
+ - Line plot per matryoshka factor: group size vs val PPL (Figure 5a)
+ - Table: all metrics at each (group size, matryoshka factor)
- Effective bits-per-param: bpp = (1 - sparsity) * (4 + 32/g)
- - Analysis: does optimal group size change with MRL deployment dim?
+ - Analysis: does optimal group size change with matryoshka deployment dim?
-------------------------------------------------------------------------------
GROUP 6: Activation Function x Sparsification Interaction (Table 6, Figure 6)
*** KEY FINDING ***
-------------------------------------------------------------------------------
Purpose: Test whether activation function choice determines sparsification
-robustness across MRL dimension slices.
+robustness across matryoshka factor slices.
Activation definitions:
- dReLU: ReLU(gate) * ReLU(up) — naturally ~75% sparse activations
@@ -195,29 +195,29 @@ Activation definitions:
--seed {42,137,256}
Deliverables:
- - Grouped bar chart per MRL dim: activation × compression → val PPL (Fig 6a)
+ - Grouped bar chart per matryoshka factor: activation × compression → val PPL (Fig 6a)
- Relative degradation: (sparse_ppl / dense_ppl) per activation per dim
(Figure 6b) — KEY CHART: sparsification robustness not just raw quality
- Analysis: does dReLU's natural activation sparsity help or hurt at
- smaller MRL dims where redundancy is already low?
+ smaller matryoshka factors where redundancy is already low?
-------------------------------------------------------------------------------
-GROUP 7: MRL Dimension-Specific Analysis (Table 7, Figure 7)
- *** MRL-SPECIFIC CONTRIBUTION ***
+GROUP 7: Matryoshka Factor-Specific Analysis (Table 7, Figure 7)
+ *** matryoshka-SPECIFIC CONTRIBUTION ***
-------------------------------------------------------------------------------
-Purpose: Deep-dive into what the model learns at each MRL dimension slice.
+Purpose: Deep-dive into what the model learns at each matryoshka factor slice.
Using best checkpoint from Group 2a:
7a. Representation similarity across dims
- - CKA (centered kernel alignment) between d'=1024 and each smaller d'
+ - CKA (centered kernel alignment) between 1x and each larger factor
- Measure: do smaller dims learn a subspace of the full representation?
7b. Per-dim generation quality
- - Generate from each MRL dim slice at inference time
+ - Generate from each matryoshka factor slice at inference time
- Compare generation diversity, coherence, repetition rate
- 7c. MRL loss weighting ablation
+ 7c. matryoshka loss weighting ablation
- Uniform weighting (current): L = (1/K) * sum(L_k)
- Scaled weighting: L = sum(d_k/D * L_k) (larger dims weighted more)
- Inverse weighting: L = sum(D/d_k * L_k) (smaller dims weighted more)
@@ -225,7 +225,7 @@ Using best checkpoint from Group 2a:
Deliverables:
- CKA heatmap: dim × dim similarity (Figure 7a)
- Table: generation quality metrics at each dim
- - Ablation table: MRL loss weighting strategy × dim → val PPL
+ - Ablation table: matryoshka loss weighting strategy × dim → val PPL
-------------------------------------------------------------------------------
GROUP 8: Inference Efficiency Validation (Table 8, Figure 8)
@@ -233,7 +233,7 @@ GROUP 8: Inference Efficiency Validation (Table 8, Figure 8)
Purpose: Translate theoretical compression into real speedup across the
full spectrum of deployment options.
-For each Pareto-optimal checkpoint from Groups 1-2, at each MRL dim:
+For each Pareto-optimal checkpoint from Groups 1-2, at each matryoshka factor:
needle test --checkpoint {path} --throughput-runs 50
Measure at each deployment dim:
@@ -243,31 +243,31 @@ Measure at each deployment dim:
Deliverables:
- Scatter plot: effective params vs actual throughput (Figure 8a)
- - Table: all Pareto-optimal (s, d') with throughput + quality
+ - Table: all Pareto-optimal (s, factor) with throughput + quality
- The "menu" figure: one chart showing ALL deployment options from a
- single checkpoint, from largest (d'=1024, no pruning) to smallest
- (d'=64, s=0.80) — THIS IS THE PAPER'S HERO FIGURE
+ single checkpoint, from largest (1x, no pruning) to smallest
+ (16x, s=0.80) — THIS IS THE PAPER'S HERO FIGURE
================================================================================
SECTION 4 — EVALUATION PROTOCOL
================================================================================
-For every checkpoint, evaluate at EACH MRL dimension slice:
+For every checkpoint, evaluate at EACH matryoshka factor slice:
1. Validation perplexity (TinyStories val split)
- Full-precision val PPL
- - INT4-quantized val PPL (at each MRL dim)
+ - INT4-quantized val PPL (at each matryoshka factor)
needle test --checkpoint {path} --max-eval-samples 5000
2. Benchmark suite (at full dim and smallest viable dim)
needle evaluate --checkpoint {path} \
--benchmarks wikitext2 lambada hellaswag arc_easy --max-samples 500
- 3. Generation quality at each MRL dim
+ 3. Generation quality at each matryoshka factor
needle test --checkpoint {path}
Report: bigram repetition rate, avg generation length, sample outputs
- 4. Throughput at each MRL dim
+ 4. Throughput at each matryoshka factor
needle test --checkpoint {path} --throughput-runs 50
================================================================================
@@ -275,23 +275,23 @@ SECTION 5 — EXPECTED TABLES AND FIGURES
================================================================================
Tables:
- T1. Dense baselines + MRL scaling curve (val PPL at each dim)
- T2. MRL + sparsification (sparsity × dim → val PPL)
- T3. Recovery epoch scaling (epochs × MRL dims)
- T4. QAT interaction (sparsity × {on,off} × MRL dims)
- T5. Group size ablation (4 sizes × MRL dims)
- T6. Activation × sparsification interaction (3 act × compression × MRL dims)
- T7. MRL dimension analysis (CKA, generation quality, loss weighting)
- T8. Inference efficiency (Pareto-optimal checkpoints × MRL dims)
+ T1. Dense baselines + matryoshka scaling curve (val PPL at each dim)
+ T2. matryoshka + sparsification (sparsity × dim → val PPL)
+ T3. Recovery epoch scaling (epochs × matryoshka factors)
+ T4. QAT interaction (sparsity × {on,off} × matryoshka factors)
+ T5. Group size ablation (4 sizes × matryoshka factors)
+ T6. Activation × sparsification interaction (3 act × compression × matryoshka factors)
+ T7. matryoshka factor analysis (CKA, generation quality, loss weighting)
+ T8. Inference efficiency (Pareto-optimal checkpoints × matryoshka factors)
Figures:
- F1. MRL scaling curve: deployment dim vs PPL + param count
- F2. MRL + sparsity: (a) heatmap, (b) Pareto per dim — KEY FIGURE
- F3. Recovery epoch scaling per MRL dim
- F4. QAT interaction: sparsity × QAT × MRL dim
+ F1. matryoshka scaling curve: deployment dim vs PPL + param count
+ F2. matryoshka + sparsity: (a) heatmap, (b) Pareto per dim — KEY FIGURE
+ F3. Recovery epoch scaling per matryoshka factor
+ F4. QAT interaction: sparsity × QAT × matryoshka factor
F5. Group size: (a) g vs PPL per dim, (b) effective bpp
F6. Activation × sparsification: (a) grouped bars per dim, (b) degradation
- F7. MRL representation analysis: (a) CKA heatmap, (b) gen quality vs dim
+ F7. matryoshka representation analysis: (a) CKA heatmap, (b) gen quality vs dim
F8. Hero figure: full deployment menu from single checkpoint
================================================================================
@@ -299,7 +299,7 @@ SECTION 6 — COMPUTE BUDGET
================================================================================
Per-run cost (MAIN-1024, 3 epochs, 1M samples, 4x TPU v5 lite):
- ~15 minutes training + ~5 minutes MRL evaluation (5 dims × val + quant)
+ ~15 minutes training + ~5 minutes matryoshka evaluation (5 dims × val + quant)
Estimated total runs:
Group 1: 2 configs × 3 seeds = 6 runs
@@ -322,26 +322,26 @@ SECTION 7 — ABLATION CHECKLIST
Before submission, verify these are addressed:
[ ] Statistical significance: 3 seeds, report mean +/- std
- [ ] MRL scaling: smooth degradation curve from full dim to smallest
- [ ] MRL + sparsity composability: both axes combine gracefully
+ [ ] matryoshka scaling: smooth degradation curve from full dim to smallest
+ [ ] matryoshka + sparsity composability: both axes combine gracefully
[ ] Matched comparisons: compare methods at SAME effective param count
[ ] Recovery saturation: diminishing returns on fine-tuning epochs
- [ ] QAT compatibility: sparsity + quantization + MRL are not antagonistic
- [ ] Generation quality at each MRL dim, not just perplexity
- [ ] Group size sensitivity: optimal g, interaction with MRL dim
- [ ] Activation × sparsification × MRL dim: three-way interaction
- [ ] MRL representation analysis: CKA, subspace structure
+ [ ] QAT compatibility: sparsity + quantization + matryoshka are not antagonistic
+ [ ] Generation quality at each matryoshka factor, not just perplexity
+ [ ] Group size sensitivity: optimal g, interaction with matryoshka factor
+ [ ] Activation × sparsification × matryoshka factor: three-way interaction
+ [ ] matryoshka representation analysis: CKA, subspace structure
[ ] Honest limitations: sparse matmuls don't accelerate on current JAX;
- MRL dimension reduction requires custom kernel for real speedup
- [ ] Comparison to baselines: training K separate small models vs one MRL
+ matryoshka factor reduction requires custom kernel for real speedup
+ [ ] Comparison to baselines: training K separate small models vs one matryoshka
================================================================================
SECTION 8 — EXECUTION ORDER
================================================================================
Phase 1 (Day 1): Groups 1 + 2 (36 runs, ~12 hrs)
- Baselines and sparsification sweeps, all with MRL evaluation.
- Deliverable: MRL scaling curves and sparsity Pareto frontiers.
+ Baselines and sparsification sweeps, all with matryoshka evaluation.
+ Deliverable: matryoshka scaling curves and sparsity Pareto frontiers.
Phase 2 (Day 2): Groups 3 + 4 (33 runs, ~11 hrs)
Recovery and QAT ablations.
@@ -352,7 +352,7 @@ Phase 3 (Day 3): Groups 5 + 6 (51 runs, ~17 hrs)
Deliverable: granularity and activation robustness analysis.
Phase 4 (Day 4): Groups 7 + 8 + writing (9 runs + eval)
- MRL analysis, inference benchmarks, paper draft.
+ matryoshka analysis, inference benchmarks, paper draft.
Deliverable: hero figure, all tables populated.
================================================================================
@@ -362,27 +362,27 @@ SECTION 9 — PAPER NARRATIVE
Framing: "Train once, deploy anywhere."
A single training run with Matryoshka loss produces a checkpoint that can be
-deployed at any dimension slice. Each slice can be further compressed with
+deployed at any matryoshka factor. Each sub-model can be further compressed with
group-wise sparsification. The result is a deployment MENU:
┌─────────────────────────────────────────────────────────────────────┐
│ Deployment option Est. params Val PPL Quant PPL │
│ ───────────────────────────────────────────────────────────────── │
- │ d'=1024, full ~44M X.XX X.XX │
- │ d'=512, full ~11M X.XX X.XX │
- │ d'=512, s=0.3 ~7M X.XX X.XX │
- │ d'=512, s=0.6 ~4M X.XX X.XX │
- │ d'=256, full ~3M X.XX X.XX │
- │ d'=256, s=0.3 ~2M X.XX X.XX │
- │ d'=128, full ~0.8M X.XX X.XX │
- │ d'=128, s=0.5 ~0.4M X.XX X.XX │
- │ d'=64, full ~0.2M X.XX X.XX │
- │ d'=64, s=0.8 ~0.04M X.XX X.XX │
+ │ 1x, full ~44M X.XX X.XX │
+ │ 2x, full ~11M X.XX X.XX │
+ │ 2x, s=0.3 ~7M X.XX X.XX │
+ │ 2x, s=0.6 ~4M X.XX X.XX │
+ │ 4x, full ~3M X.XX X.XX │
+ │ 4x, s=0.3 ~2M X.XX X.XX │
+ │ 8x, full ~0.8M X.XX X.XX │
+ │ 8x, s=0.5 ~0.4M X.XX X.XX │
+ │ 16x, full ~0.2M X.XX X.XX │
+ │ 16x, s=0.8 ~0.04M X.XX X.XX │
└─────────────────────────────────────────────────────────────────────┘
Key claims:
- 1. MRL dimension pruning is nearly free — minimal degradation at 2x reduction
- 2. Sparsification composes multiplicatively with MRL
+ 1. Matryoshka FFN shrinking is nearly free — minimal degradation at 2x reduction
+ 2. Sparsification composes multiplicatively with matryoshka
3. A single checkpoint spans 100x+ parameter range
4. INT4 QAT is compatible with both compression axes
5. MemoryMixer encoder is more compressible than standard transformer encoder
diff --git a/src/cli.py b/src/cli.py
index 93bef0c..7419065 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -23,7 +23,7 @@ HELP = """
│ --max-enc-len INT Max encoder seq length (default: 256)│
│ --max-dec-len INT Max decoder seq length (default: 256)│
│ --max-samples INT Training samples (default: all) │
- │ --mrl-dims INT [...] MRL dim targets (default: 256 128 64)│
+ │ --mat-factors INT [...] FFN shrink factors (default: 2 4 8) │
│ --sparsity-ratio FLOAT Block prune ratio (default: 0.5) │
│ --group-size INT Quant/prune group size (default: 32) │
│ --prune-interval INT Steps between mask updates (def: 100)│
@@ -118,10 +118,10 @@ def main():
help="Fraction of epoch at which pruning finishes and mask locks (default: 0.67)")
p.add_argument("--activation", type=str, default="drelu", choices=["drelu", "swiglu", "geglu"])
p.add_argument("--num-memory-slots", type=int, default=64)
- p.add_argument("--mrl-dims", type=int, nargs="*", default=[256, 128, 64],
- help="MRL dimension targets (default: 256 128 64)")
- p.add_argument("--mrl-shared-input", action="store_true",
- help="Each unique input is repeated across all MRL widths (default: unique input per width)")
+ p.add_argument("--mat-factors", type=int, nargs="*", default=[2, 4, 8],
+ help="Matryoshka FFN shrink factors, e.g. 2=half width (default: 2 4 8)")
+ p.add_argument("--mat-shared-input", action="store_true",
+ help="Each unique input is repeated across all mat widths (default: unique input per width)")
p.add_argument("--no-speech", action="store_true", help="Disable speech training (text-only)")
p.add_argument("--speech-every", type=int, default=3,
help="Do one speech step every N text steps (default: 3)")
@@ -201,7 +201,7 @@ def main():
args.num_layers = 12
args.num_dec_layers = 4
args.num_memory_slots = 128
- args.mrl_dims = [1024, 768, 512, 256, 128]
+ args.mat_factors = [2, 3, 4, 8, 16]
from .train import train
train(args)
elif args.command == "run":
diff --git a/src/export.py b/src/export.py
index ba82d97..add15d7 100644
--- a/src/export.py
+++ b/src/export.py
@@ -1,7 +1,7 @@
-"""Export MRL sub-models by slicing FFN weights to a target dimension.
+"""Export matryoshka sub-models by slicing FFN weights by a shrink factor.
With FFN interior matryoshka, d_model stays constant — only FFN intermediate
-dimensions (gate_proj, up_proj, down_proj) are sliced proportionally.
+dimensions (gate_proj, up_proj, down_proj) are sliced.
"""
import os
@@ -19,11 +19,11 @@ from .model import TransformerConfig
_FFN_KERNEL_NAMES = {"gate_proj", "up_proj", "down_proj"}
-def export_submodel(checkpoint_path, d_prime, output_path):
- """Slice a full MRL checkpoint to a sub-model at MRL dimension d_prime.
+def export_submodel(checkpoint_path, factor, output_path):
+ """Slice a full matryoshka checkpoint to a sub-model at given shrink factor.
- Only FFN weights are reduced: d_ff' = d_ff * d_prime // d_model.
- Attention, embeddings, norms, and mixer weights are unchanged.
+ factor: how many times smaller the FFN width (e.g. 2 = half, 4 = quarter).
+ Attention, embeddings, and norms are unchanged.
"""
with open(checkpoint_path, "rb") as f:
@@ -31,9 +31,9 @@ def export_submodel(checkpoint_path, d_prime, output_path):
params = data["params"]
config = TransformerConfig(**data["config"])
- d_ff_prime = config.d_ff * d_prime // config.d_model
- if d_ff_prime == 0:
- raise ValueError(f"d_prime={d_prime} too small: would give d_ff=0")
+ d_ff_new = config.d_ff // factor
+ if d_ff_new == 0:
+ raise ValueError(f"factor={factor} too large: would give d_ff=0")
d_ff = config.d_ff
@@ -53,28 +53,23 @@ def export_submodel(checkpoint_path, d_prime, output_path):
if parent_name is None:
return arr
- # Also skip mixer FFN kernels (token_mix_*, channel_mix_*)
- path_str = "/".join(
- p.key if hasattr(p, "key") else str(p) for p in key_path
- )
- if "mixer" in path_str:
- return arr
+ # Both token_mix and channel_mix are sliced via ffn_mask
rows, cols = arr.shape
if parent_name in ("gate_proj", "up_proj"):
- # (d_model, d_ff) → (d_model, d_ff')
+ # (d_in, d_ff) → (d_in, d_ff_new)
if cols == d_ff:
- return arr[:, :d_ff_prime]
+ return arr[:, :d_ff_new]
elif parent_name == "down_proj":
- # (d_ff, d_model) → (d_ff', d_model)
+ # (d_ff, d_out) → (d_ff_new, d_out)
if rows == d_ff:
- return arr[:d_ff_prime, :]
+ return arr[:d_ff_new, :]
return arr
sliced = jax.tree_util.tree_map_with_path(slice_leaf, params)
- new_config = replace(config, d_ff=d_ff_prime)
+ new_config = replace(config, d_ff=d_ff_new)
sliced_np = jax.tree.map(
lambda x: np.asarray(x) if isinstance(x, jnp.ndarray) else x, sliced
@@ -93,7 +88,8 @@ def export_submodel(checkpoint_path, d_prime, output_path):
print(f" ─────────────────────────────────────")
print(f" {'':>20s} {'Original':>12s} {'Exported':>12s}")
print(f" {'d_model':>20s} {config.d_model:>12d} {config.d_model:>12d}")
- print(f" {'d_ff':>20s} {config.d_ff:>12d} {d_ff_prime:>12d}")
+ print(f" {'d_ff':>20s} {config.d_ff:>12d} {d_ff_new:>12d}")
+ print(f" {'factor':>20s} {'1x':>12s} {str(factor)+'x':>12s}")
print(f" {'num_heads':>20s} {config.num_heads:>12d} {config.num_heads:>12d}")
print(f" {'num_kv_heads':>20s} {config.num_kv_heads:>12d} {config.num_kv_heads:>12d}")
print(f" {'params':>20s} {orig_count:>12,d} {new_count:>12,d}")
@@ -103,12 +99,12 @@ def export_submodel(checkpoint_path, d_prime, output_path):
def main(args):
checkpoint = args.checkpoint
- d_prime = args.dim
+ factor = args.factor
output = args.output
if output is None:
stem = Path(checkpoint).stem
parent = Path(checkpoint).parent
- output = str(parent / f"{stem}_d{d_prime}.pkl")
+ output = str(parent / f"{stem}_{factor}x.pkl")
- export_submodel(checkpoint, d_prime, output)
+ export_submodel(checkpoint, factor, output)
diff --git a/src/model.py b/src/model.py
index d8c27e9..74bf602 100644
--- a/src/model.py
+++ b/src/model.py
@@ -148,37 +148,22 @@ class MLPMixer(nn.Module):
num_slots: int
d_model: int
d_ff: int
+ num_layers: int
dtype: jnp.dtype = jnp.bfloat16
activation: str = "drelu"
@nn.compact
- def __call__(self, s):
+ def __call__(self, s, ffn_mask=None):
residual = s
s = ZCRMSNorm(dtype=self.dtype, name="token_mix_norm")(s)
s = s.transpose(0, 2, 1)
- gate = nn.Dense(self.d_ff, dtype=self.dtype, use_bias=False, kernel_init=default_init(), name="token_mix_gate")(s)
- up = nn.Dense(self.d_ff, dtype=self.dtype, use_bias=False, kernel_init=default_init(), name="token_mix_up")(s)
- if self.activation == "swiglu":
- s = nn.silu(gate) * up
- elif self.activation == "geglu":
- s = nn.gelu(gate) * up
- else:
- s = nn.relu(gate) * nn.relu(up)
- s = nn.Dense(self.num_slots, dtype=self.dtype, use_bias=False, kernel_init=default_init(), name="token_mix_down")(s)
+ s = FeedForward(self.num_slots, self.d_ff, self.num_layers, self.dtype, self.activation, name="token_mix")(s, ffn_mask=ffn_mask)
s = s.transpose(0, 2, 1)
s = s + residual
residual = s
s = ZCRMSNorm(dtype=self.dtype, name="channel_mix_norm")(s)
- gate = nn.Dense(self.d_ff, dtype=self.dtype, use_bias=False, kernel_init=default_init(), name="channel_mix_gate")(s)
- up = nn.Dense(self.d_ff, dtype=self.dtype, use_bias=False, kernel_init=default_init(), name="channel_mix_up")(s)
- if self.activation == "swiglu":
- s = nn.silu(gate) * up
- elif self.activation == "geglu":
- s = nn.gelu(gate) * up
- else:
- s = nn.relu(gate) * nn.relu(up)
- s = nn.Dense(self.d_model, dtype=self.dtype, use_bias=False, kernel_init=default_init(), name="channel_mix_down")(s)
+ s = FeedForward(self.d_model, self.d_ff, self.num_layers, self.dtype, self.activation, name="channel_mix")(s, ffn_mask=ffn_mask)
s = s + residual
return s
@@ -204,8 +189,8 @@ class MemoryMixerBlock(nn.Module):
rope_keys_only=True, name="pack_attn"
)(s_norm, x_norm, mask=mask, rope=rope)
- s = s + MLPMixer(self.num_slots, self.d_model, self.d_ff, self.dtype, self.activation, name="mixer")(
- ZCRMSNorm(dtype=self.dtype, name="mix_norm")(s)
+ s = s + MLPMixer(self.num_slots, self.d_model, self.d_ff, self.num_layers, self.dtype, self.activation, name="mixer")(
+ ZCRMSNorm(dtype=self.dtype, name="mix_norm")(s), ffn_mask=ffn_mask
)
residual = x
@@ -391,11 +376,17 @@ class EncoderDecoderTransformer(nn.Module):
slot_div = self._slot_diversity(encoder_out)
return logits, slot_div
- def forward_with_aux(self, src, tgt, src_mask=None, tgt_mask=None, cross_mask=None, mrl_dims=None):
- """Eval-only: separate per-width forwards for reporting per-width PPL."""
+ def _make_eval_ffn_mask(self, ff_width, B, dtype):
+ """Default prefix FFN mask for eval: first ff_width neurons active."""
+ mask = (jnp.arange(self.config.d_ff) < ff_width).astype(dtype)
+ return jnp.broadcast_to(mask[None, :], (B, self.config.d_ff))
+
+ def forward_with_aux(self, src, tgt, src_mask=None, tgt_mask=None, cross_mask=None, mat_ff_widths=None):
+ """Eval-only: separate per-width forwards for reporting per-width PPL.
+
+ mat_ff_widths: list of FFN widths to evaluate (e.g. [1024, 512, 256]).
+ """
emb = self.embedding.embedding
- d_ff = self.config.d_ff
- d_model = self.config.d_model
B = src.shape[0]
encoder_out = self.encode_text(src, src_mask=src_mask)
@@ -403,24 +394,19 @@ class EncoderDecoderTransformer(nn.Module):
logits = x_f32 @ emb.T
slot_div = self._slot_diversity(encoder_out)
- mrl_logits = []
- if mrl_dims is not None:
- for d in mrl_dims:
- if d < d_model:
- k = d_ff * d // d_model
- mask = (jnp.arange(d_ff) < k).astype(x_f32.dtype)
- mask = jnp.broadcast_to(mask[None, :], (B, d_ff))
- enc_m = self.encode_text(src, src_mask=src_mask, ffn_mask=mask)
- x_m = self._run_decoder(enc_m, tgt, tgt_mask=tgt_mask, ffn_mask=mask)
- mrl_logits.append(x_m @ emb.T)
+ mat_logits = []
+ if mat_ff_widths is not None:
+ for ff_w in mat_ff_widths:
+ mask = self._make_eval_ffn_mask(ff_w, B, x_f32.dtype)
+ enc_m = self.encode_text(src, src_mask=src_mask, ffn_mask=mask)
+ x_m = self._run_decoder(enc_m, tgt, tgt_mask=tgt_mask, ffn_mask=mask)
+ mat_logits.append(x_m @ emb.T)
- return logits, slot_div, mrl_logits
+ return logits, slot_div, mat_logits
- def forward_speech_with_aux(self, mel, tgt, src_mask=None, tgt_mask=None, mrl_dims=None):
+ def forward_speech_with_aux(self, mel, tgt, src_mask=None, tgt_mask=None, mat_ff_widths=None):
"""Eval-only: separate per-width speech forwards for reporting per-width PPL."""
emb = self.embedding.embedding
- d_ff = self.config.d_ff
- d_model = self.config.d_model
B = mel.shape[0]
encoder_out = self.encode_speech(mel, src_mask=src_mask)
@@ -428,18 +414,15 @@ class EncoderDecoderTransformer(nn.Module):
logits = x_f32 @ emb.T
slot_div = self._slot_diversity(encoder_out)
- mrl_logits = []
- if mrl_dims is not None:
- for d in mrl_dims:
- if d < d_model:
- k = d_ff * d // d_model
- mask = (jnp.arange(d_ff) < k).astype(x_f32.dtype)
- mask = jnp.broadcast_to(mask[None, :], (B, d_ff))
- enc_m = self.encode_speech(mel, src_mask=src_mask, ffn_mask=mask)
- x_m = self._run_decoder(enc_m, tgt, tgt_mask=tgt_mask, ffn_mask=mask)
- mrl_logits.append(x_m @ emb.T)
-
- return logits, slot_div, mrl_logits
+ mat_logits = []
+ if mat_ff_widths is not None:
+ for ff_w in mat_ff_widths:
+ mask = self._make_eval_ffn_mask(ff_w, B, x_f32.dtype)
+ enc_m = self.encode_speech(mel, src_mask=src_mask, ffn_mask=mask)
+ x_m = self._run_decoder(enc_m, tgt, tgt_mask=tgt_mask, ffn_mask=mask)
+ mat_logits.append(x_m @ emb.T)
+
+ return logits, slot_div, mat_logits
def init_all(self, src, tgt, mel):
"""Dummy forward through both text and speech pathways to initialize all params."""
diff --git a/src/train.py b/src/train.py
index ad2809d..a4b1d79 100644
--- a/src/train.py
+++ b/src/train.py
@@ -224,8 +224,8 @@ def _quantize_params(params, group_size=32):
_GROUP_SIZE = 32
-_MRL_DIMS = ()
-_MRL_FF_SLICES = () # precomputed d_ff slices, set alongside _MRL_DIMS
+_MAT_FACTORS = ()
+_MAT_FF_WIDTHS = () # precomputed d_ff widths per factor
_D_FF = 2048 # set in train()
@@ -269,17 +269,17 @@ def _speech_loss_fn(state, params, mel, tgt_in, tgt_out, causal_mask, ffn_mask):
return ce_loss + z_loss + div_loss
-def _make_ffn_mask(batch_size, d_ff, mrl_ff_slices):
+def _make_ffn_mask(batch_size, d_ff, mat_ff_widths):
"""Build (batch, d_ff) prefix mask: batch split equally across widths.
- First quarter = full width (all ones), remaining quarters = MRL slices.
+ First quarter = full width (all ones), remaining quarters = mat widths.
Each unique input is repeated once per width.
"""
- n_widths = 1 + len(mrl_ff_slices) # full + MRL dims
+ n_widths = 1 + len(mat_ff_widths) # full + mat widths
per_width = batch_size // n_widths
arange = jnp.arange(d_ff)
rows = [jnp.ones((per_width, d_ff), dtype=jnp.bfloat16)] # full width
- for k in mrl_ff_slices:
+ for k in mat_ff_widths:
rows.append((arange[None, :] < k).astype(jnp.bfloat16).repeat(per_width, axis=0))
# Handle remainder (assign to full width)
remainder = batch_size - per_width * n_widths
@@ -288,7 +288,7 @@ def _make_ffn_mask(batch_size, d_ff, mrl_ff_slices):
return jnp.concatenate(rows, axis=0)
-def _repeat_for_mrl(arr, n_widths):
+def _repeat_for_mat(arr, n_widths):
"""Repeat first batch/n_widths items n_widths times to fill batch."""
per_width = arr.shape[0] // n_widths
unique = arr[:per_width]
@@ -385,20 +385,20 @@ def _make_val_loss_fn(apply_fn):
return val_loss_batch
-def _make_mrl_val_loss_fn(apply_fn, mrl_dim):
- """Val loss for MRL sub-model at dimension mrl_dim (FFN interior slicing)."""
+def _make_mat_val_loss_fn(apply_fn, ff_width):
+ """Val loss for matryoshka sub-model at given FFN width."""
@jax.jit
def val_loss_batch(params, src, tgt_in, tgt_out, causal_mask):
pad_id = 0
src_mask = make_padding_mask(src, pad_id)
tgt_mask = causal_mask & make_padding_mask(tgt_in, pad_id)
- logits, _, mrl_logits = apply_fn(
+ logits, _, mat_logits = apply_fn(
{"params": params}, src, tgt_in,
src_mask=src_mask, tgt_mask=tgt_mask, cross_mask=src_mask,
- mrl_dims=(mrl_dim,),
+ mat_ff_widths=(ff_width,),
method="forward_with_aux",
)
- trunc_logits = mrl_logits[0].astype(jnp.float32)
+ trunc_logits = mat_logits[0].astype(jnp.float32)
loss = optax.softmax_cross_entropy_with_integer_labels(trunc_logits, tgt_out)
mask = (tgt_out != pad_id).astype(jnp.float32)
return jnp.sum(loss * mask), jnp.sum(mask)
@@ -422,29 +422,25 @@ def _make_speech_val_loss_fn(apply_fn):
return val_loss_batch
-def _estimate_mrl_params(config, d_prime):
- """Estimate parameter count of an exported sub-model at MRL dimension d_prime.
+def _estimate_mat_params(config, matryoshka_factor):
+ """Estimate parameter count of a sub-model at a given matryoshka factor.
- FFN interior slicing: only FFN d_ff is reduced proportionally.
- d_model, attention, embedding, and mixer are all unchanged.
- - Embedding: [vocab, d_model] (unchanged)
- - Attention: full d_model heads/projections (unchanged)
- - FFN: d_ff' = d_ff * d_prime // d_model (sliced)
- - Mixer: full d_ff (unchanged, not masked)
+ matryoshka_factor: how many times smaller the FFN widths are (e.g. 2 = half width).
+ Embedding and attention weights are unchanged.
"""
d = config.d_model
v = config.vocab_size
n_enc = config.num_encoder_layers
n_dec = config.num_decoder_layers
kv_dim = config.num_kv_heads * (d // config.num_heads)
- d_ff_prime = config.d_ff * d_prime // d
m = config.num_memory_slots
+ d_ff = config.d_ff // matryoshka_factor
emb = v * d
attn = d * d + d * kv_dim * 2 + d * d
- ffn = d * d_ff_prime * 3
- mixer_token = d * config.d_ff * 2 + config.d_ff * m
- mixer_channel = d * config.d_ff * 3
+ ffn = d * d_ff * 3
+ mixer_token = m * d_ff * 3
+ mixer_channel = d * d_ff * 3
enc_block = attn + ffn + mixer_token + mixer_channel
dec_block = attn * 2 + ffn
total = emb + n_enc * enc_block + n_dec * dec_block
@@ -551,17 +547,17 @@ def train(args):
n_mels=n_mels,
)
- global _GROUP_SIZE, _MRL_DIMS, _MRL_FF_SLICES, _D_FF
+ global _GROUP_SIZE, _MAT_FACTORS, _MAT_FF_WIDTHS, _D_FF
_GROUP_SIZE = getattr(args, "group_size", 32)
_D_FF = config.d_ff
- mrl_dims_raw = getattr(args, "mrl_dims", None)
- if mrl_dims_raw:
- _MRL_DIMS = tuple(d for d in mrl_dims_raw if d < config.d_model)
- _MRL_FF_SLICES = tuple(config.d_ff * d // config.d_model for d in _MRL_DIMS)
+ mat_factors_raw = getattr(args, "mat_factors", None)
+ if mat_factors_raw:
+ _MAT_FACTORS = tuple(f for f in mat_factors_raw if f > 1)
+ _MAT_FF_WIDTHS = tuple(config.d_ff // f for f in _MAT_FACTORS)
else:
- _MRL_DIMS = ()
- _MRL_FF_SLICES = ()
- n_widths = 1 + len(_MRL_FF_SLICES) if _MRL_FF_SLICES else 1
+ _MAT_FACTORS = ()
+ _MAT_FF_WIDTHS = ()
+ n_widths = 1 + len(_MAT_FF_WIDTHS) if _MAT_FF_WIDTHS else 1
p_train_step = _make_p_train_step()
p_train_step_masked = _make_p_train_step_masked()
p_train_step_speech = _make_p_train_step_speech()
@@ -571,10 +567,10 @@ def train(args):
rng = jax.random.PRNGKey(args.seed)
rng, init_rng = jax.random.split(rng)
- mrl_shared_input = getattr(args, "mrl_shared_input", False)
+ mat_shared_input = getattr(args, "mat_shared_input", False)
# With shared input, each unique sample is repeated n_widths times,
# so we fetch smaller batches but take more steps per epoch.
- unique_batch_size = effective_batch_size // n_widths if (mrl_shared_input and n_widths > 1) else effective_batch_size
+ unique_batch_size = effective_batch_size // n_widths if (mat_shared_input and n_widths > 1) else effective_batch_size
text_batches_per_epoch = len(enc_inputs) // unique_batch_size
speech_batches_per_epoch = text_batches_per_epoch // speech_every if (not no_speech and speech_mel is not None) else 0
num_batches = text_batches_per_epoch + speech_batches_per_epoch
@@ -630,19 +626,19 @@ def train(args):
(num_devices, 1, args.max_dec_len, args.max_dec_len),
)
- # Precompute FFN mask for heterogeneous MRL training.
- # Batch is split: 1/N full-width + 1/N per MRL dim.
- text_ffn_mask = _make_ffn_mask(args.batch_size, config.d_ff, _MRL_FF_SLICES)
+ # Precompute FFN mask for heterogeneous matryoshka training.
+ # Batch is split: 1/N full-width + 1/N per mat factor.
+ text_ffn_mask = _make_ffn_mask(args.batch_size, config.d_ff, _MAT_FF_WIDTHS)
text_ffn_mask = jnp.broadcast_to(
text_ffn_mask[None, :, :],
(num_devices, args.batch_size, config.d_ff),
)
if n_widths > 1:
- print(f" MRL widths {n_widths} (full + {', '.join(str(s) for s in _MRL_FF_SLICES)})")
- if mrl_shared_input:
- print(f" MRL mode shared input ({unique_batch_size // num_devices}/dev x {n_widths} repeats)")
+ print(f" Mat factors {n_widths} (full + {', '.join(str(f)+'x' for f in _MAT_FACTORS)})")
+ if mat_shared_input:
+ print(f" Mat mode shared input ({unique_batch_size // num_devices}/dev x {n_widths} repeats)")
else:
- print(f" MRL mode unique input ({args.batch_size}/dev, random width)")
+ print(f" Mat mode unique input ({args.batch_size}/dev, random width)")
adam_schedule = _wsd_schedule(scaled_lr, total_steps, warmup_steps)
muon_schedule = _wsd_schedule(muon_lr, total_steps, warmup_steps)
@@ -689,7 +685,7 @@ def train(args):
# --- Text step ---
t0 = time.perf_counter()
- if n_widths > 1 and mrl_shared_input:
+ if n_widths > 1 and mat_shared_input:
# Shared: repeat each unique input across all widths
src = np.tile(src, (n_widths, 1))
tgt_in = np.tile(tgt_in, (n_widths, 1))
@@ -719,7 +715,7 @@ def train(args):
if speech_iter is not None and text_step_in_epoch % speech_every == 0:
mel_batch, sp_tgt_in, sp_tgt_out = next(speech_iter)
- if n_widths > 1 and mrl_shared_input:
+ if n_widths > 1 and mat_shared_input:
mel_batch = np.tile(mel_batch, (n_widths, 1, 1))
sp_tgt_in = np.tile(sp_tgt_in, (n_widths, 1))
sp_tgt_out = np.tile(sp_tgt_out, (n_widths, 1))
@@ -849,21 +845,21 @@ def train(args):
quant_val_ppl = float(math.exp(q_total_loss / max(q_total_toks, 1)))
del q_params # free device memory
- # MRL per-dimension evaluation (reuse val_loss_fn's apply_fn)
- mrl_results = {}
- if _MRL_DIMS:
+ # Matryoshka per-factor evaluation (reuse val_loss_fn's apply_fn)
+ mat_results = {}
+ if _MAT_FACTORS:
apply_fn = jax_utils.unreplicate(state).apply_fn
- for d_prime in _MRL_DIMS:
- mrl_vl_fn = _make_mrl_val_loss_fn(apply_fn, d_prime)
- mrl_total_loss, mrl_total_toks = 0.0, 0.0
+ for factor, ff_w in zip(_MAT_FACTORS, _MAT_FF_WIDTHS):
+ mat_vl_fn = _make_mat_val_loss_fn(apply_fn, ff_w)
+ mat_total_loss, mat_total_toks = 0.0, 0.0
for vb in get_batches(val_enc, val_dec_in, val_dec_tgt, args.batch_size, shuffle=False):
- vl, vt = mrl_vl_fn(eval_params, vb[0], vb[1], vb[2], val_causal)
- mrl_total_loss += float(vl)
- mrl_total_toks += float(vt)
- avg_loss = mrl_total_loss / max(mrl_total_toks, 1)
- mrl_ppl = float(math.exp(min(avg_loss, 20)))
- mrl_params = _estimate_mrl_params(config, d_prime)
- mrl_results[d_prime] = (mrl_ppl, mrl_params)
+ vl, vt = mat_vl_fn(eval_params, vb[0], vb[1], vb[2], val_causal)
+ mat_total_loss += float(vl)
+ mat_total_toks += float(vt)
+ avg_loss = mat_total_loss / max(mat_total_toks, 1)
+ mat_ppl = float(math.exp(min(avg_loss, 20)))
+ mat_params = _estimate_mat_params(config, factor)
+ mat_results[factor] = (mat_ppl, mat_params, ff_w)
del apply_fn
# Sparsity + checkpoint — move to CPU, reuse single copy
@@ -923,15 +919,14 @@ def train(args):
print(f" Speech val ppl {speech_val_ppl:>12.2f}")
print(f" Quant val ppl {quant_val_ppl:>12.2f} (INT4 g{_GROUP_SIZE})")
print(f" Sparsity {sparsity:>11.2f}% ({near_zero:,}/{total_params:,})")
- if mrl_results:
+ if mat_results:
print(f" ─────────────────────────────────────")
- print(f" MRL exportable sub-models (FFN interior slicing):")
- print(f" {'dim':>6} {'d_ff':>6} {'val ppl':>10} {'params':>12}")
- print(f" {config.d_model:>6} {config.d_ff:>6} {last_val_ppl:>10.2f} {total_params:>12,} (full)")
- for d_prime in sorted(mrl_results.keys(), reverse=True):
- mrl_ppl, mrl_params = mrl_results[d_prime]
- d_ff_prime = config.d_ff * d_prime // config.d_model
- print(f" {d_prime:>6} {d_ff_prime:>6} {mrl_ppl:>10.2f} {mrl_params:>12,}")
+ print(f" Matryoshka exportable sub-models (FFN interior slicing):")
+ print(f" {'factor':>6} {'d_ff':>6} {'val ppl':>10} {'params':>12}")
+ print(f" {'1x':>6} {config.d_ff:>6} {last_val_ppl:>10.2f} {total_params:>12,} (full)")
+ for factor in sorted(mat_results.keys()):
+ mat_ppl, mat_params, ff_w = mat_results[factor]
+ print(f" {str(factor)+'x':>6} {ff_w:>6} {mat_ppl:>10.2f} {mat_params:>12,}")
print(f" ─────────────────────────────────────")
print(f" Throughput {tp['tokens_per_second']:>10.1f} tok/s")
print(f" Latency {tp['avg_latency_s']:>11.3f}s")
@@ -966,9 +961,9 @@ def train(args):
log_dict["epoch/avg_speech_loss"] = sum(speech_losses) / len(speech_losses)
if speech_val_ppl is not None:
log_dict["epoch/speech_val_ppl"] = speech_val_ppl
- for d_prime, (mrl_ppl, mrl_params) in mrl_results.items():
- log_dict[f"epoch/mrl_ppl_d{d_prime}"] = mrl_ppl
- log_dict[f"epoch/mrl_params_d{d_prime}"] = mrl_params
+ for factor, (mat_ppl, mat_params, _) in mat_results.items():
+ log_dict[f"epoch/mat_ppl_{factor}x"] = mat_ppl
+ log_dict[f"epoch/mat_params_{factor}x"] = mat_params
wandb.log(log_dict)
if use_wandb: