# BrainAge — Complete End-to-End Pipeline Guide > **Purpose**: This document describes every step to reproduce the BrainAge > brain-age prediction system from raw MRI scans to a deployed web > application. Provide this file to any AI assistant or human collaborator > and they can replicate the full workflow. --- ## Table of Contents 1. [Project Overview](#1-project-overview) 2. [Hardware & Software Prerequisites](#2-hardware--software-prerequisites) 3. [Repository Layout](#3-repository-layout) 4. [Dataset: The Golden Collection](#4-dataset-the-golden-collection) 5. [Phase 1 — Preprocessing (batch_preprocess)](#5-phase-1--preprocessing) 6. [Phase 2 — Cache Preparation (cache_prep)](#6-phase-2--cache-preparation) 7. [Phase 3 — Train/Val/Test Split (data_split)](#7-phase-3--trainvaltest-split) 8. [Phase 4 — Model Training (train)](#8-phase-4--model-training) 9. [Phase 5 — Evaluation (evaluate)](#9-phase-5--evaluation) 10. [Phase 6 — Post-Training Clinical Finalization (finalize)](#10-phase-6--post-training-finalization) 11. [Phase 7 — Single-Subject Inference (infer_age)](#11-phase-7--single-subject-inference) 12. [Phase 8 — 3D Viewer Demo (viewer)](#12-phase-8--3d-viewer-demo) 13. [Phase 9 — FastAPI Web Application (webapp)](#13-phase-9--fastapi-web-application) 14. [Phase 10 — Deployment](#14-phase-10--deployment) 15. [Troubleshooting](#15-troubleshooting) 16. [File Reference Table](#16-file-reference-table) --- ## 1. Project Overview BrainAge predicts **brain age** from T1-weighted MRI scans using a dual-branch deep learning model (3D SFCN + tabular MLP). A positive brain-age gap (BAG = predicted − chronological) may indicate accelerated brain aging; a negative BAG may suggest delayed maturation. **Pipeline stages:** ``` Raw T1 NIfTI → skull-strip (HD-BET, GPU) → bias correction (N4, ANTs) → MNI registration (ANTs affine) → z-score normalization → segmentation (Harvard-Oxford atlas, 69 regions) → volumetric measurements (per-region mm³) → cache tensor (.pt: 128×144×112 volume + 86-dim tabular vector) → train BrainAgeDual model (SFCN 3D CNN + MLP, regression) → evaluate (MAE, per-age-bin, TTA) → post-training: ComBat harmonization, normative curves, QC → inference: predict brain age for new subjects → 3D viewer: interactive NiiVue + Three.js visualization → web app: FastAPI dashboard + chatbot + PDF reports ``` --- ## 2. Hardware & Software Prerequisites ### Minimum hardware | Component | Requirement | |-----------|------------| | GPU | NVIDIA GPU with ≥ 16 GB VRAM (tested on A10G 24 GB) | | RAM | 16 GB (batch preprocess uses memory watchdog) | | Disk | 200 GB free (raw ~55 GB + cache ~25 GB + outputs + scratch) | ### Software stack ```bash # OS: Ubuntu 22.04+ (tested on 24.04) # Python 3.12+ # Create virtual environment python3.12 -m venv .venv source .venv/bin/activate # Core ML pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121 pip install monai nibabel nilearn antspyx scikit-image # Brain extraction pip install HD-BET # provides `hd-bet` CLI # Pipeline utilities pip install pandas numpy psutil pynvml # Web app (optional, for Phase 9+) pip install fastapi uvicorn[standard] python-multipart jinja2 itsdangerous pip install pydantic-settings sqlalchemy alembic pip install "passlib[bcrypt]" "bcrypt>=4.0,<4.2" pip install groq sentence-transformers faiss-cpu pip install "weasyprint>=62,<63" markdown pypdf httpx # All versions are pinned in webapp/requirements.txt ``` ### Environment variables (`.env`) ```ini GROQ_API_KEY= # for chatbot + PDF narrative GROQ_MODEL=openai/gpt-oss-120b ANTHROPIC_API_KEY= # for Claude-based clinical reports SESSION_SECRET=<64-random-chars> # for webapp sessions ``` --- ## 3. Repository Layout ``` /home/MRI-DataSet/ ├── Golden-0-to-25/ # Raw NIfTIs, 4782 subjects age 0–25 │ ├── manifest.csv # subject_id, age, sex, dataset, file_path, … │ └── DataSet-*_*/ # per-source-dataset folders with NIfTI files ├── Golden-25plus/ # Raw NIfTIs, 1370 subjects age 25–86 │ ├── manifest.csv │ └── DataSet-*_*/ ├── _train/ # Training workspace (gitignored) │ ├── cache/ # .pt tensors (one per subject) │ ├── scratch/ # temporary preprocessing working dirs │ ├── outputs/ # Tier-B clinical artifacts per subject │ └── logs/ # preprocess_status.csv, master.log, err_*.log ├── _demo/ │ └── runs/ # 10 demo subjects with full outputs + meshes ├── pipeline_v2/ # All pipeline code │ ├── preprocess.py # skull-strip + N4 + MNI register + z-norm │ ├── segment.py # Harvard-Oxford atlas segmentation │ ├── batch_preprocess.py # Memory-safe parallel batch driver │ ├── cache_prep.py # Build .pt cache tensors │ ├── data_split.py # Stratified train/val/test split │ ├── model.py # BrainAgeDual (SFCN + tabular MLP) │ ├── train.py # Two-phase training with early stopping │ ├── evaluate.py # Test-set evaluation with TTA │ ├── infer_age.py # Single-subject inference (checkpoint-aware) │ ├── anomaly.py # Per-region z-score anomaly detection │ ├── normative_fit.py # Fit age-conditional region norms │ ├── harmonize.py # ComBat multi-site harmonization │ ├── finalize.py # Post-training orchestrator │ ├── qc.py # Automated quality control │ ├── cognitive_rollup.py # Map regions → cognitive domains │ ├── pattern_detect.py # Detect clinical patterns in region data │ ├── llm_explain.py # Generate clinical narrative (Claude/MedGemma) │ ├── volume_age_prior.py # Literature-based volume-to-age fallback │ ├── backfill_outputs.py # Reconstruct outputs from cache for old runs │ ├── regen_reports.py # Regenerate all report.md files │ ├── run_pipeline.py # Single-subject end-to-end orchestrator │ ├── run_demo_10.py # Quick 10-subject demo │ ├── brainage_sfcn.pt # ← trained checkpoint (created in Phase 4) │ ├── norms.json # ← normative curves (created in Phase 6) │ ├── combat_params.json # ← ComBat params (created in Phase 6) │ ├── vol_age_prior.json # Volume-to-age lookup table │ ├── mni152_T1_1mm_brain.nii.gz │ └── viewer/ # Standalone 3D viewer │ ├── serve.py │ ├── mesh_builder.py │ └── static/ # index.html, viewer.html └── webapp/ # FastAPI web application ├── app/ │ ├── main.py │ ├── config.py │ ├── db.py │ ├── security.py │ ├── deps.py │ ├── models/ # User, Patient, Scan, ChatMessage, AuditLog │ ├── routers/ # auth, index, dashboard, patients, viewer, … │ ├── services/ # groq_client, rag, stats, preprocess_sync, … │ ├── templates/ # Jinja2 HTML │ └── static/ # JS, CSS ├── alembic/ ├── docs/ # RAG corpus (markdown) ├── data/ # DB, uploads, outputs, reports, rag_index ├── Dockerfile ├── docker-compose.yml ├── run_dev.sh └── requirements.txt ``` --- ## 4. Dataset: The Golden Collection ### Manifests Two CSV manifests define the full dataset: | File | Subjects | Age range | |------|----------|-----------| | `Golden-0-to-25/manifest.csv` | 4,782 | 0 – 25 years | | `Golden-25plus/manifest.csv` | 1,370 | 25 – 86 years | | **Total** | **6,152** | **0 – 86 years** | ### Manifest columns ``` dataset, subject_id, split, age_years, age_label_type, chronological_age, brain_age, sex, healthy, modality, notes, file_path, golden_path ``` ### Source datasets (12 total) | ID | Name | Age focus | |----|------|-----------| | DataSet-1 | BCP (Baby Connectome) | 0–5 y | | DataSet-2 | Calgary Preschool | 2–7 y | | DataSet-3 | ds002726 | 3–21 y | | DataSet-4 | ds000248 | 30 y (single adult) | | DataSet-5 | PTBP (Pediatric Template Brain) | 5–18 y | | DataSet-6 | IXI | 20–86 y | | DataSet-7 | MPI-Leipzig | 20–40 y | | DataSet-8 | AOMIC-ID1000 | 18–33 y | | DataSet-9 | NKI-Rockland | 6–85 y | | DataSet-10 | ABIDE-I | 6–56 y | | DataSet-11 | ABIDE-II | 5–60 y | | DataSet-12 | ADHD-200 | 7–22 y | ### Hosted copies - **Hugging Face**: `bilalahmad176176/BrainAge-Golden-Raw` (public) - Each golden_path is a symlink/copy named `__.nii.gz` --- ## 5. Phase 1 — Preprocessing **Module**: `pipeline_v2/batch_preprocess.py` **Input**: Raw T1w NIfTIs listed in manifest.csv **Output**: Preprocessed files in `_train/scratch/proc_/` → cached to `_train/cache/.pt` ### What each step does | Step | Tool | Time/subject | Output | |------|------|-------------|--------| | Skull-strip | HD-BET (GPU) | ~15-30 s | `brain.nii.gz`, `brain_bet.nii.gz` (mask) | | Bias correction | N4 (ANTsPy) | ~10 s | `brain_n4.nii.gz` | | MNI registration | ANTs Affine | ~30 s | `brain_mni.nii.gz`, `brain_mask_mni.nii.gz` | | Z-score normalize | NumPy | <1 s | `brain_mni_znorm.nii.gz` | | Segmentation | Harvard-Oxford atlas | ~2 s | `segmentation.nii.gz`, `measurements.csv` | | Volume rescaling | — | — | Rescales MNI volumes back to native-space proportions | | Anomaly scoring | `anomaly.py` | <1 s | `anomalies.csv` | | Cache tensor | `cache_prep.py` | <1 s | `.pt` (volume fp16 + tab fp32 + age + meta) | ### Command ```bash cd /home/MRI-DataSet source .venv/bin/activate python -m pipeline_v2.batch_preprocess \ --manifests Golden-0-to-25/manifest.csv \ Golden-25plus/manifest.csv \ --cache_dir _train/cache \ --scratch_root _train/scratch \ --logs_dir _train/logs \ --workers 2 ``` ### Memory safety The batch driver has a built-in watchdog: - **RAM throttle at 75 %**, panic SIGSTOP at 85 % - **VRAM throttle at 80 %**, panic SIGSTOP at 90 % - Workers are recycled every N subjects to prevent C-allocator memory creep - `OMP_NUM_THREADS=2` per worker to prevent ANTs from spawning 16 threads ### Resumability - If `cache/.pt` exists → **skipped** (idempotent) - `preprocess_status.csv` is append-only, flushed after every subject - Safe to SIGKILL and restart — picks up where it left off ### Monitoring ```bash # Live progress tail -f _train/logs/master.log # Status counts awk -F, 'NR>1{c[$5]++} END{for(k in c) print k,c[k]}' \ _train/logs/preprocess_status.csv # Cache count ls _train/cache/*.pt | wc -l ``` ### Expected runtime - 6,152 subjects × ~85 s / 2 workers ≈ **72 hours** on A10G - Expect ~1–2 % failures on first pass (mostly input quality issues) - Retry with `--retry-failed` or just rerun (cache skips successes) ### Retry fix (built into preprocess.py) `skull_strip()` has `retries=2` and verifies output file size. `_ants_write_retry()` retries ITK NIfTI writes up to 3× with backoff. These recover ~80 % of transient I/O failures. --- ## 6. Phase 2 — Cache Preparation **Module**: `pipeline_v2/cache_prep.py` **Note**: This is integrated INTO `batch_preprocess.py` — each worker calls cache_prep at the end of its subject processing. No separate run needed. ### Cache tensor format (`.pt`) ```python { "volume": torch.float16, # shape (128, 144, 112) — resized from 182×218×182 "tab": torch.float32, # shape (86,) — 70 region vols (log1p/12) + 3 sex + 13 site "age": torch.float32, # scalar — chronological age in years "meta": dict, # {subject_id, site, sex, age, split} } ``` ### Tabular vector breakdown (86 dimensions) - Dims 0–69: log1p(volume_mm³) / 12 for each of the 70 Harvard-Oxford regions - Dims 70–72: one-hot sex encoding [M, F, U] - Dims 73–85: one-hot site encoding (13 datasets) ### Volume shape Standard resize to `(128, 144, 112)` via trilinear interpolation. Input: `brain_mni_znorm.nii.gz` (182×218×182 in MNI space). --- ## 7. Phase 3 — Train/Val/Test Split **Module**: `pipeline_v2/data_split.py` **Input**: Manifest CSV(s) **Output**: `split.csv` with train/val/test assignments ```bash python -m pipeline_v2.data_split \ --manifests Golden-0-to-25/manifest.csv \ Golden-25plus/manifest.csv \ --out _train/split.csv ``` ### Split strategy - **Stratified by (site, age_bin)** — ensures every site × age combination is represented in all splits - **Age bins**: 0–2, 2–5, 5–12, 12–18, 18–25, 25–50, 50–80 - **Ratios**: 75 % train / 10 % validation / 15 % test - **Deterministic**: seed=42, reproducible ### Result (approximate) | Split | Count | |-------|-------| | train | ~4,614 | | val | ~615 | | test | ~923 | --- ## 8. Phase 4 — Model Training **Module**: `pipeline_v2/train.py` **Architecture**: `pipeline_v2/model.py` — `BrainAgeDual` ### Model architecture: BrainAgeDual ``` Image branch (SFCN — Peng 2021): 3D CNN: Conv3d(1→32→64→128→256→256→64) with BN + MaxPool + ReLU → AdaptiveAvgPool3d(1) → flatten → emb_dim=128 Tabular branch (MLP): Linear(86→128) → ReLU → Dropout(0.3) → Linear(128→128) Fusion: concat(image_emb, tab_emb) → Linear(256→64) → ReLU → Dropout → Linear(64→1) Total params: ~3M Output: predicted age (scalar, years) Loss: L1Loss (MAE) ``` ### Training strategy **Two-phase approach:** #### Phase A — Lifespan pretraining ```bash python -m pipeline_v2.train \ --cache_dir _train/cache \ --split_csv _train/split.csv \ --out_ckpt pipeline_v2/brainage_sfcn.pt \ --epochs 60 \ --batch 4 \ --lr 3e-4 ``` #### Phase B — Fine-tune on 0–25 subset (pediatric focus) ```bash python -m pipeline_v2.train \ --cache_dir _train/cache \ --split_csv _train/split.csv \ --resume_ckpt pipeline_v2/brainage_sfcn.pt \ --age_max 25 \ --epochs 30 \ --lr 1e-4 \ --out_ckpt pipeline_v2/brainage_sfcn.pt ``` ### Training features - **Mixed precision** (fp16) + gradient clipping - **Linear warmup** (5 epochs) + **cosine LR decay** - **Weighted sampler** for age-bin balance (prevents bias toward over-represented age groups) - **MONAI augmentation**: random affine, random flip, intensity shift - **Val-MAE early stopping** (patience=10) - **CSV metrics log**: epoch, train_loss, val_loss, val_mae, lr ### Checkpoint format ```python { "model": state_dict, "optimizer": optimizer_state, "epoch": int, "val_mae": float, "n_tabular": 86, "config": {...} } ``` ### Expected results (on this dataset) | Metric | Expected range | |--------|---------------| | Overall MAE | 2.0 – 3.5 years | | 0–2 y MAE | 1.0 – 2.0 years | | 2–18 y MAE | 1.5 – 3.0 years | | 18+ y MAE | 2.5 – 4.0 years | --- ## 9. Phase 5 — Evaluation **Module**: `pipeline_v2/evaluate.py` ```bash python -m pipeline_v2.evaluate \ --cache_dir _train/cache \ --split_csv _train/split.csv \ --ckpt pipeline_v2/brainage_sfcn.pt \ --out_csv _train/eval_results.csv \ --tta 5 ``` ### What it computes - Per-subject predictions with 5× flip TTA - Overall MAE, median AE, R², correlation - Per-age-bin MAE breakdown - Per-site MAE breakdown - Scatter plot data (true age vs predicted) --- ## 10. Phase 6 — Post-Training Finalization **Module**: `pipeline_v2/finalize.py` This orchestrator runs sequentially after training completes: ```bash python -m pipeline_v2.finalize \ --manifests Golden-0-to-25/manifest.csv \ Golden-25plus/manifest.csv \ --cache_dir _train/cache \ --outputs_dir _train/outputs ``` ### Stage 1: ComBat harmonization (`harmonize.py`) - Removes scanner/site batch effects from per-region volumes - Preserves biological variance (age, sex as covariates) - Output: `pipeline_v2/combat_params.json` ### Stage 2: Normative curve fitting (`normative_fit.py`) - Fits age-conditional mean and SD for each of 70 regions, stratified by sex - Uses monotone cubic splines (similar to Bethlehem 2022 brain charts) - Output: `pipeline_v2/norms.json` - This replaces the synthetic `expected_region_volume()` baseline ### Stage 3: Rebuild anomaly tables - Reruns `anomaly.py` on all subjects using fitted norms instead of crude σ - z-scores become properly calibrated ### Stage 4: BAG confidence intervals - Monte Carlo dropout on the trained model - Adds confidence intervals to each subject's report ### Stage 5: QC re-check - Volume sanity, z-norm range, registration quality - Flags ~3–5 % for manual review ### Manual commands (if not using finalize.py) ```bash # Harmonization alone python -m pipeline_v2.harmonize \ --cache _train/cache \ --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \ --out pipeline_v2/combat_params.json # Normative fit alone python -m pipeline_v2.normative_fit \ --cache _train/cache \ --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \ --out pipeline_v2/norms.json # Backfill outputs for subjects cached before outputs existed python -m pipeline_v2.backfill_outputs \ --cache_dir _train/cache \ --outputs_dir _train/outputs ``` --- ## 11. Phase 7 — Single-Subject Inference **Module**: `pipeline_v2/infer_age.py` ### How it works 1. Checks for `pipeline_v2/brainage_sfcn.pt` 2. **If checkpoint exists**: loads BrainAgeDual, runs 5× flip-TTA inference 3. **If no checkpoint**: falls back to `volume_age_prior.py` (literature-based volume-to-age curve). The response includes `"predicted_source": "volume_prior_untrained"` as an honesty flag. ### Programmatic usage ```python from pipeline_v2.infer_age import predict_age result = predict_age( mni_znorm=Path("brain_mni_znorm.nii.gz"), meas_csv=Path("measurements.csv"), total_brain_mm3=1240000.0, sex="F", site="DataSet-6_IXI" ) # result = {"predicted_brain_age": 32.5, "predicted_source": "sfcn_tta", ...} ``` ### End-to-end single subject ```bash python -m pipeline_v2.run_pipeline \ /path/to/t1.nii.gz \ sub-001 \ 25.0 \ F \ /tmp/output_sub001 ``` --- ## 12. Phase 8 — 3D Viewer Demo **Module**: `pipeline_v2/viewer/serve.py` ```bash # Start the standalone viewer python -m uvicorn pipeline_v2.viewer.serve:app --host 0.0.0.0 --port 8765 # Open http://localhost:8765 ``` ### Features - Subject list with age, predicted age, BAG - NiiVue 2D slice views (axial/coronal/sagittal) - Three.js 3D mesh rendering (marching cubes from segmentation) - Per-region panel: volume, expected, deviation %, z-score, percentile - Tissue composition (GM/WM/CSF ratios) - Bilateral asymmetry index - Lobe-wise abnormality summaries - Cognitive domain rollup - Clinical pattern detection - Top findings bullets ### Demo data 10 subjects in `_demo/runs/` with full outputs including pre-built meshes. ### Hosted version HF Space: `bilalahmad176176/BrainAge-3D-Viewer` --- ## 13. Phase 9 — FastAPI Web Application **Location**: `webapp/` ### Architecture - **Backend**: FastAPI + SQLAlchemy (SQLite) + Alembic migrations - **Frontend**: Jinja2 templates + Tailwind CSS + vanilla JS + Chart.js - **Auth**: Cookie-signed sessions, bcrypt passwords, admin + staff roles - **LLM**: Groq `gpt-oss-120b` streaming via SSE - **RAG**: FAISS + sentence-transformers/all-MiniLM-L6-v2 over project docs - **PDF**: WeasyPrint HTML→PDF with Groq narrative + user signature ### Pages / features | Route | Feature | |-------|---------| | `/` | Landing page + RAG chatbot (project Q&A) | | `/login` | Authentication | | `/dashboard` | KPIs, Chart.js graphs, activity heatmap, recent uploads | | `/patients` | Patient list (CRUD) | | `/patients/new` | Create patient | | `/patients/{pid}/upload` | Upload MRI NIfTI → triggers full pipeline | | `/scans/{id}/view` | 3D viewer + patient-scoped medical chatbot | | `/scans/{id}/report` | Generate + download PDF clinical report | | `/admin/users` | Admin user management | | `/settings` | Signature upload for PDF reports | ### Quick start ```bash cd webapp cp .env.example .env # fill SESSION_SECRET + GROQ_API_KEY ./run_dev.sh # or python -m uvicorn app.main:app --host 0.0.0.0 --port 8011 --reload ``` ### Default credentials | Username | Password | Role | |----------|----------|------| | `admin` | `admin` | admin | **Change the admin password after first login.** ### Database models - `User` (username, email, role, pwd_hash, signature_image_path) - `Patient` (first_name, last_name, dob, sex, notes) - `Scan` (patient_id, uploaded_at, status, predicted_age, bag, file_path) - `ChatMessage` (scan_id, role, content, created_at) - `AuditLog` (user_id, action, detail, created_at) ### How upload processing works 1. User uploads `.nii.gz` on `/patients/{pid}/upload` 2. Server validates NIfTI header, saves to `data/uploads/{pid}/` 3. Creates Scan row (status=processing) 4. Shows full-page spinner (`patients/processing.html`) 5. Blocking call to `preprocess_sync.run_pipeline_for_scan()`: - preprocess → segment → infer_age → score_regions - Copies all outputs (including NIfTIs!) to `data/outputs/{scan_id}/` - Updates Scan row with predicted_age, bag, status=completed 6. Redirects to 3D viewer --- ## 14. Phase 10 — Deployment ### Docker ```bash cd webapp cp .env.example .env # edit SESSION_SECRET, GROQ_API_KEY docker compose up -d --build # browse http://localhost:8000 ``` ### Production checklist 1. Set a real `SESSION_SECRET` (64+ random chars) 2. Set `COOKIE_SECURE=1` behind HTTPS (nginx/Caddy reverse proxy) 3. Restrict `TRUSTED_HOSTS` to your real domain(s) 4. Change admin password after first login 5. Back up `data/webapp.db` and `data/outputs/` regularly 6. Run migrations on upgrade: `docker compose exec web alembic upgrade head` ### Hugging Face Spaces A Docker-based Space is deployed at `bilalahmad176176/BrainAge-3D-Viewer` (standalone viewer with 10 demo subjects, no auth). --- ## 15. Troubleshooting ### Preprocessing | Problem | Cause | Fix | |---------|-------|-----| | `skull_strip: 16000+ s` | Running on CPU (no CUDA) | Ensure `nvidia-smi` works, torch sees GPU | | `NiftiImageIO failed to write` | Transient I/O contention | Built-in `_ants_write_retry()` handles it; if persistent, check disk space | | `brain_bet.nii.gz does not exist` | HD-BET silently failed | `skull_strip()` retries 2×; if persistent, the input NIfTI is likely corrupt | | OOM during batch | Too many workers / too little RAM | Reduce `--workers 1`; watchdog will SIGSTOP at 85% RAM | ### Training | Problem | Fix | |---------|-----| | CUDA OOM | Reduce `--batch 2` or `--batch 1` | | Loss not decreasing | Check split.csv exists and has all subjects; verify cache integrity | | Slow training | Ensure `.pt` cache is on SSD, not NFS | ### Webapp | Problem | Fix | |---------|-----| | `unhashable type: 'dict'` | Starlette TemplateResponse signature changed — pass `request` as 1st arg | | `password cannot be longer than 72 bytes` | Pin `bcrypt>=4.0,<4.2` for passlib compatibility | | Viewer stuck on "loading…" | `brain_mni_znorm.nii.gz` missing from scan output dir — rerun preprocess or backfill | | Port 8000 in use | Change port: `PORT=8011 ./run_dev.sh` | --- ## 16. File Reference Table | File | Purpose | Created by | |------|---------|-----------| | `Golden-*/manifest.csv` | Dataset manifests with age, sex, paths | Manual curation | | `_train/cache/.pt` | Preprocessed tensor cache | `batch_preprocess.py` | | `_train/logs/preprocess_status.csv` | Per-subject status log | `batch_preprocess.py` | | `_train/logs/master.log` | Driver log with progress/ETA | `batch_preprocess.py` | | `_train/split.csv` | Train/val/test assignments | `data_split.py` | | `pipeline_v2/brainage_sfcn.pt` | Trained model checkpoint | `train.py` | | `pipeline_v2/norms.json` | Normative curves (per-region) | `normative_fit.py` | | `pipeline_v2/combat_params.json` | ComBat harmonization params | `harmonize.py` | | `pipeline_v2/vol_age_prior.json` | Volume-to-age fallback curve | `volume_age_prior.py` | | `_train/outputs//` | Tier-B clinical artifacts | `batch_preprocess.py` or `backfill_outputs.py` | | `_demo/runs//` | Demo subjects with full outputs + meshes | `run_demo_10.py` | | `webapp/data/webapp.db` | SQLite database | FastAPI lifespan | | `webapp/data/outputs//` | Web upload scan outputs | `preprocess_sync.py` | | `webapp/data/reports//` | Generated PDF reports | `pdf_generator.py` | --- ## Quick-Start Cheat Sheet ```bash # 1. Preprocess all 6,152 subjects (~72h) python -m pipeline_v2.batch_preprocess \ --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \ --cache_dir _train/cache --scratch_root _train/scratch \ --logs_dir _train/logs --workers 2 # 2. Generate train/val/test split python -m pipeline_v2.data_split \ --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \ --out _train/split.csv # 3. Train (lifespan → finetune) python -m pipeline_v2.train \ --cache_dir _train/cache --split_csv _train/split.csv \ --out_ckpt pipeline_v2/brainage_sfcn.pt --epochs 60 --batch 4 python -m pipeline_v2.train \ --cache_dir _train/cache --split_csv _train/split.csv \ --resume_ckpt pipeline_v2/brainage_sfcn.pt \ --age_max 25 --epochs 30 --lr 1e-4 \ --out_ckpt pipeline_v2/brainage_sfcn.pt # 4. Evaluate python -m pipeline_v2.evaluate \ --cache_dir _train/cache --split_csv _train/split.csv \ --ckpt pipeline_v2/brainage_sfcn.pt --tta 5 # 5. Post-training finalization python -m pipeline_v2.finalize \ --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \ --cache_dir _train/cache --outputs_dir _train/outputs # 6. Launch webapp cd webapp && ./run_dev.sh ``` --- *Last updated: 2026-04-24. Generated from the live BrainAge pipeline on an NVIDIA A10G (24 GB VRAM) / 16 GB RAM / 193 GB disk Ubuntu server.*