SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2305.14342 · 2023

Sophia: A Scalable Stochastic Second-order Optimizer for Language Model Pre-training

arXiv · PDF · Open in the Atlas

Code that ran

13 of 19 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (4 of them constructed an object rather than computing a result; 1 honoured the contract we drafted, 0 violated it and 11 have no contract verdict; 1 failure of our instrument; 6 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/2305.14342.json · badge: /api/ran/2305.14342.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
Liuhong99/Sophia canonical (classifier label)
classifier basis: classifier_2025
2 ran · 2 no recorded run
helw150/levanter community (classifier label)
classifier basis not recorded on the link
4 ran · 2 no recorded run
stanford-crfm/levanter community (classifier label)
classifier basis not recorded on the link
3 ran · 2 no recorded run
labmlai/annotated_deep_learning_paper_implementations reimplementation (classifier label)
classifier basis: classifier_2025
3 ran · 0 no recorded run
kyegomez/Sophia reimplementation (classifier label)
classifier basis: classifier_2025
1 ran · 0 no recorded run
FunctionStatusWhere it lives
GenericAdaptiveOptimizer Ran
ran on a synthesized input · constructed an object; no result was computed
labmlai/annotated_deep_learning_paper_implementations/labml_nn/optimizers/sophia.py
code served (permissive licence) · get_code("15bc730db57a3642")
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 an instance of its own class, GenericAdaptiveOptimizer: the run constructed the object and did not call it, so no result was computed. 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
from torch import nn
from torch.optim.optimizer import Optimizer

torch.manual_seed(0)

# Create a simple model with parameters
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(4, 3)
        self.linear2 = nn.Linear(3, 2)
    
    def forward(self, x):
        return self.linear2(torch.relu(self.linear1(x)))

model = SimpleModel()

# Create parameter list with gradients
params = list(model.parameters())
for param in params:
    param.grad = torch.randn_like(param)

# Define defaults dictionary
defaults = {}

# Define hyperparameters
lr = 0.001
betas = (0.9, 0.999)
eps = 1e-8

ARGS = {
    'params': params,
    'defaults': defaults,
    'lr': lr,
    'betas': betas,
    'eps': eps
}
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 GenericAdaptiveOptimizer — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a GenericAdaptiveOptimizer 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
Sophia Ran
ran on a synthesized input · constructed an object; no result was computed
labmlai/annotated_deep_learning_paper_implementations/labml_nn/optimizers/sophia.py
code served (permissive licence) · get_code("a6e9300c48fec63f")
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 an instance of its own class, Sophia: the run constructed the object and did not call it, so no result was computed. 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
from torch import nn
from typing import Tuple, Dict, Any

torch.manual_seed(0)

# Create a minimal model
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(4, 3)
        self.linear2 = nn.Linear(3, 2)
    
    def forward(self, x):
        return self.linear2(self.linear1(x))

# Create model instance
model = SimpleModel()

# Define WeightDecay class (from the function signature)
class WeightDecay:
    def __init__(self, weight_decay: float = 0.0, weight_decouple: bool = True, absolute: bool = False):
        if not 0.0 <= weight_decay:
            raise ValueError(f'Invalid weight_decay value: {weight_decay}')
        self.absolute = absolute
        self.weight_decouple = weight_decouple
        self.weight_decay = weight_decay

    def defaults(self):
        return dict(weight_decay=self.weight_decay)

    def __call__(self, param: nn.Parameter, grad: torch.Tensor, group: Dict[str, Any]):
        if self.weight_decouple:
            if self.absolute:
                param.data.mul_(1.0 - group['weight_decay'])
            else:
                param.data.mul_(1.0 - group['lr'] * group['weight_decay'])
            return grad
        elif group['weight_decay'] != 0:
            return grad.add(param.data, alpha=group['weight_decay'])
        else:
            return grad

# Create WeightDecay instance
weight_decay_obj = WeightDecay(weight_decay=0.01, weight_decouple=True, absolute=False)

# Build ARGS dictionary with all Sophia parameters
ARGS = {
    'params': model.parameters(),
    'lr': 0.0001,
    'betas': (0.9, 0.95),
    'eps': 1e-12,
    'rho': 0.03,
    'weight_decay': weight_decay_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 Sophia — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a Sophia 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
SophiaG Ran
ran on a synthesized input · constructed an object; no result was computed
Liuhong99/Sophia/sophia.py
code served (permissive licence) · get_code("1436d0069dad845e")
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 an instance of its own class, SophiaG: the run constructed the object and did not call it, so no result was computed. 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 import Tensor
from typing import List

torch.manual_seed(0)

# Create a simple model with parameters
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(4, 3)
        self.linear2 = nn.Linear(3, 2)
    
    def forward(self, x):
        x = self.linear1(x)
        x = self.linear2(x)
        return x

model = SimpleModel()

# Extract parameters for optimizer
params = list(model.parameters())

ARGS = {
    'params': params,
    'lr': 0.0001,
    'betas': (0.965, 0.99),
    'rho': 0.04,
    'weight_decay': 0.1,
    'maximize': False,
    'capturable': False,
}
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 SophiaG — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a SophiaG 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
WeightDecay Ran
ran on a synthesized input · constructed an object; no result was computed
labmlai/annotated_deep_learning_paper_implementations/labml_nn/optimizers/sophia.py
code served (permissive licence) · get_code("ba6a2ba94fbeb5e9")
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 an instance of its own class, WeightDecay: the run constructed the object and did not call it, so no result was computed. 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

torch.manual_seed(0)

# The WeightDecay.__call__ method expects:
# - param: torch.nn.Parameter
# - grad: torch.Tensor
# - group: Dict[str, any] with keys 'weight_decay' and 'lr'

# Create a small parameter
param = torch.nn.Parameter(torch.randn(4, 3))

# Create a gradient tensor with same shape as param
grad = torch.randn(4, 3)

# Create a parameter group dict with required keys
group = {
    'weight_decay': 0.01,
    'lr': 0.001
}

ARGS = {
    'weight_decay': 0.01,
    'weight_decouple': True,
    'absolute': False
}
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 WeightDecay — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a WeightDecay 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
auto_metric_from_name Ran
ran on a synthesized input
stanford-crfm/levanter/src/levanter/metrics.py
code served (permissive licence) · get_code("de22a502eda2c3b9")
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 Metric. 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 jax
import jax.numpy as jnp
from enum import Enum

class ReductionType(Enum):
    """Reduction strategy for metric aggregation."""
    MEAN = 'mean'
    SUM = 'sum'
    MAX = 'max'
    MIN = 'min'
    LAST = 'last'

# Test cases for auto_metric_from_name
# We need to provide: name (str) and value (float | jax.Array)

# Case 1: accuracy metric (should infer MEAN)
name_1 = "accuracy"
value_1 = 0.95

# Case 2: total_samples metric (should infer SUM)
name_2 = "total_samples"
value_2 = 1000.0

# Case 3: learning_rate metric (should infer LAST)
name_3 = "learning_rate"
value_3 = 0.001

# Case 4: loss metric with JAX array (should infer MEAN)
name_4 = "loss"
value_4 = jnp.array(0.25)

# Case 5: max_accuracy metric (should infer MAX)
name_5 = "max_accuracy"
value_5 = jnp.array(0.99)

# Case 6: min_error metric (should infer MIN)
name_6 = "min_error"
value_6 = 0.05

ARGS = {
    "name": "accuracy",
    "value": 0.95
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
jax — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Metric — a Metric output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Metric 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
eval_loss_loop Ran
ran on a synthesized input
helw150/levanter/src/levanter/callbacks.py
code served (permissive licence) · get_code("1421ef5f024f6e23")
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 float, ndim 0, dtype family float, shape () 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
import torch.nn as nn

torch.manual_seed(0)

# Define a simple model that takes a batch and outputs a scalar for loss computation
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 1)
    
    def forward(self, x):
        return self.linear(x)

# Define a loss function that takes model and batch, returns a scalar loss
def loss_fn(model, batch):
    x, y = batch
    output = model(x)
    loss = nn.MSELoss()(output.squeeze(), y)
    return loss

# Create model instance
model = SimpleModel()

# Create a simple dataset as a list of batches
# Each batch is a tuple of (input_tensor, target_tensor)
dataset = [
    (torch.randn(2, 4), torch.randn(2)),
    (torch.randn(2, 4), torch.randn(2)),
    (torch.randn(2, 4), torch.randn(2)),
    (torch.randn(2, 4), torch.randn(2)),
    (torch.randn(2, 4), torch.randn(2)),
]

ARGS = {
    'loss_fn': loss_fn,
    'model': model,
    'dataset': dataset,
    'max_batches': None,
    'name': 'test_eval'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float, ndim 0, dtype family float, shape () — shape () 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_lr Ran
ran, honoured the contract we drafted
Liuhong99/Sophia/train_sophiag.py
code served (permissive licence) · get_code("a273291a5ece194d")
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) and returned float, ndim 0, dtype family float, shape () 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 math

learning_rate = 0.0003
warmup_iters = 2000
lr_decay_iters = 600000
min_lr = 1.5e-05

def get_lr(it):
    if it < warmup_iters:
        return learning_rate * it / warmup_iters
    if it > lr_decay_iters:
        return min_lr
    decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
    assert 0 <= decay_ratio <= 1
    coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
    return min_lr + coeff * (learning_rate - min_lr)

ARGS = {
    "it": 1000
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float, ndim 0, dtype family float, shape () — shape () 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
group_texts Ran
ran; our contract draft was wrong, not the code
kyegomez/Sophia/experiments/training.py
code served (permissive licence) · get_code("2382cb6829841947")
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) 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 multiprocessing
from itertools import chain

class CFG:
    SEQ_LEN: int = 1024
    NUM_CPU: int = multiprocessing.cpu_count()
    TOKENIZER: str = 'gpt2'

block_size = CFG.SEQ_LEN

def group_texts(examples):
    concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
    total_length = len(concatenated_examples[list(examples.keys())[0]])
    if total_length >= block_size:
        total_length = total_length // block_size * block_size
    result = {k: [t[i:i + block_size] for i in range(0, total_length, block_size)] for k, t in concatenated_examples.items()}
    return result

# Create minimal valid examples dict
# The function expects a dict where each key maps to a list of lists (or iterables)
# that will be flattened and then chunked by block_size
examples = {
    'input_ids': [
        [1, 2, 3, 4, 5],
        [6, 7, 8, 9, 10]
    ],
    'attention_mask': [
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1]
    ]
}

ARGS = {
    'examples': examples
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — 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
load_array_from_tensorstore Ran
ran on a synthesized input
helw150/levanter/src/levanter/tensorstore_serialization.py
code served (permissive licence) · get_code("003d0a17d2ac09ca")
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 coroutine. 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 asyncio
import jax.experimental.array_serialization.serialization as array_ser
import tensorstore
import numpy as np

# Create a minimal in-memory tensorstore spec
# Using a memory-backed zarr-like specification
spec = {
    "driver": "memory",
    "dtype": "float32",
    "shape": [2, 4],
}

ARGS = {
    "spec": spec,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
jax, numpy, tensorstore — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type coroutine — a coroutine output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a coroutine 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
local_device_grid_positions Ran
ran on a synthesized input
helw150/levanter/src/levanter/mesh.py
code served (permissive licence) · get_code("f3fb5a3a9edbf5ef")
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 tuple, ndim 2, dtype family int; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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 jax
import numpy as np

class MockDevice:
    """Mock JAX device with process_index attribute."""
    def __init__(self, process_index):
        self.process_index = process_index

class MockMesh:
    """Mock mesh object with devices array."""
    def __init__(self, devices):
        self.devices = devices

# Create a small mesh with devices
# We'll create a 2D grid of devices (4x3) where some belong to process 0
devices = np.array([
    [MockDevice(0), MockDevice(1), MockDevice(0)],
    [MockDevice(1), MockDevice(0), MockDevice(1)],
    [MockDevice(0), MockDevice(1), MockDevice(0)],
    [MockDevice(1), MockDevice(0), MockDevice(1)]
])

mesh = MockMesh(devices)

ARGS = {
    "mesh": mesh,
    "process_index": 0
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
jax, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 2, dtype family int — a tuple output has no array shape of its own; none is stated
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
process_mesh_position Ran
ran on a synthesized input
helw150/levanter/src/levanter/mesh.py
code served (permissive licence) · get_code("efa87b8fc2935200")
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 ndarray, ndim 1, dtype family int, shape (2,) 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 jax
import numpy as np
from unittest.mock import Mock

# Create a mock mesh object that mimics JAX's mesh structure
# The function expects mesh.devices to be an ndarray and mesh.local_mesh.devices to have a shape

# Create device objects with process_index attributes
class MockDevice:
    def __init__(self, process_index):
        self.process_index = process_index

# Create a 4x3 grid of devices (distinct dimensions for clarity)
devices_grid = np.array([
    [MockDevice(0), MockDevice(0), MockDevice(1)],
    [MockDevice(0), MockDevice(0), MockDevice(1)],
    [MockDevice(1), MockDevice(1), MockDevice(0)],
    [MockDevice(1), MockDevice(1), MockDevice(0)]
])

# Create mock mesh object
mock_mesh = Mock()
mock_mesh.devices = devices_grid

# Create mock local_mesh with a smaller shape (2x2)
mock_local_mesh = Mock()
mock_local_mesh.devices = Mock()
mock_local_mesh.devices.shape = (2, 2)
mock_mesh.local_mesh = mock_local_mesh

ARGS = {
    "mesh": mock_mesh,
    "process_index": 0
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
jax, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 1, dtype family int, shape (2,) — shape (2,) 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
unwrap_metrics Ran
ran on a synthesized input
stanford-crfm/levanter/src/levanter/metrics.py
code served (permissive licence) · get_code("3f1967528c23afbd")
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 jax
import jax.numpy as jnp
from dataclasses import dataclass
from enum import Enum

class ReductionType(Enum):
    """Reduction strategy for metric aggregation."""
    MEAN = 'mean'
    SUM = 'sum'
    MAX = 'max'
    MIN = 'min'
    LAST = 'last'

@dataclass
class Metric:
    """
    A foldable metric that uses internal state for reduction.

    We use a fixed-size internal representation (value + count) instead of a
    variable-length tuple to maintain constant pytree structure across fold operations.
    JAX's scan requires the carry to have the same structure in each iteration,
    so we can't use a growing list of samples.

    Internal representation by reduction type:
    - MEAN: (_value=sum, _count=count)
    - SUM: (_value=sum, _count=0)
    - MAX: (_value=max_value, _count=0)
    - MIN: (_value=min_value, _count=0)
    - LAST: (_value=last_value, _count=0)

    Forms a monoid: fold is associative.
    """
    _value: float | jax.Array = 0.0
    _count: float | jax.Array = 0.0
    reduction: ReductionType = ReductionType.MEAN

    def value(self):
        """Extract the scalar value by applying reduction."""
        value = self._value.array if hasattr(self._value, 'array') else self._value
        count = self._count.array if hasattr(self._count, 'array') else self._count
        match self.reduction:
            case ReductionType.MEAN:
                return jnp.where(count > 0, value / count, 0.0)
            case ReductionType.SUM:
                return value
            case ReductionType.MAX:
                return value
            case ReductionType.MIN:
                return value
            case ReductionType.LAST:
                return value

    def __float__(self) -> float:
        """Coerce Metric to float outside of a JIT context."""
        return float(self.value())

    @classmethod
    def from_value(cls, value: float | jax.Array, reduction: ReductionType) -> 'Metric':
        """Create metric from single observation."""
        match reduction:
            case ReductionType.MEAN:
                return cls(_value=value, _count=1, reduction=reduction)
            case ReductionType.SUM:
                return cls(_value=value, _count=0, reduction=reduction)
            case ReductionType.MAX:
                return cls(_value=value, _count=0, reduction=reduction)
            case ReductionType.MIN:
                return cls(_value=value, _count=0, reduction=reduction)
            case ReductionType.LAST:
                return cls(_value=value, _count=0, reduction=reduction)

def unwrap_metrics(pytree):
    """
    Walk a pytree and extract .value() from all Metric objects.
    """

    def _unwrap(x):
        if isinstance(x, Metric):
            return x.value()
        return x
    return jax.tree_util.tree_map(_unwrap, pytree, is_leaf=lambda x: isinstance(x, Metric))


# Setup code to construct valid arguments
metric_mean = Metric(_value=10.0, _count=2.0, reduction=ReductionType.MEAN)
metric_sum = Metric(_value=42.0, _count=0.0, reduction=ReductionType.SUM)
metric_max = Metric(_value=99.0, _count=0.0, reduction=ReductionType.MAX)
metric_min = Metric(_value=1.0, _count=0.0, reduction=ReductionType.MIN)
metric_last = Metric(_value=7.0, _count=0.0, reduction=ReductionType.LAST)

# Create a nested pytree with Metrics and other values
pytree = {
    'metrics': {
        'loss': metric_mean,
        'accuracy': metric_sum,
    },
    'auxiliary': {
        'max_val': metric_max,
        'min_val': metric_min,
        'last_val': metric_last,
    },
    'plain_values': {
        'count': 5,
        'name': 'test',
        'array': jnp.array([1.0, 2.0, 3.0]),
    },
    'nested_list': [metric_mean, 42, 'text'],
}

ARGS = {
    'pytree': pytree,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
jax — 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
value_at_step Ran
ran on a synthesized input
stanford-crfm/levanter/src/levanter/schedule.py
code served (permissive licence) · get_code("9b3a9ebcd8b2b32b")
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 list, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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 typing
from dataclasses import dataclass
from typing import Sequence, TypeVar

torch.manual_seed(0)

T = TypeVar('T')

@dataclass
class ScheduleStep(typing.Generic[T]):
    start: int
    value: T

# Test case 1: schedule with multiple steps
schedule = [
    ScheduleStep(start=0, value=0.1),
    ScheduleStep(start=5, value=0.05),
    ScheduleStep(start=10, value=0.01),
]

# Test case 2: single value (not a sequence)
single_value = 0.5

# Test case 3: schedule with string values
schedule_str = [
    ScheduleStep(start=0, value="low"),
    ScheduleStep(start=100, value="high"),
]

# Test case 4: schedule with tensor values
schedule_tensor = [
    ScheduleStep(start=0, value=torch.tensor([1.0, 2.0, 3.0, 4.0])),
    ScheduleStep(start=20, value=torch.tensor([5.0, 6.0, 7.0, 8.0])),
]

# Primary test case: schedule lookup at step 7
ARGS = {
    "schedule_or_t": schedule,
    "step": 7,
}
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 list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
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
_single_tensor_sophiag Not yet run
unverified (harvested, no recorded run)
Liuhong99/Sophia/sophia.py
code served (permissive licence) · get_code("34b6a986acbf4f68")
How it ran

no invocation recorded.

distinct_values Not yet run
unverified (harvested, no recorded run)
stanford-crfm/levanter/src/levanter/schedule.py
code served (permissive licence) · get_code("c501ae8133a11ec3")
How it ran

no invocation recorded.

fold Not yet run
unverified (harvested, no recorded run)
stanford-crfm/levanter/src/levanter/metrics.py
code served (permissive licence) · get_code("d40382c2fb844d41")
How it ran

no invocation recorded.

process_mesh_size Not yet run
unverified (harvested, no recorded run)
helw150/levanter/src/levanter/mesh.py
code served (permissive licence) · get_code("030ef454b59ac14a")
How it ran

no invocation recorded.

save_xla_dumps_to_wandb Not yet run
unverified (harvested, no recorded run)
helw150/levanter/src/levanter/logging.py
code served (permissive licence) · get_code("8b3f53737bb49ef4")
How it ran

no invocation recorded.

sophiag Not yet run
unverified (harvested, no recorded run)
Liuhong99/Sophia/sophia.py
code served (permissive licence) · get_code("24947d588d9b62aa")
How it ran

no invocation recorded.

Also present in other papers' code

Of 19 samples lifted from this paper's linked repositories, 19 carry a function identity and 0 do not. Of the 19 distinct functions with an identity, 3 are also present in other papers whose code we hold (3 with at least one paper dated earlier, 0 the same month, 1 later) and 16 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
get_lr 5 other papers
1 dated earlier, 4 later
1910.00643 (2019-10)
SlowMo: Improving Communication-Efficient Distributed SGD with Slow Momentum
2402.16788 (2024-02)
Why Transformers Need Adam: A Hessian Perspective
2404.08634 (2024-04)
When Attention Collapses: How Degenerate Layers in LLMs Enable Smaller, Stronger Models
and 2 more not named here
GenericAdaptiveOptimizer
brick of this paper's assembly: helper
1 other paper
1 dated earlier · 1 only as an assembly brick
1412.6980 (2014-12)
Adam: A Method for Stochastic Optimization
WeightDecay
brick of this paper's assembly: helper
1 other paper
1 dated earlier · 1 only as an assembly brick
1412.6980 (2014-12)
Adam: A Method for Stochastic Optimization

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

Given the massive cost of language model pre-training, a non-trivial improvement of the optimization algorithm would lead to a material reduction on the time and cost of training. Adam and its variants have been state-of-the-art for years, and more sophisticated second-order (Hessian-based) optimizers often incur too much per-step overhead. In this paper, we propose Sophia, Second-order Clipped Stochastic Optimization, a simple scalable second-order optimizer that uses a light-weight estimate of the diagonal Hessian as the pre-conditioner. The update is the moving average of the gradients divided by the moving average of the estimated Hessian, followed by element-wise clipping. The clipping controls the worst-case update size and tames the negative impact of non-convexity and rapid change of Hessian along the trajectory. Sophia only estimates the diagonal Hessian every handful of iterations, which has negligible average per-step time and memory overhead. On language modeling with GPT models of sizes ranging from 125M to 1.5B, Sophia achieves a 2x speed-up compared to Adam in the number of steps, total compute, and wall-clock time, achieving the same perplexity with 50% fewer steps, less total compute, and reduced wall-clock time. Theoretically, we show that Sophia, in a much simplified setting, adapts to the heterogeneous curvatures in different parameter dimensions, and thus has a run-time bound that does not depend on the condition number of the loss.

For agents

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

get_harvested_code_for_paper("2305.14342")
get_code_for_paper("2305.14342")
have("2305.14342")

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

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

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

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

Connect an agent — have() is free.