SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2404.10575 · 2024

EMC$^2$: Efficient MCMC Negative Sampling for Contrastive Learning with Global Convergence

arXiv · PDF · Open in the Atlas

Code that ran

11 of 14 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, 2 violated it and 1 has no contract verdict; 8 failures of our instrument; 3 no recorded run), measured 2026-11-23; 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/2404.10575.json · badge: /api/ran/2404.10575.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
amazon-science/contrastive_emc2 canonical (classifier label)
classifier basis: census
11 ran · 3 no recorded run
FunctionStatusWhere it lives
all_gather_matrices Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
amazon-science/contrastive_emc2/communication.py
code served (permissive licence) · get_code("a05a54f3fc3dbfa9")
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 3, 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 torch.distributed as dist
from unittest.mock import MagicMock, patch

torch.manual_seed(0)

# Mock distributed backend since we're running single-process
def mock_get_world_size():
    return 1

def mock_all_gather(output_list, input_tensor):
    # Simulate all_gather by filling output list with input tensor
    for i in range(len(output_list)):
        output_list[i].copy_(input_tensor)

# Patch dist functions
dist.get_world_size = mock_get_world_size
dist.all_gather = mock_all_gather

# Create a small matrix tensor (2 samples, 4 features)
matrix = torch.randn(2, 4, dtype=torch.float32)

# Use CPU device
device = 'cpu'

ARGS = {
    'matrix': matrix,
    'device': device,
}
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 3, 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
all_gather_vectors Ran
ran on a synthesized input
amazon-science/contrastive_emc2/communication.py
code served (permissive licence) · get_code("a4d6e26b346c837e")
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 2, 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 torch.distributed as dist
from unittest.mock import MagicMock, patch

torch.manual_seed(0)

# Mock distributed environment
def mock_get_world_size():
    return 2

def mock_all_gather(output_list, input_tensor):
    """Mock all_gather that simulates gathering from 2 processes"""
    # Simulate gathering: each process contributes a copy
    for i in range(len(output_list)):
        output_list[i].copy_(input_tensor)

# Patch distributed functions
with patch.object(dist, 'get_world_size', mock_get_world_size):
    with patch.object(dist, 'all_gather', mock_all_gather):
        # Create small vector on CPU
        vector = torch.randn(3, dtype=torch.float32)
        device = torch.device('cpu')
        
        ARGS = {
            'vector': vector,
            'device': device,
        }
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 2, 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
convert_layers Ran
ran; our contract draft was wrong, not the code
amazon-science/contrastive_emc2/model.py
code served (permissive licence) · get_code("fdcddcdef8722c34")
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 SimpleModel. 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)

# Build a simple model with BatchNorm2d layers that can be converted
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3)
        self.bn1 = nn.BatchNorm2d(16)
        self.conv2 = nn.Conv2d(16, 32, kernel_size=3)
        self.bn2 = nn.BatchNorm2d(32)
        self.nested = nn.Sequential(
            nn.Conv2d(32, 64, kernel_size=3),
            nn.BatchNorm2d(64)
        )
    
    def forward(self, x):
        x = self.bn1(self.conv1(x))
        x = self.bn2(self.conv2(x))
        x = self.nested(x)
        return x

# Create model instance
model = SimpleModel()

# Define layer types for conversion
layer_type_old = nn.BatchNorm2d
layer_type_new = nn.GroupNorm

# Build the ARGS dictionary
ARGS = {
    "model": model,
    "layer_type_old": layer_type_old,
    "layer_type_new": layer_type_new,
    "convert_weights": True,
    "num_groups": 8
}
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 SimpleModel — a SimpleModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a SimpleModel 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
estimate_inner_prod Ran
ran; our contract draft was wrong, not the code
amazon-science/contrastive_emc2/cache.py
code served (permissive licence) · get_code("6e1acdb5ff584cbb")
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 1, dtype family float, 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 torch

torch.manual_seed(0)

# bit_inner: a tensor that will be used in arithmetic operations
# The function computes: cos(abs(pi - 2*pi*bit_inner/dim))
# bit_inner should be a tensor with values that make sense in this context
# Keeping it small with shape (2,) for a batch of 2 values
bit_inner = torch.tensor([0.5, 1.5], dtype=torch.float32)

# dim: an integer dimension parameter used as divisor
dim = 4

ARGS = {
    "bit_inner": bit_inner,
    "dim": dim,
}
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 1, dtype family float, 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
find_classes Ran
ran; our contract draft was wrong, not the code
amazon-science/contrastive_emc2/folder.py
code served (permissive licence) · get_code("904c357058bab2d9")
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. 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 os
import tempfile
import shutil

# Create a temporary directory with class subdirectories
temp_dir = tempfile.mkdtemp()

# Create some class folders
class_names = ["class_a", "class_b", "class_c"]
for class_name in class_names:
    class_dir = os.path.join(temp_dir, class_name)
    os.makedirs(class_dir, exist_ok=True)

ARGS = {
    "directory": temp_dir
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
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 tuple — a tuple output has no array shape of its own; none is 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
get_diagonal_blocks Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
amazon-science/contrastive_emc2/evaluation.py
code served (permissive licence) · get_code("cd3d80672004efc8")
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 3, 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

torch.manual_seed(0)

# Create a square matrix where dimensions are divisible by k
# Matrix will be 8x8, k will be 2, so we get 4 diagonal blocks of 2x2 each
matrix = torch.randn(8, 8)
k = 2

ARGS = {
    "matrix": matrix,
    "k": k,
}
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 3, 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
has_file_allowed_extension Ran
ran, violated the contract we drafted
amazon-science/contrastive_emc2/folder.py
code served (permissive licence) · get_code("aec20ef76445c38c")
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 bool, 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 numpy as np
from typing import Union, Tuple

torch.manual_seed(0)

# Construct valid arguments for has_file_allowed_extension
ARGS = {
    "filename": "document.pdf",
    "extensions": (".pdf", ".txt", ".docx")
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, 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
info_nce_loss Ran
ran; our contract draft was wrong, not the code
amazon-science/contrastive_emc2/main_simclr.py
code served (permissive licence) · get_code("044dd7c8dd4adba5")
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 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)

# Set up parameters
device = 'cpu'
batch_size = 2
n_views = 2
temperature = 1.0

# Create features tensor: (batch_size * n_views, feature_dim)
# Shape: (4, 8) - 4 samples (2 views × 2 batch), 8-dim features
features = torch.randn(batch_size * n_views, 8)

# Create a criterion that accepts logits and labels
# CrossEntropyLoss expects (N, C) logits and (N,) labels
criterion = nn.CrossEntropyLoss()

ARGS = {
    'features': features,
    'criterion': criterion,
    'device': device,
    'temperature': temperature,
    'batch_size': batch_size,
    'n_views': n_views
}
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 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
is_image_file Ran
ran, violated the contract we drafted
amazon-science/contrastive_emc2/folder.py
code served (permissive licence) · get_code("d9fa6dde50b3f702")
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 bool, 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)

# The function is_image_file takes a filename string and checks if it has an image extension
# It doesn't use any complex objects, just a string parameter

ARGS = {
    'filename': 'test_image.jpg'
}
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 bool, 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
parse_args Ran
ran; our contract draft was wrong, not the code
amazon-science/contrastive_emc2/arguments.py
code served (permissive licence) · get_code("d73de0f2b46b2268")
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 argparse

torch.manual_seed(0)

ARGS = {
    'world_size': 2,
}
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
remove_diagonal_blocks Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
amazon-science/contrastive_emc2/evaluation.py
code served (permissive licence) · get_code("5ceb2c36a8c88939")
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 2, dtype family float, shape (4, 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 torch

torch.manual_seed(0)

# Construct a square matrix where shape[0] == shape[1] and shape[1] % k == 0
# Using k=2, so we need a matrix of size (4, 4) to satisfy divisibility
matrix = torch.randn(4, 4)

# Block size k
k = 2

ARGS = {
    'matrix': matrix,
    'k': k,
}
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 2, dtype family float, shape (4, 2) — shape (4, 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
all_gather_tensors Not yet run
unverified (harvested, no recorded run)
amazon-science/contrastive_emc2/communication.py
code served (permissive licence) · get_code("0f11d82afcfe7ee7")
How it ran

no invocation recorded.

build_model Not yet run
unverified (harvested, no recorded run)
amazon-science/contrastive_emc2/model.py
code served (permissive licence) · get_code("7e5b6f7d2706cbc7")
How it ran

no invocation recorded.

linear_evaluation Not yet run
unverified (harvested, no recorded run)
amazon-science/contrastive_emc2/linear_eval.py
code served (permissive licence) · get_code("2553afafba450290")
How it ran

no invocation recorded.

Also present in other papers' code

Of 14 samples lifted from this paper's linked repositories, 14 carry a function identity and 0 do not. Of the 14 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, 2 later) and 11 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
is_image_file 12 other papers
7 dated earlier, 4 later, 1 same year, order not determinable
2203.14415 (2022-03)
Mugs: A Multi-Granular Self-Supervised Learning Framework
2204.08381 (2022-04)
Multiple-environment Self-adaptive Network for Aerial-view Geo-localization
2205.03892 (2022-05)
ConvMAE: Masked Convolution Meets Masked Autoencoders
and 9 more not named here
find_classes 2 other papers
1 dated earlier, 1 later
2204.08381 (2022-04)
Multiple-environment Self-adaptive Network for Aerial-view Geo-localization
2506.13406 (2025-06)
CALM: Consensus-Aware Localized Merging for Multi-Task Learning
has_file_allowed_extension 1 other paper
1 dated earlier
2308.09951 (2023-08)
Semantics Meets Temporal Correspondence: Self-supervised Object-centric Learning in Videos

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

A key challenge in contrastive learning is to generate negative samples from a large sample set to contrast with positive samples, for learning better encoding of the data. These negative samples often follow a softmax distribution which are dynamically updated during the training process. However, sampling from this distribution is non-trivial due to the high computational costs in computing the partition function. In this paper, we propose an Efficient Markov Chain Monte Carlo negative sampling method for Contrastive learning (EMC$^2$). We follow the global contrastive learning loss as introduced in SogCLR, and propose EMC$^2$ which utilizes an adaptive Metropolis-Hastings subroutine to generate hardness-aware negative samples in an online fashion during the optimization. We prove that EMC$^2$ finds an $\mathcal{O}(1/\sqrt{T})$-stationary point of the global contrastive loss in $T$ iterations. Compared to prior works, EMC$^2$ is the first algorithm that exhibits global convergence (to stationarity) regardless of the choice of batch size while exhibiting low computation and memory cost. Numerical experiments validate that EMC$^2$ is effective with small batch training and achieves comparable or better performance than baseline algorithms. We report the results for pre-training image encoders on STL-10 and Imagenet-100.

For agents

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

get_harvested_code_for_paper("2404.10575")
get_code_for_paper("2404.10575")
have("2404.10575")

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

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

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

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

Connect an agent — have() is free.