Empirical research on a limited compute budget
Empirical research with an 8 GB GPU: distinguish scientific, nuisance, and fixed hyperparameters; design quasirandom sweeps; validate small-scale proxies; analyze sensitivity using a multiverse; and plan compute with predetermined stopping criteria. The practical case is grokking in modular arithmetic.
After this lesson you can
- Classify hyperparameters as scientific, nuisance, or fixed and design a sweep tuning nuisance parameters within each scientific condition.
- Choose among grid, random search, and quasirandom Sobol sequences for a scientific sweep.
- Validate a small-scale proxy by measuring ranking concordance with the target scale.
- Conduct a multiverse analysis and specification curve over a study's arbitrary decisions.
- Plan a GPU-hour budget with early-stopping criteria decided in advance.
Before you start
Budget a question
A small GPU can answer precise questions if the experiment distinguishes what changes and what must remain comparable. A poorly designed comparison can consume days and still fail to identify the cause of a difference. Start by writing an estimate of cost, the metric, available resources, and the decision you will make for each result. Reserve part of the budget for checking errors and repeating an observation before spending everything on search.
A scientific hyperparameter is the condition whose effect you want to study; a nuisance parameter affects performance but is not the main object; a fixed one stays constant because of scope or cost. These categories depend on the question. For two optimizers, optimizer is scientific and learning rate is usually nuisance. If studying sensitivity to rate, rate becomes scientific. A seed can be a block for estimating variation, not a configuration optimized by selecting the most favorable result.
The Tuning Playbook recommends explicitly designing tuning experiments and considering search cost. To compare attainable systems, assign each scientific condition a comparable space and budget of nuisance parameters. Using A’s optimal rate for B might measure B’s incompatibility with that rate rather than its best performance. If you deliberately keep a common rate, the question is local and should be stated as such.
Tuning also introduces selection: the maximum of noisy results tends to be optimistic. Use a development split to choose and a holdout to estimate the final result, recording every trial. Equal trial count does not always equal compute parity when models take different times; report both. An absurd search space for one method is not comparable even with equal size. The protocol should justify ranges, scales, and selection rules before seeing the final result.
One question, several decisions
In a pre-LN versus post-LN study, normalization variant is scientific. Depth can be another scientific condition if asking how stability changes with it; otherwise it is fixed by scope. Learning rate and warmup are nuisance candidates because they may affect variants differently. Batch size can be fixed for memory or treated as nuisance with an assigned budget; no classification is universal. Seeds are replicated and blocked where feasible to estimate dispersion, not selected like a performance hyperparameter.
When comparing paired seeds, record which random sources are actually shared. Two architectures may consume random numbers in different orders; one seed label does not ensure equal batches, augmentations, and initializations. Separate generators for split and order can improve control but do not eliminate uncertainty. If a configuration fails due to memory or produces nonfinite values, record it and its cost; silently discarding it changes the comparison.
Design the sweep
A scientific sweep crosses conditions of interest with a search design for each. A grid of values in each of dimensions costs trials, even if one dimension alone determines response. Random points explore more distinct values in that dimension at equal budget; Bergstra and Bengio studied this in hyperparameter search. This does not mean randomness wins for every function or domain.
A Sobol sequence is quasirandom and aims to cover the hypercube with low discrepancy. Using points of a digital net preserves its balance properties; transforming a uniform coordinate by produces logarithmic coverage between and . Rounding points for integer or categorical parameters can create duplicates; count them. Randomized scrambling and its seed make a sequence repeatable and allow sensitivity to another sequence to be studied.
The figure assumes only X matters. In a real task you do not know beforehand which dimension matters or whether a narrow interacting region exists. A grid is useful for specific levels and an interpretable curve; random search is a flexible control; Sobol provides structured coverage but does not adapt using observations. Compare at equal budget and retain each point’s configuration.
Choose the space before the algorithm
A search can only find what lies within its bounds. Before choosing Sobol or random, check that each range includes viable configurations and avoid values systematically failing for memory. If rate varies by orders of magnitude, a uniform distribution over rate concentrates trials at the high end; sampling its logarithm assigns equal mass to equal multiplicative intervals. A logarithmic transformation is inappropriate for a parameter that can be zero or negative without another parameterization.
Combining a scientific and nuisance parameter can produce spaces of unequal dimension. If one variant needs warmup and another does not, equal numbers of values do not imply equal opportunities. Explain parameters available to each condition and decide whether the question compares complete systems under a compute amount or interventions with as many shared controls as possible. Both decisions have different costs and estimands.
For each trial save a serialized configuration, code and library versions, seed, start and end, hardware condition, completion status, and development metric. If restarting a search, avoid repeating a point as if it were new information; a deliberate repetition with another seed measures variation. Report unique configurations and training runs: they are not the same unit.
Is a small experiment useful?
A small-scale proxy may use less data, a smaller network, or fewer steps to discard options before an expensive run. Validation requires evaluating some of the same configurations at proxy and target scales. Kendall’s tau compares concordant and discordant pairs; without ties, . With ties use a variant explicitly handling them. High tau on a small set does not guarantee the best candidate remains best, and low tau may hide concordance in a region of interest.
Choose configurations spanning the result range, not just proxy survivors; otherwise evaluation is conditioned on selection. Calculate uncertainty with appropriate replication or resampling and inspect pair reversals important to the decision. A proxy can detect a broken implementation even if rankings do not persist. Revalidate when dataset, architecture, or target scale changes; the measured relationship does not automatically transfer.
Concordance is not calibration: two scales may order identically while differences in magnitude are very different. To predict target performance, evaluate prediction error and bias as well as ranking. If budget allows few pairs, present tau as an unstable observation rather than a guarantee. Hold out candidates selected without the proxy to check the false-discard rate.
Proxy classification errors
Imagine two methods with target performances 0.80 and 0.81. A 0.01 difference may be smaller than dispersion across seeds. If the proxy reverses them, that may be an inevitable consequence of noise rather than a systematic scale property. If it reproducibly reverses a large difference, discarding the apparently worse method can lose a real opportunity. Record overall concordance and pairs whose order changes.
False-discard rate requires knowing which candidates would have been good at target scale, including those the proxy would have removed. With a small budget, hold out a random sample of discards and evaluate them at target scale. You cannot calculate that rate from survivors alone. A wide interval may make keeping several candidates more prudent than selecting one.
A duration proxy can also bias optimizer comparisons: one may progress faster early while another reaches a better value later. Evaluate several horizons and plot complete curves, not just the first checkpoint. The right horizon depends on the decision: filtering obvious failures differs from predicting long-training results.
Multiverse and sensitivity
A sensitivity analysis changes a procedural decision to see whether it affects the conclusion. A multiverse enumerates reasonable decision combinations and retains every estimate, including those unfavorable to the hypothesis. The sorted curve shows the effect range and the matrix below shows which decisions generate them. Steegen and colleagues propose making these alternatives transparent; enumerating every possible path does not make a design-violating path reasonable.
Specification intervals share observations and are correlated. Do not count each interval as an independent test or interpret the full range as a confidence interval. Decide admissible decisions in advance and which curve summary answers your question. If you choose a path after inspecting the result, its ordinary uncertainty ignores selection. A permutation test of the whole curve can compare a summary chosen before seeing data with a null distribution generated under exchangeability.
The lab null hypothesis is no assignment effect under a valid label permutation with group sizes preserved. In observational, temporal, grouped, or confounded data, exchanging all labels may be invalid: blocks or another design may be needed. The p-value does not prove all analyses equivalent and per-path intervals do not simultaneously control coverage of the set. Decisions depend on a fixed index and not treatment, so the same rule applies at every permutation.
Build an interpretable multiverse
The list of reasonable decisions should come from problem knowledge and be documented before exploring results. Some combinations are incompatible: a metric may require a particular transformation or a filter may leave a group empty. Exclude them by an explicit rule, count remaining paths, and retain the reason. Including thousands of arbitrary options merely to widen the range can be as misleading as showing only the most favorable.
Curve order follows the estimate, so decision columns are reordered with it. A strip of boxes may suggest one choice changes the effect, but can also be associated with another choice. Compare conditional differences holding other decisions fixed or fit a descriptive model respecting multiverse structure. That comparison describes analysis sensitivity; it does not make an analytical decision a causal intervention on the phenomenon.
The figure’s bootstrap intervals are calculated per path with resampling within each group. Interpretation requires independent units and appropriate sampling; increasing resample count is insufficient with clustered data. For repeated units resample subjects or clusters, and for time series a block bootstrap may be needed. The 16 paths use the same sample, so their errors resemble one another and the apparent number of results does not multiply sample size.
Budget and early stopping
Compute planning counts runs, expected cost per run, and a reserve for debugging, evaluation, and repetitions. Three conditions by 16 tunings by three seeds produce 144 runs: at 12 minutes each they cost 28.8 GPU hours. If 60% finish at 25% of duration, ideal savings are , or 12.96 hours, leaving 15.84 hours. This assumes equal times and ignores overhead, so compare it with measurements.
Early stopping saves resources but may remove trajectories improving late. Fix the rule, evaluation time, and indicator before running, report how many were cut, and compare some with complete trainings. A per-run wall-time limit is not a step limit when hardware shares load. Record times with GPU synchronization, completed steps, failures, and memory; the measured total here is execution time on one GPU, not energy or monetary cost.
A concrete reserve
Suppose the authorized budget is ten hours. A plan might allocate one hour to checking data and a test run, four to initial search, two to replicating candidates, and three to evaluation and contingencies. This is hypothetical, not a universal rule. After the pilot, replace predicted times with measurements and recalculate whether the plan fits. If seed cost varies greatly, use a time distribution and a reserve for the slow tail instead of multiplying only the mean.
A stopping criterion may use nonfinite loss, lack of progress, or a resource limit. The first often identifies an unusable run, whereas low initial accuracy can coexist with later improvement. In successive selection, retaining only short-term leaders can favor fast-learning methods. Keeping a small control group to the full horizon allows estimation of whether the rule removes candidates that later recover.
Separate training time from loading data, validation, preparation, and search. Summed GPU hours of parallel tasks need not equal elapsed clock time. If several people share a GPU, contention means wall duration does not exclusively measure one process’s work; record this where relevant. A reproducible budget includes hardware and numerical precision, not only epoch count.
Grokking: stopping can destroy the signal
In modular addition, the dataset contains pairs and labels . Pairs are split into training and validation, and a network learns to predict the residue. Power and colleagues observed improved generalization long after memorizing training on some tasks. Their figure uses division modulo 97 and a transformer; steps and configurations are not those of our modulo-11 addition MLP. A single training-validation accuracy difference should not be called grokking: later improvement must be observed and the criterion stated.
The lab uses eight Sobol points for weight decay and training fraction, three seeds, up to 2000 steps, and a rule stopping if training is below 0.50 at step 500. This rule seeks to discard memorization failures but has not been validated as safe for detecting delayed generalization; it could discard an interesting trajectory. Final memorization and validation phases are shown along with histories every 250 steps to examine when thresholds are reached. The complement of pairs is exploratory validation, not an independent final test after configuration selection.
Local lab: modular sweep
You need PyTorch, SciPy, and a CUDA GPU. The cell measures synchronized wall time per run and sums seconds as GPU-hours; it includes training and periodic evaluations but not prior preparation. Shared split order per seed creates approximate nesting across fractions, not three independent splits per configuration. This is a small original study; its figures do not reproduce the paper. Load can change times and hardware or version differences can change results.
import json, time, math
import numpy as np
import torch
from scipy.stats import qmc
torch.set_num_threads(1)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type!='cuda': raise RuntimeError('El ensayo precisa CUDA; adapta explícitamente el presupuesto si usas CPU')
p=11
pairs=torch.cartesian_prod(torch.arange(p),torch.arange(p)).to(device)
y=(pairs[:,0]+pairs[:,1])%p
sobol=qmc.Sobol(2,scramble=True,seed=31).random_base2(3)
results=[]
for j,(a,b) in enumerate(sobol):
wd=10**(-3+3*a); frac=.35+.35*b
for seed in (31,32,33):
torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
g=torch.Generator(device=device).manual_seed(seed+100)
perm=torch.randperm(len(pairs),generator=g,device=device); cut=round(frac*len(pairs)); tr,va=perm[:cut],perm[cut:]
class Net(torch.nn.Module):
def __init__(self):
super().__init__();self.embedding=torch.nn.Embedding(p,32);self.mlp=torch.nn.Sequential(torch.nn.Linear(64,128),torch.nn.ReLU(),torch.nn.Linear(128,p))
def forward(self,x): return self.mlp(self.embedding(x).flatten(1))
net=Net().to(device);opt=torch.optim.AdamW(net.parameters(),lr=.01,weight_decay=wd)
torch.cuda.synchronize();start=time.perf_counter();history=[];reason='presupuesto agotado'
for step in range(1,2001):
net.train();opt.zero_grad(set_to_none=True);loss=torch.nn.functional.cross_entropy(net(pairs[tr]),y[tr]);loss.backward();opt.step()
if step%250==0:
net.eval()
with torch.no_grad():
train=(net(pairs[tr]).argmax(1)==y[tr]).float().mean().item();val=(net(pairs[va]).argmax(1)==y[va]).float().mean().item()
history.append([step,train,val])
# Regla fijada antes del barrido: abandona modelos que no memorizan al paso 500.
if step==500 and train<.50: reason='abandono: train < 0.50 en paso 500';break
torch.cuda.synchronize();seconds=time.perf_counter()-start
results.append(dict(config=j,seed=seed,weight_decay=wd,fraction=frac,steps=step,seconds=seconds,reason=reason,history=history))
print(j,seed,round(wd,5),round(frac,3),history[-1],round(seconds,2),flush=True)
summary=dict(modulus=p,device=torch.cuda.get_device_name(),sobol_seed=31,description='MLP AdamW, 2000 pasos máximo; parada si train<.5 en 500',gpu_hours=sum(r['seconds'] for r in results)/3600,results=results)
print('horas GPU',summary['gpu_hours'])
for row in results:
print('fase',row['config'],row['seed'],'memorización',row['history'][-1][1]>=.95,'validación',row['history'][-1][2]>=.95)
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
fig, axes=plt.subplots(1,3,figsize=(12,3.5),sharey=True)
for ax,seed in zip(axes,(31,32,33)):
for row in (r for r in results if r['seed']==seed):
train,val=row['history'][-1][1:]; color=('#16834a' if val>=.95 else '#d97706' if train>=.95 else '#64748b')
ax.scatter(row['weight_decay'],row['fraction'],c=color,marker='x' if row['reason'].startswith('abandono') else 'o')
ax.set_xscale('log');ax.set_xlabel('weight decay');ax.set_title(f'semilla {seed}')
axes[0].set_ylabel('fracción de entrenamiento')
fig.legend(handles=[Line2D([],[],marker='o',linestyle='',color='#16834a',label='validación ≥ .95'),Line2D([],[],marker='o',linestyle='',color='#d97706',label='solo entrenamiento ≥ .95'),Line2D([],[],marker='o',linestyle='',color='#64748b',label='sin memorizar'),Line2D([],[],marker='x',linestyle='',color='#64748b',label='parada temprana')],loc='lower center',ncol=2)
fig.subplots_adjust(bottom=.30);plt.show()
npm run lab and open the connection link.In our RTX 3060 run, all 24 trajectories reached 2000 steps without triggering stopping; all reached training ≥0.95 and validation accuracy was 0 at every recorded checkpoint from step 250. Measured total was approximately 0.130 GPU hours under shared load. This MLP and horizon did not show delayed generalization: the phase diagram lies entirely in memorization without generalization. Do not extrapolate to other models or longer training.
To read a phase, compare final values with explicit thresholds, for example training ≥0.95 and validation ≥0.95; a run can memorize without generalizing within the horizon. Examine the entire history before saying generalization occurred late. The eight points combine both coordinates: a difference between them does not by itself identify weight-decay effect separately from fraction. For a causal one-factor curve, hold or cross the other and repeat with more seeds.
Pyodide lab: specifications and permutation
The example simulates 80 observations with treatment assigned in two groups, noise, and an extreme value; generating effect is 0.05. Four binary decisions combine clipping, mean or median, index filtering, and a fixed window. Output is entirely synthetic. Each bootstrap interval resamples by group within one specification and is pointwise for that path. The test uses the absolute median of the 16 estimates and 499 joint permutations; the +1 correction avoids a zero p-value from finite simulation.
import itertools
import numpy as np
def enumerate_multiverse(outcome, treatment, decisions):
y=np.asarray(outcome,float); t=np.asarray(treatment,int)
if y.ndim!=1 or y.shape!=t.shape or not np.isin(t,[0,1]).all(): raise ValueError('datos incompatibles')
rows=[]
for trim,metric,subset,window in itertools.product((0,1),repeat=4):
idx=np.arange(len(y)); keep=np.ones(len(y),dtype=bool)
if subset: keep &= idx%5 != 0 # regla fija sin mirar resultado
if window: keep &= idx < int(.75*len(y))
z=y.copy()
if trim: z=np.clip(z,-3,3)
f=np.median if metric else np.mean
if min(np.sum(keep & (t==0)),np.sum(keep & (t==1)))<2: raise ValueError('grupos insuficientes')
effect=f(z[keep & (t==1)])-f(z[keep & (t==0)])
rows.append((float(effect),[trim,metric,subset,window]))
return rows
def specification_curve(outcome,treatment,seed=31,bootstrap=300):
y=np.asarray(outcome,float);t=np.asarray(treatment,int); rows=enumerate_multiverse(y,t,None)
rng=np.random.default_rng(seed);groups=[np.flatnonzero(t==v) for v in (0,1)]; draws=np.empty((bootstrap,len(rows)))
# La remuestra estratificada reordena bloques; conservar el índice original para reglas de subconjunto.
# Para intervalos se remuestrea dentro de cada especificación su grupo filtrado.
for j,(_,bits) in enumerate(rows):
trim,metric,subset,window=bits;idx=np.arange(len(y));keep=np.ones(len(y),bool)
if subset: keep &= idx%5!=0
if window: keep &= idx<int(.75*len(y))
z=np.clip(y,-3,3) if trim else y; f=np.median if metric else np.mean
a=z[keep & (t==0)];b=z[keep & (t==1)]
for r in range(bootstrap): draws[r,j]=f(rng.choice(b,len(b)))-f(rng.choice(a,len(a)))
intervals=np.quantile(draws,[.025,.975],axis=0).T
order=sorted(range(len(rows)),key=lambda i:(round(rows[i][0],12),rows[i][1]));return [(rows[i][0],intervals[i].tolist(),rows[i][1]) for i in order]
def permutation_curve(outcome,treatment,permutations=499,seed=32):
y=np.asarray(outcome,float);t=np.asarray(treatment,int);rng=np.random.default_rng(seed)
stat=lambda labels: abs(np.median([r[0] for r in enumerate_multiverse(y,labels,None)]))
observed=stat(t); null=np.array([stat(rng.permutation(t)) for _ in range(permutations)])
return observed,(1+np.sum(null>=observed))/(permutations+1)
rng=np.random.default_rng(2026);t=np.r_[np.zeros(40,dtype=int),np.ones(40,dtype=int)];rng.shuffle(t)
y=.05*t+rng.normal(0,1,80);y[0]=5
curve=specification_curve(y,t);stat,p=permutation_curve(y,t)
print('16 especificaciones; rango:',curve[0][0],curve[-1][0]);print('mediana absoluta y p por permutación:',stat,p);print('primeras filas:',curve[:3])
Do not mix this global hypothesis test with significance of each path. The median can be small when positive and negative effects cancel, so this statistic does not detect every form of heterogeneity. A sign statistic, maximum, or predetermined region would answer different questions. A joint permutation preserves dependence across paths under the same simulated assignment; permuting each path separately would destroy that structure. For real data, document independent units, blocks, exclusion rules, and estimand.
Exercises
def specification_curve(results, decisions):
passSummary
Classify each variable for the question and assign comparable tuning budgets. Validate proxies at both scales, show sensitivity across decisions, and record costs and stopping rules. Observing memorization without delayed generalization does not prove grokking or rule out its appearance beyond the tested horizon.