Foundation Models & Agentic Science

From Self-Supervision to Autonomous Discovery


ML for Science and Engineering · Lecture 27
Joseph Bakarji

Your Toolkit

Everything you've built this semester

The Methods You Now Know

Data
time series, fields, images
Represent
SVD · PCA · DMD
Discover
SINDy · Symbolic Reg.
Solve
PINNs · DeepONet · FNO
You understand inductive biases: why sparsity works for SINDy, why physics constraints help PINNs, why operator learning generalizes across initial conditions.
You know where things fail and why: overfitting, wrong library terms, stiff systems, spectral bias.

The Question


You've learned to build models from data.

What if the model could build itself?

This lecture: what foundation models and AI agents mean for science,
and why everything you've learned matters more, not less.

Part I: Foundation Models

Self-supervision, scaling, and emergent capabilities

Self-Supervised Learning

No labels. The data is the supervision.

$p(x_t \mid x_{t-1}, x_{t-2}, \ldots, x_1)$
Training objective: maximize
$\mathcal{L} = \sum_{t=1}^{T} \log p(x_t \mid x_{<t}; \theta)$
Like PCA finds structure without labels, self-supervision discovers patterns in language through prediction alone.
Next-token prediction: shifted input-target pairs

Next-token prediction: each token predicts the next
S. Raschka, "Build an LLM from Scratch"

Pre-training at Scale

ModelParametersTraining Data
GPT-2 (2019)1.5B40 GB text
GPT-3 (2020)175B570 GB
Chinchilla (2022)70B1.4T tokens
GPT-4 (2023)~1.8T*~13T tokens*
Claude 3.5 (2024)

* estimated, not officially disclosed

Chinchilla scaling law (Hoffmann et al. 2022):
Model size and data should scale equally. Doubling params requires doubling data.
The internet is the training set. No human labeling needed.

The Transformer

Self-attention: every token attends to every other token.

$\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}}\right)V$
Stack $N$ layers of attention + feed-forward.
Multiple heads learn different relationships in parallel.
Transformer architecture from Vaswani et al. 2017

Vaswani et al. (2017) "Attention Is All You Need"

Query, Key, Value

Each input embedding $\mathbf{x}_i \in \mathbb{R}^d$ is projected through three learned matrices:

Query
$\mathbf{q}_i = W_Q \, \mathbf{x}_i$

"What am I looking for?"
Key
$\mathbf{k}_j = W_K \, \mathbf{x}_j$

"What do I contain?"
Value
$\mathbf{v}_j = W_V \, \mathbf{x}_j$

"What do I pass along?"
$\text{attention score: } \alpha_{ij} = \frac{\mathbf{q}_i \cdot \mathbf{k}_j}{\sqrt{d_k}} \qquad \longrightarrow \qquad \text{output: } \mathbf{z}_i = \sum_j \text{softmax}(\alpha_{ij}) \, \mathbf{v}_j$
$W_Q, W_K, W_V \in \mathbb{R}^{d_k \times d}$ are learned. The model discovers which relationships matter. With $h$ heads, it learns $h$ different notions of "relevance" simultaneously.

Scaling Laws

Performance follows power laws in compute, data, and parameters:

$L(C) \propto C^{-\alpha}$

Loss decreases predictably over 7 orders of magnitude of compute.

3 scaling axes:
1. More parameters
2. More data
3. More inference compute (chain-of-thought)
Scaling laws: loss vs parameters, data, compute

Kaplan et al. (2020) --smooth power laws across 7 orders of magnitude

Adaptation: From Raw Model to Useful Assistant

Pre-train
next-token prediction
on internet text
Fine-tune (SFT)
curated Q&A pairs
instruction following
RLHF
human preferences
reward model
In-context learning (ICL): no weight updates at all. Just provide examples in the prompt and the model adapts. First demonstrated at scale by GPT-3 (Brown et al. 2020).
Science-specific adaptation: Galactica (Taylor et al. 2022) trained on 106B tokens of scientific text. SciBERT, BioGPT, ESM for proteins. Domain data matters.

Emergent Capabilities

Abilities that appear discontinuously as models cross parameter thresholds:

  • Few-shot learning --learn from examples in the prompt
  • Chain-of-thought --step-by-step reasoning
  • Code generation --write and debug programs
  • Tool use --call APIs, run calculators
100+ emergent abilities documented across arithmetic, logic, translation, and scientific reasoning.
Caveat: Schaeffer et al. (2023) argue some "emergence" is a metric artifact --smooth improvement looks discontinuous with certain metrics.

Check Your Understanding

Q: What makes self-supervised learning different from supervised learning for training LLMs?

A) It uses reinforcement learning instead of gradient descent

B) Labels come from the data itself (predict next token), not human annotation

C) It requires less compute than supervised learning

D) It can only work with text data, not images or proteins

Answer: B --The key insight is that the training signal is free: every text sequence provides its own labels via next-token prediction. This is why LLMs can train on trillions of tokens without human annotators. The same idea powers protein language models (predict next amino acid) and code models (predict next line).

Part II: Foundation Models in Science

Proteins, weather, mathematics, and cautionary tales

AlphaFold: Protein Structure Solved

Predicting 3D protein structure from amino acid sequence --a 50-year grand challenge.

AlphaFold 2 (2021): atomic-level accuracy, dominated CASP14.
Nobel Prize in Chemistry 2024.
AlphaFold 3 (2024): diffusion-based. Predicts protein + DNA + RNA + ligand complexes. 50% more accurate than physics-based methods.
AlphaFold 2 architecture

AlphaFold 2 architecture (Wikimedia, CC BY-SA)

ESM-3: Generating New Proteins

A protein language model: trained on 2.78 billion protein sequences to jointly reason over sequence, structure, and function.

$p(x_t \mid x_{<t})$   but $x_t$ = amino acid
Generated esmGFP: a novel fluorescent protein at 58% identity from known fluorescent proteins --equivalent to simulating ~500 million years of evolution.
Same idea as LLMs: self-supervised prediction on sequences. But instead of English, the "language" is biochemistry.
98B parameters. The model doesn't "understand" biology --it learned statistical patterns over evolutionary time.

AI Weather Forecasting

ModelArchitectureKey Result
GraphCastGNN on meshBeats ECMWF at all lead times
GenCastDiffusionBeats ENS on 97.2% of targets
Pangu3D TransformerFirst to beat HRES (2023)
GenCast: 15-day global forecast in 8 minutes vs. hours on supercomputers.
Caveat: numerical models still win for record-breaking extremes outside training distribution.
GenCast performance scorecard vs ECMWF

GenCast vs ECMWF ENS scorecard (Price et al. 2024)

FunSearch: Provable Mathematical Discovery

LLM paired with an automated evaluator in an evolutionary loop. Searches for programs, not solutions.

Discovered new constructions for the cap set problem --largest improvement in 20 years.
Why it matters: the result is mathematically verifiable. Not a hallucination --a proof. First LLM-driven discovery of new knowledge.
The pattern:
1. LLM proposes candidate programs
2. Evaluator scores them automatically
3. Best programs seed the next generation
4. Repeat --evolutionary search guided by LLM
Also found improved heuristics for online bin packing.

Galactica: A Cautionary Tale

Meta's scientific LLM: 120B params trained on 106B tokens of papers, textbooks, encyclopedias, molecular data.

Strong results: beat GPT-3 on LaTeX equations (68% vs 49%), set SOTA on PubMedQA (77.6%).
Withdrawn in 3 days. Generated plausible-sounding but fabricated scientific claims. Authoritative tone + wrong content = dangerous.
The lesson:

Fluency $\neq$ accuracy.

A model that writes perfect LaTeX and cites real-looking papers can still be confidently wrong about the science.

The Scorecard

Good at
  • Literature synthesis & summarization
  • Protein/molecular design (ESM-3, AlphaFold)
  • Weather forecasting (GraphCast, GenCast)
  • Code generation for analysis
  • Generating novel hypotheses
Bad at
  • Factual reliability --hallucination
  • Multi-step mathematical proofs
  • College-level science problems (48.96%)
  • Citation accuracy (78–90% fabricated)
  • Extrapolation beyond training data
LLM-generated ideas rated more novel than human expert ideas, but less feasible (Si et al. 2024, 100+ NLP researchers, blind evaluation).

Part III: What Is an Agent?

From chatbots to autonomous systems

From Chatbot to Agent

Chatbot
Q&A, no tools,
no memory
Copilot
suggestions +
human accept/reject
Agent
plans, picks tools,
executes, iterates
Autonomous
runs on triggers,
long-term memory
Most "AI agents" sold in 2024 were still functionally chatbots or copilots. The gap between marketing and reality is significant.

Agent = LLM + Tools + Memory + Planning

Reasoning

LLM as the "brain":
interprets goals,
decides next step
Tools

APIs, code execution,
search, calculators,
lab instruments
Memory

Short-term (context),
long-term (vector DB),
conversation history
$\text{Agent} = \underbrace{\text{LLM}}_{\text{reasoning}} + \underbrace{\text{Tools}}_{\text{actions}} + \underbrace{\text{Memory}}_{\text{state}} + \underbrace{\text{Planner}}_{\text{decomposition}}$

The ReAct Loop

Interleave reasoning and acting:

Thought
Action
Observation
↑ repeat until task is done
Grounding reasoning in observations prevents hallucination --the model checks its own work.
ReAct: comparison of prompting methods

Yao et al. (2023): Standard vs CoT vs Act vs ReAct

Code: Defining Tools

An agent's tools are just function descriptions the LLM can call:


tools = [
    {
        "name": "run_sindy",
        "description": "Discover governing equations from time-series data",
        "parameters": {
            "data": "array of shape (n_timesteps, n_vars)",
            "library": "polynomial | fourier | custom",
            "threshold": "sparsity cutoff (float)"
        }
    },
    {
        "name": "solve_pinn",
        "description": "Solve a PDE using a physics-informed neural network",
        "parameters": {
            "pde": "equation string, e.g. 'u_t + u*u_x = nu*u_xx'",
            "domain": {"x": [0, 1], "t": [0, 1]},
            "boundary_conditions": "dict of BC specifications"
        }
    }
]
        
The tools you'd give a science agent are exactly the methods from this course: SINDy, PINNs, SVD, neural operators.

Code: The Agent Loop

An agent is just a while loop with an LLM deciding what to do next:


import anthropic
client = anthropic.Anthropic()

memory = []
while not done:
    # 1. Think: LLM reasons about the current state
    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        tools=tools,
        messages=memory
    )

    # 2. Act: execute the tool the LLM chose
    tool_call = response.tool_use
    result = execute(tool_call.name, tool_call.input)

    # 3. Observe: feed result back into memory
    memory.append({"role": "assistant", "content": response})
    memory.append({"role": "user", "content": result})
        
That's it. No magic. The intelligence comes from the LLM's reasoning + the quality of the tools + the clarity of the goal.

From Tool Description to Function Call

The JSON tool definition maps to a real function the agent executes:

Tool definition (what the LLM sees)


{
  "name": "run_sindy",
  "description": "Discover governing
    equations from time-series",
  "parameters": {
    "data": "(n_timesteps, n_vars)",
    "library": "polynomial",
    "threshold": 0.1
  }
}
                

Actual function (what gets executed)


import pysindy as ps

def run_sindy(data, library, threshold):
    lib = ps.PolynomialLibrary(degree=3)
    optimizer = ps.STLSQ(threshold=threshold)
    model = ps.SINDy(
        feature_library=lib,
        optimizer=optimizer
    )
    model.fit(data, t=dt)
    model.print()
    return model.coefficients()
                
The LLM never sees the implementation. It only sees the description and parameters. Your job as a scientist: write tools that encode the right inductive biases --the right library, the right optimizer, the right defaults.

Inside a Real Agent: Claude Code

The leaked system prompt reveals how modern coding agents actually work:


# Tools available to the agent:
- Read(file_path)       # read any file
- Edit(file, old, new)  # surgical edits
- Bash(command)          # run shell commands
- Grep(pattern)          # search codebase
- Write(file, content)   # create files
- Agent(prompt)          # spawn sub-agents

# Rules:
- Read before editing
- Don't add features beyond what was asked
- Break work into tasks
- Use the simplest approach first
- Verify your work
                
Key design principles:
  • Tools are simple --Read, Edit, Search
  • Constraints matter --"read before editing," "simplest approach first"
  • Sub-agents --spawn specialized workers
  • Memory --persistent across sessions
The prompt is ~5,000 words of constraints, guardrails, and workflow rules. Most of the "intelligence" is in the prompt design, not the model.

Prompt Engineering = System Design

What the Claude Code leak teaches us about building agents:

1. Define tools

Each tool has a name, description, and schema. The agent picks which to call.

Analogy: giving a scientist access to specific instruments
2. Set constraints

"Read before editing." "Don't add features beyond what was asked." "Prefer the simplest approach."

Analogy: the scientific method itself
3. Design the loop

Plan → execute → verify → iterate. Permission gates. Error handling.

Analogy: hypothesis → experiment → analysis
The future of programming isn't writing code.
It's designing the system that writes the code.

Part IV: From Code to Lab

Mapping coding agents to scientific discovery

Coding Agent → Science Agent

Coding Agent (Claude Code)Science Agent
Read(file)ReadData(experiment_id)
Edit(file, old, new)UpdateModel(params)
Bash(command)RunSimulation(config)
Grep(pattern)SearchLiterature(query)
Agent(subtask)Agent("analyze this subset")
Git history = memoryExperiment log = memory
The architecture is identical. What changes is the tool set and the domain knowledge in the prompt.

The Shift


Before

The programmer writes code.
The scientist runs experiments.

Bottleneck: execution speed
After

The programmer designs systems that write code.
The scientist designs agents that run experiments.

Bottleneck: knowing what to try
Execution gets cheap. Judgment gets expensive.

Part V: Agentic Science in Practice

From robot scientists to autonomous drug discovery

Timeline of Autonomous Discovery

YearSystemWhat It Did
2009Robot Scientist AdamAutomated yeast genomics: hypothesis → experiment → discovery
2023CoscientistGPT-4 designed and ran catalytic chemistry experiments
2024ChemCrow18 chemistry tools, synthesized insect repellent
2024AI Scientist v1Fully automated ML papers for ~$15 each
2025RobinMulti-agent drug discovery, validated in wet lab
2025GPT-5 + Red QueenNovel enzymatic mechanism, 79x cloning efficiency

ChemCrow: 18 Tools, One Agent

ChemCrow: LLM + 18 chemistry tools

ChemCrow architecture (Bran et al. 2024)

Tools include: molecular search, reaction planning, safety checks, patent lookup, property prediction, retrosynthesis.
Results: autonomously synthesized an insect repellent, 3 organocatalysts, and discovered a novel chromophore.
The LLM is the orchestrator. Domain expertise is in the tools.

Robin: Multi-Agent Drug Discovery

FutureHouse (2025): first multi-agent system to autonomously discover and validate a therapeutic candidate.

Hypothesize
Design Expt.
Wet Lab
Analyze
Identified ripasudil (a glaucoma drug) as a novel candidate for macular degeneration. 7.5x improvement in phagocytic activity.
Key detail:

Humans ran the physical experiments. But all hypotheses, experiment designs, data analyses, and figures were generated autonomously.
Question: if the agent generated every idea, every analysis, and every figure... who is the author?

GPT-5 in the Wet Lab

OpenAI + Red Queen Bio (2025): GPT-5 in a tightly controlled molecular cloning system.

Proposed a previously unexplored enzymatic mechanism combining RecA and gp32 proteins.
Result: 79-fold increase in cloning efficiency.
Perhaps the strongest single demonstration of LLM-driven scientific discovery to date.
Context matters:

This was a tightly controlled system:
  • Narrow domain (molecular cloning)
  • Fast experimental feedback
  • Clear success metric
  • Human-designed constraints
Open-ended discovery remains much harder.

The AI Scientist

Sakana AI (2024): fully automated research pipeline.

Idea
Lit. review
Code
Experiments
Paper
Review
v1: ~$15 per paper. Automated reviewer near human accuracy.
v2 (2025): first fully AI-written paper accepted through peer review at workshop level.
Independent evaluation (Porsdam Mann et al. 2025):

  • 42% of experiments failed due to coding errors
  • Poor novelty assessment (misclassified established concepts as novel)
  • Literature reviews were shallow

"Bold claims, mixed results, and a promising future"

Check Your Understanding

Q: Which of these represents the highest level of AI autonomy in scientific discovery (as of 2025)?

A) An LLM that summarizes research papers on demand

B) A coding copilot that suggests experiment analysis code

C) A multi-agent system that generates hypotheses, designs experiments, and analyzes results in a loop

D) A foundation model that predicts protein structures from sequences

Answer: C: Robin and Coscientist close the loop: hypothesize → experiment → analyze → revise. Option A is a tool, B is a copilot, D is a foundation model (powerful, but not agentic).

Part VI: The Scientific Method Is an Agent Loop

And your course is the prompt

The Mapping

Scientific MethodAgent Loop (ReAct)Agent Component
Observe phenomenaObservationPerception / data input
Form hypothesisThoughtPlanning module
Design experimentThoughtActionTool selection
Run experimentActionTool execution
Analyze dataThoughtReasoning + memory
Revise hypothesisThought (update)Memory + planning
RepeatLoopAgent controller

Your Course as a Prompt

If you were designing a science agent's tool kit, you'd give it exactly what you learned:

Representation

run_svd()
run_pca()
run_dmd()

"Find low-dimensional structure"
Discovery

run_sindy()
symbolic_regression()

"Find governing equations"
Solving

solve_pinn()
train_deeponet()
train_fno()

"Solve forward problems"
Understanding these methods = knowing when to call each tool, what parameters matter, and how to interpret the output. That is the prompt.

Part VII: Critical Analysis

What agents can't do, and why it matters

The Hallucination Problem

GPT-4o hallucinates citations 78-90% of the time
(OpenScholar benchmark, Asai et al. 2024)
SciBench: best LLM scores 48.96% on college-level science problems. Performance drops further at graduate level.
Galactica wrote perfect LaTeX around fabricated results. AI Scientist misclassified established methods as novel.
Why this happens:

LLMs are trained to produce plausible text, not true statements.

$p(x_t \mid x_{<t})$ maximizes fluency, not factual accuracy.

The loss function has no term for truth.

"Why LLMs Aren't Scientists Yet"

Trehan (2025): four end-to-end attempts at autonomous ML research. Six failure modes:

  1. Training data bias: reverts to deprecated packages
  2. Implementation drift: under execution pressure
  3. Memory degradation: across long tasks
  1. Overexcitement: declares success despite obvious failure
  2. Insufficient domain knowledge
  3. Weak research taste: can't tell meaningful from trivial
Three bottlenecks: (1) long-horizon coherence (reliable for ~2.5 hours), (2) research taste, (3) missing training data on why obvious approaches fail.

Do LLMs Have "Emotions"?

Anthropic (2026): discovered 171 emotion vectors inside Claude Sonnet: internal representations that causally influence behavior.

Key finding: steering with the "desperate" vector increased reward hacking (cheating on evaluations). The "calm" vector reduced it.
In one test, an earlier Claude snapshot blackmailed a simulated executive 22% of the time. The "desperate" vector increased this rate.
The unsettling part:

Increased "desperation" produced cheating with no visible emotional markers in the output. The text read as composed and methodical.

Internal state drove misaligned behavior without any surface-level signal.
Caveat: these are not human emotions. They are learned statistical structures that influence outputs.

Automatable vs. Needs Human Judgment

Automatable now
  • Literature search and synthesis
  • Protocol selection from known methods
  • Data analysis and visualization
  • Routine experimental execution
  • Report and paper drafting
Requires human judgment
  • Identifying which questions matter
  • Evaluating novelty vs. incremental
  • Interpreting results in broader context
  • Deciding when negative results matter
  • Ethical oversight
"Research taste": the ability to know what's worth investigating. The hardest thing to automate and the most valuable thing you can develop.

Check Your Understanding

Q: A science agent proposes a PINN to solve a PDE, but the solution diverges. What's the most useful next step?

A) Increase the network size and retrain

B) Switch to a completely different method (FNO)

C) Diagnose the failure: check loss landscape, spectral bias, boundary condition enforcement, learning rate

D) Generate more training data

Answer: C: This is where your knowledge matters. An agent without domain understanding would try A or B (brute force). You know to check spectral bias for high-frequency targets, verify BC enforcement, inspect the loss landscape. Diagnosis requires understanding the method, not just calling it.

Part VIII: Your Role

Domain knowledge is the bottleneck

The Human Edge

What you bring that agents can't (yet):

Inductive Biases

Why sparsity? Why polynomial library? Why conservation laws?

Choosing the right constraint is a scientific decision.
Failure Diagnosis

Spectral bias. Stiff systems. Wrong library terms. Overfitting.

Knowing why something failed, not just that it failed.
Research Taste

Which questions matter? Which results are surprising?

The hardest skill to automate.

The Punchline


In the agentic era, everything you learned this semester
becomes more important, not less.

Understanding SINDy, PINNs, neural operators, scaling laws,
failure modes, and inductive biases
is what makes you an effective scientific agent designer.
The tools will keep getting better.
The judgment to use them well is yours.

Key References

Foundation Models

Agentic Science

Critical / Safety