Module contents
Lesson 15 of 23Core 120 min

Replicating a paper: an end-to-end protocol

Distinguish repeatability, reproducibility, replicability, and robustness. Build a replication protocol with an executable specification, unknowns ledger, numerical tolerances, prespecified statistical success criterion, staged testing, and reproducible artifacts. Apply it to Lottery Ticket on MNIST and a miniature random-label memorization replication.

After this lesson you can

  • Distinguish repeatability, reproducibility, replicability, and robustness and explain what each checks.
  • Extract an executable specification and unknowns ledger prioritized by expected impact from a paper.
  • Fix a replication success criterion before execution using equivalence, direction, or small telescopes.
  • Replicate a real result in stages and classify the outcome as replicated, smaller effect, failed, or inconclusive.
  • Prepare reproducible publication artifacts following the NeurIPS checklist.

Before you start

A claim needs an independent test

A paper reports that a procedure works; a replication asks what happens when a predefined protocol is applied to that claim. Pineau and colleagues’ report on the NeurIPS reproducibility program describes practical difficulties accessing code, hyperparameters, and other details. Publishing a figure is insufficient: another person must be able to reconstruct the comparison and understand changes.

Reproducibility terminology is not universal. Following NASEM, here computational reproducibility means obtaining consistent results using the same data and methods; replicability means consistent results in studies obtaining new data for the same question. We use repeatability for repetition under close conditions and robustness for examining reasonable changes. Another field may assign different words: define the protocol before debating labels.

Another machine with the same data and code tests portability; an independent reimplementation tests sensitivity to decisions and code errors; changing dataset examines generalization. Another seed reveals initialization or sampling variation. None alone implies transfer to every population.

Conditions form a continuum and can combine. Repeating days later on the same machine tests preservation of recipe and inputs. Running the same code elsewhere adds library and hardware differences. Varying only the seed measures one source of variation but does not amount to obtaining another population sample. Another reasonable preprocessing tests robustness to a methodological choice; another dataset tests transfer under that dataset’s properties. A reimplementation may still share data, hyperparameter selection, or conceptual errors with the original, so independence also has degrees.

From figure to specification

A replication protocol fixes claim, unit, metric, data, controls, budget, seed distribution, and success criterion. Read text, appendix, figures, and original code where available; record conflicts and decisions. The unknowns ledger lists unresolved options, choice adopted, justification, and sensitivity test. Prioritize by likelihood of changing the conclusion and cost to resolve. A choice made after inspecting results is exploratory even when well explained.

For the Lottery Ticket Hypothesis, the paper describes LeNet-300-100, Glorot normal initialization, Adam at 0.0012, batches of 60, and iterative per-layer pruning of 20% in hidden layers and 10% at output. Surviving weights are restored to their initialization. On MNIST each stage lasts 50,000 steps; evaluation occurs every 100 and stopping is retrospectively determined by validation loss. The paper reports means over five trials and finds subnetworks learning with accuracy comparable to the dense network. Specifying remaining fraction, checkpoint, reinitialization control, and tolerance prevents turning any result into success.

This lesson’s implementation is a reimplementation: it uses all 60,000 training images, measures at each stage’s end, and does not retrospectively select by validation loss. The paper held out 5000 images for validation and trained with 55,000, shuffled per epoch; here sampling is with replacement. We use Glorot normal initialization and zero biases, per-layer pruning, and weight resetting; biases remain trainable. These decisions matter and limit comparison with the paper’s figure. Final accuracy is not the same estimate as accuracy at the original early-stopping point.

The unknowns ledger makes the difference between a known fact and a choice explicit. Pruning rate and granularity are described in the appendix and followed locally; measuring at the last step departs from validation selection and is declared. Resetting surviving weights to original initialization asks a different question from retaining trained values. A same-mask control with fresh initialization helps identify that particular initialization’s contribution. Biases are not counted among pruned weights, and a global fraction can hide layer differences. One architecture and MNIST do not validate the recipe for large networks or distributed training.

InteractiveDecision ledger

In appendix G.4, rates 0.1 and 0.2 retain higher accuracy and speed than rates of 0.4 or above in their LeNet experiment.

Consult the primary source. Sensitivity outside that architecture or dataset requires another measurement.

Recorded choice20% hidden; 10% output
Review protocol choices, published results, and the separately identified comparison measured in our campaign.
InteractiveSteps of a reproduction
  1. Run original code — Dependencies, files and environment
  2. Reproduce the numbers
  3. Reimplement
  4. Vary seeds
  5. Change dataset
Error or limitation exposedDependencies, files and environment
Advance through increasingly demanding tests and observe the limitation each can reveal.

Criteria before seeing results

Success criteria answer different questions. Direction agreement asks whether the estimate keeps its sign; a superiority test asks for evidence against zero; equivalence asks whether the difference lies within a useful margin. Failing to reject equality does not prove equivalence. If two independent estimates have standard errors so,srs_o,s_r, their difference has error so2+sr2\sqrt{s_o^2+s_r^2}. For two-sided TOST at 5%, its 90% interval must lie entirely within [−Δ,Δ][-\Delta,\Delta]. The margin is justified before data and expressed in metric units.

The small-telescopes proposal asks whether replication excludes effects the original study had a reasonable probability of detecting. Here d33 is the standardized effect a two-sided t-test with 20 observations per group, equal variances, and 0.05 level would detect with 33% power: approximately 0.493. It is a detectability threshold, not truth or a universal margin. A replication with a wide interval can be inconclusive even if its estimate is small.

InteractiveThree questions, three conclusions
OriginalReplicationEffect; dashed line: d33 = 0.493

The band marks the margin around the original estimate and bars are individual 95% CIs. Equivalence uses the 90% CI of the difference: [-0.53, 0.03]. The three criteria answer different questions.

0.65
0.40
0.12
0.20
Equivalence to originalNot established
Direction and significancePositive and significant
Small telescopeSmaller effect not established
Compare individual estimates and intervals with equivalence, direction, and small-telescope criteria.

The line shows individual 95% intervals; equivalence is decided using the difference interval, not visual overlap. The figure’s d33 threshold belongs to the specific example of two groups of 20 and does not automatically apply to other units.

A useful classification separates four outcomes. A result is consistent under a specific criterion when it meets its prespecified tolerance; it may retain direction without proving equivalence. A replication compatible with a smaller effect excludes a relevant threshold with adequate precision. Contradiction requires evidence against a quantitative prediction, not just a p-value above 0.05. When the interval includes both the acceptable margin and relevant discrepancies, the result is inconclusive. Publishing the interval and design differences enables interpretation beyond a label.

Local lab: tickets on MNIST

Before running, we fixed five seeds, nine stages, and comparison at stage 7, with approximately one fifth of original weights. We compare final ticket accuracy in pairs with the dense network and a network receiving the same mask but freshly initialized weights. The predefined practical margin for ticket minus dense is ±0.005 accuracy, half a percentage point. With five seeds, a paired 90% t interval within that margin indicates equivalence under the model used; outside or overlapping the margin can mean difference or an inconclusive result. The reinitialization control helps distinguish initialization from mask without establishing universal causality.

The cell downloads MNIST from Google’s public copy, uses PyTorch and GPU if available, saves each stage in JSON, and can take a long time: 2.5 million optimization steps, excluding download. Test is consulted after each stage to show the curve; it must not be used to choose a new stage and present that choice as confirmatory. Five seeds share the same test, so the between-seed interval does not capture variation from a new example population. Record versions, hardware, and GPU nondeterminism.

The first dense run on the shared GPU took 1495 seconds and obtained 0.9821 accuracy; that measurement was retained but its weights were not, and it does not test the subnetwork hypothesis. In a short MNIST test CPU was faster for this small model. We therefore ran the full campaign on one CPU thread, including all controls, so stage comparison uses the same device; the first CPU stage took 273 seconds and obtained 0.9815. The environment uses Python 3.12.14, PyTorch 2.11.0+cu128, and NumPy 2.5.4. These are measurements on this machine and load, not a universal CPU-versus-GPU benchmark. To choose CPU for the cell, set environment variable LOTTERY_DEVICE to cpu.

The local run needs Python, NumPy, PyTorch, SciPy, and Matplotlib. Before a campaign, save the exact environment dependency list, driver version, GPU model, code, and hashes of downloaded MNIST files. Do not use test as a stopping criterion or tune the margin after seeing the curve. Result JSON retains seeds, round, fraction, accuracy, and elapsed time of the ticket’s last run; that time excludes the fresh control and, if a stage resumes, counts only from resumption. Another environment may produce different figures. Every 5000 steps model, optimizer, and generator states are saved; after each stage mask and initialization are saved for the next. An interruption loses at most steps after the last checkpoint. Resume with the same device and environment and retain original data; GPU may have additional nondeterminism.

[ ]Local lottery replicationLocal GPU
"""MNIST iterative magnitude pruning; transparent local reproduction.

Five seeds, nine pruning rounds, 50,000 optimizer steps per round.
At round 7 compare original-initialized ticket and same mask with a fresh
initialization. The margin is fixed before seeing results: half a percentage
point. This is an endpoint comparison, not the original paper's retrospective
validation-loss early stopping protocol.
"""
import copy, gzip, json, os, pathlib, struct, time, urllib.request
import numpy as np
import torch
from torch import nn

torch.set_num_threads(1)
ROOT = pathlib.Path.cwd() / 'lottery-mnist'
ROOT.mkdir(parents=True, exist_ok=True)
DATA = ROOT / 'mnist'
DATA.mkdir(parents=True, exist_ok=True)
BASE = 'https://storage.googleapis.com/cvdf-datasets/mnist/'
def load(name):
    path = DATA / (name + '.gz')
    if not path.exists():
        urllib.request.urlretrieve(BASE + name + '.gz', path)
    with gzip.open(path, 'rb') as f:
        magic, n = struct.unpack('>II', f.read(8))
        if magic == 2051:
            rows, cols = struct.unpack('>II', f.read(8))
            return np.frombuffer(f.read(), np.uint8).copy().reshape(n, rows * cols)
        assert magic == 2049
        return np.frombuffer(f.read(), np.uint8).copy()

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = nn.ModuleList([nn.Linear(784, 300), nn.Linear(300, 100), nn.Linear(100, 10)])
        for layer in self.layers:
            nn.init.xavier_normal_(layer.weight)
            nn.init.zeros_(layer.bias)
    def forward(self, x):
        return self.layers[2](torch.relu(self.layers[1](torch.relu(self.layers[0](x)))))

def train(initial, masks, seed, x, y, xt, yt, steps=50000, progress_key='default'):
    torch.manual_seed(seed)
    model = Net().to(x.device)
    model.load_state_dict(initial)
    with torch.no_grad():
        for layer, mask in zip(model.layers, masks): layer.weight.mul_(mask)
    optimizer = torch.optim.Adam(model.parameters(), lr=.0012)
    generator = torch.Generator(device=x.device).manual_seed(seed + 12345)
    progress = ROOT / ('lottery-progress-' + progress_key + '.pt')
    saved = torch.load(progress, map_location=x.device, weights_only=False) if progress.exists() else None
    start = saved['step'] if saved else 0
    if saved:
        model.load_state_dict(saved['model'])
        optimizer.load_state_dict(saved['optimizer'])
        generator.set_state(saved['generator'].cpu())
        torch.set_rng_state(saved['torch_rng'].cpu())
    for step in range(start, steps):
        idx = torch.randint(len(y), (60,), generator=generator, device=x.device)
        loss = nn.functional.cross_entropy(model(x[idx]), y[idx])
        optimizer.zero_grad(set_to_none=True)
        loss.backward()
        for layer, mask in zip(model.layers, masks): layer.weight.grad.mul_(mask)
        optimizer.step()
        with torch.no_grad():
            for layer, mask in zip(model.layers, masks): layer.weight.mul_(mask)
        if (step + 1) % 5000 == 0 or step + 1 == steps:
            temporary = progress.with_suffix('.tmp')
            torch.save({'step': step + 1, 'model': model.state_dict(),
                        'optimizer': optimizer.state_dict(), 'generator': generator.get_state(),
                        'torch_rng': torch.get_rng_state()}, temporary)
            temporary.replace(progress)
            print('checkpoint', progress_key, step + 1, flush=True)
    with torch.no_grad():
        acc = (model(xt).argmax(1) == yt).float().mean().item()
    return model, acc

def prune(model, masks):
    result = []
    for i, (layer, mask) in enumerate(zip(model.layers, masks)):
        active = torch.nonzero(mask.flatten(), as_tuple=False).flatten()
        count = int(len(active) * (.1 if i == 2 else .2))
        chosen = active[torch.argsort(layer.weight.detach().abs().flatten()[active])[:count]]
        new = mask.flatten().clone()
        new[chosen] = 0
        result.append(new.reshape_as(mask))
    return result

def main():
    device = torch.device(os.environ.get('LOTTERY_DEVICE', 'cuda' if torch.cuda.is_available() else 'cpu'))
    x = torch.tensor(load('train-images-idx3-ubyte'), device=device, dtype=torch.float32) / 255
    y = torch.tensor(load('train-labels-idx1-ubyte'), device=device, dtype=torch.long)
    xt = torch.tensor(load('t10k-images-idx3-ubyte'), device=device, dtype=torch.float32) / 255
    yt = torch.tensor(load('t10k-labels-idx1-ubyte'), device=device, dtype=torch.long)
    checkpoint = ROOT / 'lottery-checkpoint.pt'
    state = torch.load(checkpoint, map_location=device, weights_only=False) if checkpoint.exists() else None
    out = state['out'] if state else {'device': str(device), 'torch': torch.__version__, 'steps': 50000, 'runs': []}
    first_seed = state['seed'] if state else 0
    for seed in range(first_seed, 5):
        torch.manual_seed(seed)
        model = Net().to(device)
        initial = copy.deepcopy(model.state_dict())
        masks = [torch.ones_like(layer.weight) for layer in model.layers]
        first_round = state['next_round'] if state and seed == first_seed else 0
        if first_round:
            initial, masks = state['initial'], state['masks']
        for round_ in range(first_round, 9):
            t = time.monotonic()
            key = f'{seed}-{round_}-ticket'
            model, acc = train(initial, masks, seed * 100 + round_, x, y, xt, yt, progress_key=key)
            fraction = sum(m.sum().item() for m in masks) / sum(m.numel() for m in masks)
            row = {'seed': seed, 'round': round_, 'fraction': fraction, 'ticket': acc, 'seconds': time.monotonic()-t}
            if round_ == 7:
                torch.manual_seed(seed + 100000)
                fresh = Net().to(device).state_dict()
                _, row['fresh'] = train(fresh, masks, seed * 100 + round_, x, y, xt, yt, progress_key=f'{seed}-{round_}-fresh')
            out['runs'].append(row)
            (ROOT / 'lottery-results.json').write_text(json.dumps(out, indent=2))
            print(json.dumps(row), flush=True)
            masks = prune(model, masks)
            temporary = checkpoint.with_suffix('.tmp')
            torch.save({'seed': seed, 'next_round': round_ + 1, 'initial': initial,
                        'masks': masks, 'out': out}, temporary)
            temporary.replace(checkpoint)
            (ROOT / ('lottery-progress-' + key + '.pt')).unlink(missing_ok=True)
            if round_ == 7:
                (ROOT / f'lottery-progress-{seed}-{round_}-fresh.pt').unlink(missing_ok=True)

if __name__ == '__main__': main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

After the run, plot accuracy against remaining fraction and calculate the paired interval at the recorded stage. The t interval depends on five approximately independent seed differences; the same test sample is still shared. The fresh control uses each trajectory’s chosen mask, not a new mask.

[ ]Curve and predefined criterionLocal GPU
import json
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import t
rows=json.loads((Path.cwd()/'lottery-mnist'/'lottery-results.json').read_text())['runs']
assert len(rows)==45, 'La campaña completa requiere cinco semillas y nueve etapas'
for seed in range(5):
    run=[r for r in rows if r['seed']==seed]
    plt.plot([r['fraction'] for r in run],[r['ticket'] for r in run],marker='.',alpha=.6)
plt.xlabel('Fracción de pesos restantes');plt.ylabel('Precisión test al final')
plt.gca().invert_xaxis();plt.title('Cinco trayectorias');plt.show()
dense=np.array([next(r['ticket'] for r in rows if r['seed']==s and r['round']==0) for s in range(5)])
selected=[next(r for r in rows if r['seed']==s and r['round']==7) for s in range(5)]
ticket=np.array([r['ticket'] for r in selected]); fresh=np.array([r['fresh'] for r in selected])
diff=ticket-dense; half=t.ppf(.95,4)*diff.std(ddof=1)/np.sqrt(5)
ci=(diff.mean()-half,diff.mean()+half)
print('billete menos densa: media, IC 90 %:',diff.mean(),ci)
print('equivalencia ±0.005:',ci[0]>-.005 and ci[1]<.005)
print('billete menos reinicializado, cinco pares:',ticket-fresh)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Our run completed all nine stages and the five-seed control. At the prespecified fraction 0.21074, mean accuracy was 0.98156 for the dense network, 0.98412 for the ticket, and 0.98028 for the same mask with fresh initialization. Paired ticket-minus-dense difference was 0.00256, with 90% t interval [0.00079, 0.00433]. The interval lies within the prespecified ±0.005 margin: under this criterion practical equivalence to the dense network is observed. All five ticket-minus-fresh-control differences were positive; their mean was 0.00384 and paired 95% t interval [0.00121, 0.00647]. The latter interval describes one comparison with only five seeds and the same shared test.

The result supports the qualitative claim in this MNIST implementation at training end, but does not reproduce the original validation stopping rule or establish that the advantage persists for other data or architectures. The between-seed interval excludes uncertainty from selecting a new test set. A computer restart interrupted one stage, resumed from checkpoint; recorded time for that stage is only elapsed time since resumption. Accuracies are real campaign measurements, not generated figure values.

Lab: memorizing random labels

Zhang and colleagues studied deep networks’ capacity to fit random labels. Here we do not replicate their architecture or scale: we use 200 digits images, one hidden layer, and three replacement rates. Epochs to reach 100% training accuracy are counted. A random label can match the original, so the chosen replacement fraction is not exactly the changed fraction. Perfect training does not demonstrate generalization, and wall time depends on hardware and load.

[ ]Data and labelsBrowser
import numpy as np
from sklearn.datasets import load_digits
from sklearn.neural_network import MLPClassifier
g=np.random.default_rng(15)
X,y=load_digits(return_X_y=True)
idx=g.choice(len(y),200,replace=False); X=X[idx]/16; y=y[idx]
noise=g.integers(0,10,len(y)); order=g.permutation(len(y))
def target(f):
    t=y.copy(); chosen=order[:int(f*len(y))];t[chosen]=noise[chosen]
    return t
print('fracción realmente cambiada:',[(f,np.mean(target(f)!=y)) for f in [0,.5,1.]])
[ ]Fit the three networksBrowser
import time
def memorize(f):
    labels=target(f)
    model=MLPClassifier(hidden_layer_sizes=(256,),solver='adam',alpha=0,
        learning_rate_init=.01,batch_size=100,max_iter=1,random_state=31)
    start=time.perf_counter()
    for epoch in range(1,121):
        model.partial_fit(X,labels,classes=np.arange(10))
        if np.mean(model.predict(X)==labels)==1: break
    return epoch,np.mean(model.predict(X)==labels),round(time.perf_counter()-start,3)
print([(f,memorize(f)) for f in [0,.5,1.]])

In a Pyodide run with seed 15, actual changed fractions were 0, 0.46, and 0.91; networks reached 100% accuracy on their training labels in 13, 36, and 38 epochs and took 0.337, 0.803, and 0.984 seconds respectively. Wall times depend on load and browser, so need not grow monotonically in every run. Epoch count is another work measure for this configuration. Execution stops at 120 epochs; if a network does not reach 100%, report the observed result. Change the seed to study variation without selecting only the most favorable.

Publish so others can check

The reproducibility checklist asks about assumptions, limits, experimental details, error bars, resources, and artifacts. Consult the current NeurIPS checklist and explain negative or inapplicable answers. A research artifact includes code and revision, runnable instructions, dependencies and versions, data access and license, seeds, configuration, disaggregated metrics, and known errors. A model card documents intended use, evaluation, and limits. Check the package from a clean installation: an isolated code file without environment or data does not guarantee even repeatability.

Exercises

Numeric
Two groups of 20, two-sided t-test at 5% with equal variances. What d yields 33% power?
Quiz
What best tests sensitivity to details omitted from the original code?
Proof
Prove: Classify what each change tests using this lesson's definitions.
0
The starting point is a documented run with one dataset and seed.

Step 1 of 3. Same code and data on another machine; same machine days later: what is examined first?

Quiz
Which lottery replication decisions deserve highest priority in the ledger?
Code
Implement classify_replication(orig_est, orig_se, rep_est, rep_se, margin). Return a tuple (equivalent, significant_positive_direction), using a 90% normal interval for the difference and a two-sided 95% interval for the replication.
def classify_replication(orig_est, orig_se, rep_est, rep_se, margin):
  pass
Shift+Enter to run
Key idea
Specify claim and tolerance before running, document unknowns, and retain results from all seeds. Equivalence, direction, and generalization are different questions.