Foundation model · Matrix completion

MatrixFormer

A pretrained transformer that fills in the missing entries of any numerical matrix: ratings, panels, sensor grids, tables. No training, no fine-tuning, no hyperparameters to tune.

Dwaipayan Saha*, Jacob Feitelberg*, Kyuseong Choi*, Raaz Dwivedi, Anish Agarwal
* Equal contribution

12 × 9 matrix · 30 missing
Observed Missing Imputed
Illustration on a synthetic low-rank matrix, the same shape as the package's built-in demo. Not live model output.

Zero-shot

Pretrained once on synthetic matrices. At inference, one forward pass completes your matrix. No weights are updated.

Any shape

Attention along rows and columns works for any number of rows and columns. Large matrices are processed in overlapping windows.

Observed entries kept

Only missing cells are predicted. Every observed value is returned exactly, in its original units.

Results

One set of frozen weights, with no fine-tuning, evaluated across four domains: tabular imputation, causal inference on panel data, recommender systems and language-model evaluation. All numbers are from the paper. Hover any chart for exact values.

Tabular imputation

Two suites, scored on masked cells with column-normalized RMSE (NRMSE). MissBench: 42 OpenML datasets under 11 missingness mechanisms at 40% missingness. UCI: 12 datasets under MCAR, MAR and MNAR at 10–50% missingness, with 10 repeats each. MatrixFormer has the lowest overall error on both.

Lower is better. Whiskers are 95% intervals from 10,000 dataset-bootstrap resamples. Rows are sorted by overall NRMSE, and that order is kept across patterns. † marks incomplete coverage.

Show data table

Causal inference: counterfactual completion

Estimating a treatment effect means predicting what treated units would have done untreated. On placebo panels where the true effect is zero, we hide the treated block and score its completion. Benchmarks: CPS state wage panels, the Kansas semi-synthetic design, and the California smoking donor pool. Scores are min–max normalized within each draw across the seven methods: 0 is best and 1 is worst.

Lower is better. Means over draws, with the designs within a benchmark weighted equally. MatrixFormer is lowest in five of six panels; HyperImpute is lowest for the Kansas effect error (0.119 vs 0.125).

Show data table

Recommender systems

Rating prediction on sparse user–item matrices, with a frozen 80/20 rating holdout. Baselines are Cornac's collaborative-filtering models. RMSE and MAE are in rating units, averaged over test users. MatrixFormer is lowest on both datasets and both metrics; on Netflix, its RMSE margin over SVD is small.

Lower is better. The axis is zoomed to separate the top methods. BPR is trained for ranking, not rating calibration, so it falls off the scale; its value is shown at the edge.

Show data table

Language-model benchmark completion

Rows are language models and columns are benchmark tasks. For a held-out model we reveal its scores on k tasks chosen by greedy mutual information, then predict the rest. The baseline is the Gaussian conditional-mean estimator from the task-selection release. MatrixFormer is higher on MTEB, Merged and BenchPress, with the largest gains on the two sparsest matrices. The Gaussian estimator is slightly higher on dense MMLU.

MatrixFormer Gaussian conditional mean

R² on held-out scores, higher is better, averaged over ten model folds. Each panel has its own y-axis. Observed fractions: MTEB 77%, MMLU 100%, Merged 31%, BenchPress 34%.

Show data table

Inference speed

TabImpute builds a separate prediction problem for every missing entry. MatrixFormer completes the whole matrix in one forward pass. With 10 columns, the speedup grows from 2.1× at 16 rows to 107× at 1,024 rows: 4.17 s for TabImpute vs 0.039 s for MatrixFormer-Impute.

MatrixFormer-Impute TabImpute (legacy)

Median runtime on one NVIDIA H200, 10 columns, both axes logarithmic.

Show data table

The paper's benchmark runs use task-specific preprocessing that this package does not include (for example, bias centering for ratings), so running the package's generic recipe will not reproduce every number exactly. See Good to know.

How it works

Each matrix cell becomes a token. Eight transformer blocks alternate attention along rows and along columns, so every cell can borrow information from its row and its column. A decoder then predicts a distribution over the missing value.

Input NaN = missing column-normalized Cell encoder value → MLP → 768-d missing → mask token + missingness embedding + 12 row & 12 column CLS tokens Axial transformer block × 8 Attention across columns within each row · RMSNorm · RoPE Attention across rows within each column · RMSNorm · RoPE SwiGLU feed-forward per cell · 768 → 1536 → 768 Decoder MLP → 5000 bins predictive mean Output original units, observed kept
Scroll sideways to see the full diagram →

One expert network, about 78M parameters. MatrixFormer+ runs two of these experts and blends them (below).

Normalize each column

Observed values are standardized per column, so columns in very different units become comparable. Predictions are mapped back afterwards.

Embed every cell

Observed values pass through a small MLP. Missing cells get a learned mask token. A missingness embedding tells the model which is which, and learned CLS tokens border each row and column.

Alternate row and column attention

Each block first lets cells in the same row attend to each other, then cells in the same column, then applies a per-cell feed-forward layer. Stacking eight blocks spreads information across the whole matrix.

Decode a distribution

For each cell the decoder outputs probabilities over 5000 value bins. The prediction is the mean of that distribution, which is written into the missing cells only.

Trained only on synthetic data. Both experts learned from randomly generated matrices with varied structure and missingness patterns. No real ratings or tables were used for gradient updates.

Architecture deep dive

Everything below is read directly from the inference code in src/matrixformer and the released expert configs.

Where the 78M parameters live

Each expert has exactly 77,998,496 parameters. The eight transformer blocks hold 85% of them. The decoder is large too, because its last layer maps 1536 features to 5000 bin logits. The cell encoder is tiny: it only has to lift one scalar into a 768-dimensional token.

8 blocks · 66.16M
decoder · 11.23M
ComponentParametersShareWhat it contains
Cell encoder612,8640.8%Value MLP (1 → 768 → 768), mask token, 2 missingness embeddings, 12 + 12 CLS embeddings
Each block8,269,82710.6%Two attention layers (2.36M each), SwiGLU feed-forward (3.54M), 3 RMSNorms, 3 residual scales
All 8 blocks66,158,61684.8%
Decoder11,227,01614.4%MLP 768 → 1536 → 1536 → 5000 with GELU

The token grid

An R × C input becomes an (R + 12) × (C + 12) grid of 768-dimensional tokens. There are no position embeddings at this stage; position enters later through RoPE inside attention.

  • Observed cell: its standardized value goes through Linear(1, 768) → GELU → Linear(768, 768).
  • Missing cell: replaced by one shared, learned mask token.
  • Every cell then adds a missingness embedding, one of two learned vectors, so the model always knows which cells are real.
  • 12 row-CLS tokens are prepended to every row, and 12 column-CLS tokens to every column. They are identical across rows (or columns) at input and become per-row and per-column summaries as attention runs.
  • Corner tokens are the sum of a row-CLS and a column-CLS embedding.

CLS tokens act as learned scratch registers. The decoder never reads them: it decodes only the R × C data cells.

Corner Column CLS Row CLS Observed Mask token

Axial attention: global context in one block

Full attention over every cell would compare all RC tokens with each other. MatrixFormer instead factorizes attention along the two axes. Each block runs two separate attention layers with their own weights: first every row attends across its columns, then every column attends across its rows. After those two steps, a cell has seen its row, and through each cell in its column, every other row too. A single block already has a receptive field covering the whole matrix. Eight blocks repeat this mixing.

Cost per block, 2000 × 1000 window
Full attention over all tokens4.1 × 10¹² pairs
Axial (rows, then columns)6.2 × 10⁹ pairs
Reduction≈ 670×

Token pairs scored by attention, including the 12 CLS rows and columns. Axial cost grows as RC(R + C) instead of (RC)².

  • 16 heads of width 48, bidirectional, no masking or dropout (PyTorch scaled_dot_product_attention).
  • Rotary position embeddings on half of each head (the first 24 of 48 dimensions), base 10,000. The position is the row or column index within the window.
  • CLS tokens are not rotated. RoPE starts after the 12 CLS positions, so they stay position-free registers.

Block anatomy

# pre-norm residual updates; α are learned scalar gains
h ← h + αrow · RowAttn( RMSNorm₁(h) )
h ← h + αcol · ColAttn( RMSNorm₂(h) )

# SwiGLU feed-forward, applied to every token independently
n = RMSNorm₃(h)
h ← h + αffn · Wout( SiLU(Wgate n) ⊙ Wval n )
  • Pre-norm with RMSNorm (ε = 10⁻⁶) before each of the three sublayers.
  • Learned residual gains. Each sublayer's output is multiplied by its own learned scalar α before it is added back, in the style of ReZero.
  • SwiGLU feed-forward with hidden width 1536: a gated unit with separate gate and value projections.
  • Separate weights for row attention and column attention in every block: 16 attention layers in total.

Decoder: a distribution, not a point

For each data cell, a three-layer GELU MLP outputs 5000 logits. A softmax turns them into probabilities over 5000 value bins defined by fixed borders (assets/borders.pt), in units of column standard deviations. The imputed value is the mean of that distribution:

x̂ = Σk softmax(logits)k · mk
  • Bins are not uniform. About 300 bins cover each unit near the center, roughly 0.003 standard deviations wide. Half of all bins fall within ±4.2 standard deviations.
  • The range is wide: borders run from −93 to +87 standard deviations, so outliers stay representable.
  • The two edge bins are open-ended tails. Their representative values come from a half-normal fit rather than the bin midpoint.
  • The softmax and mean are always computed in float32, even under BF16 autocast.

Bin borders per one-standard-deviation interval, from −16 to +16. 37 borders lie outside this range.

Scaling to large matrices

Global column normalization

Means and population standard deviations come from the observed entries of the whole matrix before any windowing. An entirely missing column gets mean 0 and scale 1.

Overlapping windows

Each axis is cut into windows of at most 2000 rows and 1000 columns. The last window is shifted back to end at the edge, so it overlaps its neighbor. Cells covered twice get the average of both predictions. For example, 4500 rows split into [0, 2000), [2000, 4000) and [2500, 4500).

Exact streaming

Within a window, attention runs in batches of 32 rows or columns, the feed-forward in chunks of 8192 tokens, with in-place residual updates. Every sequence is still attended in full, so streaming bounds memory without changing the math.

The hidden grid stays in float32 even under BF16 autocast: about 6.3 GB for a full 2000 × 1000 window, on top of the weights. Use smaller max_rows and max_cols to reduce it, at the cost of less context per window.

Training

Like prior-data fitted networks (TabPFN) and TabImpute, MatrixFormer never sees a real dataset during training. It learns from an endless stream of synthetic complete matrices, each masked into a reconstruction task. Details below follow Section 2 and Appendix A of the paper.

Three phases, one architecture

Each phase continues from the best checkpoint of the previous one. Two frozen teacher models, trained beforehand from the base checkpoint, guide the main and size-extension phases.

Phase 1

Base

17k updates
  • Latent-factor matrices, rank 1–11
  • 10–50 rows × 5–50 columns
  • 40% MCAR missingness
  • AdamW, peak LR 2×10⁻⁴
Side branch

Teachers

2 × 64k updates
  • Two main-phase runs from the base model
  • One on the main data mixture, one on a continuous-spectrum variant
  • Trained on true values; best validation checkpoints frozen
Phase 2

Main

128k updates
  • Diverse spectral prior and missingness mechanisms
  • Teacher-distilled objective
  • Batches of 2 matrices, peak LR 10⁻⁵
  • Best checkpoint at 98k updates
Phase 3

Size extension

5k updates
  • Matrices grow in stages up to 2000 × 1000
  • 20% of episodes stay at main-phase sizes
  • Peak LR 5×10⁻⁶
  • Selected after 4k updates

Size extension plays the role of context-length extension in language models. Attention cost grows with matrix size, so most training uses moderate sizes. A short final phase then adapts the model, including the range of its rotary positions, to large matrices.

Size-extension stageUpdatesRowsColumns
Bridge1–500256–512128–256
Large501–1500512–1024256–512
Larger1501–3000768–1536384–768
Full3001–50001024–2000512–1000

The synthetic data prior

The main phase draws from four equally likely matrix families. Together they vary rank, the shape of the singular-value spectrum, the geometry of the singular vectors, matrix size, and which entries are observed.

FamilyRank kTail exponent α
Low-rank2–160.2–2
Slow tail2–1600–0.5
Steep tail2–1601–2.5
Latent factor1–11n/a

The three spectral families build T = U diag(s) Vᵀ with orthonormal U, V. Each singular value blends a fast-decaying head with a power-law tail and a terminal taper:

wj = (1 − e−ω) e−tj/H
gj = [ wj e−(tj/h)p + (1 − wj) τ (1 + tj)−α ] · e−λ (tj/(k−1))q
sj = smax · gj / g1,   tj = j − 1

The input adds tiny Gaussian noise (σ ≤ 10⁻³), but the target keeps the full clean signal. The latent-factor family sets T = PQᵀ, with each factor vector drawn from a Gaussian, Laplace, Student-t, spike-and-slab or centered Dirichlet distribution. It is kept at base-phase sizes as rehearsal, because training on spectral matrices alone degraded performance on it.

Sampled spectra · sj / s1, log scale
Low-rank Slow tail Steep tail

Drawn live in your browser from the formula above with the paper's parameter ranges (Table 7), two draws per family. Rank is capped at 100 for display; each curve drops to zero after its rank k.

Singular-vector geometry

Each axis independently picks one of four constructions before QR orthonormalization: Gaussian (a uniformly random basis), coherent (variation concentrated in a few rows), smooth (random cosine features) or offset-bearing (a near-constant first direction).

From matrices to training episodes

Each family is paired with one of two masking schemes, giving eight equally weighted components: fixed 40% MCAR, or a mixed kernel that samples a missingness mechanism per matrix. Missingness can therefore depend on the values themselves.

Mixed mechanismProbability
MCAR: missing completely at random0.30
MAR: depends on observed values0.20
MNAR: depends on the hidden values0.20
Censoring below or above a quantile0.10
Two-phase subsampling0.10
Skip logic0.05
Cluster-level missingness0.05
  • Missing rate: 40% with probability 0.25, otherwise 0.05 + 0.7·B with B ~ Beta(2, 2), so it ranges from 5% to 75%.
  • Sparse-support thinning in 75% of episodes mimics new users with few ratings. The matrix is transposed with probability ½, then 10–40% of rows are picked and keep observations in only a log-uniform 1–60% of columns. The loss is scored on those rows' hidden entries.
  • Normalization applies one per-column affine map to both the masked input and the clean target. For sparsely observed columns the variance is shrunk toward the pooled within-column variance: (SSc + v̄) / (nc + 1).

Teacher–student objective

The model is trained to predict a full distribution for every hidden entry. Its probabilistic terms are supervised by the true value. Its point prediction is instead distilled toward two frozen teachers: models with the same architecture that receive the same masked input. Their averaged predictive mean, with gradients stopped, becomes the point target.

Masked episode synthetic X, mask M Student θ being trained Teachers ψ₁, ψ₂ frozen, same architecture mean of μ, stop-gradient distribution p mean μ μ̄ −log p(y) + 0.05 · CDF loss against the true value y 2 · Huber(μ − μ̄) point loss vs. teacher mean Σ over hidden scored entries mean per matrix
# per scored hidden entry, averaged over the set S
L = −log pθ(y)
  + 2 · ρ( μθ − sg[ ½(μψ₁ + μψ₂) ] )
  + 0.05 · (1/O) Σk ( Fθ(b̃k) − 1{y ≤ b̃k} )²

# ρ = Huber loss with threshold 1
  • Negative log-likelihood of the true value under the bar distribution trains the full predictive density.
  • CDF alignment is a ranked probability score at the 5000 bin midpoints, a discrete form of CRPS.
  • Huber, not squared error, for the point term: with squared error, a few extreme residuals dominated the point loss.
  • Teachers are training-only. Inference is a single forward pass of one model.

Optimization

SettingMain phaseSize extension
OptimizerAdamW, β = (0.9, 0.999), weight decay 0.02same
Gradient clipping0.50.5
Peak learning rate1 × 10⁻⁵5 × 10⁻⁶
Schedule600 warmup updates, cosine to 5%200 warmup updates, cosine to 5%
Batch2 matrices2 matrices, accumulated serially
PrecisionFP32 parameters and Adam moments, BF16 compute
Model selectionlowest macro RMSE on a fixed synthetic validation suitebest large-matrix error, with ≤ 3% loss on main-size matrices

The recommender specialist: MatrixFormer-RecSys

MatrixFormer-RecSys shares the architecture and differs only in its weights. It is fine-tuned on synthetic rating matrices that look like recommender data: very sparse, with heterogeneous users and popular items. The settings below come from the released checkpoint's config; the paper describes this expert only briefly.

  • Synthetic only: no real ratings in any gradient update, and model selection used inner synthetic validation only.
  • Rating episodes of 1000 × 1000 with only 0.4%–8% of entries observed, drawn from mixed user-preference families.
  • Realistic noise: per-user noise levels and power-law item popularity.
  • Recommender normalization: two-way (user and item) centering with per-user scaling.
  • Objective: point loss on expected rating RMSE, plus small weights on NLL (0.1), MAE (0.1) and a ranking term (0.05).
  • Short fine-tune: 400 updates at learning rate 5 × 10⁻⁶ from an earlier recommender checkpoint.
  • User-balanced query sampling, and the released weights are an exponential moving average (decay 0.95).

MatrixFormer+: a two-expert blend

MatrixFormer+ runs two experts with the same architecture: a general imputation model and a recommender-system specialist trained on sparse, rating-like matrices. It then picks one mixing weight for your matrix from how well each expert reconstructs the entries you did observe.

# per-cell errors on observed entries, column-standardized
eg = (general − x) / σ
es = (specialist − x) / σ

# least-squares weight, clipped to [0, 1]
w = clip( −eg·(es−eg) / ‖es−eg‖², 0, 1 )

# final completion
x̂ = (1 − w)·general + w·specialist

This is a closed-form fit of one number per matrix. No neural network weights change, and no held-out values are used.

Both experts contribute. MatrixFormer+ reports the fitted weight in model.last_decision["specialist_weight"].

Quickstart

Needs Python 3.10+, PyTorch 2.4+, NumPy and huggingface-hub. Weights download automatically from Hugging Face on first use. A GPU is optional.

bash · CPU setup
git clone https://github.com/jacobf18/MatrixFormer.git
cd MatrixFormer
python3 -m venv .venv && source .venv/bin/activate
python -m pip install "torch>=2.4,<3" --index-url https://download.pytorch.org/whl/cpu
python -m pip install .
python -m matrixformer --device cpu --precision float32   # runs a small demo

For an NVIDIA GPU, install PyTorch from the PyTorch selector instead. See the README for Windows and troubleshooting.

Choose a model

ModelExpertsWeights
MatrixFormerPlus
default · --model plus
General + specialist, blended~624 MB
MatrixFormerImpute
--model impute
General only~312 MB
MatrixFormerRecSys
--model recsys
Recommender specialist only (how it was trained)~312 MB

Architecture at a glance

Parameters per expert77,998,496
Blocks · width · heads8 · 768 · 16
Feed-forward width1536 (SwiGLU)
Output bins5000
Default context window2000 × 1000

Good to know

Citation

If you use MatrixFormer, please cite the paper.

bibtex
@article{saha2026matrixformer,
  title={MatrixFormer: A Foundation Model for Matrix Completion},
  author={Saha, Dwaipayan and Feitelberg, Jacob and Choi, Kyuseong and Dwivedi, Raaz and Agarwal, Anish},
  journal={arXiv preprint arXiv:2610.06751},
  year={2026}
}