SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2508.20577 · ICML · 2025

MERIT: Maximum-normalized Element-wise Ratio for Language Model Large-batch Training

Yong Liu, Yang You, Zangwei Zheng, Zirui Zhu, Yang Luo, Ziheng Qin

arXiv · PDF · Open in the Atlas

Code that ran

4 of 4 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (1 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 2 have no contract verdict; 2 failures of our instrument; 0 no recorded run), measured 2026-11-23; 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/2508.20577.json · badge: /api/ran/2508.20577.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
kyleliang919/C-Optim community
Papers with Code archive
3 ran · 0 no recorded run
NUS-HPC-AI-Lab/MERIT community
Papers with Code archive
1 ran · 0 no recorded run
FunctionStatusWhere it lives
MERIT Ran
ran on a synthesized input
NUS-HPC-AI-Lab/MERIT/optim/merit.py
code served (permissive licence) · get_code("c6756a24b0ff22ea")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned NoneType. 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.optim import Optimizer

class MERIT(Optimizer):
    """Implements MERIT algorithm.

    Arguments:
        params (iterable): iterable of parameters to optimize or dicts defining
            parameter groups
        lr (float, optional): learning rate (default: 1e-3)
        betas (Tuple[float, float], optional): coefficients used for computing
            running averages of gradient and its square (default: (0.9, 0.999))
        eps (float, optional): term added to the denominator to improve
            numerical stability (default: 1e-8)
        weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
        adam (bool, optional): always use trust ratio = 1, which turns this into
            Adam. Useful for comparison purposes.

    """

    def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-06, weight_decay=0, adam=False):
        if not 0.0 <= lr:
            raise ValueError('Invalid learning rate: {}'.format(lr))
        if not 0.0 <= eps:
            raise ValueError('Invalid epsilon value: {}'.format(eps))
        if not 0.0 <= betas[0] < 1.0:
            raise ValueError('Invalid beta parameter at index 0: {}'.format(betas[0]))
        if not 0.0 <= betas[1] < 1.0:
            raise ValueError('Invalid beta parameter at index 1: {}'.format(betas[1]))
        defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
        self.adam = adam
        super(MERIT, self).__init__(params, defaults)

    def step(self, closure=None):
        """Performs a single optimization step.

        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            loss = closure()
        for group in self.param_groups:
            for i, p in enumerate(group['params']):
                if p.grad is None:
                    continue
                grad = p.grad.data
                if grad.is_sparse:
                    raise RuntimeError('Lamb does not support sparse gradients, consider SparseAdam instad.')
                state = self.state[p]
                if len(state) == 0:
                    state['step'] = 0
                    state['exp_avg'] = torch.zeros_like(p.data)
                    state['exp_avg_sq'] = torch.zeros_like(p.data)
                exp_avg, exp_avg_sq = (state['exp_avg'], state['exp_avg_sq'])
                beta1, beta2 = group['betas']
                state['step'] += 1
                exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
                exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
                step_size = group['lr']
                adam_step = exp_avg / exp_avg_sq.sqrt().add(group['eps'])
                if group['weight_decay'] != 0:
                    adam_step.add_(p.data, alpha=group['weight_decay'])
                if len(grad.shape) >= 2:
                    weight_abs = p.data.abs()
                    adam_abs = adam_step.abs()
                    weight_ratio = weight_abs.max() / adam_abs.max()
                    row_weight_norm = weight_abs.amax(dim=1, keepdim=True).expand_as(grad)
                    col_weight_norm = weight_abs.amax(dim=0, keepdim=True).expand_as(grad)
                    row_adam_norm = adam_abs.amax(dim=1, keepdim=True).expand_as(grad)
                    col_adam_norm = adam_abs.amax(dim=0, keepdim=True).expand_as(grad)
                    row_trust_ratio = row_weight_norm / row_adam_norm
                    col_trust_ratio = col_weight_norm / col_adam_norm
                    idx = (row_weight_norm == 0) | (row_adam_norm == 0) | (col_weight_norm == 0) | (col_adam_norm == 0)
                    trust_ratio = torch.max(col_trust_ratio, row_trust_ratio)
                    trust_ratio = trust_ratio.clamp(min=weight_ratio)
                    trust_ratio[idx] = 1
                    adam_step.mul_(trust_ratio)
                    adam_step_clip = adam_step.abs().clamp(None, 1)
                    adam_step = adam_step.sign() * adam_step_clip
                    p.data.add_(adam_step, alpha=-step_size)
                else:
                    weight_max = p.data.abs().max()
                    adam_max = adam_step.abs().max()
                    if weight_max == 0 or adam_max == 0:
                        trust_ratio = 1
                    else:
                        trust_ratio = weight_max / adam_max
                    adam_step.mul_(trust_ratio)
                    adam_step_clip = adam_step.abs().clamp(None, 1)
                    adam_step = adam_step.sign() * adam_step_clip
                    p.data.add_(adam_step, alpha=-step_size)
        return loss


# Create test parameters: a 2D weight matrix and a 1D bias vector
param_2d = torch.randn(4, 3, requires_grad=True)
param_1d = torch.randn(4, requires_grad=True)

INIT_ARGS = {
    'params': [param_2d, param_1d],
    'lr': 0.001,
    'betas': (0.9, 0.999),
    'eps': 1e-6,
    'weight_decay': 0.0,
    'adam': False,
}

ARGS = {
    'closure': None,
}

METHOD = 'step'

if __name__ == '__main__':
    optimizer = MERIT(**INIT_ARGS)
    
    # Simulate gradients
    param_2d.grad = torch
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type NoneType — a NoneType output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a NoneType 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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
Muon Ran
ran on a synthesized input · constructed an object; no result was computed
kyleliang919/C-Optim/c_muon.py
code served (permissive licence) · get_code("9ecf8c035e1046ea")
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, Muon: 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
import torch.distributed as dist
from unittest.mock import MagicMock

torch.manual_seed(0)

# Mock dist functions since we're running in single-process mode
dist.get_world_size = MagicMock(return_value=1)
dist.get_rank = MagicMock(return_value=0)
dist.all_gather = MagicMock()

# Create a simple model with hidden weight layers
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden1 = nn.Linear(4, 8)
        self.hidden2 = nn.Linear(8, 6)
    
    def forward(self, x):
        x = self.hidden1(x)
        x = self.hidden2(x)
        return x

model = SimpleModel()

# Extract parameters that should be optimized with Muon (hidden weights only)
params_to_optimize = [
    model.hidden1.weight,
    model.hidden2.weight,
]

# Simulate gradients for the parameters
for p in params_to_optimize:
    p.grad = torch.randn_like(p)

ARGS = {
    'params': params_to_optimize,
    'lr': 0.02,
    'weight_decay': 0.0,
    'momentum': 0.95,
}
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 Muon — 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 Muon 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
muon_update Ran
ran; our contract draft was wrong, not the code
kyleliang919/C-Optim/c_muon.py
code served (permissive licence) · get_code("cb1f2229e6a594f7")
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. 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)

# Create small tensors for testing
# grad: gradient tensor that will be used in lerp_, multiplication, and shape operations
grad = torch.randn(2, 4, 3, 5)  # 4D tensor for conv-like gradients

# momentum: same shape as grad, used in lerp_, multiplication, and masking operations
momentum = torch.randn(2, 4, 3, 5)

ARGS = {
    "grad": grad,
    "momentum": momentum,
    "beta": 0.95,
    "ns_steps": 5,
    "nesterov": True,
}
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, shape (2, 60) — shape (2, 60) as a later run recorded it
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
zeropower_via_newtonschulz5 Ran
ran; our contract draft was wrong, not the code
kyleliang919/C-Optim/c_muon.py
code served (permissive licence) · get_code("88b19bfaad9384f8")
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. 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)

# Construct a small matrix G for testing
# G should be at least 2D according to the assert
# Let's use a 4x3 matrix (tall matrix) to test both orientations
G = torch.randn(4, 3)

ARGS = {
    "G": G,
    "steps": 5
}
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, shape (4, 3) — shape (4, 3) as a later run recorded it
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

Also present in other papers' code

Of 4 samples lifted from this paper's linked repositories, 4 carry a function identity and 0 do not. Of the 4 distinct functions with an identity, 2 are also present in other papers whose code we hold (2 with at least one paper dated earlier, 0 the same month, 1 later) and 2 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
zeropower_via_newtonschulz5
brick of this paper's assembly: helper
4 other papers
1 dated earlier, 3 later · 1 only as an assembly brick
2411.16085 (2024-11)
Cautious Optimizers: Improving Training with One Line of Code
2603.10067 (2026-03)
HTMuon: Improving Muon via Heavy-Tailed Spectral Correction
2605.09991 (2026-05)
Optimizer-Induced Mode Connectivity: From AdamW to Muon
and 1 more not named here
muon_update
brick of this paper's assembly: update_rule
1 other paper
1 dated earlier
2411.16085 (2024-11)
Cautious Optimizers: Improving Training with One Line of Code

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-23.

Repositories linked to this paper

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

Abstract

Large-batch training has become a cornerstone in accelerating the training of deep neural networks, yet it poses challenges in optimization and generalization. Existing optimizers like AdamW present performance degradation during language models' large-batch training, due to the information bottleneck in attention layers caused by the sharp increase of max attention logit. While the LAMB optimizer partially addresses this issue, some attention layers still face this issue. The reason is that l 2 -norm-based trust ratios in LAMB are less effective in directly influencing the max value of query/key weights. Furthermore, the weightwise trust ratio in LAMB is error-prone as it overlooks relationships of weight values within rows or columns. Building on these observations, we propose a novel optimizer, MERIT, which leverages the max-norm to calculate the trust ratio to constrain the max attention logit more effectively. Moreover, we further construct element-wise trust ratios to provide more robust update scaling by focusing on local weight structures. Extensive experiments of large-batch training across various sizes of GPT-2 models demonstrate the superior performance of MERIT. Notably, during the training of GPT-2 Medium, MERIT enables a 6k batch size without any performance degradation compared to the standard batch size (480) with 48B training tokens. This work highlights the importance of considering the max attention logit and finer-granularity trust ratio in large-batch training. It successfully improves the training stability and paves the way for larger batch usage, enabling faster development and iteration of large language models. Code is available at https://github.com/NUS-HPC-AI-Lab/MERIT.

For agents

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

get_harvested_code_for_paper("2508.20577")
get_code_for_paper("2508.20577")
have("2508.20577")

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

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

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

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

Connect an agent — have() is free.