tutorial · MRS Spring 2026

Foundation Models Adaptation Tutorial

From few-shot prompting to frozen features to LoRA fine-tuning, with notebook examples, adapted from MRS Spring 26 MT01 tutorial materials

01

Tutorial roadmap

We start with the adaptation options, then cover evaluation, then walk through the XRD notebook examples and results.

I

Foundation models and adaptation

choose what to change

II

Evaluation is part of the method

know whether it worked

III

XRD example

compare the notebook results

part I

Foundation models and how to adapt them

Start with the simplest method that can answer your question. Add complexity only when the evidence calls for it.

02

Where foundation models fit in

Foundation models are deep-learning models trained broadly once, then adapted many times for specific tasks.

Artificial intelligence
systems that perform useful tasks
Machine learning
models that learn from data
Deep learning
models that learn representations
Foundation models
broad pretraining reused for many tasks
language
vision
multimodal
reasoning
generation
science
03

What foundation models can do

A pretrained model can help with routine analysis, natural-language interfaces, and discovery workflows when the task is well defined.

Automate routine tasks

Summarize, classify, extract, write code, and check repeated analysis steps.

Create natural interfaces

Let scientists ask for analysis, metadata, and visual explanations in normal language.

Accelerate discovery

Combine search, simulation, and experiment loops around measured outputs.

04

Pretraining is done once. Adaptation happens in the lab.

Model providers usually handle broad pretraining. Scientific users decide how the model is adapted, tested, and used.

provider
Pretrain

model learns broad patterns from large datasets

lab
Adapt

choose prompts, examples, features, or adapters

workflow
Deploy

use only after behavior has been measured

risks
  • Domain mismatch
  • Hallucinations
  • Hidden failure modes
strategy
  • Benchmark first
  • Adapt if needed
  • Scaffold with workflows
05

The adaptation landscape

This map compares strategies by how much they change the input, how much they change the model, and how much work they require.

less task data
more task data
less trainable compute
more trainable compute

Describe the task and ask the model. Model weights do not change. Useful as a baseline even when you expect it to fail.

labels
0
compute
API or local CPU
iteration
seconds
good for
  • fast triage
  • format testing
  • early prototyping
weak points
  • unstable formats
  • hallucinated labels
  • weaker domain grounding

Click a strategy to compare its costs. More expensive is not automatically better: move to heavier methods only when simpler ones stop making real progress.

Fig. 1 | The adaptation landscape. Click a strategy; the detail panel reports what changes (input, weights, or both) and roughly what it costs.
06

Compute and memory trade-offs

Labels, compute, and iteration time change quickly as you move from prompting to adapters and full fine-tuning.

01
Zero-shot prompt (API)
labels
0
compute
remote API, no local compute
iteration
seconds
02
Zero-shot prompt (local)
labels
0
compute
GPU not necessary, CPU works
iteration
seconds
03
Few-shot prompt (API)
labels
5–50
compute
remote API, no local compute
iteration
seconds / minutes
04
Few-shot prompt (local)
labels
5–50
compute
GPU not necessary, CPU works
iteration
seconds / minutes
05
Frozen features
labels
100 – 10k
compute
encoder needs GPU for forward pass
iteration
minutes
06
LoRA fine-tune (bf16)
labels
1k – 100k
compute
multi-GPU for 7B+ in bf16
iteration
hours
07
QLoRA fine-tune (int4)
labels
1k – 100k
compute
single GPU (int4 quantized base)
iteration
hours
08
Full fine-tune
labels
10k – millions
compute
multi-GPU cluster (all weights)
iteration
days
07

Strategy 0: zero-shot prompting

A good prompt states the task, goal, context, and constraints clearly. Start simple before adding fragile prompt tricks.

simple baseline

Given this diffraction image, identify every anomaly that applies.

01
Task

What should the model do?

02
Goal

What counts as a useful answer?

03
Context

What domain facts or label definitions matter?

04
Specs

What constraints, units, or format should be respected?

good for
  • Fast triage
  • Format testing
  • Early prototyping
weak points
  • Unstable formats
  • Hallucinated labels
  • Weaker domain grounding
Prompt engineering is useful when it clarifies the interface. Newer reasoning models may be less sensitive to highly engineered prompts, so extra prompt details should earn their place.
08

Ask for structured outputs

For automation, the answer needs to be easy to parse and check. A schema helps downstream code trust what it receives.

JSON mode
response_format={"type": "json_object"}

{
  "wavelength_A": 0.9763,
  "detector_distance_mm": 250.0,
  "beam_center_px": [1024, 1024],
  "exposure_s": 0.5
}

Simple and low-boilerplate, but you still need to validate the fields.

structured outputs
class XRDMetadata(BaseModel):
    wavelength_A: float
    detector_distance_mm: float
    beam_center_px: tuple[int, int]
    exposure_s: float | None = None

response_format=XRDMetadata

More setup, but the response is easier to check and use in Python.

gate 1
schema
gate 2
parser
gate 3
validator
09

Few-shot prompting

Few-shot prompting puts worked examples in the prompt. The model weights do not change.

support image for multimodal few-shot prompting
support image
blurry; losing features
support image for multimodal few-shot prompting
support image
major features; low contrast
support image for multimodal few-shot prompting
support image
dark halo artifacts
query image for multimodal few-shot prompting
query image
model predicts labels
multimodal few-shot pattern
Each support example pairs an image with the answer format you want. The query image comes after the examples, and the weights do not change.
teaches
  • Allowed label set
  • Expected answer format
  • Multi-label edge cases
cannot fix
  • A model that cannot read the pattern
  • Data leakage
  • An evaluation split that does not match the task
10

Frozen features

A scientific image becomes an embedding vector. A small classifier then works on those saved vectors.

image
image
frozen encoder
embedding
0.120.68-0.310.440.03-0.770.520.19
small head: kNN / linear classifier / shallow MLP
embedding / featurizer
  • Numeric summary of an image
  • Similar images should be nearby
  • The classifier learns from vectors instead of raw pixels
workflow
  • Run the pretrained encoder once
  • Save one vector per image
  • Train a small head on vectors + labels
  • Evaluate with the same split
11

Example clustering of embeddings

If the encoder is useful, visually similar diffraction patterns should sit near one another in embedding space.

Cluster 1
Cluster 2
Cluster 3
Cluster 4
projected latent space
Projected embedding space with visible clusters.
12

kNN vs. linear probe

Both methods use the same saved embeddings. kNN predicts from nearby examples; a linear probe learns a simple boundary.

embedding space · drag the query point
cleananomalous
linear boundary

Both methods read the same embedding. kNN votes with the 5 nearest labeled points; the linear probe only checks which side of its boundary you are on. Try the pocket of anomalous points at the bottom left: kNN follows the local labels, the linear probe cannot.

kNN (k = 5)
clean
1 of 5 neighbors anomalous
linear probe
clean
side of the fixed boundary
they agree here

Move toward the boundary, or into the bottom-left pocket, to find where the two rules split.

kNN
Store labeled embeddings
Prediction comes from nearby labeled examples.
useful when labels change
linear probe
Learn a boundary
A small model learns a boundary in embedding space.
useful with enough labels
kNN watch-outs
  • Sensitive to noisy labels
  • Needs similarity search at inference
  • Does not give calibrated probabilities by default
linear probe watch-outs
  • Needs enough examples per class
  • Must be re-fit when labels change
  • Does not show similar examples by itself
Fig. 2 | Same embeddings, two classifiers. Drag the query point; kNN votes with its neighbours while the linear probe answers by which side of its boundary the point falls on, and the anomalous pocket shows where they disagree.
13

LoRA fine-tuning

LoRA keeps most model weights fixed and learns a small low-rank update for the task.

W
frozen base
+
B A
small trainable update
=
W + BA
adapted behavior
cost spectrum
  • Full fine-tune: update all weights
  • LoRA: train adapter matrices
  • QLoRA: quantized base plus LoRA adapters
rank r
  • Rank controls adapter size
  • Typical r = 8-32
  • Larger r adds flexibility and overfit risk
adapter files
  • Swap adapters without replacing the base model
  • Each task can have its own adapter
  • QLoRA stores the base in 4-bit and trains adapters in float16
14

Fine-tuning tools

There are many post-training methods beyond this tutorial. Open-source tools make them practical enough to try.

supervised tuning
SFTinstruction tuningadapter tuning
preference tuning
RLHFRLAIFDPOPPO / GRPO
efficient tuning
LoRAQLoRAprompt tuningprefix tuning
model editing
distillationreward modelingtool-use tuning
useful open-source tools
PEFTTRLUnslothAxolotlVERL

These tools make experiments easier to run, but they do not replace clean splits, metrics, and ablations.

part II

Evaluation is part of the method

A model result is only useful if the evaluation matches the scientific question.

15

Train, validation, test - and why it matters

Use training for fitting, validation for choices, and test once for reporting. Split by physical object when related images could leak information.

80%
Train

fit parameters

10%
Validation

choose thresholds and settings

10%
Test

report once

Split by physical object or experiment when related images may share information.
loss curve intuition
earlybest checkpointlatetrain lossvalidation loss

Training loss can keep improving while validation loss turns upward. Report the held-out test result after model choices are finished.

16

Confusion matrices and F1

Precision, recall, and F1 all come from the same four counts. Choose the metric that matches the scientific cost of mistakes.

model scores vs. decision threshold
threshold 0.50

Drag the threshold. Coral dots are mistakes: positives that fall below it (FN) and negatives that clear it (FP). Every metric on the right is just a different way of counting them.

TP19

predicted +, actually +

FP9

predicted +, actually -

FN5

predicted -, actually +

TN27

predicted -, actually -

precision
0.68
recall
0.79
F1
0.73
Fig. 3 | One threshold, four counts. Move the decision threshold and watch TP, FP, FN and TN redistribute, dragging precision, recall and F1 with them.
17

Multi-label metrics: micro-F1 and macro-F1

Micro-F1 pools all decisions. Macro-F1 makes rare labels visible.

example image
ground truth
ice ring, halo
prediction
ice ring
exact match?
no, but not necessarily scientifically useless
per-label F1 on a synthetic test set
ice ring40 instances0.90
halo30 instances0.85
loop scattering6 instances0.44

The two common labels stay fixed. Only the rare label degrades, and the two averages tell very different stories about it.

micro-F1
0.85

Pools all decisions first. Frequent labels dominate, so it barely notices the rare label failing.

macro-F1
0.73

Averages per-label scores. The rare label carries a full third of the weight, so its failure is visible.

Thresholds are part of the method. Lower thresholds catch more anomalies but create more false alarms; higher thresholds are cleaner but miss subtle cases. Tune on validation, not test.
Fig. 4 | Micro vs macro F1. Slide the number of missed rare anomalies; pooled micro-F1 barely moves while macro-F1 falls, because rare labels only count when averaged per class.
18

Non-classification metrics

Use the lightest evaluator that can catch the failure: schema checks, runnable tests, reference answers, grounding checks, or judges.

first question
What makes this output wrong?
Format fixed?

Use schema checks and parsers.

Code must run?

Run unit tests, examples, and integration tests.

Known answer?

Compare against reference outputs.

Must cite evidence?

Check grounding, retrieval, and source coverage.

Open-ended quality?

Use rubrics, human review, or LLM judges as a last layer.

Pick the lightest reliable evaluator before asking another model to judge the answer.
part III

The XRD example

A public diffraction dataset, three notebooks, and a reminder to measure before adding complexity.

19

The public dataset

The RefleX dataset has 6,311 diffraction images, seven anomaly labels, official splits, and many images with more than one anomaly.

6,311
total images
1024 × 1024
pixels per PNG
7
anomaly labels
72.1%
contain > 1 anomaly
Background ring60.5 %
Strong background46.6 %
Loop scattering46.4 %
Non-uniform detector33.7 %
Artifact15.6 %
Ice ring7.6 %
Diffuse scattering7.2 %
RefleX dataset: Zenodo DOI 10.5281/zenodo.2605120.
20

The task: multi-label XRD anomaly detection

Input one diffraction image. Return every anomaly label that applies.

Grid of XRD anomaly examples.
output
Return every anomaly that applies. A single image may have multiple labels.
21

Preparing scientific images for foundation models

Dynamic range choices matter. The training and inference preprocessing should be the same.

raw detector view
raw detector view
preprocess
scale

clip, log-scale, normalize

pipeline
model input

use the same transform for training and inference

dynamic range
  • Detector counts span orders of magnitude
  • Raw values can exceed 10,000
  • Natural-image encoders expect different image statistics
bit-depth conversion
  • Convert 16-bit detector images before modeling
  • Use a fixed range for comparability
  • Percentile normalization can reduce outlier effects
log scaling
  • Use log10(x + epsilon) when needed
  • Compress bright peaks
  • Expose weak features humans inspect
22

Notebook 1: few-shot prompting

Send diffraction images and text examples in the prompt. The model weights never change.

notebook access
QR code for Notebook 1: few-shot prompting
what it does
few-shot prompting
images plus a text prompt; weights never change
focus
  • Prompt design
  • Output parsing
  • Effect of adding support examples
  • Set OPENAI_API_KEY before running
k = 0
0.53
k = 1
0.61
k = 3
0.60
k = 5
0.67
k = 7
0.63

Random support examples can miss important labels. A stronger version would choose examples by similarity and label balance.

23

Notebook 2: frozen features + light classifier

Encode the images once with CLIP, then fit kNN or a linear classifier on the embeddings.

notebook access
QR code for Notebook 2: frozen features + light classifier
what it does
frozen CLIP + light classifier
encode once, then fit kNN or linear classification heads
details
  • Frozen CLIP ViT-L/14-336 encoder
  • Mean-max pooled patch-token embeddings
  • Heads: kNN, one-vs-rest logistic regression, low-shot logistic regression
  • The encoder is reused rather than retrained
CLIP ViT-L/14-336 + kNN
0.851 micro-F1

0.819 macro-F1 on full RefleX test set

Logistic regression (one-vs-rest, val-tuned threshold)
0.826 micro-F1

0.789 macro-F1 with validation-tuned threshold

24

Notebook 3: LoRA fine-tuning of Gemma 3 4B

Fine-tune Gemma 3 4B with QLoRA, PEFT, and TRL. In this run, extra few-shot examples hurt after SFT.

notebook access
QR code for Notebook 3: LoRA fine-tuning of Gemma 3 4B
what it does
Gemma 3 4B + QLoRA
PEFT + TRL SFTTrainer with a 4-bit quantized base model
recipe and warnings
  • LoRA r=16, alpha=16, dropout 0.05
  • 1 epoch, lr 2e-4, gradient accumulation 4, MAX_SOFT_TOKENS=280
  • Accept the model terms before downloading
  • A free-tier T4 GPU is not enough for this run
k = 0
0.80
k = 1
0.72
k = 3
0.73
k = 5
0.73
k = 7
0.74

After SFT, extra in-context examples made this run worse. Measure the adapted model both with and without examples.

25

Simpler methods can be better

On this benchmark, frozen CLIP plus kNN is simpler and stronger than the more complex alternatives tested here.

GPT-5 few-shot (k=5)67 % micro-F1
API model on 16-image curated split
Frozen CLIP + kNN85.1 % micro-F1
full 632-image test set
Frozen CLIP + linear82.6 % micro-F1
full 632-image test set
Gemma 3 4B LoRA (k=0)80 % micro-F1
full 632-image test set
Note: GPT-5 few-shot used a curated 16-image sample, while kNN and LoRA used the full 632-image test set. Treat the bars as a practical comparison, not a controlled leaderboard.
26

SFT and few-shot may not help each other

Prompting and fine-tuning do not automatically combine well. Test the combined setup before relying on it.

what it does
GPT-5 few-shot
examples help up to k = 5
k = 0
0.53
k = 1
0.61
k = 3
0.60
k = 5
0.67
k = 7
0.63
what it does
Gemma after SFT
examples hurt this adapted model
k = 0
0.80
k = 1
0.72
k = 3
0.73
k = 5
0.73
k = 7
0.74
Note: the GPT-5 group is a curated 16-image test; the Gemma LoRA group is the full 632-image test.
wrap-up

Glossary

Key terms from the tutorial, related ptychography references, and acknowledgements.

27

Glossary

A quick reference for the main terms used above.

Zero-shot

Ask the model directly, no worked examples.

Few-shot

Include a handful of worked examples in the prompt.

Embedding

A numeric summary of an image or text.

Encoder

The model part that turns input into a representation.

kNN

Predict from the most similar labeled examples.

Linear classifier

A simple rule drawn in feature space.

Fine-tuning

Updating model weights on your task.

Adapter / LoRA

A small trainable add-on instead of full retraining.

Quantization

Lower-precision storage to save memory.

Leakage

Related samples in train and test that inflate scores beyond real-world performance.

Micro-F1 / Macro-F1

Pool-then-score (micro) vs. score-then-average across classes (macro).

SFT

Supervised fine-tuning on labeled input–output pairs.

QLoRA

LoRA on a quantized base model, often small enough for a single GPU.

OOD

Out-of-distribution: inputs unlike what the model trained on.

For ptychography examples beyond this XRD tutorial, see arXiv:2511.02503 and arXiv:2410.09034, which show how LLMs and VLMs can be adapted to ptychography tasks and how agentic workflows can be built around tested model recipes.

Acknowledgement: this research used resources of the Advanced Photon Source, a U.S. DOE Office of Science User Facility operated under Contract DE-AC02-06CH11357, with funding support from Argonne LDRD 2023-0049. Thanks to APS MIC/CAI/SDM groups, USC Shao Group, Rice Han Group, and Cornell Muller Group.