A Knowledge-guided Optimization Framework Enables Computationally Efficient Adaptation of Whole-Slide Foundation Models
PathSculpt adapts a frozen slide-level foundation model (SLFM; TITAN or PRISM) to a diagnostic task while encoding only a small, task-relevant part of each whole-slide image (WSI). Pathology knowledge, written as class-specific cell- and tissue-level descriptions, is turned into visual anchors with a vision-language text encoder (CONCH). The anchors drive two steps:
- Knowledge-anchored importance sampling (KIS) scores up to 2,048 evenly spaced candidate patches with a lightweight VLM image encoder and selects 256 of them for the heavyweight SLFM patch encoder.
- Knowledge-guided token merging (KTM) progressively merges redundant tokens inside the slide encoder, guided by the same importance scores, so that the tokens deemed most important are preserved.
Only the learnable prompt tokens of the descriptions and a linear classification head are trained; all encoders stay frozen.
models/pathsculpt_common.py– knowledge anchors, learnable prompts and the AdaSP loss, KIS (task-relevance and task-discriminability scores), Gumbel top-k selectionmodels/pathsculpt_titan.py,models/pathsculpt_prism.py– PathSculpt on TITAN (CONCH v1.5 features) and PRISM (Virchow features)models/ktm.py– KTM attached at run time to the official Hugging Face TITAN and PRISM modelsmodels/merge.py– importance-weighted bipartite token matching (adapted from ToMe, see Licenses)train.py,scripts/– k-fold training with evaluation on an external cohorttext_prompts/– example description files
Raw WSIs, extracted features, label files, splits and model weights are not included.
conda create -n pathsculpt python=3.11 -y
conda activate pathsculpt
pip install -r requirements.txtrequirements.txt lists the versions the code was tested with (PyTorch 2.6.0, transformers 4.51.3, timm 1.0.15). CONCH is installed from https://github.com/Mahmoodlab/CONCH; its checkpoint (conch.bin) is passed with CONCH_CHECKPOINT.
The slide encoders are downloaded from Hugging Face and need approved access:
- TITAN:
MahmoodLab/TITAN - PRISM:
paige-ai/Prism
huggingface-cli loginKTM wraps the forward pass of these models. The code pins the model revision it was validated against (TITAN_REVISION / PRISM_REVISION); override it with ENCODER_REVISION=<sha> or point ENCODER_NAME to a local copy of the official model.
We recommend TRIDENT for tissue segmentation, patching (20×, 512 px, no overlap) and feature extraction. Each slide needs two feature files with the same patches in the same order:
| role | TITAN | PRISM |
|---|---|---|
| primary (SLFM patch encoder) | features_conch_v15 |
features_virchow |
| secondary (KIS scoring, CONCH space) | features_conch_v1 |
features_conch_v1 |
<cohort>/features/20x_512px_0px_overlap/
├── features_conch_v15/<slide_id>.h5
└── features_conch_v1/<slide_id>.h5
Each H5 file contains features [num_patches, dim] and coords [num_patches, 2] (level-0 pixel coordinates). coords.attrs["patch_size_level0"] is used when present.
Labels. One CSV per cohort with slide_id,case_id,label.
Splits. site_splits/<SPLIT>/splits_<fold>.csv with columns train,val,test. Training and validation slides come from the training cohort (e.g. TCGA, split by tissue source site); the test column lists the slides of the external validation cohort.
Tasks. Each task in scripts/tasks.json gives the label files, class dictionary, feature roots, split directory and exp_code. Edit the paths to your local layout.
A description file has two levels, each a list with one group of descriptions per class:
{
"desc_cell": [["class 0 cell-level descriptions", "..."], ["class 1 ...", "..."]],
"desc_tissue": [["class 0 tissue-level descriptions", "..."], ["class 1 ...", "..."]]
}- Any number of classes. Add one group per class (in the order of
label_dict). Groups may contain different numbers of descriptions. For K classes, the task-discriminability score is||M_R p|| / ||M_R||_F, where the rows ofM_Rare the centred class anchors; for K = 2 this is the projection onto the difference of the two class anchors. - Multi-label tasks. Give one negative and one positive group per binary label and add
"label_pairs": [[neg_0, pos_0], [neg_1, pos_1], ...](group indices). The score is then the root mean square of the per-label binary scores. This affects patch scoring only; the training script in this repository trains single-label classifiers.
See text_prompts/brca_er_2l_gpt54_v2.json for an example. Files are looked up as text_prompts/<task>_<n_classes>l_<llm><PROMPT_VERSION>.json (task name in lower case), or set CONCEPTS_PATH to use a specific file.
export CONCH_CHECKPOINT=/path/to/conch.bin
# PathSculpt-TITAN
bash scripts/pathsculpt_titan.sh BRCA_ER conch_v15 conch_v1 gpt54
# PathSculpt-PRISM
bash scripts/pathsculpt_prism.sh BRCA_ER virchow conch_v1 gpt54Defaults follow the Methods of the paper and can be overridden through environment variables:
| variable | default | meaning |
|---|---|---|
CANDIDATE_NUM |
2048 | evenly spaced candidates scored by KIS; 0 scores every patch |
DS_NUM |
256 | patches selected by KIS |
IS_TEMP |
1.0 | sampling temperature of softmax(S^I / IS_TEMP) |
SIM_W |
0.5 0.5 |
cell / tissue weights of the task-relevance score |
LDA_W |
0.5 0.5 |
cell / tissue weights of the task-discriminability score |
WAVG_W_LDA |
0.2 | weight of the task-discriminability score, 1 - α (α = 0.8) |
TEXT_CTX |
4 | learnable prompt tokens per description |
W_PROMPT |
1.0 | weight of the AdaSP prompt loss |
TOME |
1 | knowledge-guided token merging on (1) or off (0) |
TOME_RATIO |
0.2 | token merge ratio r_m per layer |
CUSTOM_LR, CUSTOM_EPOCHS |
2e-4, 10 | Adam learning rate and epochs |
K_FOLDS, K_START, K_END |
10, –, – | folds to run |
ENCODER_NAME, ENCODER_REVISION |
official model | slide encoder location / revision |
OVERWRITE |
– | set to replace an existing results directory |
Examples:
# score every patch (no candidate step)
CANDIDATE_NUM=0 bash scripts/pathsculpt_titan.sh BRCA_ER conch_v15 conch_v1 gpt54
# KIS only, without token merging
TOME=0 bash scripts/pathsculpt_titan.sh BRCA_ER conch_v15 conch_v1 gpt54
# single-fold smoke test (needs site_splits/<SPLIT>/splits_0.csv)
K_FOLDS=1 OVERWRITE=1 bash scripts/pathsculpt_titan.sh BRCA_ER conch_v15 conch_v1 gpt54At evaluation, the Gumbel noise used for patch selection is seeded from the slide id, so each slide is always encoded from the same patches.
results/<exp_code>/s<seed>_<test_name>/
├── training_log.log
├── experiment_<exp_code>.txt # all settings
├── split_<fold>_results_test.pkl # per-slide predictions on the external cohort
├── s_<fold>_checkpoint.pt # best checkpoint, kept only with --save_ckpt
└── summary.csv # per-fold and mean AUROC, weighted F1, kappa, balanced accuracy
<test_name> encodes the configuration (score weights, candidates, budget, temperature, prompt length, merge ratio), so runs with different settings do not overwrite each other. Kappa is quadratic-weighted for binary tasks and unweighted for tasks with more than two classes.
The PathSculpt code is released under the MIT License (LICENSE), with one exception: models/merge.py is adapted from ToMe and remains under the CC BY-NC 4.0 license of that project.
No TITAN, PRISM, CONCH or Virchow source code or weights are distributed here. They are downloaded from their official sources and are subject to their own licenses and terms of use.
This work builds on CLAM, CONCH, TRIDENT, TITAN, PRISM, Virchow, CoOp (learnable prompts), ToMe and AdaSP.
