Commit ·
76eb7b3
0
Parent(s):
Optimized release: verified metadata, download instructions and package structure
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+7
- LICENSEAdded+21
- README.mdAdded+138
- USAGE.mdAdded+277
- adaptive/README.mdAdded+18
- adaptive/ge/abdomen_draw0.npzAdded+3
- adaptive/ge/abdomen_draw1.npzAdded+3
- adaptive/ge/base.ptAdded+3
- adaptive/ge/chest_draw0.npzAdded+3
- adaptive/ge/chest_draw1.npzAdded+3
- adaptive/siemens/abdomen_draw0.npzAdded+3
- adaptive/siemens/abdomen_draw1.npzAdded+3
- adaptive/siemens/base.ptAdded+3
- adaptive/siemens/chest_draw0.npzAdded+3
- adaptive/siemens/chest_draw1.npzAdded+3
- config.jsonAdded+39
- convention.jsonAdded+14
- figures/routine_demo.pdfAdded+3
- figures/routine_demo.pngAdded
- figures/routine_results.pdfAdded
- figures/routine_results.pngAdded
- figures/workflow.pdfAdded
- figures/workflow.pngAdded
- infer.pyAdded+226
- manifest.jsonAdded+84
- preprocessing/ge/denoiser.ptAdded+3
- preprocessing/siemens/denoiser.ptAdded+3
- proj2rep/__init__.pyAdded+7
- proj2rep/__main__.pyAdded+30
- proj2rep/bank.pyAdded+77
- proj2rep/calibrate_cli.pyAdded+31
- proj2rep/data.pyAdded+201
- proj2rep/dist.pyAdded+41
- proj2rep/encode.pyAdded+71
- proj2rep/evaluate.pyAdded+79
- proj2rep/feature_offset.pyAdded+92
- proj2rep/geometry.pyAdded+173
- proj2rep/lesion.pyAdded+47
- proj2rep/models.pyAdded+131
- proj2rep/report.pyAdded+91
- proj2rep/stress.pyAdded+104
- proj2rep/train_denoiser.pyAdded+128
- proj2rep/train_encoder.pyAdded+248
- readout.pyAdded+38
- refined/README.mdAdded+18
- refined/ge/draw0.ptAdded+3
- refined/ge/draw1.ptAdded+3
- refined/siemens/draw0.ptAdded+3
- refined/siemens/draw1.ptAdded+3
- requirements.txtAdded+6
1234567*.pt filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textfigures/routine_demo.pdf filter=lfs diff=lfs merge=lfs -textfigures/routine_demo.png filter=lfs diff=lfs merge=lfs -textfigures/routine_results.png filter=lfs diff=lfs merge=lfs -textfigures/workflow.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021MIT License
Copyright (c) 2026 The rawct authors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138---library_name: pytorchlanguage:- entags:- medical-imaging- ct- feature-extraction- research---# Proj2Rep-CTFM
**CT projections to image foundation-model representations.**
Proj2Rep predicts CT-FM embeddings from CT detector measurements, using a measurement denoiser, analytic back-projection and a learned encoder. It produces 512-dimensional slab embeddings and regional features for representation research in chest and abdomen CT.
Paper: *Proj2Rep: Predicting image foundation-model representations from CT detector measurements*.

**Input:** prepared CT projections and scanner geometry. **Output:** CT-FM feature representations. Denoising is already part of inference.
## Results at a glance
Selected **routine-dose, full-view** results from the latest release (RC3):
- **0.970 chest / 0.959 abdomen Pearson r** in five-fold patient-level cross-validation of the measurement-encoder recipe.- **0.945 Refined / 0.933 Adaptive r** in the separate 117-patient manufacturer-adaptation evaluation.- **Refined R² = 0.886**, compared with **0.873** for the unrefined parent, in that adaptation evaluation.

Left: held-out fold models, 197 patients. Right: manufacturer adaptation, 117 patients. Bars show pointwise 95% whole-patient bootstrap intervals (2,000 resamples), conditional on trained fits. The two panels use distinct evaluation protocols. Chest and pooled abdomen are the primary cross-validation groups; the two abdomen manufacturer rows subdivide the pooled abdomen group.
## Demo images

Routine-dose chest example at the same anatomical position and display window (−1250 to 450 HU). **Left:** scanner reference. **Middle:** back-projection of the original measurements. **Right:** back-projection after the learned measurement denoiser. The lower row enlarges the cyan-marked regions using the same normalized crop. These are stored preprocessing outputs from the all-development denoiser, shown as a qualitative illustration; the held-out results are reported separately below. Denoising operates on projections before back-projection; the model then encodes the resulting volume into embeddings.
400 dpi PNGs and vector PDFs: [results](figures/routine_results.pdf) · [routine-dose demo](figures/routine_demo.pdf) · [workflow](figures/workflow.pdf).
## Choose a model
| Model | Folder | Intended use ||---|---|---|| **Proj2Rep-Universal** | `universal/` | Encoder and denoiser trained on all 197 development scans; general embedding extraction within the supported data conventions || **Proj2Rep-Adaptive** | `adaptive/` | GE/Siemens base encoders with chest/abdomen readouts, two support draws, full or 1/2, 1/4, 1/8 views || **Proj2Rep-Refined** | `refined/` | GE/Siemens encoders refined with full-view support data; full-view inference only |
Manufacturer denoisers are in `preprocessing/`. Adaptive uses ten target patients per body region and a readout matched to view stride. Refined uses ten chest and ten abdomen support patients per manufacturer. Draws 0 and 1 are alternative support selections, not independent evaluation cohorts. The CLI retains `--model adapter` for Adaptive compatibility.
## Cross-validation results
197 patients (99 chest, 98 abdomen), five folds, routine dose and full views. Results describe the held-out fold models of the Universal training recipe. The released Universal checkpoint was subsequently fitted to all 197 development scans.
| Group | Patients | Measurement r (95% CI) | Trained image r | Measurement R² ||---|---:|---|---:|---:|| Chest | 99 | 0.970 (0.967–0.972) | 0.968 | 0.940 || Abdomen | 98 | 0.959 (0.955–0.962) | 0.957 | 0.919 || Abdomen GE | 49 | 0.944 (0.938–0.950) | 0.941 | 0.890 || Abdomen Siemens | 49 | 0.956 (0.951–0.961) | 0.954 | 0.913 |
[Routine-dose CV estimates](results/cv.csv). Pearson r measures association with the routine-image CT-FM features; R² additionally reflects scale and offset agreement.
## Adaptation results
117 evaluation patients, 3,432 slabs, routine dose and full views. Overall scores equally weight four manufacturer/body-region strata. The two support draws use the same evaluation patients.
| Group | Patients | Adaptive r (95% CI) | Refined r (95% CI) | Refined R² ||---|---:|---|---|---:|| GE chest | 29 | 0.952 (0.946–0.957) | 0.955 (0.949–0.961) | 0.906 || GE abdomen | 29 | 0.913 (0.893–0.934) | 0.923 (0.912–0.934) | 0.846 || Siemens chest | 30 | 0.938 (0.926–0.950) | 0.958 (0.953–0.964) | 0.913 || Siemens abdomen | 29 | 0.931 (0.921–0.938) | 0.942 (0.933–0.948) | 0.881 |
Overall Adaptive r: **0.933 (0.927–0.940)**; Refined r: **0.945 (0.941–0.948)**.
Refinement improves R² over the unrefined parent by **0.013** (95% CI 0.012–0.015). This is an absolute R² difference, evaluated on the same patients.
[Overall estimates](results/overall.csv) · [Manufacturer and region estimates](results/adaptation.csv).
## Run inference
Install the download utility with `pip install -U huggingface_hub`. Download the repository:
```pythonfrom huggingface_hub import snapshot_downloadsnapshot_download("markjiang1/Proj2Rep-CTFM", local_dir="Proj2Rep-CTFM")```
Install a suitable PyTorch build, then from the downloaded directory:
```bashpip install -r requirements.txtpython infer.py --helppython infer.py scan --case /data/C001 --region chest --model adapter --draw 0 --source routine --view-stride 1 --output embeddings.npzpython infer.py scan --case /data/L004 --region abdomen --model refined --draw 1 --source routine --view-stride 1 --output refined.npzpython -m proj2rep encode --cases /data/C001 --work universal --folds -1 --out embeddings/```
The case directory must follow the projection and geometry conventions; see [input preparation and public API](USAGE.md). Ordinary CT image files alone are insufficient. Universal returns slab positions (`z0`), slab embeddings (`slab`) and regional embeddings (`regions`). Keep `manifest.json` and scanner conventions with the models; they are required runtime inputs.
## Smaller downloads
For **Universal-only embedding extraction**, download about **321 MB** of runtime files instead of the full **2.24 GB** repository:
```bashhf download markjiang1/Proj2Rep-CTFM --local-dir Proj2Rep-Universal \ --include 'config.json' 'universal/*' 'proj2rep/*' 'requirements.txt' 'README.md' 'USAGE.md' 'LICENSE'cd Proj2Rep-Universalpip install -r requirements.txtpython -m proj2rep encode --cases /data/C001 --work universal --folds -1 --out embeddings/```
Use the complete package for Adaptive or Refined. Download sizes describe the current files and exclude installed dependencies. Keep `config.json` in filtered downloads so normal Hub download counting remains available. Add `--revision <commit-id>` to pin a reproducible version.
## Current release
This repository distributes the latest release (RC3). Earlier packaging snapshots contained identical weights and have been removed. Universal, Adaptive and Refined are distinct functional configurations within this single release.
## Evaluation scope
This card presents selected routine-dose, full-view CT-FM embedding-agreement results for chest and abdomen from GE and Siemens scanners. Clinical outcome validation is outside this evaluation. Pearson correlation was added post hoc using saved predictions.
Code: [MIT license](LICENSE). Upstream terms: [CT-FM model card](https://huggingface.co/project-lighter/ct_fm_feature_extractor).
## Download the complete model package
```bashhf download markjiang1/Proj2Rep-CTFM --local-dir Proj2Rep-CTFM```
This downloads the model files together with `config.json`, the package metadata used by Hugging Face's native download counter. Use the inference instructions above to load the model. The package metadata does not replace the runtime model configuration.
Download totals appear on this repository's model page. Hugging Face counts requests for designated files; downloading individual weight files without the configuration may not register. Counts represent Hub requests, not unique users. See [Hugging Face download statistics](https://huggingface.co/docs/hub/models-download-stats).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277# proj2rep
**Read CT scans straight from the scanner's detector measurements, in the feature space of a CTimage foundation model.**
`proj2rep` trains an encoder to predict the CT-FM features of a routine-dose scanner imagefrom helical CT projection measurements. In five-fold patient-held-out testing, image-trainedprobes localized lung nodules and liver lesions in regional measurement features at routineand supplied low dose. [Regional localization results](#regional-lesion-localization).
```measurements ─► denoiser ─► back-projection ─► encoder ─► embeddings (512 per slab + 4×4 regional grid) ▲routine-dose image ─► CT-FM (frozen) ─── target ──┘```
---
## 1. Install
You need Python 3.10+, an NVIDIA GPU and PyTorch with CUDA ([pytorch.org](https://pytorch.org)).
```bashgit clone <this repository> proj2rep && cd proj2reppip install -r requirements.txtpython -m pytest tests -q # quick check, runs on CPU```
## 2. Download
**Model weights (teacher).** Download `model.safetensors` from[project-lighter/ct_fm_feature_extractor](https://huggingface.co/project-lighter/ct_fm_feature_extractor)and save it, e.g. as `weights/ct_fm.safetensors`.
**Data.** You need CT scans with their raw projection data in **DICOM-CT-PD** format, plus thereconstructed images of the same scans. A public example is the *LDCT and Projection Data*collection on The Cancer Imaging Archive (TCIA), which provides routine-dose and simulatedreduced-dose projections with matching images for chest, abdomen and head scans. Download it withthe TCIA tools (NBIA Data Retriever or `idc-index`). Any scanner exporting DICOM-CT-PD works.
## 3. Prepare the data
Convert each scan once into a folder with a few `.npy` / `.json` files (layout below). Use anyDICOM reader (e.g. `pydicom`). Per scan:
1. **Projections → `proj_full.npy`.** Read every DICOM-CT-PD projection file in acquisition order. Each file is one view: a `rows × columns` detector array. Convert pixels to line integrals with `RescaleSlope` / `RescaleIntercept` and stack them to `(views, rows, columns)`, float16. Averaging consecutive views in groups of 2–4 keeps files small and works well.2. **Per-view positions → `views.npz`.** From each view: gantry angle (7031,1001) → `angle_rad`, table position (7031,1002) → `z_mm`, and source distance (7031,1003) plus the flying focal spot offset (7033,100D) → `source_isocenter_mm`. Average them the same way if you averaged views.3. **Scanner geometry → `geometry.json`** (fields in the table below). From the first view: detector spacing (7029,1002 / 7029,1006), detector size (7029,1010 / 7029,1011), source-detector distance (7031,1031), central element (7031,1033), water attenuation (7041,1001), plus `Manufacturer` and `PatientPosition`. Set `stored_views_per_rotation` to the views per rotation (7033,1013) divided by your averaging factor.4. **Images → `image_full.npy` + `image.json`.** The reconstructed routine-dose series as `(slices, rows, columns)` int16 HU, sorted by table position, with slice positions and pixel grid in `image.json`.5. **Low dose (optional) → `proj_low.npy`.** If you have a reduced-dose version of the same scan (e.g. the simulated reduced-dose projections in the TCIA collection), convert it exactly like step 1. It must have the same views as `proj_full`. Its reconstructed image can go in `image_low.npy` for comparison.6. **Cohort table → `cases.csv`** with one row per scan: `case_id` (the folder name), `region` (e.g. `chest`), and `low_dose_fraction` (e.g. `0.25`) if you have `proj_low`.
That is all; the pipeline does everything else.
## 4. Train (cross-validation)
One command runs the full pipeline with 5-fold cross-validation on 8 GPUs:
```bashscripts/run_cv.sh /path/to/data /path/to/work weights/ct_fm.safetensors 8 5# DATA_ROOT WORK_DIR TEACHER GPUS FOLDS```
What it runs for every fold:
| step | what it does ||---|---|| `calibrate` | learns each scanner vendor's geometry convention and draws the folds (once) || `train-denoiser` | trains the measurement denoiser || `bank` | builds denoised back-projections at several dose levels and view counts || `train-encoder` | trains the encoder to match CT-FM || `evaluate` | embeds the held-out scans || `stress` | tests the held-out scans at lower dose and fewer views || `report` | summarises all folds (at the end) |
You can also run steps one by one, on any number of GPUs:
```bashtorchrun --standalone --nproc_per_node 8 -m proj2rep train-encoder --data DATA --work WORK --fold 0 --teacher weights/ct_fm.safetensorspython -m proj2rep report --data DATA --work WORK # single process works too```
`bank`, `evaluate` and `stress` split the scans across processes and are mostly CPU-bound, so theyrun faster with several processes per GPU: `--nproc_per_node 24` on 8 GPUs puts three on each(about 10 GB of GPU memory per process). With the script: `PROCS=24 scripts/run_cv.sh ...`.
**Final model.** Cross-validation tells you how well the method works on your data. For the modelyou deploy, train on every scan with `--fold -1`:
```bashRUN="torchrun --standalone --nproc_per_node 8 -m proj2rep"$RUN train-denoiser --data DATA --work WORK --fold -1$RUN bank --data DATA --work WORK --fold -1$RUN train-encoder --data DATA --work WORK --fold -1 --teacher weights/ct_fm.safetensors```
If a run is interrupted, just start it again: finished steps are skipped and training continuesfrom its last checkpoint. Change settings by passing options, e.g.`ENCODER_ARGS="--steps 12000" scripts/run_cv.sh ...` (all options: `python -m proj2rep <step> --help`).
## 5. Results
Everything is written to the work directory:
```WORK/report/agreement.csv how well the encoder matches CT-FM on held-out scans, per region and scannerWORK/report/stress.csv the same at each dose level and view count, raw route vs. reconstruct-then-encodeWORK/encoder/fold<F>.pt trained encoders WORK/denoiser/fold<F>.pt trained denoisersWORK/eval/, WORK/stress/ held-out embeddings per scanWORK/logs/ logs of every step```
The agreement score is R²: the share of the CT-FM embedding's variance that the encoderreproduces (1 = identical), with 95% confidence intervals.
## 6. Pretrained model
A pretrained model is provided with the releases of this repository (`proj2rep_weights.zip`). It wastrained on the 197 chest and abdomen scans (Siemens and GE) of the TCIA *LDCT and Projection Data*collection. Unpack it and use the folder as the work directory when encoding:
```bashunzip proj2rep_weights.zip -d weights/ # weights/proj2rep_weights/{encoder,denoiser}/fold-1.pt, convention.jsonpython -m proj2rep encode --cases /path/to/scanA --work weights/proj2rep_weights --folds -1 --out embeddings/```
Selected routine-dose evaluation results are in the [model card](README.md#cross-validation-results).
## 7. Encode new scans
Prepare the new scans the same way (images are not needed — only `image.json` to set the outputgrid), then:
```bashpython -m proj2rep encode --cases /path/to/scanA /path/to/scanB --work WORK --folds -1 --out embeddings/```
`--folds -1` uses the final model; `--folds 0 1 2 3 4` averages the cross-validation modelsinstead. Each `embeddings/<scan>.npz` contains `z0` (slab positions, every 12 mm), `slab``(n, 512)` and `regions` `(n, 16, 512)`. Use them anywhere you would use CT-FMimage embeddings.
### Regional lesion localization
Generate an 8 × 8 grid for each slab, then apply the packaged lung nodule or liver lesion probe. For example, from the release directory run
```bashpython -m proj2rep encode --cases /path/to/scanA --work WORK --folds -1 --grid 8 --out embeddings/python -m proj2rep lesion --task nodule --input embeddings/scanA.npz --out scanA_nodules.npz```
Use `--task liver` for abdominal scans. Each output contains `scores` with shape`(slabs, 8, 8)` and the matching slab positions `z0`. Rows and columns follow theregional encoder grid. The class-balanced logistic scores rank regions for aresearch localization task and have no calibrated diagnostic threshold.
Both probes use the 512 local CT-FM features of each region. The packagedweights were refitted on all routine-dose training images after five-foldpatient-held-out evaluation. Comparisons in the paper use the held-outpredictions. The 4 × 4 and 8 × 8 grids have different region labels and classprevalence.
## Feature offsets for a new manufacturer
A frozen measurement encoder can be calibrated with paired routine-dose scans. Fit one offset per encoder, manufacturer and body region using scanner-image and measurement embeddings of the same slab centres. Each input directory holds one NPZ per examination with matching filenames, physical slab centres in `z0` and 512-feature embeddings in `slab`. The output contains corrected global slab embeddings.
```bashpython -m proj2rep feature-offset fit measurement/ reference/ offset.npzpython -m proj2rep feature-offset apply offset.npz evaluation_scan.npz corrected_slab.npz```
## Reference
### Data layout
```DATA_ROOT/ cases.csv <case_id>/ geometry.json scanner geometry views.npz angle_rad (V,), z_mm (V,) [, source_isocenter_mm (V,)] proj_full.npy (V, rows, columns) line integrals, routine dose proj_low.npy optional, reduced dose, same shape image.json image grid image_full.npy (S, H, W) int16 HU, routine-dose image image_low.npy optional, reduced-dose image```
**cases.csv**
| column | needed | meaning ||---|---|---|| `case_id` | yes | folder name || `region` | recommended | any label (`chest`, `abdomen`, `head`, ...) || `low_dose_fraction` | with `proj_low` | dose of `proj_low` relative to routine, e.g. `0.25` || `manufacturer` | no | taken from `geometry.json` if empty || `fold` | no | your own folds; otherwise drawn by region and scanner and saved to `WORK/folds.csv` || `exclude` | no | `1` to leave a scan out |
Extra columns are kept and ignored.
**geometry.json**
| field | meaning ||---|---|| `manufacturer` | `SIEMENS`, `GE`, `PHILIPS`, `CANON`, ... || `source_detector_mm` | source-to-detector distance || `source_isocenter_mm` | source-to-isocentre distance (if not per view in `views.npz`) || `column_spacing_mm`, `row_spacing_mm` | detector element spacing || `central_element` | `[column, row]` of the central ray, 1-based || `detector_rows`, `detector_columns` | detector size || `water_mu_per_mm` | water attenuation, for HU || `stored_views_per_rotation` | views per rotation as stored in `proj_full.npy` || `patient_position` | `FFS`, `HFS`, ... || `low_dose_fraction` | optional, used if `cases.csv` has none |
**image.json**: `z_mm` (slice positions), `pixel_spacing_mm` `[row, column]`, `origin_mm` `[x, y]`,`thickness_mm`, `rows`, `columns`, and optionally `rotation_center_mm` `[x, y]` (default `[0, 0]`).
### Main options
| step | option | default | meaning ||---|---|---|---|| calibrate | `--folds` | 5 | number of folds || train-denoiser | `--steps` / `--batch` / `--lr` | 8000 / 8 / 3e-4 | `--batch` is split across GPUs || | `--min-dose` | 0.02 | lowest simulated dose || | `--views` | 1 1 2 4 8 | view-thinning factors used in training || bank | `--levels` | full low | dose levels to build (`min` adds a lower one) || | `--views` | 1 2 4 8 | view counts to build (every k-th view) || train-encoder | `--steps` / `--batch` / `--lr` | 16000 / 16 / 1e-4 | `--batch` is split across GPUs || | `--views` | 1 2 4 8 | view counts used in training || | `--max-dose-level` | 1 | 1 = down to `proj_low`; 2 = down to the `min` level || | `--clean` | 0.15 | share of routine-dose samples || | `--snap-z` | 0.5 | share of training slabs placed with an edge exactly on a slice, as evaluation slabs are || bank, train-encoder | `--no-thin` | — | `REGION:MANUFACTURER` groups kept at all views |
### Adding more data
New scanners, body regions and sites need no code changes — add folders and rows to `cases.csv`.To keep an existing split, copy the `fold` column from `WORK/folds.csv` into `cases.csv` and givethe new scans a fold. New vendors are calibrated automatically from a few scans with images.
A model trained on one manufacturer reproduces the anatomy of another manufacturer's scans but inthe image style of the one it was trained on, so agreement drops on a manufacturer it has neverseen. About ten scans per body region from the new manufacturer, added to training, restore most ofit. Train on every manufacturer you plan to encode.
### Code
```proj2rep/data.py cases, folds, slabsproj2rep/geometry.py back-projection and vendor calibrationproj2rep/models.py denoiser, CT-FM teacher, encoderproj2rep/train_denoiser.py proj2rep/bank.py proj2rep/train_encoder.pyproj2rep/evaluate.py proj2rep/stress.py proj2rep/report.py proj2rep/encode.pyscripts/run_cv.sh full pipelinetests/ synthetic-data tests```
## License
MIT123456789101112131415161718# Proj2Rep-Adaptive
Current release: RC3.
## Selected routine-dose, full-view results
Manufacturer-adaptation evaluation on 117 patients; both support draws use the same evaluation patients.
| Group | Patients | Adaptive r (95% CI) | Refined r (95% CI) | Refined R² ||---|---:|---|---|---:|| GE chest | 29 | 0.952 (0.946–0.957) | 0.955 (0.949–0.961) | 0.906 || GE abdomen | 29 | 0.913 (0.893–0.934) | 0.923 (0.912–0.934) | 0.846 || Siemens chest | 30 | 0.938 (0.926–0.950) | 0.958 (0.953–0.964) | 0.913 || Siemens abdomen | 29 | 0.931 (0.921–0.938) | 0.942 (0.933–0.948) | 0.881 |

See the [main model card](../README.md) for confidence intervals, model selection, input preparation and inference commands.123version https://git-lfs.github.com/spec/v1oid sha256:5f02e1f964415424d185242a421e39caf2e828476dac95f82d8eb1fb667ed454size 3942256123version https://git-lfs.github.com/spec/v1oid sha256:7c5067d65de9c33ba5f0ba907de355fc05db0db57297e495d5c5564966ad9066size 3943029123version https://git-lfs.github.com/spec/v1oid sha256:54b532b56b90af0f3a30f648cb8d8b231c926fab5b8d47d5803f783687c43f64size 311152534123version https://git-lfs.github.com/spec/v1oid sha256:d6f90c33f3b93480f210a1e442018be0bbeba993d045bd534e09ea0b295a54ecsize 3950959123version https://git-lfs.github.com/spec/v1oid sha256:b1daa48d0514468922fc3c41a842501bb2a90a3ae0ad2ecb060073a3faebeab1size 3947849123version https://git-lfs.github.com/spec/v1oid sha256:51974a4f0faecfffaa720d64bce3fa3fd8a41c60146d4637eb26be954d797f30size 3935703123version https://git-lfs.github.com/spec/v1oid sha256:bdcd7efccfa4199375b52021ae76de1c85ddd7474ced937cfbab2d0e33f8afeasize 3927879123version https://git-lfs.github.com/spec/v1oid sha256:316b5812e22e99bcbeb4b3227b0edb13b33c9d11358174303337a1444b824a1csize 311152534123version https://git-lfs.github.com/spec/v1oid sha256:1a3068bc042874e7e176c4db0bfc901ad8e8f13ee396096b1a111eaff50f86a5size 3945065123version https://git-lfs.github.com/spec/v1oid sha256:ffe8ec7cb85cfbe3fc6ebfbcf6e2efab026a6e273a4a6d692a6ce790094fc912size 3943373123456789101112131415161718192021222324252627282930313233343536373839{ "package_name": "Proj2Rep-CTFM", "repository_id": "markjiang1/Proj2Rep-CTFM", "weight_files": [ "adaptive/ge/abdomen_draw0.npz", "adaptive/ge/abdomen_draw1.npz", "adaptive/ge/base.pt", "adaptive/ge/chest_draw0.npz", "adaptive/ge/chest_draw1.npz", "adaptive/siemens/abdomen_draw0.npz", "adaptive/siemens/abdomen_draw1.npz", "adaptive/siemens/base.pt", "adaptive/siemens/chest_draw0.npz", "adaptive/siemens/chest_draw1.npz", "preprocessing/ge/denoiser.pt", "preprocessing/siemens/denoiser.pt", "refined/ge/draw0.pt", "refined/ge/draw1.pt", "refined/siemens/draw0.pt", "refined/siemens/draw1.pt", "universal/denoiser/fold-1.pt", "universal/encoder/fold-1.pt" ], "configuration_scope": "Repository package metadata. Use the documented inference entry point and runtime configuration to load the model.", "model_family": "Proj2Rep", "variants": [ "Universal", "Adaptive", "Refined" ], "embedding_dim": 512, "runtime_manifest": "manifest.json", "scanner_conventions": "convention.json", "minimum_python_version": "3.11", "entry_points": { "universal": "python -m proj2rep encode", "adaptive_and_refined": "python infer.py scan" }}1234567891011121314{ "GE": [ 1, 2, 1, -1 ], "SIEMENS": [ 1, 2, 1, 1 ]}123version https://git-lfs.github.com/spec/v1oid sha256:b8b52581d964b55df0a0b31210043d0a7c0456aca54036b700b2605a75dea15csize 345921123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226"""Proj2Rep: infer one draw of a CT projection encoder or apply its readout to archived base features."""
import argparseimport hashlibimport jsonimport osimport tempfilefrom pathlib import Path
import numpy as npfrom readout import predict
class Bundle: def __init__(self, path): self.path = path self.manifest = json.loads((path / "manifest.json").read_text())
def checked(self, name): path = self.path / name with path.open("rb") as source: digest = hashlib.file_digest(source, "sha256").hexdigest() if digest != self.manifest["sha256"][name]: raise ValueError(f"asset digest mismatch: {name}") return path
def saved_features(args, bundle): assets = bundle.manifest["manufacturers"][args.manufacturer] expected = bundle.manifest["sha256"][assets["base"]] with np.load(args.input, allow_pickle=False) as data: if "patient" in data and len(np.unique(data["patient"])) != 1: raise ValueError("supply one patient per input archive") if "region" in data and str(data["region"].item()) != args.region: raise ValueError("archived region differs from requested region") if ( args.key in ("slab", "base_slab") and "model" in data and args.key != "base_slab" ): raise ValueError("use base_slab from adapter output to apply another draw") internal = str(data["base_sha256"].item()) if "base_sha256" in data else None if internal and args.base_sha256 and internal != args.base_sha256: raise ValueError("conflicting input and command-line base digests") if (internal or args.base_sha256) != expected: raise ValueError( "specify the SHA-256 of the matching unadapted base encoder" ) if ( "view_stride" in data and int(data["view_stride"].item()) != args.view_stride ): raise ValueError("input acquisition stride differs from requested stride") if ( args.key.startswith("raw_views_") and args.key != f"raw_views_{args.view_stride}" ): raise ValueError("archive key and requested angular stride differ") if ( args.key.startswith("raw_dose") or args.key in ("raw_full", "raw_low") ) and args.view_stride != 1: raise ValueError("dose arrays use full angular sampling") x, z = data[args.key], data["z0"] return x, z
def infer_scan(args, bundle): import torch from proj2rep.data import Case, slab_rows, to_input from proj2rep.geometry import Conventions, Geometry, reconstruct, sparse from proj2rep.models import Denoiser, Encoder, denoise_scan
if args.view_stride > 1 and (args.source != "routine" or args.model != "adapter"): raise ValueError( "sparse-view inference requires routine projections and the adapter model" ) if args.source == "routine-bank" and args.model != "adapter": raise ValueError( "refined routine inference already uses the rounded bank convention" ) case = Case(args.case.parent, args.case.name) vendor = case.manufacturer.upper() args.manufacturer = next( ( name for name in bundle.manifest["manufacturers"] if vendor.startswith(name.upper()) ), None, ) if args.manufacturer is None: raise ValueError(f"no packaged model for {vendor}") assets = bundle.manifest["manufacturers"][args.manufacturer] encoder_name = ( assets["base"] if args.model == "adapter" else assets["refined"][str(args.draw)] ) device = torch.device(args.device) if device.type != "cuda" or not torch.cuda.is_available(): raise ValueError("scan inference requires a CUDA device supporting bfloat16") with torch.cuda.device(device): if not torch.cuda.is_bf16_supported(): raise ValueError("scan inference requires CUDA bfloat16 support")
def load(module, name): module.load_state_dict( torch.load(bundle.checked(name), map_location="cpu", weights_only=True) ) return module.to(device).eval().requires_grad_(False)
with torch.inference_mode(): dn = load(Denoiser(), assets["denoiser"]) enc = load(Encoder(), encoder_name).to(memory_format=torch.channels_last_3d) geo = Geometry(case) zs, z = geo.image_z[geo.valid()], case.grid() if not len(z): raise ValueError("scan covers no complete 36-mm slab") if args.slab_index is not None: z = z[args.slab_index] convention = Conventions(bundle.checked("convention.json"))(geo) views = case.array("proj_low" if args.source == "supplied" else "proj_full") if views.shape != (len(geo.angle), geo.rows, geo.cols) or len(geo.z) != len( geo.angle ): raise ValueError("projections and original per-view geometry disagree") stride = args.view_stride geometry = sparse(geo, stride) if stride > 1 else geo measurements = np.ascontiguousarray(views[::stride], dtype=np.float32) denoised = denoise_scan(dn, measurements, device) del measurements vol = reconstruct(geometry, denoised, zs, device, convention) if args.model == "refined" or args.source in ("supplied", "routine-bank"): vol = vol.clamp(-2000, 6000).round().short() out = [] for centre in z: rows, flip = slab_rows(zs, centre) slab = vol[rows].float() x = to_input(slab.flip(0) if flip else slab)[None].contiguous( memory_format=torch.channels_last_3d ) with torch.autocast("cuda", dtype=torch.bfloat16): out.append(enc(x)[0][0].cpu().numpy()) return np.stack(out), z, encoder_name
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--root", type=Path, default=Path(__file__).resolve().parent, help="unpacked model bundle", ) shared = argparse.ArgumentParser(add_help=False) shared.add_argument("--region", choices=("chest", "abdomen"), required=True) shared.add_argument("--draw", type=int, choices=(0, 1), required=True) shared.add_argument("--view-stride", type=int, choices=(1, 2, 4, 8), required=True) shared.add_argument("--output", type=Path, required=True) modes = parser.add_subparsers(dest="mode", required=True) scan = modes.add_parser("scan", parents=[shared]) scan.add_argument("--case", type=Path, required=True) scan.add_argument( "--source", choices=("routine", "supplied", "routine-bank"), default="routine" ) scan.add_argument("--model", choices=("adapter", "refined"), required=True) scan.add_argument("--device", default="cuda:0") scan.add_argument( "--slab-index", type=int, nargs="+", help="optional zero-based indices on the full physical grid", ) features = modes.add_parser("features", parents=[shared]) features.add_argument("--input", type=Path, required=True) features.add_argument("--key", required=True) features.add_argument( "--base-sha256", help="required for archives without embedded base_sha256" ) features.add_argument("--manufacturer", choices=("GE", "Siemens"), required=True) args = parser.parse_args() if args.output.exists(): parser.error(f"output already exists: {args.output}") bundle = Bundle(args.root) if args.mode == "scan": x, z, encoder = infer_scan(args, bundle) else: args.model = "adapter" x, z = saved_features(args, bundle) encoder = bundle.manifest["manufacturers"][args.manufacturer]["base"] values = { "z0": z, "manufacturer": args.manufacturer, "region": args.region, "model": args.model, "draw": args.draw, "view_stride": args.view_stride, "encoder_sha256": bundle.manifest["sha256"][encoder], } if z.shape != (len(x),) or not np.isfinite(z).all() or not np.isfinite(x).all(): raise ValueError("invalid slab features or z0") if args.mode == "scan": values.update(case_id=args.case.name, source=args.source) if args.model == "adapter": assets = bundle.manifest["manufacturers"][args.manufacturer] key = assets["heads"][args.region][str(args.draw)] with np.load(bundle.checked(key), allow_pickle=False) as head: metadata = json.loads(head["metadata"].item()) if metadata["sha256"] != values["encoder_sha256"]: raise ValueError("readout and base encoder digests disagree") values.update( slab=predict(head, x, args.view_stride), base_slab=x, base_sha256=values["encoder_sha256"], readout_sha256=bundle.manifest["sha256"][key], ) else: values["slab"] = x args.output.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=args.output.parent, suffix=".npz") as tmp: np.savez_compressed(tmp, **values) tmp.flush() os.link(tmp.name, args.output) print(f"{args.output}: {len(x)} slabs")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384{ "format": 1, "manufacturers": { "GE": { "base": "adaptive/ge/base.pt", "denoiser": "preprocessing/ge/denoiser.pt", "fold": 10, "heads": { "abdomen": { "0": "adaptive/ge/abdomen_draw0.npz", "1": "adaptive/ge/abdomen_draw1.npz" }, "chest": { "0": "adaptive/ge/chest_draw0.npz", "1": "adaptive/ge/chest_draw1.npz" } }, "refined": { "0": "refined/ge/draw0.pt", "1": "refined/ge/draw1.pt" } }, "Siemens": { "base": "adaptive/siemens/base.pt", "denoiser": "preprocessing/siemens/denoiser.pt", "fold": 11, "heads": { "abdomen": { "0": "adaptive/siemens/abdomen_draw0.npz", "1": "adaptive/siemens/abdomen_draw1.npz" }, "chest": { "0": "adaptive/siemens/chest_draw0.npz", "1": "adaptive/siemens/chest_draw1.npz" } }, "refined": { "0": "refined/siemens/draw0.pt", "1": "refined/siemens/draw1.pt" } } }, "release": { "snapshot": "correlation", "supported_modes": { "adapter": [ 1, 2, 4, 8 ], "refined": [ 1 ] }, "weights_identical_across_historical_snapshots": true }, "sha256": { "adaptive/ge/base.pt": "54b532b56b90af0f3a30f648cb8d8b231c926fab5b8d47d5803f783687c43f64", "preprocessing/ge/denoiser.pt": "aea29f6c832a2e6fcd05ae4369acc14ceca72a161627cb5de88597aae3daf83a", "refined/ge/draw0.pt": "54b290e77a01bab1fe3feab0cd41d11910d51b88550ed8b73a4b2290a4bfb370", "refined/ge/draw1.pt": "19bd30de60567dbeea90174fd2cf853a5dc58d95ad90fe5e31757d87162d4ffd", "adaptive/ge/chest_draw0.npz": "d6f90c33f3b93480f210a1e442018be0bbeba993d045bd534e09ea0b295a54ec", "adaptive/ge/chest_draw1.npz": "b1daa48d0514468922fc3c41a842501bb2a90a3ae0ad2ecb060073a3faebeab1", "adaptive/ge/abdomen_draw0.npz": "5f02e1f964415424d185242a421e39caf2e828476dac95f82d8eb1fb667ed454", "adaptive/ge/abdomen_draw1.npz": "7c5067d65de9c33ba5f0ba907de355fc05db0db57297e495d5c5564966ad9066", "adaptive/siemens/base.pt": "316b5812e22e99bcbeb4b3227b0edb13b33c9d11358174303337a1444b824a1c", "preprocessing/siemens/denoiser.pt": "00f45f34db1b1f8c6af407f97efc0429bd94fd66de3335ee7d9701aa01e7aff2", "refined/siemens/draw0.pt": "fe224da48c0e9cfe50e657abcf86146d1ca945202770ae0cd6bc49ae5b18aed4", "refined/siemens/draw1.pt": "95dba94ad1e89eb33087382ef588a496c1a5c6e1da8b666487a7f3b09d2b2085", "adaptive/siemens/chest_draw0.npz": "1a3068bc042874e7e176c4db0bfc901ad8e8f13ee396096b1a111eaff50f86a5", "adaptive/siemens/chest_draw1.npz": "ffe8ec7cb85cfbe3fc6ebfbcf6e2efab026a6e273a4a6d692a6ce790094fc912", "adaptive/siemens/abdomen_draw0.npz": "51974a4f0faecfffaa720d64bce3fa3fd8a41c60146d4637eb26be954d797f30", "adaptive/siemens/abdomen_draw1.npz": "bdcd7efccfa4199375b52021ae76de1c85ddd7474ced937cfbab2d0e33f8afea", "convention.json": "f974350d8b516cb7e533e08c548b4281958a92ad8736613157b064a31e11c811" }, "name": "Proj2Rep-CTFM", "model_family": "Proj2Rep", "variants": [ "Universal", "Adaptive", "Refined" ]}123version https://git-lfs.github.com/spec/v1oid sha256:aea29f6c832a2e6fcd05ae4369acc14ceca72a161627cb5de88597aae3daf83asize 10145213123version https://git-lfs.github.com/spec/v1oid sha256:00f45f34db1b1f8c6af407f97efc0429bd94fd66de3335ee7d9701aa01e7aff2size 101452131234567"""proj2rep: read CT detector measurements into the feature space of a frozen CT image foundation model.
Pipeline (see README.md): calibrate -> train-denoiser -> bank -> train-encoder -> evaluate / stress -> encode"""
__version__ = "1.0.0"123456789101112131415161718192021222324252627282930"""Command line: python -m proj2rep <command> [options] (multi-GPU: torchrun --nproc_per_node N -m proj2rep <command> ...)"""
import sys
COMMANDS = { "calibrate": "proj2rep.calibrate_cli", "feature-offset": "proj2rep.feature_offset", "train-denoiser": "proj2rep.train_denoiser", "bank": "proj2rep.bank", "train-encoder": "proj2rep.train_encoder", "evaluate": "proj2rep.evaluate", "stress": "proj2rep.stress", "report": "proj2rep.report", "encode": "proj2rep.encode", "lesion": "proj2rep.lesion",}
def main(): if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS: print(__doc__) print("commands: " + ", ".join(COMMANDS)) sys.exit(0 if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help") else 2) import importlib
importlib.import_module(COMMANDS[sys.argv[1]]).main(sys.argv[2:])
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Denoised back-projections of every case at several dose levels and view fractions, for one fold.
Uses the fold's own denoiser, so held-out cases are processed by a model that never saw them.Levels: `full` (routine dose), `low` (the supplied reduced dose), `min` (noise scaled to--min-dose of routine). View fractions: keep every k-th view. Cases are split across GPUs.
torchrun --nproc_per_node 8 -m proj2rep bank --data DATA --work WORK --fold 0Output: WORK/bank/fold<F>/<case>/<level>_v<k>.npy (int16 HU, 256 x 256) and z_mm.npy"""
import argparsefrom pathlib import Path
import numpy as np
from . import distfrom .data import group_of, load_cohortfrom .geometry import Conventions, Geometry, reconstruct, sparsefrom .models import denoise_scanfrom .train_denoiser import load, noise_scale
def bank_dir(work, fold, case_id): return Path(work) / "bank" / f"fold{fold}" / case_id
def build_case(case, model, conv, out, device, levels, views, min_dose): geo = Geometry(case) zs = geo.image_z[geo.valid()] out.mkdir(parents=True, exist_ok=True) np.save(out / "z_mm.npy", zs) full = np.asarray(case.array("proj_full"), dtype=np.float32) noise = None if case.has("proj_low"): noise = np.asarray(case.array("proj_low"), dtype=np.float32) - full for level in levels: if level != "full" and (noise is None or not case.low_dose_fraction): continue scale = {"full": 0.0, "low": 1.0}[level] if level != "min" else noise_scale(case.low_dose_fraction, min_dose) for k in views if level != "min" else [1]: path = out / f"{level}_v{k}.npy" if path.exists(): continue data = np.ascontiguousarray((full + scale * noise if scale else full)[::k]) g = sparse(geo, k) if k > 1 else geo vol = reconstruct(g, denoise_scan(model, data, device), zs, device, conv(geo)) tmp = path.with_suffix(".tmp.npy") np.save(tmp, vol.clamp(-2000, 6000).round().short().cpu().numpy()) tmp.replace(path)
def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--data", required=True) p.add_argument("--work", required=True) p.add_argument("--fold", type=int, required=True, help="fold whose models are used (-1: the model trained on every case)") p.add_argument("--levels", nargs="+", default=["full", "low"], choices=["full", "low", "min"]) p.add_argument("--views", type=int, nargs="+", default=[1, 2, 4, 8]) p.add_argument("--min-dose", type=float, default=0.025) p.add_argument("--no-thin", nargs="*", default=[], help="REGION:MANUFACTURER groups built at all views only") a = p.parse_args(argv)
rank, world, device = dist.init() cohort = load_cohort(a.data, work_dir=a.work) model = load(a.work, a.fold, device) conv = Conventions(Path(a.work) / "convention.json") ids = cohort.cases(cohort.ids(), image=False)[rank::world] for i, case in enumerate(ids): cid = case.id views = [1] if group_of(case, a.no_thin) else a.views build_case(case, model, conv, bank_dir(a.work, a.fold, cid), device, a.levels, views, a.min_dose) print(f"[rank {rank}] bank fold {a.fold}: {cid} ({i + 1}/{len(ids)})", flush=True) dist.done(sync=False)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031"""Calibrate each manufacturer's geometric convention against the scanner images.
python -m proj2rep calibrate --data DATA --work WORKWrites WORK/convention.json (needed by every later step) and draws the cross-validation folds(WORK/folds.csv) if cases.csv has no fold column."""
import argparsefrom pathlib import Path
import torch
from .data import load_cohortfrom .geometry import calibrate
def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--data", required=True) p.add_argument("--work", required=True) p.add_argument("--folds", type=int, default=5) p.add_argument("--cases-per-manufacturer", type=int, default=3) p.add_argument("--device", default="cuda:0" if torch.cuda.is_available() else "cpu") a = p.parse_args(argv) cohort = load_cohort(a.data, folds=a.folds, work_dir=a.work) print(f"{len(cohort.table)} cases, folds:", cohort.table.fold.value_counts().sort_index().to_dict(), flush=True) calibrate(cohort, Path(a.work) / "convention.json", a.device, a.cases_per_manufacturer)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201"""Cohort, folds and per-case data access.
A data root holds one folder per case plus a cohort table:
<data_root>/cases.csv <data_root>/<case_id>/geometry.json scanner and detector geometry <data_root>/<case_id>/views.npz angle_rad (V,), z_mm (V,) [, source_isocenter_mm (V,)] <data_root>/<case_id>/proj_full.npy (V, rows, cols) line integrals, routine dose <data_root>/<case_id>/proj_low.npy optional, same shape: reduced-dose scan of the same acquisition <data_root>/<case_id>/image.json reconstruction grid: z_mm, pixel_spacing_mm, origin_mm, thickness_mm <data_root>/<case_id>/image_full.npy (S, H, W) HU, routine-dose reconstruction (teacher input) <data_root>/<case_id>/image_low.npy optional, scanner reconstruction of proj_low (same slices)
See README.md for every field."""
import jsonimport osfrom dataclasses import dataclassfrom functools import cached_propertyfrom pathlib import Path
import numpy as npimport pandas as pdimport torchimport torch.nn.functional as Ffrom sklearn.model_selection import StratifiedKFold
HALF = 18.0 # slab half-length along the table, mm (a slab is 36 mm)STEP = 12.0 # spacing of evaluation slabs, mmSLAB_SHAPE = (24, 256, 256) # encoder input (slices, rows, columns)HU_RANGE = (-1024.0, 2048.0) # intensity window of the encoder input
def to_input(x): """HU volume (S, H, W) -> encoder input (1, 24, 256, 256), values in [0, 1].""" lo, hi = HU_RANGE x = (x.clamp(lo, hi) - lo) / (hi - lo) return F.interpolate(x[None, None], SLAB_SHAPE, mode="trilinear", align_corners=False)[0]
def slab_rows(z, z0): keep = np.flatnonzero(np.abs(z - z0) <= HALF) if len(keep) == 0: raise ValueError(f"no slices within {HALF} mm of z0={z0:.1f}") return slice(keep[0], keep[-1] + 1), z[keep[0]] > z[keep[-1]]
class Case: """Lazy access to one case folder."""
def __init__(self, root, case_id, row=None): self.id, self.dir = case_id, Path(root) / case_id self.row = row or {}
@cached_property def geometry(self): return json.loads((self.dir / "geometry.json").read_text())
@cached_property def image_meta(self): return json.loads((self.dir / "image.json").read_text())
@cached_property def views(self): with np.load(self.dir / "views.npz") as v: return {k: v[k] for k in v.files}
def _field(self, name): """Value from cases.csv, falling back to geometry.json when the cell is empty.""" v = self.row.get(name) if v is None or (isinstance(v, float) and np.isnan(v)) or str(v).strip() in ("", "nan"): v = self.geometry.get(name) return v
@property def manufacturer(self): return str(self._field("manufacturer")).strip()
@property def region(self): return str(self.row.get("region", "unknown"))
@property def low_dose_fraction(self): f = self._field("low_dose_fraction") if f is None: return None f = float(f) if not 0 < f < 1: raise ValueError(f"{self.id}: low_dose_fraction must be between 0 and 1, got {f}") return f
def has(self, name): return (self.dir / f"{name}.npy").exists()
def array(self, name): """proj_full, proj_low, image_full, image_low as read-only memory maps.""" return np.load(self.dir / f"{name}.npy", mmap_mode="r")
@cached_property def image_z(self): return np.asarray(self.image_meta["z_mm"], dtype=np.float64)
@cached_property def slab_range(self): """Slab centres with full image coverage and measurements around them.""" vz = self.views["z_mm"] lo = max(self.image_z.min(), vz.min()) + HALF hi = min(self.image_z.max(), vz.max()) - HALF return lo, hi
def image_slab(self, z0, mirror=False, dose="full"): """Scanner image slab in the encoder input convention (1, 24, 256, 256).""" rows, flip = slab_rows(self.image_z, z0) x = torch.from_numpy(np.array(self.array(f"image_{dose}")[rows], dtype=np.float32)) x = to_input(x.flip(0) if flip else x) return x.flip(-1) if mirror else x
def grid(self): lo, hi = self.slab_range return np.arange(lo, hi + 1e-6, STEP)
def usable(self, image=True): """Covers at least one 36 mm slab (and has a routine-dose image when image=True).""" lo, hi = self.slab_range return hi >= lo and (self.has("image_full") or not image)
@dataclassclass Cohort: root: Path table: pd.DataFrame # one row per case: case_id, region, manufacturer, fold, ...
def case(self, case_id): return Case(self.root, case_id, self.table.set_index("case_id").loc[case_id].to_dict())
def split(self, fold): """(training case ids, held-out case ids) for a cross-validation fold.""" t = self.table return t.case_id[t.fold != fold].tolist(), t.case_id[t.fold == fold].tolist()
def ids(self): return self.table.case_id.tolist()
def cases(self, ids, image=True): """Case objects for ids, skipping (with a message) cases too short or without images.""" out = [] for c in map(self.case, ids): if c.usable(image): out.append(c) else: print(f"skipping {c.id}: shorter than one slab" + (" or no image_full.npy" if image else ""), flush=True) return out
def load_cohort(data_root, folds=5, seed=1234, strata=("region", "manufacturer"), work_dir=None): """Read cases.csv; draw stratified folds if the table has no `fold` column.
Cases with `exclude` set are dropped after the folds are drawn, so excluding a case never moves another case to a different fold. Drawn folds are written to <work_dir>/folds.csv so later steps and reruns use the same split. """ root = Path(data_root) t = pd.read_csv(root / "cases.csv", dtype={"case_id": str}) if "manufacturer" not in t: t["manufacturer"] = None t["manufacturer"] = [Case(root, c, {"manufacturer": m}).manufacturer for c, m in zip(t.case_id, t.manufacturer)] if "region" not in t: t["region"] = "unknown" saved = Path(work_dir) / "folds.csv" if work_dir else None if "fold" not in t: if saved and saved.exists(): t = t.merge(pd.read_csv(saved, dtype={"case_id": str}), on="case_id", how="left") if t.fold.isna().any(): raise ValueError(f"{saved} does not cover every case in cases.csv; delete it to redraw folds") else: key = t[list(strata)].astype(str).agg("|".join, axis=1) small = key.map(key.value_counts()) < folds # rare strata are pooled key[small] = "other" t["fold"] = -1 for f, (_, te) in enumerate(StratifiedKFold(folds, shuffle=True, random_state=seed).split(t, key)): t.loc[t.index[te], "fold"] = f if saved: # atomic: concurrent ranks write identical content saved.parent.mkdir(parents=True, exist_ok=True) tmp = saved.with_suffix(f".{os.getpid()}.tmp") t[["case_id", "fold"]].to_csv(tmp, index=False) os.replace(tmp, saved) t["fold"] = t.fold.astype(int) if "exclude" in t: t = t[~t.exclude.fillna(0).astype(bool)] return Cohort(root, t.reset_index(drop=True))
def group_of(case, no_thin): """True if the case belongs to a REGION:MANUFACTURER group listed in no_thin.""" for g in no_thin: region, _, maker = g.partition(":") if (region in ("*", case.region)) and case.manufacturer.upper().startswith(maker.upper()): return True return False1234567891011121314151617181920212223242526272829303132333435363738394041"""Multi-GPU helpers. Every entry point works under `torchrun --nproc_per_node N` and as a plain single process."""
import osfrom datetime import timedelta
import torchimport torch.distributed as dist
# Steps that split cases across GPUs can leave ranks idle for a long time; keep collectives patient.TIMEOUT = timedelta(hours=12)
def init(): """Start the process group when launched by torchrun. Returns (rank, world size, device).""" local = int(os.environ.get("LOCAL_RANK", "0")) if torch.cuda.is_available(): local %= torch.cuda.device_count() # more processes than GPUs: several share a GPU torch.cuda.set_device(local) if "RANK" in os.environ and not dist.is_initialized(): dist.init_process_group("nccl" if torch.cuda.is_available() else "gloo", timeout=TIMEOUT) rank, world = (dist.get_rank(), dist.get_world_size()) if dist.is_initialized() else (0, 1) return rank, world, torch.device(f"cuda:{local}" if torch.cuda.is_available() else "cpu")
def broadcast(t, src=0): if dist.is_initialized(): dist.broadcast(t, src) return t
def done(sync=True): """End the process group. sync=False for steps whose ranks work on independent cases.""" if dist.is_initialized(): if sync: dist.barrier() dist.destroy_process_group()
def log(rank, *a): if rank == 0: print(*a, flush=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Encode new scans from their measurements with a trained denoiser and encoder.
A case folder needs geometry.json, views.npz, proj_full.npy (any dose) and image.json, whichhere only defines the output grid (z_mm, pixel_spacing_mm, origin_mm, thickness_mm); no imagearray is read. Embeddings of the fold models are averaged when several folds are given.
python -m proj2rep encode --cases DIR [DIR ...] --work WORK --folds 0 1 2 3 4 --out embeddings/Output per case: <out>/<case>.npz with z0 (n,), slab (n, 512), regions (n, grid*grid, 512)."""
import argparsefrom pathlib import Path
import numpy as npimport torch
from .data import STEP, Case, slab_rows, to_inputfrom .evaluate import embedfrom .geometry import Conventions, Geometry, reconstructfrom .models import denoise_scanfrom .train_denoiser import load as load_denoiserfrom .train_encoder import load as load_encoder
def encode_case(case, models, conv, device, grid=4): geo = Geometry(case) zs = geo.image_z[geo.valid()] lo, hi = case.slab_range z = np.arange(lo, hi + 1e-6, STEP) data = case.array("proj_full") slabs, regions = [], [] for enc, dn in models: vol = reconstruct(geo, denoise_scan(dn, data, device), zs, device, conv(geo)) xs = [] for z0 in z: rows, flip = slab_rows(zs, z0) x = vol[rows].float().cpu() xs.append(to_input(x.flip(0) if flip else x))
def run(x, enc=enc): with torch.autocast("cuda", dtype=torch.bfloat16): return enc(x.to(device).contiguous(memory_format=torch.channels_last_3d), grid=grid)
s, r = embed(run, xs) slabs.append(s) regions.append(r.astype(np.float32)) return {"z0": z, "slab": np.mean(slabs, 0), "regions": np.mean(regions, 0).astype(np.float16)}
def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--cases", nargs="+", required=True, help="case folders") p.add_argument("--work", required=True, help="training work directory (models and convention.json)") p.add_argument("--folds", type=int, nargs="+", default=[0]) p.add_argument("--grid", type=int, choices=[4, 8], default=4, help="regional grid side length (8 for lesion scoring)") p.add_argument("--out", required=True) p.add_argument("--device", default="cuda:0" if torch.cuda.is_available() else "cpu") a = p.parse_args(argv) device = torch.device(a.device) models = [(load_encoder(a.work, f, device), load_denoiser(a.work, f, device)) for f in a.folds] conv = Conventions(Path(a.work) / "convention.json") out = Path(a.out) out.mkdir(parents=True, exist_ok=True) for folder in map(Path, a.cases): case = Case(folder.parent, folder.name) np.savez_compressed(out / f"{case.id}.npz", **encode_case(case, models, conv, device, a.grid)) print("encoded", case.id, flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Held-out evaluation of one fold: embeddings on a fixed 12 mm grid of slabs for every held-out case.
Writes WORK/eval/fold<F>/<case>.npz with z0 slab centres teacher_full teacher on the scanner routine-dose image (the target) raw_full, raw_low encoder on denoised measurements at routine and at the supplied low dose teacher_low teacher on the scanner's own low-dose image, where image_low.npy exists(each slab embedding (n, 512); regional embeddings with suffix _regions, (n, 16, 512)).
torchrun --nproc_per_node 8 -m proj2rep evaluate --data DATA --work WORK --fold 0 --teacher ct_fm.safetensors"""
import argparsefrom pathlib import Path
import numpy as npimport torch
from . import distfrom .bank import bank_dirfrom .data import load_cohortfrom .models import load_teacher, teachfrom .train_encoder import BankSlabs, load
@torch.inference_mode()def embed(fn, xs, batch=16): s, r = [], [] for i in range(0, len(xs), batch): u, w = fn(torch.stack(xs[i : i + batch])) s.append(u.float().cpu().numpy()) r.append(w.float().cpu().numpy().astype(np.float16)) return np.concatenate(s), np.concatenate(r)
def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--data", required=True) p.add_argument("--work", required=True) p.add_argument("--fold", type=int, required=True) p.add_argument("--teacher", required=True) a = p.parse_args(argv)
rank, world, device = dist.init() work = Path(a.work) cohort = load_cohort(a.data, work_dir=work) _, held = cohort.split(a.fold) teacher, model = load_teacher(a.teacher, device), load(work, a.fold, device) out = work / "eval" / f"fold{a.fold}" out.mkdir(parents=True, exist_ok=True)
def run_encoder(x): with torch.autocast("cuda", dtype=torch.bfloat16): return model(x.to(device).contiguous(memory_format=torch.channels_last_3d))
def run_teacher(x): return teach(teacher, x.to(device))
for case in cohort.cases(held)[rank::world]: cid = case.id path = out / f"{cid}.npz" if path.exists(): continue src = BankSlabs(case, bank_dir(work, a.fold, cid)) z = case.grid() res = {"z0": z} res["teacher_full"], res["teacher_full_regions"] = embed(run_teacher, [case.image_slab(z0) for z0 in z]) res["raw_full"], res["raw_full_regions"] = embed(run_encoder, [src.slab(z0, 0.0) for z0 in z]) if src.has("low", 1): res["raw_low"], res["raw_low_regions"] = embed(run_encoder, [src.slab(z0, 1.0) for z0 in z]) if case.has("image_low"): res["teacher_low"], res["teacher_low_regions"] = embed(run_teacher, [case.image_slab(z0, dose="low") for z0 in z]) np.savez_compressed(path, **res) print(f"[rank {rank}] evaluated fold {a.fold}: {cid} ({len(z)} slabs)", flush=True) dist.done(sync=False)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Fit and apply a constant offset for global CT-FM slab embeddings."""
import argparsefrom pathlib import Pathfrom tempfile import NamedTemporaryFile
import numpy as np
def exam_residual(measurement, reference): if ( measurement.ndim != 2 or not len(measurement) or measurement.shape != reference.shape or measurement.shape[1] != 512 ): raise ValueError("Expected paired nonempty arrays of 512 features per slab") if not np.isfinite(measurement).all() or not np.isfinite(reference).all(): raise ValueError("Nonfinite calibration feature") return (reference.astype(np.float64) - measurement).mean(axis=0)
def load_scan(path): with np.load(path) as scan: z, slab = scan["z0"], scan["slab"] if z.ndim != 1 or len(z) == 0 or slab.shape != (len(z), 512): raise ValueError(f"{path}: inconsistent slab coordinates or features") if ( not np.isfinite(z).all() or len(np.unique(z)) != len(z) or not np.isfinite(slab).all() ): raise ValueError(f"{path}: invalid slab coordinates or features") return z, slab
def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) subs = parser.add_subparsers(dest="action", required=True) fit = subs.add_parser( "fit", help="pair equally named exam files from each directory" ) fit.add_argument("measurement_dir", type=Path) fit.add_argument("reference_dir", type=Path) fit.add_argument("out", type=Path) apply = subs.add_parser( "apply", help="write corrected global embeddings for one scan" ) apply.add_argument("offset", type=Path) apply.add_argument("scan", type=Path) apply.add_argument("out", type=Path) args = parser.parse_args(argv) if args.action == "fit": measurement = {p.name: p for p in args.measurement_dir.glob("*.npz")} reference = {p.name: p for p in args.reference_dir.glob("*.npz")} if not measurement or measurement.keys() != reference.keys(): parser.error( "Expected one matched pair of files per calibration examination" ) if args.out.resolve() in { p.resolve() for p in [*measurement.values(), *reference.values()] }: parser.error("Choose an offset file separate from the calibration scans") residuals = [] for name in sorted(measurement): z, x = load_scan(measurement[name]) rz, y = load_scan(reference[name]) if not np.array_equal(z, rz): raise ValueError(f"{name}: calibration slab coordinates differ") residuals.append(exam_residual(x, y)) arrays = {"offset": np.mean(residuals, axis=0), "examinations": len(residuals)} else: if args.out.resolve() in (args.scan.resolve(), args.offset.resolve()): parser.error("Choose an output path separate from the scan and offset") z, x = load_scan(args.scan) with np.load(args.offset) as saved: offset = saved["offset"] if offset.shape != (512,) or not np.isfinite(offset).all(): raise ValueError("Expected a finite 512-feature offset") arrays = {"z0": z, "slab": x.astype(float) + offset} with NamedTemporaryFile(dir=args.out.parent, delete=False) as file: tmp = Path(file.name) try: np.savez_compressed(file, **arrays) file.flush() tmp.replace(args.out) finally: tmp.unlink(missing_ok=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173"""Analytic back-projection of helical fan-beam measurements onto the reconstruction grid.
Ramp filter along detector columns with fan-beam cosine weighting, then, for every outputslice, back-projection of the gantry rotation of views nearest to that slice, with detectorrows chosen by the cone angle. A fast, vendor-independent reconstruction that the encoder istrained to read. Output is in HU on the case's image grid at 256 x 256.
Vendors store angles, columns and rows with different signs and offsets. `calibrate` picks,per manufacturer, the convention whose back-projection best matches the scanner images."""
import copyimport itertoolsimport jsonimport mathfrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as F
SIZE = 256 # output pixels per side
class Geometry: def __init__(self, case, size=SIZE): g, im, v = case.geometry, case.image_meta, case.views self.case, self.manufacturer = case.id, case.manufacturer.upper() self.head_first = str(g.get("patient_position", "FFS")).upper().startswith("HF") sid = v.get("source_isocenter_mm") self.sid = float(np.mean(sid)) if sid is not None else float(g["source_isocenter_mm"]) self.sdd = float(g["source_detector_mm"]) self.dgamma = float(g["column_spacing_mm"]) / self.sdd self.drow = float(g["row_spacing_mm"]) self.c0, self.r0 = g["central_element"][0] - 1, g["central_element"][1] - 1 # 1-based in the file self.rows, self.cols = int(g["detector_rows"]), int(g["detector_columns"]) self.mu = float(g["water_mu_per_mm"]) self.n = round(float(g["stored_views_per_rotation"])) self.angle, self.z = v["angle_rad"].astype(np.float64), v["z_mm"].astype(np.float64) self.image_z = np.asarray(im["z_mm"], dtype=np.float64) self.thickness = float(im.get("thickness_mm", 1.5)) # DICOM order: pixel_spacing_mm = [between rows (y), between columns (x)] sy, sx = (float(v) for v in im["pixel_spacing_mm"]) width, height = int(im.get("columns", 512)), int(im.get("rows", im.get("columns", 512))) self.x = im["origin_mm"][0] + (np.arange(size) + 0.5) * sx * width / size - 0.5 * sx self.y = im["origin_mm"][1] + (np.arange(size) + 0.5) * sy * height / size - 0.5 * sy c = im.get("rotation_center_mm") or [0.0, 0.0] self.centre = (float(c[0]), float(c[1]))
def valid(self): """Indices of image slices with measurements on both sides.""" return np.flatnonzero((self.image_z >= self.z.min()) & (self.image_z <= self.z.max()))
def sparse(geo, k): """The same acquisition keeping every k-th view (use with data[::k]).""" g = copy.copy(geo) g.angle, g.z, g.n = geo.angle[::k], geo.z[::k], max(geo.n // k, 1) return g
def ramp(geo, device): """Equiangular fan-beam ramp kernel, including the column step.""" n = torch.arange(-(geo.cols - 1), geo.cols, device=device, dtype=torch.float64) k = torch.zeros_like(n) odd = (n.abs() % 2) == 1 k[odd] = -1 / (2 * math.pi**2 * torch.sin(n[odd] * geo.dgamma) ** 2) k[n == 0] = 1 / (8 * geo.dgamma**2) return (k * geo.dgamma).float()
def _filter(geo, views, kernel): gamma = (torch.arange(geo.cols, device=views.device) - geo.c0) * geo.dgamma x = views.float() * (geo.sid * torch.cos(gamma)) return F.conv1d(x.reshape(-1, 1, geo.cols), kernel[None, None], padding=geo.cols - 1).reshape(views.shape)
class Conventions: """Per-manufacturer geometric convention (angle sign, quarter turns, column sign, row sign)."""
def __init__(self, path): self.path = Path(path) self.table = json.loads(self.path.read_text()) if self.path.exists() else {}
def __call__(self, geo): key = next((k for k in self.table if geo.manufacturer.startswith(k)), None) if key is None: raise KeyError(f"no calibrated convention for manufacturer {geo.manufacturer!r}; run `proj2rep calibrate`") return oriented(self.table[key], geo)
def oriented(conv, geo): """Feet-first convention -> the one for this case (head-first mirrors left-right and the table axis).""" sa, quarter, sc, sr = conv return [-sa, quarter, -sc, -sr] if geo.head_first else [sa, quarter, sc, sr]
@torch.no_grad()def backproject(geo, data, zs, device, conv): """data: (V, rows, cols) line integrals -> HU volume (len(zs), SIZE, SIZE).""" sa, quarter, sc, sr = conv kernel = ramp(geo, device) x = torch.tensor(geo.x - geo.centre[0], device=device, dtype=torch.float32) y = torch.tensor(geo.y - geo.centre[1], device=device, dtype=torch.float32) yy, xx = torch.meshgrid(y, x, indexing="ij") out = torch.zeros(len(zs), len(y), len(x), device=device) for i, z in enumerate(zs): c = int(np.abs(geo.z - z).argmin()) a = min(max(c - geo.n // 2, 0), max(len(geo.z) - geo.n, 0)) pick = slice(a, a + geo.n) q = _filter(geo, torch.from_numpy(np.array(data[pick], dtype=np.float32)).to(device), kernel) beta = torch.tensor(sa * geo.angle[pick] + quarter * math.pi / 2, device=device, dtype=torch.float32) dz = torch.tensor(z - geo.z[pick], device=device, dtype=torch.float32) ux, uy = -torch.sin(beta)[:, None, None], torch.cos(beta)[:, None, None] along = geo.sid - (xx * ux + yy * uy) across = xx * uy - yy * ux dist2 = along**2 + across**2 col = geo.c0 + sc * torch.atan2(across, along) / geo.dgamma row = geo.r0 + sr * dz[:, None, None] * geo.sdd / dist2.sqrt() / geo.drow grid = torch.stack([2 * col / (geo.cols - 1) - 1, 2 * row.clamp(0, geo.rows - 1) / (geo.rows - 1) - 1], -1) s = F.grid_sample(q[:, None], grid, mode="bilinear", padding_mode="zeros", align_corners=True)[:, 0] out[i] = (s / dist2).sum(0) * (2 * math.pi / len(beta)) return 1000 * (out / geo.mu - 1)
def reconstruct(geo, data, zs, device, conv, chunk=8): """Back-projection averaged over the image slice thickness, in chunks of slices.""" n = max(1, round(geo.thickness / 1.5)) offsets = (np.arange(n) - (n - 1) / 2) * geo.thickness / n zs = np.asarray(zs) parts = [] for i in range(0, len(zs), chunk): z = zs[i : i + chunk] parts.append(sum(backproject(geo, data, z + o, device, conv) for o in offsets) / n) return torch.cat(parts)
def reference(case, geo, zs): """Scanner image at the given slices, on the 256 x 256 grid, HU.""" im = case.array("image_full") idx = [int(np.abs(geo.image_z - z).argmin()) for z in zs] x = torch.from_numpy(np.stack([im[i] for i in idx]).astype(np.float32)).clamp(-1024, 3000) return F.interpolate(x[:, None], (SIZE, SIZE), mode="area")[:, 0]
def calibrate(cohort, out, device, per_vendor=3): """Choose each manufacturer's convention by correlation with the scanner images.""" result, report = {}, {} cases = cohort.cases(cohort.ids()) makers = sorted({c.manufacturer.upper().split()[0] for c in cases}) for maker in makers: mine = sorted((c for c in cases if c.manufacturer.upper().startswith(maker)), key=lambda c: Geometry(c).head_first) pick = mine[:per_vendor] # feet-first cases first; head-first cases are scored through `oriented` if not pick: continue score = {} for case in pick: geo = Geometry(case) data = case.array("proj_full") v = geo.valid() zs = geo.image_z[v[[len(v) // 3, 2 * len(v) // 3]]] ref = reference(case, geo, zs).to(device) for conv in itertools.product((1, -1), (0, 1, 2, 3), (1, -1), (1, -1)): r = backproject(geo, data, zs, device, oriented(conv, geo)).clamp(-1024, 3000) c = torch.corrcoef(torch.stack([r.flatten(), ref.flatten()]))[0, 1].item() score[conv] = score.get(conv, 0) + c / len(pick) best = sorted(score, key=score.get, reverse=True) result[maker] = list(best[0]) report[maker] = {"cases": [c.id for c in pick], "top": [[list(b), round(score[b], 4)] for b in best[:4]]} print(maker, report[maker], flush=True) Path(out).parent.mkdir(parents=True, exist_ok=True) Path(out).write_text(json.dumps(result, indent=1) + "\n") return report1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Score lung nodule or liver lesion localization on CT-FM v12 regional features.
python -m proj2rep lesion --task nodule --input embeddings/scan.npz --out scan_nodule.npz"""
import argparsefrom pathlib import Path
import numpy as npfrom scipy.special import expit
def local_scores(regions, weights): """Apply the training standardization and logistic head; output rows and columns follow the encoder grid.""" grid = int(weights["grid"]) if regions.ndim != 3 or regions.shape[1:] != (grid**2, len(weights["coef"])): raise ValueError(f"Expected (slabs, {grid**2}, {len(weights['coef'])}) CT-FM features; encode with --grid {grid}") if not np.isfinite(regions).all(): raise ValueError("The scan contains missing or non-finite regional embeddings") x = regions.astype(np.float32, copy=True) x -= weights["mean"] x /= weights["scale"] logits = x.reshape(-1, x.shape[-1]) @ weights["coef"] + weights["intercept"] return expit(logits).reshape(len(x), grid, grid)
def main(argv=None): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--task", choices=("nodule", "liver"), required=True) parser.add_argument("--input", type=Path, required=True, help="one scan produced by proj2rep encode --grid 8") parser.add_argument("--out", type=Path, required=True, help="output NPZ with slab positions and regional scores") args = parser.parse_args(argv) path = Path(__file__).parent / "weights" / f"{args.task}_grid8.npz" with np.load(path) as weights, np.load(args.input) as scan: scores = local_scores(scan["regions"], weights) z0 = scan["z0"] if z0.shape != (len(scores),) or not np.isfinite(z0).all(): raise ValueError("Expected one finite z0 coordinate per slab") if args.out.resolve() == args.input.resolve(): raise ValueError("Use a separate file for the output scores") with args.out.open("wb") as file: np.savez_compressed(file, z0=z0, scores=scores, task=args.task, grid=int(weights["grid"])) print(f"Scored {len(scores)} slabs for {args.task} localization")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""Networks: measurement denoiser, frozen image teacher, and the measurement encoder.
Teacher: the CT-FM image encoder (SegResNet encoder, 512 output features), frozen.Encoder: the same architecture, initialised from the teacher and trained to reproduce theteacher's embedding of the routine-dose image from back-projected measurements.Both return a slab embedding (B, 512) and a 4 x 4 grid of regional embeddings (B, 16, 512)."""
import torchimport torch.nn.functional as Ffrom torch import nn
DIM, GRID = 512, 4CT_FM = {"spatial_dims": 3, "in_channels": 1, "init_filters": 32, "blocks_down": [1, 2, 2, 4, 4]}CLIP, SCALE = 12.0, 4.0 # line integrals are clipped to [-1, CLIP] and divided by SCALE in the denoiser
def segres_encoder(): from monai.networks.nets.segresnet_ds import SegResEncoder
return SegResEncoder(**CT_FM)
def load_teacher(path, device): """Frozen CT-FM weights from a .safetensors file (see README for where to obtain them).""" from safetensors.torch import load_file
model = segres_encoder() model.load_state_dict(load_file(str(path)), strict=True) return model.to(device).eval().requires_grad_(False)
def pool(h, grid=GRID): return h.mean((2, 3, 4)), F.adaptive_avg_pool3d(h, (1, grid, grid)).flatten(2).transpose(1, 2)
@torch.no_grad()def teach(teacher, x): with torch.autocast("cuda", dtype=torch.bfloat16): h = teacher(x)[-1].float() return pool(h)
class Encoder(nn.Module): """Back-projected measurements (B, 1, 24, 256, 256) -> teacher-space embeddings."""
def __init__(self, teacher_path=None): super().__init__() self.net = segres_encoder() if teacher_path: from safetensors.torch import load_file
self.net.load_state_dict(load_file(str(teacher_path)), strict=True)
def forward(self, x, grid=GRID): return pool(self.net(x)[-1].float(), grid)
class _Block(nn.Module): def __init__(self, c): super().__init__() self.a, self.b = nn.Conv3d(c, c, 3, padding=1), nn.Conv3d(c, c, 3, padding=1) self.n1, self.n2 = nn.GroupNorm(8, c), nn.GroupNorm(8, c)
def forward(self, x): return x + self.b(F.silu(self.n2(self.a(F.silu(self.n1(x))))))
class Denoiser(nn.Module): """Residual network over (views, detector rows, detector columns): reduced-dose -> routine-dose line integrals.
Two levels; the coarse level halves views and columns, not rows. The output layer starts at zero, so an untrained denoiser is the identity. """
def __init__(self, c=48): super().__init__() self.stem = nn.Conv3d(1, c, 3, padding=1) self.fine1 = nn.Sequential(_Block(c), _Block(c)) self.down = nn.Conv3d(c, 2 * c, (2, 1, 2), stride=(2, 1, 2)) self.coarse = nn.Sequential(*[_Block(2 * c) for _ in range(4)]) self.up = nn.ConvTranspose3d(2 * c, c, (2, 1, 2), stride=(2, 1, 2)) self.fine2 = nn.Sequential(_Block(c), _Block(c)) self.head = nn.Conv3d(c, 1, 3, padding=1) nn.init.zeros_(self.head.weight) nn.init.zeros_(self.head.bias)
def forward(self, x): u = x.clamp(-1, CLIP) / SCALE h = self.fine1(self.stem(u)) h = self.fine2(h + self.up(self.coarse(self.down(h)))) return (u + self.head(h)) * SCALE
@torch.inference_mode()def denoise_scan(model, scan, device, chunk=96, margin=8): """Whole scan (V, rows, cols) -> denoised float16 array, processed in overlapping view chunks.""" import numpy as np
v, _, c = scan.shape out = np.empty(scan.shape, np.float16) for a in range(0, v, chunk): lo, hi = max(a - margin, 0), min(a + chunk + margin, v) hi -= (hi - lo) % 2 if hi <= a: out[a:] = scan[a:] continue x = torch.from_numpy(np.asarray(scan[lo:hi], dtype=np.float32)).to(device)[None, None] if c % 2: x = F.pad(x, (0, 1)) with torch.autocast("cuda", dtype=torch.bfloat16): y = model(x)[0, 0, :, :, :c].float() stop = min(a + chunk, hi) out[a:stop] = y[a - lo : stop - lo].cpu().numpy() if stop < min(a + chunk, v): out[stop : min(a + chunk, v)] = scan[stop : min(a + chunk, v)] return out
def short_ramp(device, n=31): """Short ramp kernel used in the denoiser loss (shape of what back-projection sees).""" k = torch.arange(-n, n + 1, device=device, dtype=torch.float32) w = torch.zeros_like(k) odd = k.abs() % 2 == 1 w[odd] = -1 / (torch.pi * k[odd]) ** 2 w[n] = 0.25 return w * 4
def ramp_columns(x, kernel): return F.conv1d(x.reshape(-1, 1, x.shape[-1]), kernel[None, None], padding=len(kernel) // 2).reshape(x.shape)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Cross-validated report: agreement with the teacher by region and manufacturer, pooled over folds.
Agreement is the variance of the teacher's routine-dose slab embedding explained by a route (R²,averaged over the 512 features), with 95% intervals from a case-level bootstrap.
python -m proj2rep report --data DATA --work WORKWrites WORK/report/agreement.csv, WORK/report/stress.csv and prints both tables."""
import argparsefrom pathlib import Path
import numpy as npimport pandas as pd
from .data import load_cohort
def r2(x, t): return float(np.mean(1 - ((x - t) ** 2).sum(0) / ((t - t.mean(0)) ** 2).sum(0)))
def bootstrap(parts, keys, b=500, seed=0): """parts: {case: {key: (n, 512)}}; {key: (estimate, low, high, cases)} for each route against teacher_full, each route scored on every case that has it.""" rng = np.random.default_rng(seed) out = {} for k in keys: cases = [c for c in parts if k in parts[c]] if not cases: continue
def stat(who, k=k): return r2(np.concatenate([parts[c][k] for c in who]), np.concatenate([parts[c]["teacher_full"] for c in who]))
draws = [stat(rng.choice(cases, len(cases))) for _ in range(b)] out[k] = (stat(cases), *np.quantile(draws, [0.025, 0.975]), len(cases)) return out
def load_parts(work, sub, cohort): parts = {} for f in sorted((Path(work) / sub).glob("fold*/*.npz")): if f.stem in set(cohort.ids()): with np.load(f) as d: parts[f.stem] = {k: d[k] for k in d.files if not k.endswith("_regions")} return parts
def table(parts, cohort, keys): t = cohort.table.set_index("case_id") groups = {"all": list(parts)} for (reg, man), g in t.loc[list(parts)].groupby(["region", "manufacturer"]): groups[f"{reg} / {man}"] = g.index.tolist() rows = [] for name, ids in groups.items(): sub = {c: parts[c] for c in ids} for k, (est, lo, hi, n) in bootstrap(sub, [k for k in keys if any(k in v for v in sub.values())]).items(): rows.append({"group": name, "route": k, "cases": n, "r2": est, "low": lo, "high": hi}) return pd.DataFrame(rows)
def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--data", required=True) p.add_argument("--work", required=True) a = p.parse_args(argv) cohort = load_cohort(a.data, work_dir=a.work) out = Path(a.work) / "report" out.mkdir(parents=True, exist_ok=True) pd.set_option("display.width", 200)
ev = load_parts(a.work, "eval", cohort) if ev: t = table(ev, cohort, ["raw_full", "raw_low", "teacher_low"]) t.to_csv(out / "agreement.csv", index=False) print("Held-out agreement with the teacher (R²):") print(t.pivot_table(index="group", columns="route", values="r2", sort=False).round(3).to_string(), "\n")
st = load_parts(a.work, "stress", cohort) if st: keys = sorted({k for v in st.values() for k in v if k.startswith(("raw_", "plain_"))}) t = table(st, cohort, keys) t[["route", "condition"]] = t.route.str.split("_", n=1, expand=True) t.to_csv(out / "stress.csv", index=False) print("Stress test (R² against the teacher on the routine-dose image):") print(t.pivot_table(index=["group", "condition"], columns="route", values="r2", sort=False).round(3).to_string())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Stress test of one fold's held-out cases: lower dose and fewer views than routine.
Two routes per condition, both scored against the teacher on the routine-dose scanner image: raw measurements -> fold denoiser -> back-projection -> fold encoder plain measurements -> back-projection -> frozen teacher (reconstruct, then encode)Dose levels are reached by scaling the supplied noise (proj_low - proj_full) to the target dosefraction. View conditions keep every k-th view of the routine-dose scan.
torchrun --nproc_per_node 8 -m proj2rep stress --data DATA --work WORK --fold 0 --teacher ct_fm.safetensors"""
import argparsefrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as F
from . import distfrom .data import load_cohort, slab_rows, to_inputfrom .evaluate import embedfrom .geometry import SIZE, Conventions, Geometry, reconstruct, sparsefrom .models import denoise_scan, load_teacher, teachfrom .train_denoiser import load as load_denoiserfrom .train_denoiser import noise_scalefrom .train_encoder import load as load_encoder
DOSES = (1.0, 0.25, 0.1, 0.05, 0.025)VIEWS = (2, 4, 8)
def conditions(case): out = [("views", k) for k in VIEWS] if case.has("proj_low") and case.low_dose_fraction: out = [("dose", d) for d in DOSES] + out else: out = [("dose", 1.0)] + out return out
def label(kind, value): return f"{kind}_{value:g}"
def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--data", required=True) p.add_argument("--work", required=True) p.add_argument("--fold", type=int, required=True) p.add_argument("--teacher", required=True) a = p.parse_args(argv)
rank, world, device = dist.init() work = Path(a.work) cohort = load_cohort(a.data, work_dir=work) _, held = cohort.split(a.fold) teacher, enc, dn = load_teacher(a.teacher, device), load_encoder(work, a.fold, device), load_denoiser(work, a.fold, device) conv = Conventions(work / "convention.json") out = work / "stress" / f"fold{a.fold}" out.mkdir(parents=True, exist_ok=True)
def run_encoder(x): with torch.autocast("cuda", dtype=torch.bfloat16): return enc(x.to(device).contiguous(memory_format=torch.channels_last_3d))
def run_teacher(x): return teach(teacher, x.to(device))
for case in cohort.cases(held)[rank::world]: cid = case.id path = out / f"{cid}.npz" if path.exists(): continue geo = Geometry(case) zs = geo.image_z[geo.valid()] z = case.grid() res = {"z0": z, "teacher_full": embed(run_teacher, [case.image_slab(z0) for z0 in z])[0]} # Where the scanner image holds padding instead of data (outside its reconstruction circle), # the plain route is blanked too, so both of the teacher's inputs cover the same field. scanner = torch.from_numpy(np.asarray(case.array("image_full")[geo.valid()], dtype=np.float32)) blank = (F.interpolate(scanner[:, None], (SIZE, SIZE), mode="area")[:, 0] < -1500).to(device) full = np.asarray(case.array("proj_full"), dtype=np.float32) noise = np.asarray(case.array("proj_low"), dtype=np.float32) - full if case.has("proj_low") else None for kind, value in conditions(case): if kind == "dose": s = 0.0 if value == 1 else noise_scale(case.low_dose_fraction, value) g, data = geo, (full + s * noise if s else full) else: g, data = sparse(geo, value), np.ascontiguousarray(full[::value]) for route, vol in (("raw", reconstruct(g, denoise_scan(dn, data, device), zs, device, conv(geo))), ("plain", reconstruct(g, data, zs, device, conv(geo)).masked_fill(blank, -1024))): # fmt: skip slabs = [] for z0 in z: rows, flip = slab_rows(zs, z0) x = vol[rows].float().cpu() slabs.append(to_input(x.flip(0) if flip else x)) res[f"{route}_{label(kind, value)}"] = embed(run_encoder if route == "raw" else run_teacher, slabs)[0] np.savez_compressed(path, **res) print(f"[rank {rank}] stress fold {a.fold}: {cid}", flush=True) dist.done(sync=False)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Train the measurement denoiser for one cross-validation fold.
Reduced-dose line integrals -> routine-dose line integrals of the same acquisition. Trainingspans a continuous dose range by scaling the supplied noise (proj_low - proj_full) to a randomdose fraction, and optionally keeps only every 2nd, 4th or 8th view (sparse acquisitions).Loss: L1 on the line integrals plus L1 after a ramp filter along detector columns.
torchrun --nproc_per_node 8 -m proj2rep train-denoiser --data DATA --work WORK --fold 0"""
import argparseimport jsonimport timefrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as Ffrom torch import nnfrom torch.nn.parallel import DistributedDataParallel as DDPfrom torch.utils.data import DataLoader, Dataset
from . import distfrom .data import load_cohortfrom .models import CLIP, Denoiser, ramp_columns, short_ramp
CROP = (24, 32, 512) # views, rows, columns
def noise_scale(supplied, fraction): """Multiple of the supplied noise whose variance matches `fraction` of routine dose.""" return float(np.sqrt((1 / fraction - 1) / (1 / supplied - 1)))
class Crops(Dataset): """Random crops of one fixed shape from every case, so scanners with different detectors batch together."""
def __init__(self, cases, n, seed, min_dose, views): self.cases, self.n, self.seed, self.min_dose, self.views = cases, n, tuple(seed), min_dose, views shapes = np.array([c.array("proj_full").shape for c in cases]) cols = min(CROP[2], int(shapes[:, 2].min())) self.shape = (CROP[0], min(CROP[1], int(shapes[:, 1].min())), cols - cols % 2)
def __len__(self): return self.n
def __getitem__(self, i): rng = np.random.default_rng((*self.seed, i)) case = self.cases[rng.integers(len(self.cases))] full, low = case.array("proj_full"), case.array("proj_low") nv, nr, nc = self.shape k = int(rng.choice([k for k in self.views if nv * k <= full.shape[0]] or [1])) v = int(rng.integers(0, full.shape[0] - nv * k + 1)) r, c = int(rng.integers(0, full.shape[1] - nr + 1)), int(rng.integers(0, full.shape[2] - nc + 1)) s = (slice(v, v + nv * k, k), slice(r, r + nr), slice(c, c + nc)) y, x = torch.from_numpy(full[s].astype(np.float32)), torch.from_numpy(low[s].astype(np.float32)) f = float(np.exp(rng.uniform(np.log(self.min_dose), np.log(0.6)))) a = 0.0 if rng.random() < 0.1 else noise_scale(case.low_dose_fraction, f) x = y + a * (x - y) for d in (0, 1, 2): if rng.random() < 0.5: x, y = x.flip(d), y.flip(d) return x[None], y[None]
def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--data", required=True) p.add_argument("--work", required=True) p.add_argument("--fold", type=int, required=True, help="cross-validation fold; -1 trains on every case") p.add_argument("--steps", type=int, default=8000) p.add_argument("--batch", type=int, default=8, help="global batch (split across GPUs)") p.add_argument("--lr", type=float, default=3e-4) p.add_argument("--min-dose", type=float, default=0.02, help="lowest simulated dose fraction") p.add_argument("--views", type=int, nargs="+", default=[1, 1, 2, 4, 8], help="view-keeping factors to draw from") p.add_argument("--workers", type=int, default=8) a = p.parse_args(argv)
rank, world, device = dist.init() work = Path(a.work) cohort = load_cohort(a.data, work_dir=work) train, _ = cohort.split(a.fold) cases = [c for c in cohort.cases(train, image=False) if c.has("proj_low") and c.low_dose_fraction] if not cases: raise SystemExit("no training case has proj_low and low_dose_fraction") out = work / "denoiser" out.mkdir(parents=True, exist_ok=True) torch.manual_seed(a.fold + 1) model = Denoiser().to(device) if world > 1: model = DDP(model, device_ids=[device.index]) opt = torch.optim.AdamW(model.parameters(), a.lr, weight_decay=1e-4) sched = torch.optim.lr_scheduler.OneCycleLR(opt, a.lr, total_steps=a.steps, pct_start=0.05) per = max(a.batch // world, 1) data = Crops(cases, a.steps * per, (a.fold + 1, rank), a.min_dose, a.views) loader = DataLoader(data, per, num_workers=a.workers, drop_last=True, persistent_workers=a.workers > 0) kernel = short_ramp(device) dist.log(rank, f"fold {a.fold}: {len(cases)} training cases, {world} GPU(s), batch {per}/GPU") start, hist = time.time(), [] for step, (x, y) in enumerate(loader): x, y = x.to(device), y.to(device).clamp(-1, CLIP) with torch.autocast("cuda", dtype=torch.bfloat16): pred = model(x).float() loss = F.l1_loss(pred, y) + F.l1_loss(ramp_columns(pred, kernel), ramp_columns(y, kernel)) opt.zero_grad(set_to_none=True) loss.backward() nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() sched.step() hist.append(loss.item()) if step % 100 == 99: dist.log(rank, f"denoiser fold {a.fold} step {step + 1} loss {np.mean(hist[-100:]):.4f} {time.time() - start:.0f}s") if rank == 0: net = model.module if world > 1 else model torch.save(net.state_dict(), out / f"fold{a.fold}.pt") (out / f"fold{a.fold}.json").write_text(json.dumps({"steps": a.steps, "batch": a.batch, "cases": len(cases), "seconds": time.time() - start}, indent=1) + "\n") # fmt: skip dist.done()
def load(work, fold, device): model = Denoiser().to(device) model.load_state_dict(torch.load(Path(work) / "denoiser" / f"fold{fold}.pt", map_location=device, weights_only=True)) return model.eval()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248"""Train the measurement encoder for one cross-validation fold.
Input: a 36 mm slab of the denoised back-projection (from `proj2rep bank`) at a random dose leveland view fraction. Target: the frozen teacher's slab and regional embeddings of the scanner'sroutine-dose image of the same slab. The encoder starts from the teacher's weights. Both inputsget the same random mirror, in-plane zoom and shift. Half of the slabs are placed with an edge ona slice position, as the evaluation grid is (--snap-z).
Multi-GPU: DistributedDataParallel with synchronised BatchNorm; each GPU draws its own slabs.Training state is saved every --save-every steps and resumed automatically.
torchrun --nproc_per_node 8 -m proj2rep train-encoder --data DATA --work WORK --fold 0 --teacher ct_fm.safetensors"""
import argparseimport jsonimport timefrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as Ffrom torch import nnfrom torch.nn.parallel import DistributedDataParallel as DDPfrom torch.utils.data import DataLoader, Dataset
from . import distfrom .bank import bank_dirfrom .data import HALF, group_of, load_cohort, slab_rows, to_inputfrom .models import Encoder, load_teacher, teach
class BankSlabs: """Denoised back-projections of one case at the levels and view fractions on disk."""
def __init__(self, case, folder): self.case, self.dir, self.z, self.files = case, folder, np.load(folder / "z_mm.npy"), {}
def vol(self, level, k): if (level, k) not in self.files: self.files[level, k] = np.load(self.dir / f"{level}_v{k}.npy", mmap_mode="r") return self.files[level, k]
def has(self, level, k): return (self.dir / f"{level}_v{k}.npy").exists()
def slab(self, z0, u=0.0, k=1, mirror=False): """Dose position u: 0 routine, 1 supplied low dose, 2 lowest level; linear in between.""" rows, flip = slab_rows(self.z, z0)
def get(level): return torch.from_numpy(np.array(self.vol(level, k)[rows], dtype=np.float32))
if u <= 0: x = get("full") elif u <= 1: x = get("full") x = x + u * (get("low") - x) else: x = get("low") x = x + (u - 1) * (get("min") - x) x = to_input(x.flip(0) if flip else x) return x.flip(-1) if mirror else x
class Slabs(Dataset): def __init__(self, sources, n, seed, a, offset=0): """Sample i is drawn from seed and offset + i, so a resumed run continues the same stream.""" self.sources, self.n, self.seed, self.a, self.offset = sources, n, seed, a, offset
def __len__(self): return self.n
def __getitem__(self, i): a, rng = self.a, np.random.default_rng((*self.seed, self.offset + i)) src = self.sources[rng.integers(len(self.sources))] lo, hi = src.case.slab_range z0, mirror = snap(rng.uniform(lo, hi), src.z, lo, hi, rng.random() < a.snap_z), bool(rng.integers(2)) views = [k for k in a.views if src.has("full", k)] if not group_of(src.case, a.no_thin) else [1] views = views or [1] k = int(rng.choice(views, p=view_weights(views))) top = a.max_dose_level if k == 1 else min(a.max_dose_level, 1.0) if not src.has("low", k): top = 0.0 if top > 1 and not src.has("min", 1): top = 1.0 u = 0.0 if rng.random() < a.clean else float(rng.uniform(0, top)) return src.slab(z0, u, k, mirror), src.case.image_slab(z0, mirror)
def snap(z0, z, lo, hi, on=True): """Nearest slab centre whose edge lies exactly on a slice position.
Evaluation slabs start at the first slice, so their edges fall on slices whenever the slice spacing divides the slab length, and such a slab holds one slice more than a slab at a random position. Training half of the slabs this way keeps both kinds in distribution. """ if not on: return z0 edge = np.concatenate([z + HALF, z - HALF]) edge = edge[(edge >= lo) & (edge <= hi)] return float(edge[np.abs(edge - z0).argmin()]) if len(edge) else z0
def view_weights(views): """All views (k = 1) on 40% of slabs, the thinned fractions sharing the rest.""" if len(views) == 1: return None w = np.array([0.4 if k == 1 else 0.6 / (len(views) - (1 in views)) for k in views]) return w / w.sum()
def field_of_view(x, y, gen, zoom=(0.8, 1.2), move=0.2): """Same random in-plane zoom and shift for input and target; half of the batch unchanged.""" n = len(x) scale = torch.where(torch.rand(n, generator=gen) < 0.5, torch.ones(n), torch.empty(n).uniform_(*zoom, generator=gen)) shift = (torch.rand(n, 2, generator=gen) - 0.5) * move * (scale != 1)[:, None] theta = torch.zeros(n, 3, 4) theta[:, 0, 0], theta[:, 1, 1], theta[:, 2, 2] = scale, scale, 1 theta[:, 0, 3], theta[:, 1, 3] = shift[:, 0], shift[:, 1] g = F.affine_grid(theta.to(x.device), x.shape, align_corners=False) return F.grid_sample(x, g, align_corners=False), F.grid_sample(y, g, align_corners=False)
def target_stats(teacher, sources, n, device, seed): """Mean and spread of the teacher embeddings, for a balanced loss across features.""" rng = np.random.default_rng(seed) s, r = [], [] for _ in range(n // 8): xs = [] for _ in range(8): src = sources[rng.integers(len(sources))] lo, hi = src.case.slab_range xs.append(src.case.image_slab(rng.uniform(lo, hi))) u, w = teach(teacher, torch.stack(xs).to(device)) s.append(u) r.append(w.flatten(0, 1)) s, r = torch.cat(s), torch.cat(r) return torch.stack([s.mean(0), s.std(0).clamp_min(1e-4), r.mean(0), r.std(0).clamp_min(1e-4)])
def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--data", required=True) p.add_argument("--work", required=True) p.add_argument("--fold", type=int, required=True, help="cross-validation fold; -1 trains on every case") p.add_argument("--teacher", required=True, help="CT-FM feature extractor weights (.safetensors)") p.add_argument("--steps", type=int, default=16000) p.add_argument("--batch", type=int, default=16, help="global batch (split across GPUs)") p.add_argument("--lr", type=float, default=1e-4) p.add_argument("--views", type=int, nargs="+", default=[1, 2, 4, 8], help="view fractions to train on") p.add_argument("--max-dose-level", type=float, default=1.0, help="1: down to the supplied low dose; 2: down to the bank's min level") p.add_argument("--clean", type=float, default=0.15, help="share of slabs at routine dose") p.add_argument("--no-thin", nargs="*", default=[], help="REGION:MANUFACTURER groups trained at all views only") p.add_argument("--snap-z", type=float, default=0.5, help="share of slabs placed with an edge exactly on a slice") p.add_argument("--stats", type=int, default=800, help="slabs used for the target statistics") p.add_argument("--save-every", type=int, default=500) p.add_argument("--workers", type=int, default=8) a = p.parse_args(argv)
rank, world, device = dist.init() work = Path(a.work) cohort = load_cohort(a.data, work_dir=work) train, _ = cohort.split(a.fold) sources = [BankSlabs(c, bank_dir(work, a.fold, c.id)) for c in cohort.cases(train)] missing = [s.case.id for s in sources if not s.has("full", 1)] if missing: raise SystemExit(f"no bank for {len(missing)} training cases (e.g. {missing[0]}); run `proj2rep bank --fold {a.fold}` first") if 1 not in a.views: raise SystemExit("--views must include 1 (all views)") out = work / "encoder" out.mkdir(parents=True, exist_ok=True) name, resume = f"fold{a.fold}", out / f"fold{a.fold}.resume.pt"
teacher = load_teacher(a.teacher, device) stats = torch.zeros(4, 512, device=device) if rank == 0: stats = target_stats(teacher, sources, max(a.stats, 64), device, a.fold + 1) sm, ss, rm, rs = dist.broadcast(stats)
torch.manual_seed(a.fold + 1) model = Encoder(a.teacher).to(device) if world > 1: model = nn.SyncBatchNorm.convert_sync_batchnorm(model) model = model.to(memory_format=torch.channels_last_3d) opt = torch.optim.AdamW(model.parameters(), a.lr, weight_decay=0.01) sched = torch.optim.lr_scheduler.OneCycleLR(opt, a.lr, total_steps=a.steps, pct_start=0.05) gen = torch.Generator() first = 0 if resume.exists(): state = torch.load(resume, map_location=device, weights_only=False) if state.get("steps", a.steps) != a.steps or state.get("batch", a.batch) != a.batch: raise SystemExit( f"{resume} was saved with --steps {state.get('steps')} --batch {state.get('batch')}; use the same or delete it" ) model.load_state_dict(state["model"]) opt.load_state_dict(state["opt"]) sched.load_state_dict(state["sched"]) first = state["step"] dist.log(rank, f"resumed {resume} at step {first}") net = DDP(model, device_ids=[device.index]) if world > 1 else model
per = max(a.batch // world, 1) data = Slabs(sources, (a.steps - first) * per, (a.fold + 1, rank), a, offset=first * per) loader = DataLoader( data, per, num_workers=a.workers, drop_last=True, persistent_workers=a.workers > 0, prefetch_factor=4 if a.workers else None ) dist.log(rank, f"encoder fold {a.fold}: {len(sources)} training cases, {world} GPU(s), batch {per}/GPU, steps {first}..{a.steps}") net.train() start, hist = time.time(), [] for step, (x, image) in enumerate(loader, start=first): gen.manual_seed(1_000_003 * (a.fold + 1) + 1000 * step + rank) # per-step seed: identical after a resume x, image = field_of_view(x.to(device), image.to(device), gen) ts, tr = teach(teacher, image) with torch.autocast("cuda", dtype=torch.bfloat16): ps, pr = net(x) loss = F.mse_loss((ps - sm) / ss, (ts - sm) / ss) + F.mse_loss((pr - rm) / rs, (tr - rm) / rs) opt.zero_grad(set_to_none=True) loss.backward() nn.utils.clip_grad_norm_(net.parameters(), 5.0) opt.step() sched.step() hist.append(loss.item()) if step % 100 == 99: dist.log(rank, f"encoder fold {a.fold} step {step + 1} loss {np.mean(hist[-100:]):.4f} {time.time() - start:.0f}s") if (step + 1) % a.save_every == 0 and step + 1 < a.steps and rank == 0: torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "sched": sched.state_dict(), "step": step + 1, "steps": a.steps, "batch": a.batch}, resume.with_suffix(".tmp")) # fmt: skip resume.with_suffix(".tmp").replace(resume) if rank == 0: # SyncBatchNorm keeps BatchNorm's parameter names, so the weights load into a plain Encoder torch.save(model.state_dict(), out / f"{name}.pt") resume.unlink(missing_ok=True) meta = {k: v for k, v in vars(a).items() if k not in ("data", "work", "teacher")} (out / f"{name}.json").write_text( json.dumps({**meta, "cases": len(sources), "gpus": world, "seconds": time.time() - start}, indent=1) + "\n" ) dist.done()
def load(work, fold, device): model = Encoder().to(device) model.load_state_dict(torch.load(Path(work) / "encoder" / f"fold{fold}.pt", map_location=device, weights_only=True)) return model.eval().to(memory_format=torch.channels_last_3d)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738"""Apply a trained residual readout to v12 leave-one-manufacturer-out slab features."""
import argparsefrom pathlib import Path
import numpy as np
def predict(head, features, view_stride): strides = head["view_strides"].tolist() if view_stride not in strides: raise ValueError(f"view stride must be one of {strides}") x = np.asarray(features, dtype=np.float32) if x.ndim != 2 or x.shape[1] != 512 or not len(x) or not np.isfinite(x).all(): raise ValueError("expected finite slab features with shape (slabs, 512)") i = strides.index(view_stride) return x + head["bias"][i] + (x - head["input_mean"][i]) @ head["matrix"][i]
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("head", type=Path) parser.add_argument( "features", type=Path, help="Numpy .npy matrix from the matching base encoder" ) parser.add_argument("output", type=Path, help="output .npy file") parser.add_argument("--view-stride", type=int, required=True, choices=[1, 2, 4, 8]) args = parser.parse_args() with np.load(args.head, allow_pickle=False) as head: result = predict( head, np.load(args.features, allow_pickle=False), args.view_stride ) with args.output.open("wb") as stream: np.save(stream, result)
if __name__ == "__main__": main()123456789101112131415161718# Proj2Rep-Refined
Current release: RC3.
## Selected routine-dose, full-view results
Manufacturer-adaptation evaluation on 117 patients; both support draws use the same evaluation patients.
| Group | Patients | Adaptive r (95% CI) | Refined r (95% CI) | Refined R² ||---|---:|---|---|---:|| GE chest | 29 | 0.952 (0.946–0.957) | 0.955 (0.949–0.961) | 0.906 || GE abdomen | 29 | 0.913 (0.893–0.934) | 0.923 (0.912–0.934) | 0.846 || Siemens chest | 30 | 0.938 (0.926–0.950) | 0.958 (0.953–0.964) | 0.913 || Siemens abdomen | 29 | 0.931 (0.921–0.938) | 0.942 (0.933–0.948) | 0.881 |

See the [main model card](../README.md) for confidence intervals, model selection, input preparation and inference commands.123version https://git-lfs.github.com/spec/v1oid sha256:54b290e77a01bab1fe3feab0cd41d11910d51b88550ed8b73a4b2290a4bfb370size 311152534123version https://git-lfs.github.com/spec/v1oid sha256:19bd30de60567dbeea90174fd2cf853a5dc58d95ad90fe5e31757d87162d4ffdsize 311152534123version https://git-lfs.github.com/spec/v1oid sha256:fe224da48c0e9cfe50e657abcf86146d1ca945202770ae0cd6bc49ae5b18aed4size 311152534123version https://git-lfs.github.com/spec/v1oid sha256:95dba94ad1e89eb33087382ef588a496c1a5c6e1da8b666487a7f3b09d2b2085size 311152534123456numpy>=1.26torch>=2.4monai>=1.4pandas>=2.0scikit-learn>=1.4safetensors>=0.4.gitattributesAdded+7
LICENSEAdded+21
README.mdAdded+138
USAGE.mdAdded+277
adaptive/README.mdAdded+18
adaptive/ge/abdomen_draw0.npzAdded+3
adaptive/ge/abdomen_draw1.npzAdded+3
adaptive/ge/base.ptAdded+3
adaptive/ge/chest_draw0.npzAdded+3
adaptive/ge/chest_draw1.npzAdded+3
adaptive/siemens/abdomen_draw0.npzAdded+3
adaptive/siemens/abdomen_draw1.npzAdded+3
adaptive/siemens/base.ptAdded+3
adaptive/siemens/chest_draw0.npzAdded+3
adaptive/siemens/chest_draw1.npzAdded+3
config.jsonAdded+39
convention.jsonAdded+14
figures/routine_demo.pdfAdded+3
figures/routine_demo.pngAdded

Large File Pointer Details
- SHA256: 0f6773b06cab97f3642c1327c34f15fb9cc72cb67264b9ea3dba8905dc33ddad
- Pointer size: 132 Bytes
- Size of remote file: 1.02 MB
figures/routine_results.pdfAdded
figures/routine_results.pngAdded

Large File Pointer Details
- SHA256: e8a04f9e4d2ebdb6aab02082765df8f7283986e1689b09414ccbcef0047e5487
- Pointer size: 131 Bytes
- Size of remote file: 195 kB
figures/workflow.pdfAdded
figures/workflow.pngAdded

Large File Pointer Details
- SHA256: 61c7dca43b483de82e2716c088eebda0c88e2b315079f5564c59e8dfc5e21c89
- Pointer size: 131 Bytes
- Size of remote file: 125 kB
infer.pyAdded+226
manifest.jsonAdded+84
preprocessing/ge/denoiser.ptAdded+3
preprocessing/siemens/denoiser.ptAdded+3
proj2rep/__init__.pyAdded+7
proj2rep/__main__.pyAdded+30
proj2rep/bank.pyAdded+77
proj2rep/calibrate_cli.pyAdded+31
proj2rep/data.pyAdded+201
proj2rep/dist.pyAdded+41
proj2rep/encode.pyAdded+71
proj2rep/evaluate.pyAdded+79
proj2rep/feature_offset.pyAdded+92
proj2rep/geometry.pyAdded+173
proj2rep/lesion.pyAdded+47
proj2rep/models.pyAdded+131
proj2rep/report.pyAdded+91
proj2rep/stress.pyAdded+104
proj2rep/train_denoiser.pyAdded+128
proj2rep/train_encoder.pyAdded+248
readout.pyAdded+38
refined/README.mdAdded+18
refined/ge/draw0.ptAdded+3
refined/ge/draw1.ptAdded+3
refined/siemens/draw0.ptAdded+3
refined/siemens/draw1.ptAdded+3
requirements.txtAdded+6