SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2310.07707 · NeurIPS · 2024

MatFormer: Nested Transformer for Elastic Inference

Prateek Jain, Sham Kakade, Ali Farhadi, Hannaneh Hajishirzi, Inderjit Dhillon, Yulia Tsvetkov, Devvrit, Aditya †⋄, Kusupati, Tim †⋄+, Dettmers, Kaifeng Chen, and 3 more

arXiv · PDF · Open in the Atlas

Code that ran

5 of 6 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 4 have no contract verdict; 1 failure of our instrument; 1 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2310.07707.json · badge: /api/ran/2310.07707.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
RAIVNLab/MatFormer-OLMo community (classifier label)
classifier basis not recorded on the link
5 ran · 1 no recorded run
FunctionStatusWhere it lives
apply_rotary_pos_emb Ran
ran on a synthesized input
RAIVNLab/MatFormer-OLMo/olmo/model.py
code served (permissive licence) · get_code("79a6291839e80304")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 4, dtype family float, shape (2, 3, 4, 8) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Analyze the function:
# - apply_rotary_pos_emb takes pos and t (both torch.Tensor)
# - It calls pos.cos(), pos.sin(), and rotate_half(t)
# - rotate_half expects x with shape (B, nh, T, hs) where hs is divisible by 2
# - The output is t * pos.cos() + rotate_half(t) * pos.sin()
# - This means pos and t must be broadcastable together

# For rotate_half to work:
# - Input shape: (B, nh, T, hs) where hs is even
# - It reshapes to (B, nh, T, 2, hs//2)
# - Returns shape (B, nh, T, hs)

# So t should have shape (B, nh, T, hs)
# pos should have compatible shape for broadcasting

B = 2      # batch size
nh = 3     # num heads
T = 4      # sequence length
hs = 8     # head size (must be even)

# t: the token embeddings with shape (B, nh, T, hs)
t = torch.randn(B, nh, T, hs)

# pos: positional embeddings, same shape as t for element-wise operations
# It needs .cos() and .sin() methods (standard torch.Tensor has these)
pos = torch.randn(B, nh, T, hs)

ARGS = {
    "pos": pos,
    "t": t,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 4, dtype family float, shape (2, 3, 4, 8) — shape (2, 3, 4, 8) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
clean_opt Ran
ran on a synthesized input
RAIVNLab/MatFormer-OLMo/olmo/util.py
code served (permissive licence) · get_code("0575de7c31b2b8b5")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned str. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

def clean_opt(arg: str) -> str:
    if '=' not in arg:
        arg = f'{arg}=True'
    name, val = arg.split('=', 1)
    name = name.strip('-').replace('-', '_')
    return f'{name}={val}'

# The function takes a single string argument
# It processes command-line style arguments, handling flags and key=value pairs
# Test with a typical argument string

ARGS = {
    'arg': '--learning-rate=0.001'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
fix_optim_state_dict Ran
ran on a synthesized input
RAIVNLab/MatFormer-OLMo/olmo/optim.py
code served (permissive licence) · get_code("dd8259ebeb7e5221")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from torch.optim import SGD

torch.manual_seed(0)

# Create a simple model with parameters
model = nn.Sequential(
    nn.Linear(4, 3),
    nn.ReLU(),
    nn.Linear(3, 2)
)

# Get model parameters split into two groups: with and without weight decay
decay_params = []
no_decay_params = []
for name, param in model.named_parameters():
    if 'weight' in name:
        decay_params.append(param)
    else:
        no_decay_params.append(param)

# Create an optimizer with two param groups
optimizer = SGD(
    [
        {'params': decay_params, 'weight_decay': 0.01},
        {'params': no_decay_params, 'weight_decay': 0.0}
    ],
    lr=0.1
)

# Create a state dict with only 1 param group (simulating a checkpoint from a model
# that was trained with a single param group)
state_dict = {
    'state': {},
    'param_groups': [
        {
            'lr': 0.1,
            'momentum': 0,
            'dampening': 0,
            'weight_decay': 0.01,
            'nesterov': False,
            'params': [0, 1, 2, 3, 4, 5]  # Dummy param indices
        }
    ]
}

ARGS = {
    'optimizer': optimizer,
    'state_dict': state_dict
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
move_to_device Ran
ran; our contract draft was wrong, not the code
RAIVNLab/MatFormer-OLMo/olmo/util.py
code served (permissive licence) · get_code("ff37eb2ce67445b2")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Test case 1: Move a tensor to device
tensor_obj = torch.randn(2, 4)
device_obj = torch.device('cpu')

# Test case 2: Move a dict containing tensors
dict_obj = {
    'tensor1': torch.randn(2, 4),
    'tensor2': torch.randn(3, 5),
    'nested': {
        'tensor3': torch.randn(1, 6)
    }
}

# Test case 3: Move a list containing tensors
list_obj = [torch.randn(2, 4), torch.randn(3, 5), 'string_value']

# Test case 4: Move a tuple containing tensors
tuple_obj = (torch.randn(2, 4), torch.randn(3, 5), 42)

# Test case 5: Complex nested structure with tensors, dicts, lists, tuples
complex_obj = {
    'tensors': [torch.randn(2, 4), torch.randn(3, 5)],
    'tuple_data': (torch.randn(1, 6), 'info'),
    'scalar': 10,
    'nested_list': [[torch.randn(2, 3)], torch.randn(4, 7)]
}

ARGS = {
    'o': complex_obj,
    'device': device_obj
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
rotate_half Ran
ran on a synthesized input
RAIVNLab/MatFormer-OLMo/olmo/model.py
code served (permissive licence) · get_code("db83ffe217e8539f")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 4, dtype family float, shape (2, 3, 4, 8) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# The function expects a tensor with shape (B, nh, T, hs)
# where hs (hidden size) must be even since it's divided by 2
# B = batch size
# nh = number of heads
# T = sequence length
# hs = hidden size (must be even)

B = 2
nh = 3
T = 4
hs = 8  # Must be even

x = torch.randn(B, nh, T, hs)

ARGS = {
    "x": x
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 4, dtype family float, shape (2, 3, 4, 8) — shape (2, 3, 4, 8) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_param_groups Not yet run
unverified (harvested, no recorded run)
RAIVNLab/MatFormer-OLMo/olmo/optim.py
code served (permissive licence) · get_code("3691aa6ac5b99fd5")
How it ran

no invocation recorded.

Also present in other papers' code

Of 6 samples lifted from this paper's linked repositories, 6 carry a function identity and 0 do not. Of the 6 distinct functions with an identity, 1 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 1 later) and 5 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
move_to_device 1 other paper
1 later
2602.11543 (2026-02)
Pretraining A Large Language Model using Distributed GPUs: A Memory-Efficient Decentralized Paradigm

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Foundation models are applied in a broad spectrum of settings with different inference constraints, from massive multi-accelerator clusters to resource-constrained standalone mobile devices. However, the substantial costs associated with training these models often limit the number of unique model sizes that can be offered. Consequently, practitioners are compelled to select a model that may not be optimally aligned with their specific latency and cost requirements. We present MatFormer 2 , a novel Transformer architecture designed to provide elastic inference across diverse deployment constraints. MatFormer achieves this by incorporating a nested Feed Forward Network (FFN) block structure within a standard Transformer model. During training, we optimize the parameters of multiple nested FFN blocks with varying sizes, enabling the extraction of hundreds of accurate smaller models without incurring additional computational costs. We empirically validate the efficacy of MatFormer across different model classes (decoders and encoders) and modalities (language and vision), demonstrating its potential for real-world deployment. We show that a 850M decoder-only MatFormer language model (MatLM) allows us to extract multiple smaller models spanning from 582M to 850M parameters, each exhibiting better validation loss and one-shot downstream evaluations than independently trained counterparts. Furthermore, we observe that smaller encoders extracted from a universal MatFormer-based ViT (MatViT) encoder preserve the metric-space structure for adaptive large-scale retrieval. Finally, we showcase that speculative decoding with the accurate and consistent submodels extracted from MatFormer can lead to significant reduction in inference latency. Project website. * Equal technical contribution. + Aditya Kusupati and Prateek Jain led the project.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2310.07707")
get_code_for_paper("2310.07707")
have("2310.07707")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2310.07707.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2310.07707.svg)](https://syntology.ai/paper/2310.07707)

Connect an agent — have() is free.