Frontier: meta-science of ML and AI in the research process
Metascience of ML, reproducibility and preregistration, automated algorithm discovery, research agents, their evaluation and risks.
After this lesson you can
- Classify Kapoor and Narayanan's leakage types and detect them in study descriptions.
- Explain the FunSearch and AlphaEvolve loops and why the evaluator is critical.
- Implement evolutionary program search with an evaluator and held-out instances.
- Audit an agent-generated paper using the module checklist.
- Critically assess evidence about LLM-generated ideas and agents replicating papers.
Before you start
Researching how we research
Metascience studies how results are produced and checked. A script that regenerates a table helps computational reproducibility, but does not establish that the split, measurement and inference answer the scientific question. Replication requires declaring data, code, environment and decisions, and examining whether evidence supports the claims.
In their review, Kapoor and Narayanan collect 20 works on errors in 17 fields that together affect 329 papers. They do not present this collection as a representative sample of all papers: no prevalence rate can be inferred from it. Their broad definition of reproducibility includes correct analysis as well as data and code availability. The reproducibility crisis in ML-based science includes leakage that can produce optimistic estimates and conclusions that do not survive correction.
The taxonomy separates lack of a clean training–test separation (no test, joint preprocessing, joint feature selection and duplicates), illegitimate features and a test that does not represent the distribution of interest (temporal leakage, dependence between units and sampling bias). A feature can be legitimate for describing an already known diagnosis and illegitimate for predicting it before it exists: the time of use and the question determine the judgment.
An image-level split is insufficient if images from the same patient appear on both sides and the claim concerns new patients. Splitting by patient changes the question being evaluated. If a model predicts future observations, a random split can include data from after prediction time. Fitting an imputer before splitting also allows the test set to influence training. Each case requires tracing how features and units were created and when they were known.
Conversely, if the intended use is predicting a new image of an already known patient, some dependence may be part of the distribution of interest. The split should match that claim rather than a mechanical rule. For a new hospital, holding out patients from the same hospital may not measure transfer between centers either. Draw units, dates, sources and transformation arrows before examining the metric; then explain what information was available at each decision.
The authors propose model information sheets with arguments about separation, feature legitimacy and test representativeness. An empty or incorrect sheet does not eliminate leakage, and without code or data it may be impossible to check. The purpose is to make a claim explicit so another person can challenge it. When privacy prevents sharing the dataset, explain the constraints and what independent checks are possible without identifying people.
Preregistration fixes hypotheses, samples, metrics and a decision rule before confirmatory analysis. A registered report adds protocol review before results are known, according to the venue’s rules. It does not prevent exploration: it distinguishes an exploratory finding from a planned test and records deviations. Herrmann and colleagues argue that some empirical ML research is presented as confirmatory although it is exploratory. Labeling the phase and preserving selection history help interpret the strength of evidence.
An example protocol might fix the population, hospital split, primary metric, a baseline and tuning budget. If access to a hospital changes later, document the change and its consequence before looking at results. A later analysis can discover a valuable anomaly, but should present it as a new hypothesis for another test. Registration does not protect against poorly collected data or make an irrelevant question significant.
Searching for programs with an evaluator
Automated algorithm discovery combines a candidate space, generator and evaluation function. FunSearch uses a language model to propose programs, evaluates their results and maintains diversity through islands; it studies cap-set constructions and online bin-packing heuristics. The generated program describes a rule for constructing solutions, and an evaluation checks properties or measures performance. The evaluator and search framework are part of the contribution.
AlphaEvolve combines proposed code changes, evaluation and evolutionary selection for several problems. The authors describe a procedure for multiplying complex matrices with 48 scalar multiplications. That specific claim has its own mathematical verification; it does not imply that any model-proposed program is correct or novel. Search with imperfect metrics can optimize the measurement without solving the task.
In online packing, objects with sizes between zero and one arrive; each is placed without knowledge of the future in a bin of capacity one. First fit uses the first bin that fits and best fit the one leaving the least free capacity. A priority heuristic assigns a score to each valid bin and picks the maximum. The optimal number is not generally known; is a lower bound, not necessarily the optimum. An excess of two over that bound does not prove the solution is two worse than optimal.
Evaluator overfitting arises when candidates are repeatedly selected using a finite set. Hold out instances from distributions and seeds unused for selection, freeze the candidate and open them once. If you look at the holdout after every iteration and change the search, it becomes validation. A second independent holdout or external evaluation provides new evidence; there is no universal generalization figure for every distribution shift.
An evaluator should reject invalid solutions before measuring quality. In packing, check that each object appears exactly once and no bin exceeds capacity; otherwise a rule that omits objects would look excellent. Limit time and resources so a candidate that does not terminate cannot block the whole search. For mathematical problems, an independent check of the construction can provide a different guarantee from an empirical score. Evaluator quality still depends on whether its tests cover relevant cases.
Selection on few examples may favor a rule that exploits their order or sizes. In the lab the holdout uses a different seed and size interval; this introduces one specific change, not every possible change. Also compare with known rules and record how many candidates were evaluated. An improvement of 0.1 bins on average over twelve cases is a toy observation, not proof of general superiority.
For objects totaling 37.4 and bins of capacity one, the lower bound is . A heuristic using 40 has excess relative to that bound of . If the actual optimum were 39, its excess over optimum would be smaller. Always state which denominator you use and remember that a lower bound may be unattainable.
Research agents and evaluation
Research agents chain idea generation, code, execution, analysis and writing. The AI Scientist presents that workflow and uses an automated reviewer to evaluate generated papers. An automated review score is not equivalent to human acceptance and does not prove validity of results. Inspect logs, code, citations, baselines, number of seeds and data used, just as in peer review.
In PaperBench, 20 ICML 2024 papers are broken down into 8,316 gradable tasks to measure replication. In the 2025 version, the best tested agent scored an average of 21.0% under that rubric and configuration; the human comparison covers a subset. This is not the general probability that any agent will replicate any paper or a current measurement of all models. The score also depends on the rubric, resources and evaluator.
A subtask rubric distinguishes, for example, installing dependencies from reproducing a table or checking a theoretical claim. Its advantage is showing where replication fails; its limit is that it scores only what its criteria capture. An automated evaluator itself needs validation against human judgments and review of disagreements. An agent can satisfy a superficial check without capturing the experiment, or perform a reasonable variant the rubric does not anticipate.
Si, Yang and Hashimoto compared ideas from NLP experts and an agent: in their study reviewers judged the agent’s ideas more novel and somewhat less feasible. A novelty rating is not proof of priority or a reproducible result. The authors identify diversity and self-evaluation problems; executing the ideas and checking their prior work are additional steps.
Sources and responsibility
Risks of LLM assistance include nonexistent citations, mixed identifiers, claims absent from the source, incorrect code and convincing-looking results without verification. Check title, authors, year and DOI or identifier in a primary source. Then open the paper: matching metadata does not prove it supports the attributed statement.
Keep the model version, instructions, tools, seed when available and outputs used, so another person can review the process. An agent can generate a useful hypothesis, but someone must decide whether the question is relevant, the data legitimate and the evaluator measures what is intended. Attribution and confidentiality rules depend on the venue; check them before giving manuscripts or nonpublic data to external tools.
A citation audit has two stages. First check that title, authors and identifier refer to the same work and distinguish preprint date from publication date. Then find the table, theorem or specific result in the text that supports the statement. An authentic reference may be misattributed, cite a different version or describe a limitation omitted by the summary. Save the link and section reviewed alongside the claim.
Lab: a miniature heuristic search
This program built from scratch uses arithmetic operation trees, two islands and random mutation, without an LLM. It selects by mean excess over the bound on 12 training instances and only then calculates the result on 12 held-out instances generated with another seed and distribution. It compares first fit and best fit on both sets. The data are synthetic: it does not reproduce FunSearch’s instances, model or results.
"""Búsqueda didáctica de expresiones acotadas para empaquetado en línea.
No ejecuta Python generado. Los árboles solo permiten +, -, *, r, x y
constantes. Las instancias reservadas no participan en selección.
"""
import ast
import math
import random
import statistics
OPS = ('+', '-', '*')
LEAVES = ('r', 'x', -1., 0., .5, 1.)
def size(tree):
return 1 if not isinstance(tree, tuple) else 1 + size(tree[1]) + size(tree[2])
def depth(tree):
return 1 if not isinstance(tree, tuple) else 1 + max(depth(tree[1]), depth(tree[2]))
def score(tree, r, x):
if tree == 'r': return r
if tree == 'x': return x
if isinstance(tree, (int, float)): return float(tree)
op, a, b = tree
left, right = score(a, r, x), score(b, r, x)
return left + right if op == '+' else left - right if op == '-' else left * right
def parse_expression(source):
"""Analiza sin eval/exec, limita longitud, nodos y profundidad."""
if len(source) > 200: raise ValueError('Expresión demasiado larga')
root = ast.parse(source, mode='eval')
if sum(1 for _ in ast.walk(root)) > 64: raise ValueError('Demasiados nodos')
def convert(node):
if isinstance(node, ast.Name) and node.id in ('r', 'x'): return node.id
if isinstance(node, ast.Constant) and type(node.value) in (int, float) and abs(node.value) <= 10:
return float(node.value)
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
return ('-', 0., convert(node.operand))
if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult)):
op = '+' if isinstance(node.op, ast.Add) else '-' if isinstance(node.op, ast.Sub) else '*'
return (op, convert(node.left), convert(node.right))
raise ValueError('Solo r, x, constantes y operaciones +, -, *')
tree = convert(root.body)
if size(tree) > 31 or depth(tree) > 6: raise ValueError('Árbol demasiado complejo')
return tree
def pack(items, tree=None, baseline=None):
if len(items) > 200 or any(not math.isfinite(x) or not 0 < x <= 1 for x in items):
raise ValueError('Tamaños deben estar en (0, 1], máximo 200 objetos')
bins = []
for x in items:
valid = [i for i, r in enumerate(bins) if r + 1e-12 >= x]
if not valid:
bins.append(1-x)
continue
if baseline == 'first': index = valid[0]
elif baseline == 'best': index = min(valid, key=lambda i: bins[i]-x)
else: index = max(valid, key=lambda i: score(tree, bins[i], x))
bins[index] -= x
return len(bins)
def excess(tree, instances, baseline=None):
if not instances: raise ValueError('Se requieren instancias')
gaps = []
for items in instances:
lower = math.ceil(sum(items)-1e-12)
if lower == 0: raise ValueError('Instancia vacía')
gaps.append(pack(items, tree, baseline)-lower)
return statistics.mean(gaps)
def random_tree(rng, remaining=2):
if remaining == 0 or rng.random() < .35: return rng.choice(LEAVES)
return (rng.choice(OPS), random_tree(rng, remaining-1), random_tree(rng, remaining-1))
def mutate(tree, rng):
if not isinstance(tree, tuple) or rng.random() < .3: return random_tree(rng, 2)
op, a, b = tree
candidate = (op, mutate(a, rng), b) if rng.random() < .5 else (op, a, mutate(b, rng))
return candidate if size(candidate) <= 31 and depth(candidate) <= 6 else tree
def evolve(train, seed=23, islands=2, population=8, generations=10):
"""Selección por entrenamiento; reserva solo para evaluación posterior."""
rng = random.Random(seed)
groups = [[random_tree(rng) for _ in range(population)] for _ in range(islands)]
calls = 0
for _ in range(generations):
for k, group in enumerate(groups):
ranked = sorted(group, key=lambda t: excess(t, train)); calls += len(group)
elite = ranked[:2]
groups[k] = elite + [mutate(rng.choice(elite), rng) for _ in range(population-2)]
all_trees = [tree for group in groups for tree in group]
best = min(all_trees, key=lambda tree: excess(tree, train)); calls += len(all_trees)
return best, calls
def make_instances(seed, n, length, lo, hi):
rng = random.Random(seed)
return [[rng.uniform(lo, hi) for _ in range(length)] for _ in range(n)]
train = make_instances(23, 12, 30, .1, .7)
holdout = make_instances(24, 12, 30, .2, .8)
winner, evaluations = evolve(train)
print('Expresión seleccionada:', winner, '| evaluaciones:', evaluations)
print('Búsqueda: entrenamiento', round(excess(winner,train),3), 'reserva', round(excess(winner,holdout),3))
for baseline in ('first','best'):
print(baseline, 'entrenamiento', round(excess(None,train,baseline),3),
'reserva', round(excess(None,holdout,baseline),3))
assert pack([.6,.4,.4], baseline='first') == 2
assert parse_expression('x-r') == ('-', 'x', 'r')
try:
parse_expression('__import__("os")')
except ValueError:
print('Llamada rechazada por la gramática')
else:
raise AssertionError('No se rechazó la llamada')The interpreter limits expression size and depth; it does not use eval or execute generated programs. The number of objects is limited to 200 per instance. This limits work in the example, but is not an operating-system sandbox for arbitrary Python code. The holdout is a teaching set: once consulted, it should not be used to choose another heuristic without holding out new data.
Local lab: model proposals
First check which environment will run the experiment. This local cell does not load the model or perform the search:
import importlib.metadata
import torch
print('PyTorch:', torch.__version__)
print('Transformers:', importlib.metadata.version('transformers'))
print('CUDA disponible:', torch.cuda.is_available())npm run lab and open the connection link.Download mini_funsearch.py, llm_mutator.py and its tests to the same folder. First run python test_mini_funsearch.py. In a local environment with PyTorch and Transformers, run python llm_mutator.py --device cuda --out llm_results.json; use --device cpu if you do not have CUDA. By default it loads Qwen2.5-0.5B-Instruct and may need to download the model; --offline requires it already be cached. The file records the four responses, valid proposals, time and results. This program does not send the prompt to an external API.
The model proposes only an expression with r, x, constants and operations +, -, *; the parser rejects calls, attributes, loops and expressions outside the limits. Each evaluation occurs in a separate process with a five-second limit. Arbitrary Python is not executed and the process is not claimed to be a general security sandbox. The comparison uses four model proposals and four genetic-programming evaluations, with the same training selection. There may be no valid proposal; the program reports that case instead of inventing a score.
In a CPU check run with the specified model and the script’s four seeds, no proposal passed the grammar: three were text and one included prohibited division and a call. A separate CUDA run also had no valid proposals; the device can change outputs. The four-evaluation genetic search achieved mean excess 1.167 in training and 2.667 on holdout; with no valid proposal there is no comparable model score in those runs. This result depends on the prompt, model, seed and grammar; it does not establish a general ranking of models or methods.
You can inspect the real CPU and CUDA outputs, with prompts and rejections. The current script pins the model revision; if using another identifier, also provide its revision with --revision. Responses and times may vary by version and hardware.
Exercises
def evaluate_heuristic(priority_fn, instances, holdout):
pass