SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2103.17182 · ICML · 2021

Positive-Negative Momentum: Manipulating Stochastic Gradient Noise to Improve Generalization

Zeke Xie, Masashi Sugiyama, Zhanxing Zhu, Li Yuan

arXiv · PDF · Open in the Atlas

Code that ran

1 of 1 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 1 has no contract verdict; 0 failures of our instrument; 0 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/2103.17182.json · badge: /api/ran/2103.17182.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
zeke-xie/Positive-Negative-Momentum canonical (classifier label)
classifier basis: classifier_2025
1 ran · 0 no recorded run
FunctionStatusWhere it lives
PNM Ran
ran on a synthesized input · constructed an object; no result was computed
zeke-xie/Positive-Negative-Momentum/pnm_optim/pnm.py
code served (permissive licence) · get_code("2586fe86865ad227")
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, PNM: 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.optim.optimizer import Optimizer, required

class PNM(Optimizer):
    """Implements Positive-Negative Momentum (PNM).
    It has be proposed in 
    `Positive-Negative Momentum: Manipulating Stochastic Gradient Noise to Improve 
    Generalization`__.
    Args:
        params (iterable): iterable of parameters to optimize or dicts defining
            parameter groups
        lr (float): learning rate
        betas (Tuple[float, float], optional): inertia coefficients used for computing
            pn momentum(default: (0.9, 1.))
        weight_decay (float, optional): weight decay (default: 0)
        decoupled (bool, optional): decoupled weight decay or L2 regularization (default: True)
    """

    def __init__(self, params, lr=required, betas=(0.9, 1.0), weight_decay=0, decoupled=True):
        if lr is not required and lr < 0.0:
            raise ValueError('Invalid learning rate: {}'.format(lr))
        if not 0.0 <= betas[0] < 1.0:
            raise ValueError('Invalid beta parameter at index 0: {}'.format(betas[0]))
        if weight_decay < 0.0:
            raise ValueError('Invalid weight_decay value: {}'.format(weight_decay))
        defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay, decoupled=decoupled)
        super(PNM, self).__init__(params, defaults)

    def __setstate__(self, state):
        super(PNM, self).__setstate__(state)
        for group in self.param_groups:
            group.setdefault('decoupled', True)

    @torch.no_grad()
    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:
            with torch.enable_grad():
                loss = closure()
        for group in self.param_groups:
            beta1, beta2 = group['betas']
            for p in group['params']:
                if p.grad is None:
                    continue
                d_p = p.grad
                if group['decoupled']:
                    p.mul_(1 - group['lr'] * group['weight_decay'])
                else:
                    d_p.add_(p.data, alpha=group['weight_decay'])
                state = self.state[p]
                if len(state) == 0:
                    state['step'] = 0
                state['step'] += 1
                param_state = self.state[p]
                if state['step'] == 1:
                    pos_momentum = param_state['pos_momentum'] = torch.zeros_like(p, memory_format=torch.preserve_format)
                    neg_momentum = param_state['neg_momentum'] = torch.zeros_like(p, memory_format=torch.preserve_format)
                elif state['step'] % 2 == 1:
                    pos_momentum = param_state['pos_momentum']
                    neg_momentum = param_state['neg_momentum']
                else:
                    neg_momentum = param_state['pos_momentum']
                    pos_momentum = param_state['neg_momentum']
                pos_momentum.mul_(beta1 ** 2).add_(d_p, alpha=1 - beta1 ** 2)
                import math
                noise_norm = math.sqrt((1 + beta2) ** 2 + beta2 ** 2)
                delta_p = pos_momentum.mul(1 + beta2).add(neg_momentum, alpha=-beta2).mul(1 / noise_norm)
                p.add_(delta_p, alpha=-group['lr'])
        return loss


torch.manual_seed(0)

# Create a small model with parameters
model = nn.Linear(4, 3)

# Create parameters list
params = list(model.parameters())

# Add gradients to parameters so step() can work
for p in params:
    p.grad = torch.randn_like(p)

ARGS = {
    'params': params,
    'lr': 0.01,
    'betas': (0.9, 1.0),
    'weight_decay': 0.0,
    'decoupled': 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 PNM — 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 PNM 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

Also present in other papers' code

Of 1 samples lifted from this paper's linked repositories, 1 carry a function identity and 0 do not. Of the 1 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 1 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.

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

It is well-known that stochastic gradient noise (SGN) acts as implicit regularization for deep learning and is essentially important for both optimization and generalization of deep networks. Some works attempted to artificially simulate SGN by injecting random noise to improve deep learning. However, it turned out that the injected simple random noise cannot work as well as SGN, which is anisotropic and parameter-dependent. For simulating SGN at low computational costs and without changing the learning rate or batch size, we propose the Positive-Negative Momentum (PNM) approach that is a powerful alternative to conventional Momentum in classic optimizers. The introduced PNM method maintains two approximate independent momentum terms. Then, we can control the magnitude of SGN explicitly by adjusting the momentum difference. We theoretically prove the convergence guarantee and the generalization advantage of PNM over Stochastic Gradient Descent (SGD). By incorporating PNM into the two conventional optimizers, SGD with Momentum and Adam, our extensive experiments empirically verified the significant advantage of the PNM-based variants over the corresponding conventional Momentum-based optimizers.

For agents

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

get_harvested_code_for_paper("2103.17182")
get_code_for_paper("2103.17182")
have("2103.17182")

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

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

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

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

Connect an agent — have() is free.