Local-first Transformer for single-cell perturbation response prediction, trained on Norman2019 (K562 · 10,500 cells · 512 HVGs · 105 single-gene conditions).
Tech stack: Python 3.11 · PyTorch · scanpy · scikit-learn · XGBoost · Streamlit · uv
| Model | Unseen Pearson | Unseen MSE | Top-100 DEG Overlap |
|---|---|---|---|
| Transformer | 0.824 | 0.0011 | 0.976 |
| MLP | 0.837 | 0.00085 | — |
| XGBoost | 0.840 | 0.00084 | — |
All three models generalize to unseen perturbations with Pearson ≥ 0.82.
The Transformer's top-100 DEG overlap of 0.976 confirms that predicted
expression shifts identify the correct differentially expressed genes at high recall.
Across 3 real Transformer seeds (42, 7, 21), unseen Pearson is
0.830 +/- 0.007 and unseen top-100 DEG overlap is 0.985 +/- 0.007.
See Real Norman2019 results for per-split tables and figures.
Provenance guardrail: unless a section is explicitly labeled synthetic, metrics in this README refer to the real Norman2019 run. The synthetic showcase exists only for offline pipeline/UI demos and must not be cited as biological performance.
No dataset download required to try the offline demo:
# 1. Set up environment
./scripts/bootstrap_env.sh && source .venv/bin/activate
# 2. Generate offline synthetic showcase (trains all three models)
./scripts/run_generate_synthetic_showcase.sh
# 3. Launch Streamlit app
./scripts/run_app.shThis quick start uses the synthetic offline showcase. It is intended for product/demo validation, not for reporting real perturbation biology results.
For the full Norman2019 real-data flow, see Real Norman2019 workflow below.
Build a job-ready MVP that can:
- preprocess public Perturb-seq data into a reproducible training set
- predict perturbation-induced expression changes with a Transformer
- compare against MLP and XGBoost baselines
- produce DEG-based target rankings
- expose inference results in a Streamlit demo
See docs/architecture.md for model and data-flow details.
- dataset:
scPerturb / Norman2019 - sample scope: single-gene perturbations only
- target:
delta expression - primary metric:
per-perturbation Pearson - default HVG count:
512
This repository now uses uv as the default environment and dependency manager.
- Python version:
3.11 - local virtual environment:
.venv - local uv cache:
.uv-cache - dependency source of truth:
pyproject.toml - locked dependency snapshot:
uv.lock
Create the local development environment:
./scripts/bootstrap_env.shThis will:
- create
.venvin the current repository - install Python
3.11ifuvneeds to fetch it - sync runtime and dev dependencies with
uv
source .venv/bin/activateYou can also avoid manual activation and run everything through uv run or the shell wrappers in scripts/.
Run tests:
./scripts/run_tests.sh
# or
make testRun linting and type checking:
make lint # ruff check --fix
make typecheck # mypy src/Inspect local project/demo readiness:
./scripts/run_doctor.sh
# or
make doctorThe doctor command checks:
- core repository files (
README.md,PROJECT_PLAN.md,pyproject.toml,uv.lock, CI workflow) - local environment pinning (
.python-version,.venv) - notebooks
- offline synthetic demo artifacts
- real Norman2019 bundle and result artifacts
- model-comparison summaries for MLP and XGBoost
Export an interview-friendly project snapshot:
./scripts/run_snapshot.sh
# or
make snapshotUseful variants:
./scripts/run_snapshot.sh --json
./scripts/run_snapshot.sh --output-path artifacts/project_snapshot.jsonThe snapshot command summarizes:
- project readiness modes from
doctor - headline real-data results across Transformer / MLP / XGBoost
- Transformer DEG-overlap highlights
- Transformer multi-seed stability when
artifacts/multi_seed_report.jsonis available - Transformer error-analysis highlights when
*_error_summary.jsonartifacts are available - key demo asset paths
- recommended commands for a live walkthrough
Prepare a live interview/demo flow:
./scripts/run_showcase.sh
# or
make showcaseLaunch the showcase and open the app immediately:
./scripts/run_showcase.sh --launch-appThe showcase command:
- reuses real Norman2019 artifacts when available
- regenerates the offline synthetic showcase only when needed
- writes
artifacts/project_snapshot.json - surfaces a talk track for stability plus failure-case highlights when saved diagnostics exist
- prints the recommended order for a live walkthrough
Export an interview speaking script:
./scripts/run_pitch.sh
# or
make pitchUseful variants:
./scripts/run_pitch.sh --track ai4bio
./scripts/run_pitch.sh --track ml-engineering
./scripts/run_pitch.sh --json
./scripts/run_pitch.sh --output-path artifacts/interview_script.txtThe pitch command includes:
- 30-second project intro
- 2-minute technical walkthrough
- real Transformer multi-seed stability when available
- saved error-analysis / failure-case talking points when available
- live demo script
- honest limitations
- next-step talking points
- suggested answers to common interviewer questions
Install pre-commit hooks (runs ruff automatically before each commit):
source .venv/bin/activate
pre-commit installStart the Streamlit app:
./scripts/run_app.shThe app prefers the real local demo artifacts when they exist:
- bundle:
data/processed/norman2019_demo_bundle - artifact dir:
artifacts/transformer_seen_norman2019_demo - checkpoint:
<artifact dir>/best_model.pt
Offline fallback when raw data download is unavailable:
./scripts/run_generate_synthetic_demo.shThis generates a clearly labeled synthetic bundle and demo artifacts:
- bundle:
data/processed/synthetic_demo_bundle - artifact dir:
artifacts/transformer_seen_synthetic_demo - files:
best_model.pt,seen_test_metrics.json,unseen_test_metrics.json,deg_artifact.csv,run_summary.json
When the real Norman2019 demo artifacts are absent but the synthetic ones exist, the Streamlit app will default to the synthetic paths automatically. The app now surfaces whether the loaded artifacts are real or synthetic, and the model-comparison tab filters rows to the active provenance mode to avoid mixing the two.
Generate the full offline showcase, including baselines and result figures:
./scripts/run_generate_synthetic_showcase.shThis also produces:
artifacts/mlp_seen_synthetic_demo/artifacts/xgboost_seen_synthetic_demo/docs/assets/model_comparison_seen_synthetic_demo.pngdocs/assets/transformer_inference_preview_synthetic_demo.png
Current app behavior:
- load a saved torch checkpoint
- select a perturbation gene from the processed bundle
- run aggregated inference for that perturbation
- if
deg_artifact.csvexists in the artifact directory, combine predicted delta with real DEG significance - if
multi_seed_report.jsonexists, show Transformer multi-seed stability for the active real/synthetic mode - if
*_error_summary.jsonand*_per_perturbation.csvexist, show split-level failure highlights and selected-perturbation condition-level explanations - if
docs/assets/transformer_error_analysis_preview.pngexists, show the saved error-analysis preview figure inside the Diagnostics tab - show predicted vs observed delta, top predicted genes, true DEG rows, target ranking, and top-k DEG overlap
Preprocess a dataset bundle:
./scripts/run_preprocess_demo.sh \
--input-path data/raw/your_dataset.h5ad \
--output-dir data/processed/demo_bundleDownload the default Norman2019 dataset:
./scripts/download_norman2019.shIf curl keeps resetting on your network, retry with the alternate backend:
./scripts/download_norman2019.sh --backend wgetIf you downloaded the file manually, verify the checksum before continuing:
./scripts/download_norman2019.sh --verify-onlyInspect AnnData schema and auto-resolved columns:
./scripts/run_inspect_anndata.sh \
--input-path data/raw/NormanWeissman2019_filtered.h5ad \
--output-json data/interim/norman2019_schema.jsonRun the full Norman2019 local demo flow:
./scripts/run_norman2019_demo.shTrain the Transformer:
./scripts/run_train_transformer.sh \
--bundle-dir data/processed/demo_bundle \
--output-dir artifacts/transformer_seenTrain baselines:
./scripts/run_train_baselines.sh \
--bundle-dir data/processed/demo_bundle \
--output-dir artifacts/baselines \
--baseline mlpThe baseline output directory stores split-specific metrics:
mlp_seen_test_metrics.jsonandmlp_unseen_test_metrics.jsonxgboost_seen_test_metrics.jsonandxgboost_unseen_test_metrics.jsonxgboost_model.joblibandxgboost_run_summary.jsonfor the tree baseline
Generate a real DEG artifact for app ranking:
./scripts/run_generate_deg_artifact.sh \
--input-path data/raw/NormanWeissman2019_filtered.h5ad \
--bundle-dir data/processed/norman2019_demo_bundle \
--output-dir artifacts/transformer_seen_norman2019_demoEvaluate a saved model:
./scripts/run_evaluate.sh \
--bundle-dir data/processed/demo_bundle \
--checkpoint-path artifacts/transformer_seen/best_model.pt \
--model-type transformer \
--output-path artifacts/transformer_seen/test_metrics.json \
--deg-artifact-path artifacts/transformer_seen/deg_artifact.csvWhen --deg-artifact-path is provided, the evaluation also computes top-k DEG overlap metrics.
It can also emit perturbation-level error analysis artifacts:
./scripts/run_evaluate.sh \
--bundle-dir data/processed/demo_bundle \
--checkpoint-path artifacts/transformer_seen/best_model.pt \
--model-type transformer \
--output-path artifacts/transformer_seen/test_metrics.json \
--deg-artifact-path artifacts/transformer_seen/deg_artifact.csv \
--per-perturbation-output-path artifacts/transformer_seen/test_per_perturbation.csv \
--error-summary-output-path artifacts/transformer_seen/test_error_summary.jsonThe perturbation-level CSV is useful for answering:
- which perturbations perform worst
- whether errors come from low-signal conditions, magnitude underestimation, or high residual mismatch
- which genes dominate the residual for a failed condition
Evaluate all three models in one command:
./scripts/run_full_evaluation.sh
# or
make evalThis evaluates Transformer and MLP on both seen and unseen test splits. XGBoost metrics are already written at train time. For Transformer and MLP it also writes:
- split-specific perturbation-level CSV files
- split-specific
*_error_summary.jsonfiles listing the worst conditions
Write a structured local run summary:
./scripts/run_summarize_run.sh \
--bundle-dir data/processed/demo_bundle \
--output-dir artifacts/transformer_seen \
--checkpoint-path artifacts/transformer_seen/best_model.pt \
--model-type transformer \
--split-prefix seen \
--seen-metrics-path artifacts/transformer_seen/seen_test_metrics.json \
--unseen-metrics-path artifacts/transformer_seen/unseen_test_metrics.jsonMulti-seed reporting:
# create repeated runs with distinct output dirs
./scripts/run_train_transformer.sh \
--bundle-dir data/processed/norman2019_demo_bundle \
--output-dir artifacts/transformer_seen_norman2019_seed7 \
--seed 7
# record the actual seed in run_summary.json
./scripts/run_summarize_run.sh \
--bundle-dir data/processed/norman2019_demo_bundle \
--output-dir artifacts/transformer_seen_norman2019_seed7 \
--checkpoint-path artifacts/transformer_seen_norman2019_seed7/best_model.pt \
--model-type transformer \
--split-prefix seen \
--seen-metrics-path artifacts/transformer_seen_norman2019_seed7/seen_test_metrics.json \
--unseen-metrics-path artifacts/transformer_seen_norman2019_seed7/unseen_test_metrics.json \
--seed 7
# aggregate mean/std across repeated runs
./scripts/run_multi_seed_report.sh --artifact-root artifacts
./scripts/run_multi_seed_report.sh --artifact-root artifacts --json \
--output-path artifacts/multi_seed_report.jsonThe current real Transformer aggregate groups
transformer_seen_norman2019_demo with transformer_seen_norman2019_seed7
and transformer_seen_norman2019_seed21, yielding:
- seen Pearson:
0.601 +/- 0.007 - unseen Pearson:
0.830 +/- 0.007 - seen top-100 DEG overlap:
0.964 +/- 0.002 - unseen top-100 DEG overlap:
0.985 +/- 0.007
Synthetic and real artifact groups are kept separate in artifacts/multi_seed_report.json.
The repository includes committed synthetic showcase figures that can be regenerated with:
./scripts/run_generate_synthetic_showcase.shUse this offline showcase for:
- local product and UI demos
- interview-time walkthroughs of the training/evaluation pipeline
- repository validation when the real dataset is not available yet
Do not present these synthetic metrics as real biological results.
| Model | Seen Test Pearson | Seen Test MSE | Unseen Test Pearson | Unseen Test MSE |
|---|---|---|---|---|
| Transformer | 0.9988 | 0.0040 | 0.9989 | 0.0040 |
| MLP | 0.9984 | 0.0047 | 0.9995 | 0.0036 |
| XGBoost | 0.9992 | 0.0046 | 0.9999 | 0.0014 |
Interpretation:
- the offline showcase verifies that preprocessing artifacts, model training, evaluation, ranking, and visualization all run locally
- all models perform strongly on the synthetic task because the signal is intentionally structured and low-noise
- this section is useful for engineering demonstration, not for claiming real perturbation biology performance
The preview above is generated from the same synthetic checkpoint and bundle that the app can fall back to automatically.
Launch the interactive app locally with:
./scripts/run_app.shRegenerate the README result assets with:
./scripts/run_generate_results_assets.shThis now refreshes:
docs/assets/model_comparison_seen_norman2019_demo.pngdocs/assets/transformer_inference_preview.pngdocs/assets/transformer_error_analysis_preview.png
For the offline synthetic showcase:
./scripts/run_generate_synthetic_showcase.shThe figures below are generated from the real Norman2019 dataset
(scPerturb / Norman2019, K562, single-gene perturbations, 10,500 cells, 512 HVGs, 105 conditions).
| Model | Seen Test Pearson | Seen Test MSE | Unseen Test Pearson | Unseen Test MSE |
|---|---|---|---|---|
| Transformer | 0.604 | 0.0071 | 0.824 | 0.0011 |
| MLP | 0.633 | 0.0066 | 0.837 | 0.00085 |
| XGBoost | 0.618 | 0.0066 | 0.840 | 0.00084 |
Transformer top-k DEG overlap (seen_test / unseen_test):
- top-20: 0.816 / 0.930
- top-50: 0.914 / 0.953
- top-100: 0.964 / 0.976
All three models achieve Pearson ≥ 0.82 on unseen perturbations, indicating strong generalization. The Transformer top-100 DEG overlap of 0.96–0.98 confirms that predicted expression shifts identify the correct differentially expressed genes at high recall.
Transformer multi-seed stability on the real Norman2019 bundle
(transformer_seen_norman2019_demo, transformer_seen_norman2019_seed7,
transformer_seen_norman2019_seed21):
- seen Pearson:
0.601 +/- 0.007 - unseen Pearson:
0.830 +/- 0.007 - seen top-100 DEG overlap:
0.964 +/- 0.002 - unseen top-100 DEG overlap:
0.985 +/- 0.007
This 3-run spread is modest, so the Transformer story is not coming from one cherry-picked seed.
The aggregate report is written to artifacts/multi_seed_report.json.
The split-specific *_error_summary.json artifacts show that the current real-data failure cases are
dominated by low-signal perturbations, not by widespread directional collapse:
- Transformer unseen worst Pearson:
MAP2K6(pearson=0.565,mse=0.0010) - Transformer unseen worst MSE:
FOXO4(pearson=0.873,mse=0.00164) - MLP unseen worst Pearson:
KMT2A(pearson=0.676,mse=0.00085) - MLP unseen worst MSE:
SAMD1(pearson=0.922,mse=0.00129)
On the seen split, the more pathological cases are easier to separate:
- low-support conditions such as
ZC3HAV1andTBX2 - magnitude overestimation on
CEBPE - high-residual mismatch on
SPI1
This makes the next debugging step clearer: prioritize condition-level signal strength and sample support
before assuming the core perturbation representation is fundamentally broken.

The error-analysis preview figure condenses the saved seen/unseen failure summaries plus a selected-condition story for the preview perturbation, so the README and interview assets can show not just aggregate metrics but also what kind of failure is happening and where it concentrates.
Regenerate these figures after training with:
./scripts/run_generate_results_assets.shReal Norman2019 raw data and generated artifact directories are intentionally not committed by default.
Once data/raw/NormanWeissman2019_filtered.h5ad is present and verified, the supported local flow is:
./scripts/run_norman2019_demo.sh
./scripts/run_train_transformer.sh \
--bundle-dir data/processed/norman2019_demo_bundle \
--output-dir artifacts/transformer_seen_norman2019_demo
./scripts/run_train_baselines.sh \
--bundle-dir data/processed/norman2019_demo_bundle \
--output-dir artifacts/mlp_seen_norman2019_demo \
--baseline mlp
./scripts/run_train_baselines.sh \
--bundle-dir data/processed/norman2019_demo_bundle \
--output-dir artifacts/xgboost_seen_norman2019_demo \
--baseline xgboostAfter the real bundle exists, regenerate real-data figures with:
./scripts/run_generate_results_assets.shThe notebooks/ directory contains two runnable Jupyter notebooks.
Launch them with:
source .venv/bin/activate
jupyter lab notebooks/| Notebook | Description |
|---|---|
01_data_exploration.ipynb |
EDA of the Norman2019 bundle: dataset overview, perturbation frequency, control-mean distributions, delta-expression histogram, per-perturbation heatmap |
02_model_comparison.ipynb |
Side-by-side metrics for Transformer, MLP, XGBoost; top-k DEG overlap; saved error-analysis highlights and worst-case tables; selected-condition failure story; training curves |
Both notebooks load from data/processed/norman2019_demo_bundle and artifacts/.
Run ./scripts/run_norman2019_demo.sh first to generate the required bundle.
PROJECT_PLAN.md: development plan and architecture decisionsAGENTS.md: implementation constraints and anti-drift guardrailsdocs/architecture.md: model and data-flow detailsdocs/artifact-generation-guide.md: script dependency DAG and recommended execution orderpyproject.toml: uv project definition and dependency source of truthconfigs/data.yaml: data and preprocessing defaultsconfigs/model.yaml: model and memory defaultsconfigs/train.yaml: training, evaluation, and ranking defaults
- bootstrap the environment with
./scripts/bootstrap_env.sh - place a
.h5adfile underdata/raw/ - optionally inspect schema resolution with
./scripts/run_inspect_anndata.sh - preprocess it into a bundle under
data/processed/ - train a minimal Transformer on the seen split
- evaluate seen and unseen metrics
- write
run_summary.jsonfor the completed experiment - inspect ranking outputs or start Streamlit for demo artifacts
requirements.txtis kept as a compatibility fallback; updatepyproject.tomlfirst and refreshuv.lockwithuv sync.- the shell wrappers export
UV_PROJECT_ENVIRONMENT,UV_CACHE_DIR, andPYTHONPATHso the project can be run consistently from the repo root - if you change runtime dependencies, resync with
./scripts/bootstrap_env.sh - each meaningful local training run should keep
history.json,best_model.pt, evaluation JSONs, andrun_summary.jsonin the same artifact directory



