Strong baselines and fair comparisons
Evaluate improvements against well-tuned baselines using evidence from Melis et al., Lucic et al., Musgrave et al., and Dacrema et al.; tuning-budget parity; Dodge et al.'s expected-maximum curve; compute-matched comparisons; and a ladder of trivial baselines and oracles.
After this lesson you can
- Build a baseline ladder including trivial, simple, retuned standard, state-of-the-art, and oracle alternatives.
- Match tuning budgets and explain the bias in comparing best results under unequal budgets.
- Derive and implement expected maximum performance as a function of tuning-trial count.
- Compare methods at matched compute and on a performance-cost Pareto frontier.
- Measure the difference between a baseline's reported figure and a careful reproduction.
Before you start
An improvement needs a strong comparator
A new method exceeds a published figure by two points. Does it also beat the previous method with the same tuning effort, data, and selection criterion? The difference may be real while failing to measure only the contribution being attributed. A strong baseline is a relevant alternative implemented and tuned under a documented protocol that tests the specific claim.
Melis and colleagues reevaluated language models with extensive tuning and found well-regularized LSTMs highly competitive on the tasks studied. Lucic and colleagues observed that several GANs reached similar results with sufficient tuning and restarts in their experiments. Musgrave and colleagues found methodological problems in metric-learning comparisons. In recommendation, Ferrari Dacrema and colleagues reproduced seven of eighteen studied methods and found that six were often outperformed by simple alternatives under their conditions. None of these studies proves that every improvement in its field is illusory.
The baseline ladder can start with majority class or average, continue with a simple method, a retuned standard implementation, and strong recent alternatives. An oracle represents information or capability unavailable in the real problem; define precisely what advantage it receives before using it as a bound. If a figure is unavailable or incomparable, leave it missing. The figure uses published Penn Treebank perplexities, where lower is better, and Recall@1 of pretrained networks for CUB200, where higher is better. Configurations are not identical in every detail.
In the cited table, Zaremba’s medium LSTM has test perplexity 82.7; Melis’s 10M two-layer LSTM, 60.8; the 10M depth-5 RHN, 63.5. The latter two use shared embeddings and study tuning, whereas the first is an earlier result. Do not attribute the entire difference to one decision without a control isolating it. A baseline may be strong on one metric and weak on another; also check latency, memory, and data regime if part of the question.
Choose alternatives that can genuinely win
A trivial baseline is a sanity check, not a sufficient alternative for a scientific improvement claim. In imbalanced classification, always predicting the majority class may yield high accuracy without detecting the minority class. Add a metric reflecting error costs and a simple baseline using information available at prediction time. If the method does not beat that control, review data, split, and metric before increasing complexity.
A standard baseline can be old yet strong. Its implementation should respect the same information set, evaluation unit, and data access as the proposed method. For time series, do not allow any alternative future observations; for recommendations, check that candidate items and exclusion of previously seen items are identical. A comparator denied information available to the new method does not answer superiority under comparable conditions.
An oracle needs a concrete definition. It may know a future label or retrospectively choose the best prediction per example, impossible at deployment. Its score can serve as an upper reference for that scenario, but need not be an attainable goal. An analytical bound, a Bayes decision known in simulation, and a system with privileged information are distinct objects. If you cannot calculate an oracle under well-defined conditions, do not fill its bar with an imagined value.
Budget and selection
Tuning-budget parity means defining resources assigned to each search before comparing. If two methods have the same trial-result distribution, the maximum of twenty trials tends to exceed the maximum of five. The method need not be better: it has more opportunities. The panel simulates independent uniform draws to show the mechanism; it does not use real results.
Equal trial counts do not necessarily equalize time or FLOPs. One trial may take longer or fail more often; a wider search space may be harder to explore. Report both budgets and the search algorithm, including restarts and stopping rules. A fair comparison does not mean identical hyperparameters: both methods need a reasonable, documented opportunity for tuning given the question and resources.
What counts as a trial?
A search consists of a distribution or strategy proposing configurations, training, a stopping rule, and evaluation. If a method uses a prior search on another dataset to choose its space, that information is also part of development. Trials do not all cost the same: a large network may take longer than logistic regression, and a diverging configuration may stop early. Record total cost, not just the best training time.
The hyperparameter space is part of the procedure. Comparing twenty draws from a reasonable space against twenty from a poorly chosen one can still be unfair. Document ranges, logarithmic or linear scales, and constraints. Prior knowledge can justify different ranges for different methods, but should be visible. If one receives iterative manual search and another defaults only, trial count does not describe the whole development advantage.
The selection criterion matters as much as attempt count. Choosing the best validation checkpoint each epoch and then the best of many configurations creates more opportunities to overfit validation. Test must not enter that choice. Record validation for every configuration and evaluate the finally fixed recipe on a holdout. If that holdout has been examined, call the analysis exploratory and obtain a new independent evaluation for a confirmatory claim.
Expected maximum of a search
The expected maximum performance of Dodge and colleagues describes the validation result expected with a given number of trials. Let be a sorted list and its empirical distribution. For independent draws with replacement, . The maximum’s mass at each value is the difference of cumulative-distribution powers; multiplying by the value and summing gives its expectation.
With sorted observations, a form that also handles ties is
Terms for repeated values sum to the correct joint mass. This is an expectation under the empirical distribution and sampling with replacement; a search without replacement, adaptive, or conditioned on earlier results has a different distribution. The validation curve is not a direct estimate of the selected model’s test performance, especially after many validation consultations.
In this particular sample, MLP slightly exceeds logistic regression in expected maximum with one trial, while logistic exceeds it from two onward; there is no universal ranking. Search spaces, split, and one training seed influence the result. Bootstrap bands reflect variation from resampling twelve scores, not dependence, space selection, or between-dataset uncertainty.
Understand the formula and its limits
For a value , the maximum of draws does not exceed exactly when none of the draws exceeds it. Under independence, probability is . The probability that the maximum takes a particular value is the difference between the cumulative distribution there and just before it. Multiplying each value by its probability and summing gives the expectation. Ties group the mass of repeated indices; the sorted formula still works by telescoping.
The empirical curve is nondecreasing when maximizing because adding a draw cannot reduce the maximum of a coupled sequence. For a minimized loss, use expected minimum or change sign and state the convention. For perplexity lower is better; for accuracy higher is better. Accidentally reversing orientation can make a worse method appear to win.
Bootstrap resamples observed results and recalculates the curve. With twelve configurations, many repetitions do not create new configurations or eliminate search-space bias. Bands can be narrow if observed results are similar even when the real space has unexplored regions. An adaptive Bayesian search need not produce independent identically distributed trials; simulate or repeat its full procedure instead of mechanically applying this formula.
Lab: three real searches
Use digits with 600 training, 300 validation, and 300 test examples selected by a fixed permutation; the rest are unused. Twelve configurations are drawn for logistic regression, gradient boosting, and MLP from spaces declared in code. Each search cell reuses preparation. Figure results were generated in CPython; other versions or runtimes can vary. Wall times measured under shared load are descriptive and do not generally compare hardware.
The exploratory preparation also calculated test for every configuration, although the displayed choice used validation. Those results are therefore not blind confirmatory evaluation. The code below calculates test only for each method’s chosen configuration; to confirm a new decision, reserve a genuinely unconsulted set and fix the procedure before opening it.
import warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.exceptions import ConvergenceWarning
X,y=load_digits(return_X_y=True);X=X/16
ids=np.random.default_rng(31).permutation(len(y));train,valid,test=ids[:600],ids[600:900],ids[900:1200]
rng=np.random.default_rng(51)
settings={'logistic':[{'C':float(10**rng.uniform(-3,2))} for _ in range(12)],
'boosting':[{'learning_rate':float(10**rng.uniform(-1.5,-.2)),'n_estimators':int(rng.choice([20,35,50])),'max_depth':int(rng.choice([1,2,3]))} for _ in range(12)],
'mlp':[{'hidden':int(rng.choice([8,16,32,64])),'alpha':float(10**rng.uniform(-5,-1)),'learning_rate_init':float(10**rng.uniform(-3,-1.5))} for _ in range(12)]}
def run_search(name, start=0, stop=12):
out=[]
for i in range(start,stop):
setting=settings[name][i]
if name=='logistic':model=LogisticRegression(max_iter=120,**setting)
elif name=='boosting':model=GradientBoostingClassifier(random_state=31,**setting)
else:model=MLPClassifier(hidden_layer_sizes=(setting['hidden'],),alpha=setting['alpha'],learning_rate_init=setting['learning_rate_init'],max_iter=80,random_state=31)
with warnings.catch_warnings():
warnings.simplefilter('ignore',ConvergenceWarning);model.fit(X[train],y[train])
out.append({'trial':i,'params':setting,'validation':float(model.score(X[valid],y[valid])),'model':model})
return out
def expected_max(values,nmax):
x=np.sort(np.asarray(values,dtype=float));m=len(x);F=np.arange(1,m+1)/m;prev=np.arange(m)/m
return np.array([np.sum(x*(F**n-prev**n)) for n in range(1,nmax+1)])
results={}
results['logistic']=[]
results['logistic'].extend(run_search('logistic',0,4))
print('logistic 1-4', [round(r['validation'],3) for r in results['logistic'][0:4]])results['logistic'].extend(run_search('logistic',4,8))
print('logistic 5-8', [round(r['validation'],3) for r in results['logistic'][4:8]])results['logistic'].extend(run_search('logistic',8,12))
print('logistic 9-12', [round(r['validation'],3) for r in results['logistic'][8:12]])results['boosting']=[]
results['boosting'].extend(run_search('boosting',0,2))
print('boosting 1-2', [round(r['validation'],3) for r in results['boosting'][0:2]])results['boosting'].extend(run_search('boosting',2,4))
print('boosting 3-4', [round(r['validation'],3) for r in results['boosting'][2:4]])results['boosting'].extend(run_search('boosting',4,6))
print('boosting 5-6', [round(r['validation'],3) for r in results['boosting'][4:6]])results['boosting'].extend(run_search('boosting',6,8))
print('boosting 7-8', [round(r['validation'],3) for r in results['boosting'][6:8]])results['boosting'].extend(run_search('boosting',8,10))
print('boosting 9-10', [round(r['validation'],3) for r in results['boosting'][8:10]])results['boosting'].extend(run_search('boosting',10,12))
print('boosting 11-12', [round(r['validation'],3) for r in results['boosting'][10:12]])results['mlp']=[]
results['mlp'].extend(run_search('mlp',0,4))
print('mlp 1-4', [round(r['validation'],3) for r in results['mlp'][0:4]])results['mlp'].extend(run_search('mlp',4,8))
print('mlp 5-8', [round(r['validation'],3) for r in results['mlp'][4:8]])results['mlp'].extend(run_search('mlp',8,12))
print('mlp 9-12', [round(r['validation'],3) for r in results['mlp'][8:12]])rng=np.random.default_rng(31)
for name,rows in results.items():
values=np.array([r['validation'] for r in rows])
curves=np.array([expected_max(rng.choice(values,len(values),replace=True),12) for _ in range(1000)])
best=max(rows,key=lambda r:r['validation'])
print(name,'Emax n=1,2,12',np.round(expected_max(values,12)[[0,1,11]],4),
'bootstrap n=5',np.round(np.quantile(curves[:,4],[.025,.975]),4),
'test de la configuración seleccionada',round(float(best['model'].score(X[test],y[test])),4))
Compute and the Pareto frontier
A compute-matched comparison measures quality attainable under a relevant budget. Equal epoch counts do not imply equal time, energy, or FLOPs when methods have different costs. The Pareto frontier contains nondominated points: one point dominates another if it costs no more, performs no worse, and strictly improves at least one dimension. The observed frontier depends on tested configurations, hardware, and cost measure.
A quality curve against cumulative search cost is more informative for a team choosing a recipe under a limited budget than the fit and evaluation time of the sole winner. Distinguish training, search, evaluation, and inference. Wall time depends on concurrency, initialization, caches, and hardware; record repetitions and distribution if used for a cost decision. This cloud is illustrative and its times were measured in a shared session.
Compare under a real constraint
Imagine a budget allowing one hour of search and ten thousand predictions per second in production. A method may dominate accuracy at equal trial count but lose when each trial takes ten times longer; another may train cheaply but have slow inference. The frontier should use quantities relevant to the decision and may need more than two axes. Do not combine training time and inference latency into one figure without justifying the weighting.
A dominated point in one sample can cease to be dominated when hardware changes or accuracy uncertainty is large. Panel point boundaries are calculated from available measurements, not statistical intervals or exhaustive search. A robust comparison repeats timings, controls load, and records device. Theoretical FLOPs omit memory, parallelism, and library effects; wall time includes them but also environment variation.
The panel’s trial order indicates when a configuration appeared in one sequence, not cumulative time spent. To build a genuine accumulated-compute curve, order trials as run, sum costs, and record the best available value after each. If trials run in parallel, distinguish clock time from device-hours. Exploratory frontier points suggest where to invest budget; independent evaluation should check the final choice.
The reproduction gap
The reproduction gap compares a published figure with a rerun under sufficiently equivalent conditions. Record dataset version, vocabulary, preprocessing, architecture, optimizer, search, selection rule, and metric before subtracting numbers. A result on another subset or duration can illustrate protocol sensitivity, but its difference from the published figure does not identify a reproduction gap.
A protocol for interpreting discrepancies
Start with the original work’s figure, version, and metric definition. Then record the replication environment and a differences table: data and split, model size, hyperparameter selection, training time, seed, checkpoint, and evaluation. If the figure is not reproduced, first check preprocessing and a minimal run. A discrepancy may reveal an error, a legitimate implementation difference, or insufficient description; do not attribute a cause until isolating it.
Replicating an architecture does not imply reproducing the entire search protocol. Reproducing the figure also needs sufficiently comparable data, metric, selection, and budget, and may require several seeds. The reduced adaptation below shares architecture family and corpus, but not training duration or size. Its result helps teach how to construct a comparison, not conclude that Zaremba’s figure is wrong or Melis’s progress disappears generally.
Local lab: reduced recurrent comparison
Zaremba and colleagues report test perplexity 114.5 for a small unregularized LSTM: two layers of 200 units, uniform initialization in [-0.1,0.1], batch 20, 20 steps, and 13 epochs. The following GPU test uses the PTB corpus from their repository, but only 20,000 training tokens, 5,000 validation and 5,000 test tokens, two epochs, and a PyTorch implementation. It compares LSTM and GRU at three rates each, selected by validation. It does not reproduce the full protocol or published figure; the numerical gap is not a valid reproduction gap. An initial exploration evaluated test for every rate, so this comparison is exploratory.
In an RTX 3060 run, the rate-1 LSTM obtained test perplexity 1144.12 and the rate-2 selected LSTM obtained 1060.18; the selected rate-0.5 GRU obtained 1164.68. Those high values reflect this reduced protocol and are not comparable with the paper’s 114.5. The rate-2 GRU reached validation perplexity approximately 1.43 × 10¹¹ and is retained as a failure, not hidden. The code selects using validation only; test results had already been consulted in earlier exploration.
To run it, place train.txt, valid.txt, and test.txt in ptb/. Original sources are train, validation, and test. The cell does not download data and requires PyTorch and CUDA. This demonstration cannot infer the full-protocol figure run below.
import math,time,json,hashlib
from pathlib import Path
import numpy as np
import torch
from torch import nn
torch.set_num_threads(2)
if not torch.cuda.is_available():raise RuntimeError('CUDA requerida')
root=Path('ptb')
hashes={'train':'fcea919f6cf83f35d4d00c6cbf08040d13d4155226340912e2fef9c9c4102cbf','valid':'c9fe6985fe0d4ccb578183407d7668fc6066c20700cb4cf87d8ff1cc34df1bf2','test':'dd65dff31e70846b2a6030a87482edcd5d199130cdcfa1f3dccbb033728deee0'}
for part,digest in hashes.items():
if hashlib.sha256((root/f'{part}.txt').read_bytes()).hexdigest()!=digest:raise ValueError(f'Hash distinto en {part}')
def tokens(part):return (root/f'{part}.txt').read_text(encoding='utf8').replace('\n',' <eos> ').split()
train=tokens('train');vocab={w:i for i,w in enumerate(sorted(set(train)))}
def encoded(words):return torch.tensor([vocab.get(w,vocab['<unk>']) for w in words],dtype=torch.long,device='cuda')
def batchify(t,batch):return t[:t.numel()//batch*batch].view(batch,-1).T.contiguous()
train=batchify(encoded(train[:20000]),20);valid=batchify(encoded(tokens('valid')[:5000]),20);test=batchify(encoded(tokens('test')[:5000]),20)
class Model(nn.Module):
def __init__(self,kind):
super().__init__();self.emb=nn.Embedding(len(vocab),200);self.rnn=(nn.LSTM if kind=='LSTM' else nn.GRU)(200,200,2);self.head=nn.Linear(200,len(vocab))
for p in self.parameters():nn.init.uniform_(p,-.1,.1)
def forward(self,x,state):
h,state=self.rnn(self.emb(x),state);return self.head(h),state
def epoch(model,data,opt=None):
model.train(opt is not None);state=None;total=0.;count=0
for start in range(0,data.size(0)-1,20):
seq=min(20,data.size(0)-1-start);x=data[start:start+seq];y=data[start+1:start+1+seq]
if state is not None:state=tuple(z.detach() for z in state) if isinstance(state,tuple) else state.detach()
with torch.set_grad_enabled(opt is not None):
logits,state=model(x,state);loss=nn.functional.cross_entropy(logits.reshape(-1,len(vocab)),y.reshape(-1))
if opt is not None:opt.zero_grad(set_to_none=True);loss.backward();nn.utils.clip_grad_norm_(model.parameters(),5);opt.step()
total+=float(loss.detach())*y.numel();count+=y.numel()
return math.exp(total/count)
out=[];start=time.perf_counter()
for kind in ('LSTM','GRU'):
candidates=[]
for lr in (.5,1.,2.):
torch.manual_seed(31);model=Model(kind).cuda();opt=torch.optim.SGD(model.parameters(),lr=lr)
for _ in range(2):epoch(model,train,opt)
val=epoch(model,valid);candidates.append({'model':kind,'lr':lr,'validation_ppl':val,'parameters':sum(p.numel() for p in model.parameters()),'state':{k:v.cpu().clone() for k,v in model.state_dict().items()}})
print(kind,lr,'validación',val,flush=True)
best=min(candidates,key=lambda v:v['validation_ppl'])
for label,item in [('receta de tasa 1',next(c for c in candidates if c['lr']==1.)),('seleccionada',best)]:
chosen=Model(kind).cuda();chosen.load_state_dict(item['state'])
summary={k:v for k,v in item.items() if k!='state'};summary['test_ppl']=epoch(chosen,test);out.append(summary);print(label,summary,flush=True)
print('segundos',round(time.perf_counter()-start,2),'vocabulario',len(vocab),'GPU',torch.cuda.get_device_name(0))
npm run lab and open the connection link.Full-corpus protocol
Zaremba’s official code includes a small unregularized recipe: two layers of 200 units, batch 20, sequences of 20 tokens, uniform initialization between -0.1 and 0.1, norm clipping at 5, SGD with initial rate 1, and thirteen epochs. After the fifth epoch the rate is halved each epoch. The code accumulates mean batch loss for each time step before clipping the gradient. Also averaging across the 20 steps would change gradient scale and the effect of clipping.
The full-corpus script uses the same three PTB files and verifies their SHA-256. It trains a PyTorch adaptation of that LSTM and a two-layer GRU with initial rates 1 and 0.5: two trials and thirteen epochs per architecture. It chooses rate by validation perplexity and only then calculates test; it saves an epoch checkpoint for resumption. Download it alongside the ptb/ folder and run python ptb_full.py in an environment with PyTorch and CUDA. Two trials equalize count and duration in epochs, not FLOPs or time across architectures.
The local recipe is not a run of the original Torch7 program: libraries, random initialization, last-fragment handling, and arithmetic differ. Evaluation uses batches of 20, like the original code, retaining state between fragments and resetting while traversing each split. The initial reduced exploration already consulted the first 5000 test tokens, so this full comparison remains exploratory. It is not Melis’s search protocol or an independent generalization test.
An RTX 3060 run with PyTorch 2.11 and seed 31 produced these perplexities. Each row uses the final model after thirteen epochs; selection compares validation, not test.
| Architecture | Initial rate | Validation | Test | Role |
|---|---|---|---|---|
| LSTM | 1 | 120.570 | 115.137 | Adapted published recipe |
| LSTM | 0.5 | 118.859 | 114.463 | Selected on validation |
| GRU | 1 | 186.632 | 180.144 | Same initial rate |
| GRU | 0.5 | 131.181 | 126.263 | Selected on validation |
The Zaremba et al. table gives 120.7 validation and 114.5 test for the unregularized LSTM. Our rate-1 recipe adaptation differs on test by +0.637 points; the LSTM selected from two rates is 0.037 points below the published figure. Closeness does not demonstrate identical implementations or statistical precision of those differences. The rate-1 GRU reached validation 404.318 in epoch five and improved after lowering the rate: that trial is retained, although the alternative configuration was selected on validation. The LSTM has 4.653.200 parameters and the GRU 4.492.400, so equalizing two trials and thirteen epochs does not automatically equalize compute.
In the first LSTM, after epoch five, only loss accumulation for logging changed: from summing CPU scalars to summing in double precision on GPU. An independent CPU and GPU test gave identical gradients and parameters for both procedures. Resumption started from the epoch checkpoint; without dropout or shuffling there are no random draws during training steps. The downloadable script uses the second form from the start.
The same Zaremba table cites an earlier deep recurrent network with test 107.5: its published difference from their LSTM is 7.0 perplexity points. Subtracting that fixed figure from our retuned LSTM gives an arithmetic difference of 6.963 points. This illustrates how the numerical contrast changes, but does not measure a surviving causal improvement under an equalized protocol: we did not retrain that earlier network and the paper combines results from different works. In our own equal-trial-count comparison, the selected GRU is 11.801 points above the selected LSTM on exploratory test. One seed, partially consulted test, and very small search spaces prevent generalizing that ordering.
A decision checklist before publication
For each method, report the base recipe, search space, trial count, seeds, budget per trial, failures, and selection criterion. Show validation results rather than only the best test. If test was used during development, explain how and reserve another set for confirmatory evaluation where possible. Publish the conditions under which a configuration was chosen, not just its final score.
Include simple alternatives and discuss what information they receive. If a baseline is tuned over a smaller space due to time limits, quantify the difference and avoid attributing the gap exclusively to architecture. An improvement persisting across tasks, budgets, and seeds is more informative than one win; an improvement disappearing after fair tuning also limits the claim supported. The goal is comparisons another person can reconstruct and test.
Exercises
Step 1 of 2. What is P(M_n ≤ v)?
import numpy as np
def expected_max_curve(results, n_max):
passSummary
A strong baseline is selected and tuned for the question; a ladder shows simple alternatives and limits. Expected maximum separates the trial distribution from the budget effect, and the Pareto frontier incorporates cost. A reproduction gap is interpretable only when conditions are sufficiently equivalent.