SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2105.12628 · ICML · 2021

Predict then Interpolate: A Simple Algorithm to Learn Stable Classifiers

Regina Barzilay, Shiyu Chang, Yujia Bao

arXiv · PDF · Open in the Atlas

Code that ran

7 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, 0 violated it and 4 have no contract verdict; 3 failures of our instrument; 7 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/2105.12628.json · badge: /api/ran/2105.12628.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
YujiaBao/Predict-then-Interpolate marked official in Papers with Code
Papers with Code archive
7 ran · 7 no recorded run
FunctionStatusWhere it lives
CNN Ran
ran on a synthesized input
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("ca25c33b3ca5cfdf")
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 Tensor, ndim 2, dtype family float, shape (2, 128) 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
import torch.nn.functional as F

class CNN(nn.Module):

    def __init__(self, include_fc, hidden_dim):
        super(CNN, self).__init__()
        self.conv1 = nn.Conv2d(10, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout2d(0.25)
        self.dropout2 = nn.Dropout2d(0.5)
        self.fc1 = nn.Linear(9216, hidden_dim)
        self.include_fc = include_fc
        if self.include_fc:
            self.out_dim = hidden_dim
        else:
            self.out_dim = 9216

    def forward(self, input):
        x = input.view(input.shape[0], 10, 28, 28)
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        if self.include_fc:
            x = self.fc1(x)
            x = F.relu(x)
        return x


INIT_ARGS = {
    'include_fc': True,
    'hidden_dim': 128
}

ARGS = {
    'input': torch.randn(2, 10, 28, 28)
}

if __name__ == '__main__':
    model = CNN(**INIT_ARGS)
    model.eval()
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output: {output}")
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 Tensor, ndim 2, dtype family float, shape (2, 128) — shape (2, 128) 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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
EnvSampler Ran
ran on a synthesized input
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("f7ae688015090bda")
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 generator. 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 random
from torch.utils.data import Sampler

class EnvSampler(Sampler):

    def __init__(self, num_batches, batch_size, env_id, idx_list, seed=0):
        """
            Sample @num_episodes episodes for each epoch. If set to -1, iterate
            through the entire dataet (test mode)

            env_id specifies the env that we are sampling from

            idx_list is the list of data index
        """
        self.num_batches = num_batches
        self.batch_size = batch_size
        self.env_id = env_id
        self.idx_list = idx_list
        random.seed(seed)
        if self.num_batches == -1:
            self.length = (len(self.idx_list) + self.batch_size - 1) // self.batch_size
        else:
            self.length = self.num_batches

    def __iter__(self):
        """
            Return a list of keys
        """
        if self.num_batches == -1:
            random.shuffle(self.idx_list)
            for i in range(self.length):
                start = i * self.batch_size
                end = min((i + 1) * self.batch_size, len(self.idx_list))
                yield [(idx, self.env_id) for idx in self.idx_list[start:end]]
        else:
            for _ in range(self.num_batches):
                if self.batch_size < len(self.idx_list):
                    yield [(idx, self.env_id) for idx in random.sample(self.idx_list, self.batch_size)]
                else:
                    yield [(idx, self.env_id) for idx in self.idx_list]

    def __len__(self):
        return self.length


INIT_ARGS = {
    'num_batches': 3,
    'batch_size': 2,
    'env_id': 'env_0',
    'idx_list': [0, 1, 2, 3, 4, 5],
    'seed': 42
}

ARGS = {}

METHOD = '__iter__'

sampler = EnvSampler(**INIT_ARGS)
batches = list(sampler)
for batch in batches:
    print(batch)
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 generator — a generator output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a generator 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)
MLP Ran
ran on a synthesized input
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("4abbc1fe2ff8fe59")
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 tuple. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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.nn.functional as F

class MLP(nn.Module):

    def __init__(self, input_dim, hidden_dim, output_dim, dropout, depth=1):
        super(MLP, self).__init__()
        modules = [nn.Dropout(dropout)]
        last_dim = input_dim
        for i in range(depth - 1):
            modules.extend([nn.Linear(last_dim, hidden_dim), nn.Dropout(dropout), nn.ReLU()])
            last_dim = hidden_dim
        modules.append(nn.Linear(last_dim, output_dim))
        self._main = nn.Sequential(*modules)

    def forward(self, x, y=None, return_pred=False, grad_penalty=False):
        """
            @param x: batch_size * ebd_dim
            @param y: batch_size

            @return acc
            @return loss
        """
        logit = self._main(x)
        if y is None:
            return F.log_softmax(logit, dim=-1)
        loss = F.cross_entropy(logit, y)
        acc = self.compute_acc(logit, y)
        if return_pred:
            return (torch.argmax(logit, dim=1), loss)
        elif grad_penalty:
            dummy = torch.tensor(1.0).requires_grad_()
            loss_tmp = F.cross_entropy(logit * dummy, y)
            grad = torch.autograd.grad(loss_tmp, [dummy], create_graph=True)[0]
            return (acc, loss, torch.sum(grad ** 2))
        else:
            return (acc, loss)

    @staticmethod
    def compute_acc(pred, true):
        """
            Compute the accuracy.
            @param pred: batch_size * num_classes
            @param true: batch_size
        """
        return torch.mean((torch.argmax(pred, dim=1) == true).float()).item()


INIT_ARGS = {
    'input_dim': 4,
    'hidden_dim': 8,
    'output_dim': 3,
    'dropout': 0.1,
    'depth': 2
}

ARGS = {
    'x': torch.randn(2, 4),
    'y': torch.tensor([0, 2]),
    'return_pred': False,
    'grad_penalty': False
}

if __name__ == '__main__':
    model = MLP(**INIT_ARGS)
    result = model(**ARGS)
    print(f"Result: {result}")
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 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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
TextCNN Ran
ran on a synthesized input
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("6db576db849cbc06")
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 Tensor, 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.nn as nn

# Create a minimal vocab object with vectors
class MockVocab:
    def __init__(self, vocab_size=10, embedding_dim=4):
        self.vectors = torch.randn(vocab_size, embedding_dim)

vocab = MockVocab(vocab_size=10, embedding_dim=4)

INIT_ARGS = {
    'vocab': vocab,
    'finetune_ebd': False,
    'num_filters': 50,
    'dropout': 0.1
}

ARGS = {
    'x': torch.randint(0, 10, (2, 8))
}
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 Tensor, ndim 2, dtype family float — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
get_worst_acc Ran
ran; our contract draft was wrong, not the code
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("293739fa3f3d2442")
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 numpy as np

torch.manual_seed(0)

# Construct the arguments for get_worst_acc

# true and pred: tensors of shape (batch_size,) with binary values
# These should be equal for some samples and different for others
true = torch.tensor([1, 0, 1, 0, 1], dtype=torch.float32)
pred = torch.tensor([1, 0, 1, 1, 1], dtype=torch.float32)

# idx: list of tensors that will be concatenated
# These represent original indices in the dataset
idx = [torch.tensor([0, 1, 2]), torch.tensor([3, 4])]

# loss: a scalar value representing loss
loss = 0.456

# att_idx_dict: dictionary mapping attribute names to dictionaries
# The inner dictionaries map attribute values (k) to lists of original indices (v)
att_idx_dict = {
    'color': {
        'red': [0, 1],
        'blue': [2, 3, 4]
    },
    'shape': {
        'circle': [0, 2],
        'square': [1, 3, 4]
    }
}

ARGS = {
    'true': true,
    'pred': pred,
    'idx': idx,
    'loss': loss,
    'att_idx_dict': att_idx_dict
}
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 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
train_dro_loop Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("7a36ba56dd14524a")
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. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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 numpy as np
import types as _types

torch.manual_seed(0)

# Define small models
class EmbeddingModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 8)
    
    def forward(self, x):
        return self.linear(x)

class ClassifierModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(8, 3)
    
    def forward(self, x):
        return self.linear(x)

# Helper functions that will be available
def squeeze_batch(batch):
    res = {}
    for k, v in batch.items():
        assert len(v) == 1
        res[k] = v[0]
    return res

def to_cuda(d):
    for k, v in d.items():
        d[k] = v.cuda() if torch.cuda.is_available() else v
    return d

# Create model dict
model = {
    'ebd': EmbeddingModel(),
    'clf_all': ClassifierModel()
}

# Create optimizer
opt = torch.optim.SGD(
    list(model['ebd'].parameters()) + list(model['clf_all'].parameters()),
    lr=0.01
)

# Create train loaders - 2 loaders with 2 batches each
# Each batch is a dict with 'X' and 'Y' keys, values wrapped in lists for squeeze_batch
def create_batch(batch_size, num_classes):
    return {
        'X': [torch.randn(batch_size, 4)],
        'Y': [torch.randint(0, num_classes, (batch_size,))]
    }

train_loader_1 = [create_batch(2, 3), create_batch(2, 3)]
train_loader_2 = [create_batch(2, 3), create_batch(2, 3)]
train_loaders = [train_loader_1, train_loader_2]

# Create args
class Args:
    def __init__(self):
        self.dataset = 'cifar'

args = Args()

# Create utils namespace
utils = _types.SimpleNamespace(**{
    'squeeze_batch': squeeze_batch,
    'to_cuda': to_cuda
})

ARGS = {
    'train_loaders': train_loaders,
    'model': model,
    'opt': opt,
    'ep': 0,
    'args': args
}
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 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
train_loop Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("d20003ab7073cb3f")
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. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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 numpy as np
import types as _types

torch.manual_seed(0)

# Create mock utility functions that are referenced
def squeeze_batch(batch):
    res = {}
    for k, v in batch.items():
        assert len(v) == 1
        res[k] = v[0]
    return res

def to_cuda(d):
    # In CPU-only mode, just return the dict as-is
    return d

utils = _types.SimpleNamespace(**{
    'squeeze_batch': squeeze_batch,
    'to_cuda': to_cuda
})

# Create embedding model
class EmbeddingModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 8)
    
    def forward(self, x):
        return self.linear(x)

# Create classifier model
class ClassifierModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(8, 2)
    
    def forward(self, x, y, return_pred=False, grad_penalty=False):
        logits = self.linear(x)
        loss_fn = nn.CrossEntropyLoss()
        loss = loss_fn(logits, y)
        
        preds = torch.argmax(logits, dim=1)
        acc = (preds == y).float().mean()
        
        return acc, loss

# Create model dict
model = {
    'ebd': EmbeddingModel(),
    'clf_all': ClassifierModel()
}

# Create optimizer
opt = torch.optim.SGD(
    list(model['ebd'].parameters()) + list(model['clf_all'].parameters()),
    lr=0.01
)

# Create train loader - list of batches
# Each batch is a dict with 'X' and 'Y' keys
# 'X' shape: (1, 2, 4) - batch size 1, 2 samples, 4 features
# 'Y' shape: (1, 2) - batch size 1, 2 labels
train_loader = [
    {
        'X': torch.randn(1, 2, 4),
        'Y': torch.randint(0, 2, (1, 2))
    },
    {
        'X': torch.randn(1, 2, 4),
        'Y': torch.randint(0, 2, (1, 2))
    }
]

# Create args dict
args = {
    'learning_rate': 0.01,
    'epochs': 1
}

# Define ARGS with all parameters for train_loop
ARGS = {
    'train_loader': train_loader,
    'model': model,
    'opt': opt,
    'ep': 0,
    'args': args
}
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 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
Resnet50 Not yet run
unverified (harvested, no recorded run)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("ebd9154ebe926d64")
How it ran

no invocation recorded.

get_model Not yet run
unverified (harvested, no recorded run)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("b58c9caa079f744b")
How it ran

no invocation recorded.

ours Not yet run
unverified (harvested, no recorded run)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("07ef6f8504081267")
How it ran

no invocation recorded.

print_group_stats Not yet run
unverified (harvested, no recorded run)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("d6e4cdf35a01a72d")
How it ran

no invocation recorded.

print_pretrain_res Not yet run
unverified (harvested, no recorded run)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("a0f178bab1948c23")
How it ran

no invocation recorded.

print_res Not yet run
unverified (harvested, no recorded run)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("a4a4e5dc0293f2f0")
How it ran

no invocation recorded.

test_loop Not yet run
unverified (harvested, no recorded run)
YujiaBao/Predict-then-Interpolate/src/training/ours.py
code served (permissive licence) · get_code("5f76e1e3b6bc10e1")
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, 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 14 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-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

We propose Predict then Interpolate (PI), a simple algorithm for learning correlations that are stable across environments. The algorithm follows from the intuition that when using a classifier trained on one environment to make predictions on examples from another environment, its mistakes are informative as to which correlations are unstable. In this work, we prove that by interpolating the distributions of the correct predictions and the wrong predictions, we can uncover an oracle distribution where the unstable correlation vanishes. Since the oracle interpolation coefficients are not accessible, we use group distributionally robust optimization to minimize the worst-case risk across all such interpolations. We evaluate our method on both text classification and image classification. Empirical results demonstrate that our algorithm is able to learn robust classifiers (outperforms IRM by 23.85% on synthetic environments and 12.41% on natural environments). Our code and data are available at https://github.com/YujiaBao/ Predict-then-Interpolate.

For agents

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

get_harvested_code_for_paper("2105.12628")
get_code_for_paper("2105.12628")
have("2105.12628")

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

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

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

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

Connect an agent — have() is free.