Add --precision fp16 for GPUs without fast bf16 (T4, V100)
Browse files`hecate.py` offers `--precision fp32` (default) and `bf16`. GPUs before Ampere, such as the free-Colab T4, have no fast `bf16` path: on a T4, `bf16` is slower than `fp32`.
## Summary
- `predict()` accepts `precision='fp16'` and runs `torch.autocast('cuda', dtype=torch.float16)`.
- `fp16` and `bf16` are both refused on CPU with `"bf16 and fp16 require CUDA; otherwise use fp32"`.
- `--precision` gains `fp16` and a help string; default remains `fp32`.
- One sentence added in `README.md`.
- Note on [discussion #3](https://huggingface.co/scrollprize/hecate/discussions/3) (`--resample`): `#3` adds `--resample` on the line right after `--precision`, so whichever merges second will have a one-line argparse context conflict (verified cleanly against `refs/pr/3` @ `f4386b19`).
## Parity Measurements (`fp16` vs `fp32`)
### 1. Both checkpoints (`2.4 um` and `9.6 um`), 2D `--output` & 3D `--output-3d`, forward & `--reverse` (`RTX 4060 Laptop GPU`, `torch 2.10.0+cu128`, `--batch-size 1`, `[64, 256, 256]` structural crops from public `PHerc0846A` 2.403 um CT & `PHerc0306B` 8.640 um control)
| Run | Seconds (`fp16` / `fp32`) | 2D `max \|Δ\|` (uint8) | 2D `mean \|Δ\|` | 2D `r` | 3D `max \|Δ\|` (uint8) | 3D `mean \|Δ\|` | 3D `r` |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `2.4 um` forward | 5.22 / 5.34 | **1** | 0.004013 | 0.999647 | **1** | 0.000589 | 0.999866 |
| `2.4 um` `--reverse` | 6.22 / 5.83 | **1** | 0.003311 | 0.999683 | **1** | 0.000539 | 0.999755 |
| `9.6 um` forward | 9.18 / 12.24 | **1** | 0.000732 | 0.999135 | **1** | 0.000125 | 0.999959 |
| `9.6 um` `--reverse` | 9.46 / 11.90 | **1** | 0.000931 | 0.999545 | **1** | 0.000126 | 0.999953 |
Peak allocated+reserved GPU delta dropped `1940 -> 1590 MiB` (`2.4 um`) and `972 -> 944 MiB` (`9.6 um`) at batch 1. All 8 comparisons differ by at most `1` uint8 level across both 2D PNG and 3D Zarr outputs.
### 2. Colab T4 timing (`torch 2.14.1+cu130`, `hecate_9.6um.pth`, 2D `--output`, `--batch-size 32`, `27 x 999 x 999` public `PHerc. 0841` crop, fresh process per run)
| precision | seconds | vs `fp32` output (uint8 levels) |
| --- | ---: | --- |
| **`fp16`** | **41.2** | **max 1, mean 0.047, `r = 0.99999`** |
| `fp32` (default) | 123.6 | — |
| `bf16` | 228.6 | max 11, mean 0.321, `r = 0.999893` |
On CPU, `--precision fp16` raises `ValueError('bf16 and fp16 require CUDA; otherwise use fp32')`, and default `fp32` behavior is unchanged. MIT license preserved, checkpoints untouched.
|
@@ -1,165 +1,165 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: mit
|
| 3 |
-
library_name: pytorch
|
| 4 |
-
pipeline_tag: image-segmentation
|
| 5 |
-
base_model: scrollprize/ink_canonical_2um
|
| 6 |
-
buckets:
|
| 7 |
-
- scrollprize/datasets
|
| 8 |
-
tags:
|
| 9 |
-
- hecate
|
| 10 |
-
- experimental
|
| 11 |
-
- vesuvius-challenge
|
| 12 |
-
- ink-detection
|
| 13 |
-
- 3d-segmentation
|
| 14 |
-
- knowledge-distillation
|
| 15 |
-
inference: false
|
| 16 |
-
---
|
| 17 |
-
|
| 18 |
-
# Hecate
|
| 19 |
-
|
| 20 |
-
**Hecate is an experimental architecture designed to locate ink on the middle papyrus sheet of a surface-conditioned render, while also producing the usual 2D ink map.**
|
| 21 |
-
|
| 22 |
-
Its name evokes Hecate, the three-formed goddess of thresholds and crossroads. Here, the threshold lies between a volume and a page: traces scattered through depth must become writing on a surface. The model looks into both spaces, seeking the hidden layer while gathering its marks into a readable image.
|
| 23 |
-
|
| 24 |
-
This release contains checkpoints for **2.4 µm** and **9.6 µm** inputs.
|
| 25 |
-
|
| 26 |
-
## From a volume to a page
|
| 27 |
-
|
| 28 |
-
A **surface-conditioned render (surface volume)** is a CT scan resampled around a mesh that follows a papyrus sheet. Although flattened, it still contains depth—and often several neighbouring sheets. The intended sheet can also wander above and below the centre of the render.
|
| 29 |
-
|
| 30 |
-
A conventional 2D ink detector must therefore learn two things together: which sheet to follow, and where that sheet carries ink.
|
| 31 |
-
|
| 32 |
-
We started from the **[canonical 2 µm ink detector](https://huggingface.co/scrollprize/ink_canonical_2um)** and modified it to expose a volumetric ink prediction. Hecate predicts ink throughout the render, then uses learned attention to combine its predictions across depth into a 2D map.
|
| 33 |
-
|
| 34 |
-
The two outputs share the same backbone. Supervision applied to the 2D map can therefore change how the model locates ink in 3D. The attention is learned, without a fixed Gaussian preference for the centre.
|
| 35 |
-
|
| 36 |
-
## Learning without new labels
|
| 37 |
-
|
| 38 |
-
**We created no additional manual labels for this work.** We used existing 2D annotations and predictions from frozen models, which served as teachers for the student's 3D output.
|
| 39 |
-
|
| 40 |
-
We began with three sources of guidance:
|
| 41 |
-
|
| 42 |
-
- **Strong 2D supervision** from the existing ink annotations.
|
| 43 |
-
- **Moderate 3D supervision on Paris4**, supplied by a precise **[Paris4 ink model](https://huggingface.co/scrollprize/ink_3d_dino_guided)**. We oversampled examples carrying these targets to give the student frequent exposure to reliable volumetric guidance.
|
| 44 |
-
- **Weak 3D supervision on other scrolls**, supplied by a less precise model.
|
| 45 |
-
|
| 46 |
-
These sources did not always describe the same task. A 3D teacher could detect ink on several neighbouring sheets, while the 2D annotations described writing on the intended middle sheet.
|
| 47 |
-
|
| 48 |
-
During training, we began to see the student's volumetric predictions concentrate on that middle sheet, even where its teacher responded to multiple layers. The shared architecture appeared to let the stronger 2D guidance shape a more selective 3D prediction.
|
| 49 |
-
|
| 50 |
-
We then froze selected student snapshots and used their predictions as new teaching targets. We reduced the special treatment of Paris4 and repeatedly adjusted the balance between 2D and 3D supervision. Dark background voxels were removed from positive teacher targets. When volumetric guidance became too restrictive and suppressed real ink, we weakened its influence.
|
| 51 |
-
|
| 52 |
-
The models reached these checkpoints through a gradual drift: **no new manual annotations, but a changing balance of imperfect teachers**. Their agreement improved in some places and remained imperfect in others.
|
| 53 |
-
|
| 54 |
-
## The 2.4 µm model
|
| 55 |
-
|
| 56 |
-
We preserved as much of the canonical model's architecture and pretrained weights as possible.
|
| 57 |
-
|
| 58 |
-
We removed its CT intensity clipping but retained division by **200**. This allowed brighter values to remain distinguishable while keeping the input scale familiar to the pretrained representation.
|
| 59 |
-
|
| 60 |
-
The model predicts ink on a coarser internal grid and interpolates the volumetric output back to the input grid. Its full-sized output should therefore not be mistaken for equally fine localization.
|
| 61 |
-
|
| 62 |
-

|
| 63 |
-
|
| 64 |
-
*Hecate at 2.4 µm. The output images in the diagram are illustrative, not measured predictions. Tensor dimensions are depth × height × width; feature channels are omitted.*
|
| 65 |
-
|
| 66 |
-
## The 9.6 µm model
|
| 67 |
-
|
| 68 |
-
We next transferred knowledge from the 2.4 µm model into a model operating at **9.6 µm**. Both its 2D and 3D teaching targets came from the finer-resolution model, rescaled to the new sampling.
|
| 69 |
-
|
| 70 |
-
The smaller input covers approximately the same physical region with fewer voxels. This model divides CT intensities by **255** and removes the canonical model's initial spatial reduction, allowing its decoder to predict on the input grid. Its encoder still uses internal multiscale stages.
|
| 71 |
-
|
| 72 |
-
Initially, its inputs were derived by downsampling fine CT. We subsequently introduced surface-conditioned renders from native coarse-resolution scans. Where both scans were available, we aligned their renders so that predictions from the fine scan could supervise the corresponding native CT. Blur and contrast augmentation helped bridge their different appearances. Where native patches failed the alignment checks, we retained fine-derived inputs instead.
|
| 73 |
-
|
| 74 |
-
**Surface-conditioned renders supplied to this model must be sampled at 9.6 µm in both the surface plane and the depth direction.** A scan described as “approximately 9 µm” may have a different acquisition spacing. Use its actual spacing when rendering or resampling.
|
| 75 |
-
|
| 76 |
-

|
| 77 |
-
|
| 78 |
-
*Hecate at 9.6 µm. The output images in the diagram are illustrative, not measured predictions. Tensor dimensions are depth × height × width; feature channels are omitted.*
|
| 79 |
-
|
| 80 |
-
## A view through the sheet
|
| 81 |
-
|
| 82 |
-
<img src="assets/pherc139-cross-section.png" alt="PHerc139 CT cross-section with Hecate's predicted ink shown as a coloured overlay along the papyrus surface" width="360" />
|
| 83 |
-
|
| 84 |
-
*A cross-section from a PHerc139 segment, with Hecate's predicted ink shown as a coloured overlay. The prediction follows a thin layer along the papyrus surface. The measurement shown is a local viewer measurement, not an estimate of the model's accuracy or spatial resolution.*
|
| 85 |
-
|
| 86 |
-
## Outputs and limitations
|
| 87 |
-
|
| 88 |
-
Both models produce:
|
| 89 |
-
|
| 90 |
-
- **A 3D ink probability volume**, intended to localize ink on the middle sheet.
|
| 91 |
-
- **A 2D ink probability map**, obtained by combining volumetric ink logits across depth using learned attention, then converting the result to probabilities.
|
| 92 |
-
|
| 93 |
-
The 3D output is not a papyrus-surface segmentation. It can miss faint ink, respond to fibres, or include neighbouring sheets. Middle-sheet localization is an intended behaviour rather than a guarantee.
|
| 94 |
-
|
| 95 |
-
Results also depend on the surface geometry, depth orientation, scan appearance, and whether the intended sheet lies within the surface-conditioned render.
|
| 96 |
-
|
| 97 |
-
## Running inference
|
| 98 |
-
|
| 99 |
-
Download `hecate.py`, `requirements.txt`, and the checkpoint you need from this repository. No training code, W&B account, or other model downloads are required.
|
| 100 |
-
|
| 101 |
-
```bash
|
| 102 |
-
python -m pip install -r requirements.txt
|
| 103 |
-
python hecate.py --checkpoint hecate_9.6um.pth --input surface.zarr \
|
| 104 |
-
--spacing-um 9.6 --output prediction.png --device cuda
|
| 105 |
-
```
|
| 106 |
-
|
| 107 |
-
For the finer model, use `--checkpoint hecate_2.4um.pth --spacing-um 2.4`. Add `--reverse` to reverse the **full render depth before selecting the central planes**. If the correct direction is unknown, run both directions into different output files.
|
| 108 |
-
|
| 109 |
-
Inputs must be **unnormalized uint8 arrays in Z, Y, X order**, stored as a local Zarr array, a Zarr group containing array `0` (override with `--array`), or a `.npy` file. Supply a surface-conditioned render, not a raw scroll volume. The render must already have the model's sampling in all three axes; the script does not resample. `--spacing-um` declares the render spacing and checks it against the checkpoint. It does not infer spacing from scan metadata.
|
| 110 |
-
|
| 111 |
-
| Checkpoint | Input patch, Z × Y × X | CT normalization |
|
| 112 |
-
|---|---|---|
|
| 113 |
-
| `hecate_2.4um.pth` | 64 × 256 × 256 | Divide by 200; no clipping |
|
| 114 |
-
| `hecate_9.6um.pth` | 16 × 64 × 64 | Divide by 255; no clipping |
|
| 115 |
-
|
| 116 |
-
The script selects the central input depth, slides over XY with half-patch overlap, and blends probabilities using a floored Hann window. Small XY inputs are zero-padded. Empty CT columns receive zero output. It saves a losslessly compressed PNG with **pixel value = round(255 × probability)**, plus a small JSON describing the inference settings. There is no per-image min–max scaling. Output XY dimensions match the input.
|
| 117 |
-
|
| 118 |
-
The default is float32 with batch size one. On compatible NVIDIA GPUs, `--precision bf16` enables the mixed precision used for production inference;
|
| 119 |
-
|
| 120 |
-
### Saving a 3D probability volume
|
| 121 |
-
|
| 122 |
-
Use `--output-3d` to save a compressed uint8 Zarr:
|
| 123 |
-
|
| 124 |
-
```bash
|
| 125 |
-
python hecate.py --checkpoint hecate_9.6um.pth --input surface.zarr --spacing-um 9.6 --output-3d ink_3d.zarr --reverse --device cuda
|
| 126 |
-
```
|
| 127 |
-
|
| 128 |
-
Add `--output prediction.png` to also save the 2D map. When only `--output-3d` is requested, attention and the 2D projection are not executed. Requesting both outputs runs two inference passes to keep the implementation and memory use simple.
|
| 129 |
-
|
| 130 |
-
The 3D Zarr is a **single-resolution array**, not a multiscale OME-Zarr. It stores `round(255 × probability)` with lossless Zstandard compression. Its ZYX shape and voxel order match the input, including after reversed inference: predictions are flipped back before saving. No cropping or per-volume min–max scaling is applied.
|
| 131 |
-
|
| 132 |
-
Inference tiles over XY and evaluates only the checkpoint's **central depth window**, not sliding windows through the entire Z axis. Unevaluated planes, including the finer model's excluded edge planes, are zero. The Zarr attributes record the half-open `evaluated_z_interval`, spacing, orientation, and inference settings so those zeros can be distinguished from evaluated predictions. Empty CT columns are zeroed; no additional voxel-intensity threshold is applied. Source world-coordinate transforms are not copied; the output is aligned to the input's voxel indices.
|
| 133 |
-
|
| 134 |
-
Temporary disk use for 3D blending is approximately `(4 × input_patch_depth + 4) × height × width` bytes, in addition to the compressed output. Set `TMPDIR` appropriately for large renders.
|
| 135 |
-
|
| 136 |
-
### Accessing the 3D output
|
| 137 |
-
|
| 138 |
-
The same file provides a small Python API. `model(image)` returns 2D logits; `model.forward_3d(image)` returns 3D logits without executing the learned projection. The CLI can write either output or both.
|
| 139 |
-
|
| 140 |
-
```python
|
| 141 |
-
import numpy as np
|
| 142 |
-
import torch
|
| 143 |
-
from hecate import load_model
|
| 144 |
-
|
| 145 |
-
model = load_model("hecate_9.6um.pth", "cuda")
|
| 146 |
-
# One correctly oriented uint8 patch, with shape model.patch_size.
|
| 147 |
-
ct = np.load("patch.npy").astype(np.float32)
|
| 148 |
-
ct /= model.divisor
|
| 149 |
-
image = torch.from_numpy(ct[None, None]).to("cuda")
|
| 150 |
-
with torch.inference_mode():
|
| 151 |
-
ink_3d = model.forward_3d(image).sigmoid()[0, 0].cpu().numpy()
|
| 152 |
-
np.save("ink_3d.npy", ink_3d)
|
| 153 |
-
```
|
| 154 |
-
|
| 155 |
-
The 2.4 µm model excludes its first and last input planes from the network and pads their 3D logits with −20; these planes are not valid learned predictions. Its interior 3D logits are interpolated to the input grid. The 9.6 µm model uses all sixteen planes. The Python API returns model predictions without applying an additional CT-background threshold.
|
| 156 |
-
|
| 157 |
-
The standalone runtime was checked against the original inference implementation on real CT crops with both released checkpoints: 2D and 3D patch logits, tiled forward/reverse predictions, padded edges, blank inputs, lossless PNG decoding, and compressed 3D Zarr round trips. Tiled 3D exports matched the original model in both depth directions, and checks confirmed that 3D-only inference bypasses attention. Float32 and CUDA bfloat16 were tested. The checkpoints load strictly, including their saved EMA batch-normalization buffers.
|
| 158 |
-
|
| 159 |
-
## Sources and acknowledgements
|
| 160 |
-
|
| 161 |
-
This work builds on the **[canonical 2 µm ink detector](https://huggingface.co/scrollprize/ink_canonical_2um)** and the **[Paris4 3D ink teacher](https://huggingface.co/scrollprize/ink_3d_dino_guided)**.
|
| 162 |
-
|
| 163 |
-
Development used the **[Scroll Prize ink dataset](https://huggingface.co/buckets/scrollprize/datasets/tree/ink)** and scans from the **[Vesuvius Challenge open-data collection](https://vesuvius-challenge-open-data.s3.amazonaws.com/index.html)**.
|
| 164 |
-
|
| 165 |
-
Hecate is released for experimentation and evaluation. It is a step toward finding writing in depth, not a finished solution to reliable 3D ink localization.
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
library_name: pytorch
|
| 4 |
+
pipeline_tag: image-segmentation
|
| 5 |
+
base_model: scrollprize/ink_canonical_2um
|
| 6 |
+
buckets:
|
| 7 |
+
- scrollprize/datasets
|
| 8 |
+
tags:
|
| 9 |
+
- hecate
|
| 10 |
+
- experimental
|
| 11 |
+
- vesuvius-challenge
|
| 12 |
+
- ink-detection
|
| 13 |
+
- 3d-segmentation
|
| 14 |
+
- knowledge-distillation
|
| 15 |
+
inference: false
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
# Hecate
|
| 19 |
+
|
| 20 |
+
**Hecate is an experimental architecture designed to locate ink on the middle papyrus sheet of a surface-conditioned render, while also producing the usual 2D ink map.**
|
| 21 |
+
|
| 22 |
+
Its name evokes Hecate, the three-formed goddess of thresholds and crossroads. Here, the threshold lies between a volume and a page: traces scattered through depth must become writing on a surface. The model looks into both spaces, seeking the hidden layer while gathering its marks into a readable image.
|
| 23 |
+
|
| 24 |
+
This release contains checkpoints for **2.4 µm** and **9.6 µm** inputs.
|
| 25 |
+
|
| 26 |
+
## From a volume to a page
|
| 27 |
+
|
| 28 |
+
A **surface-conditioned render (surface volume)** is a CT scan resampled around a mesh that follows a papyrus sheet. Although flattened, it still contains depth—and often several neighbouring sheets. The intended sheet can also wander above and below the centre of the render.
|
| 29 |
+
|
| 30 |
+
A conventional 2D ink detector must therefore learn two things together: which sheet to follow, and where that sheet carries ink.
|
| 31 |
+
|
| 32 |
+
We started from the **[canonical 2 µm ink detector](https://huggingface.co/scrollprize/ink_canonical_2um)** and modified it to expose a volumetric ink prediction. Hecate predicts ink throughout the render, then uses learned attention to combine its predictions across depth into a 2D map.
|
| 33 |
+
|
| 34 |
+
The two outputs share the same backbone. Supervision applied to the 2D map can therefore change how the model locates ink in 3D. The attention is learned, without a fixed Gaussian preference for the centre.
|
| 35 |
+
|
| 36 |
+
## Learning without new labels
|
| 37 |
+
|
| 38 |
+
**We created no additional manual labels for this work.** We used existing 2D annotations and predictions from frozen models, which served as teachers for the student's 3D output.
|
| 39 |
+
|
| 40 |
+
We began with three sources of guidance:
|
| 41 |
+
|
| 42 |
+
- **Strong 2D supervision** from the existing ink annotations.
|
| 43 |
+
- **Moderate 3D supervision on Paris4**, supplied by a precise **[Paris4 ink model](https://huggingface.co/scrollprize/ink_3d_dino_guided)**. We oversampled examples carrying these targets to give the student frequent exposure to reliable volumetric guidance.
|
| 44 |
+
- **Weak 3D supervision on other scrolls**, supplied by a less precise model.
|
| 45 |
+
|
| 46 |
+
These sources did not always describe the same task. A 3D teacher could detect ink on several neighbouring sheets, while the 2D annotations described writing on the intended middle sheet.
|
| 47 |
+
|
| 48 |
+
During training, we began to see the student's volumetric predictions concentrate on that middle sheet, even where its teacher responded to multiple layers. The shared architecture appeared to let the stronger 2D guidance shape a more selective 3D prediction.
|
| 49 |
+
|
| 50 |
+
We then froze selected student snapshots and used their predictions as new teaching targets. We reduced the special treatment of Paris4 and repeatedly adjusted the balance between 2D and 3D supervision. Dark background voxels were removed from positive teacher targets. When volumetric guidance became too restrictive and suppressed real ink, we weakened its influence.
|
| 51 |
+
|
| 52 |
+
The models reached these checkpoints through a gradual drift: **no new manual annotations, but a changing balance of imperfect teachers**. Their agreement improved in some places and remained imperfect in others.
|
| 53 |
+
|
| 54 |
+
## The 2.4 µm model
|
| 55 |
+
|
| 56 |
+
We preserved as much of the canonical model's architecture and pretrained weights as possible.
|
| 57 |
+
|
| 58 |
+
We removed its CT intensity clipping but retained division by **200**. This allowed brighter values to remain distinguishable while keeping the input scale familiar to the pretrained representation.
|
| 59 |
+
|
| 60 |
+
The model predicts ink on a coarser internal grid and interpolates the volumetric output back to the input grid. Its full-sized output should therefore not be mistaken for equally fine localization.
|
| 61 |
+
|
| 62 |
+

|
| 63 |
+
|
| 64 |
+
*Hecate at 2.4 µm. The output images in the diagram are illustrative, not measured predictions. Tensor dimensions are depth × height × width; feature channels are omitted.*
|
| 65 |
+
|
| 66 |
+
## The 9.6 µm model
|
| 67 |
+
|
| 68 |
+
We next transferred knowledge from the 2.4 µm model into a model operating at **9.6 µm**. Both its 2D and 3D teaching targets came from the finer-resolution model, rescaled to the new sampling.
|
| 69 |
+
|
| 70 |
+
The smaller input covers approximately the same physical region with fewer voxels. This model divides CT intensities by **255** and removes the canonical model's initial spatial reduction, allowing its decoder to predict on the input grid. Its encoder still uses internal multiscale stages.
|
| 71 |
+
|
| 72 |
+
Initially, its inputs were derived by downsampling fine CT. We subsequently introduced surface-conditioned renders from native coarse-resolution scans. Where both scans were available, we aligned their renders so that predictions from the fine scan could supervise the corresponding native CT. Blur and contrast augmentation helped bridge their different appearances. Where native patches failed the alignment checks, we retained fine-derived inputs instead.
|
| 73 |
+
|
| 74 |
+
**Surface-conditioned renders supplied to this model must be sampled at 9.6 µm in both the surface plane and the depth direction.** A scan described as “approximately 9 µm” may have a different acquisition spacing. Use its actual spacing when rendering or resampling.
|
| 75 |
+
|
| 76 |
+

|
| 77 |
+
|
| 78 |
+
*Hecate at 9.6 µm. The output images in the diagram are illustrative, not measured predictions. Tensor dimensions are depth × height × width; feature channels are omitted.*
|
| 79 |
+
|
| 80 |
+
## A view through the sheet
|
| 81 |
+
|
| 82 |
+
<img src="assets/pherc139-cross-section.png" alt="PHerc139 CT cross-section with Hecate's predicted ink shown as a coloured overlay along the papyrus surface" width="360" />
|
| 83 |
+
|
| 84 |
+
*A cross-section from a PHerc139 segment, with Hecate's predicted ink shown as a coloured overlay. The prediction follows a thin layer along the papyrus surface. The measurement shown is a local viewer measurement, not an estimate of the model's accuracy or spatial resolution.*
|
| 85 |
+
|
| 86 |
+
## Outputs and limitations
|
| 87 |
+
|
| 88 |
+
Both models produce:
|
| 89 |
+
|
| 90 |
+
- **A 3D ink probability volume**, intended to localize ink on the middle sheet.
|
| 91 |
+
- **A 2D ink probability map**, obtained by combining volumetric ink logits across depth using learned attention, then converting the result to probabilities.
|
| 92 |
+
|
| 93 |
+
The 3D output is not a papyrus-surface segmentation. It can miss faint ink, respond to fibres, or include neighbouring sheets. Middle-sheet localization is an intended behaviour rather than a guarantee.
|
| 94 |
+
|
| 95 |
+
Results also depend on the surface geometry, depth orientation, scan appearance, and whether the intended sheet lies within the surface-conditioned render.
|
| 96 |
+
|
| 97 |
+
## Running inference
|
| 98 |
+
|
| 99 |
+
Download `hecate.py`, `requirements.txt`, and the checkpoint you need from this repository. No training code, W&B account, or other model downloads are required.
|
| 100 |
+
|
| 101 |
+
```bash
|
| 102 |
+
python -m pip install -r requirements.txt
|
| 103 |
+
python hecate.py --checkpoint hecate_9.6um.pth --input surface.zarr \
|
| 104 |
+
--spacing-um 9.6 --output prediction.png --device cuda
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
For the finer model, use `--checkpoint hecate_2.4um.pth --spacing-um 2.4`. Add `--reverse` to reverse the **full render depth before selecting the central planes**. If the correct direction is unknown, run both directions into different output files.
|
| 108 |
+
|
| 109 |
+
Inputs must be **unnormalized uint8 arrays in Z, Y, X order**, stored as a local Zarr array, a Zarr group containing array `0` (override with `--array`), or a `.npy` file. Supply a surface-conditioned render, not a raw scroll volume. The render must already have the model's sampling in all three axes; the script does not resample. `--spacing-um` declares the render spacing and checks it against the checkpoint. It does not infer spacing from scan metadata.
|
| 110 |
+
|
| 111 |
+
| Checkpoint | Input patch, Z × Y × X | CT normalization |
|
| 112 |
+
|---|---|---|
|
| 113 |
+
| `hecate_2.4um.pth` | 64 × 256 × 256 | Divide by 200; no clipping |
|
| 114 |
+
| `hecate_9.6um.pth` | 16 × 64 × 64 | Divide by 255; no clipping |
|
| 115 |
+
|
| 116 |
+
The script selects the central input depth, slides over XY with half-patch overlap, and blends probabilities using a floored Hann window. Small XY inputs are zero-padded. Empty CT columns receive zero output. It saves a losslessly compressed PNG with **pixel value = round(255 × probability)**, plus a small JSON describing the inference settings. There is no per-image min–max scaling. Output XY dimensions match the input.
|
| 117 |
+
|
| 118 |
+
The default is float32 with batch size one. On compatible NVIDIA GPUs, `--precision bf16` enables the mixed precision used for production inference; on GPUs without native bf16 (compute capability below 8.0, e.g. the T4), use `--precision fp16`. Increase `--batch-size` if memory permits. `--device cpu` also works, but this remains a large 3D network. Temporary disk-backed accumulators use approximately nine bytes per output pixel; set `TMPDIR` to a disk with enough free space for large surfaces.
|
| 119 |
+
|
| 120 |
+
### Saving a 3D probability volume
|
| 121 |
+
|
| 122 |
+
Use `--output-3d` to save a compressed uint8 Zarr:
|
| 123 |
+
|
| 124 |
+
```bash
|
| 125 |
+
python hecate.py --checkpoint hecate_9.6um.pth --input surface.zarr --spacing-um 9.6 --output-3d ink_3d.zarr --reverse --device cuda
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
Add `--output prediction.png` to also save the 2D map. When only `--output-3d` is requested, attention and the 2D projection are not executed. Requesting both outputs runs two inference passes to keep the implementation and memory use simple.
|
| 129 |
+
|
| 130 |
+
The 3D Zarr is a **single-resolution array**, not a multiscale OME-Zarr. It stores `round(255 × probability)` with lossless Zstandard compression. Its ZYX shape and voxel order match the input, including after reversed inference: predictions are flipped back before saving. No cropping or per-volume min–max scaling is applied.
|
| 131 |
+
|
| 132 |
+
Inference tiles over XY and evaluates only the checkpoint's **central depth window**, not sliding windows through the entire Z axis. Unevaluated planes, including the finer model's excluded edge planes, are zero. The Zarr attributes record the half-open `evaluated_z_interval`, spacing, orientation, and inference settings so those zeros can be distinguished from evaluated predictions. Empty CT columns are zeroed; no additional voxel-intensity threshold is applied. Source world-coordinate transforms are not copied; the output is aligned to the input's voxel indices.
|
| 133 |
+
|
| 134 |
+
Temporary disk use for 3D blending is approximately `(4 × input_patch_depth + 4) × height × width` bytes, in addition to the compressed output. Set `TMPDIR` appropriately for large renders.
|
| 135 |
+
|
| 136 |
+
### Accessing the 3D output
|
| 137 |
+
|
| 138 |
+
The same file provides a small Python API. `model(image)` returns 2D logits; `model.forward_3d(image)` returns 3D logits without executing the learned projection. The CLI can write either output or both.
|
| 139 |
+
|
| 140 |
+
```python
|
| 141 |
+
import numpy as np
|
| 142 |
+
import torch
|
| 143 |
+
from hecate import load_model
|
| 144 |
+
|
| 145 |
+
model = load_model("hecate_9.6um.pth", "cuda")
|
| 146 |
+
# One correctly oriented uint8 patch, with shape model.patch_size.
|
| 147 |
+
ct = np.load("patch.npy").astype(np.float32)
|
| 148 |
+
ct /= model.divisor
|
| 149 |
+
image = torch.from_numpy(ct[None, None]).to("cuda")
|
| 150 |
+
with torch.inference_mode():
|
| 151 |
+
ink_3d = model.forward_3d(image).sigmoid()[0, 0].cpu().numpy()
|
| 152 |
+
np.save("ink_3d.npy", ink_3d)
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
The 2.4 µm model excludes its first and last input planes from the network and pads their 3D logits with −20; these planes are not valid learned predictions. Its interior 3D logits are interpolated to the input grid. The 9.6 µm model uses all sixteen planes. The Python API returns model predictions without applying an additional CT-background threshold.
|
| 156 |
+
|
| 157 |
+
The standalone runtime was checked against the original inference implementation on real CT crops with both released checkpoints: 2D and 3D patch logits, tiled forward/reverse predictions, padded edges, blank inputs, lossless PNG decoding, and compressed 3D Zarr round trips. Tiled 3D exports matched the original model in both depth directions, and checks confirmed that 3D-only inference bypasses attention. Float32 and CUDA bfloat16 were tested. The checkpoints load strictly, including their saved EMA batch-normalization buffers.
|
| 158 |
+
|
| 159 |
+
## Sources and acknowledgements
|
| 160 |
+
|
| 161 |
+
This work builds on the **[canonical 2 µm ink detector](https://huggingface.co/scrollprize/ink_canonical_2um)** and the **[Paris4 3D ink teacher](https://huggingface.co/scrollprize/ink_3d_dino_guided)**.
|
| 162 |
+
|
| 163 |
+
Development used the **[Scroll Prize ink dataset](https://huggingface.co/buckets/scrollprize/datasets/tree/ink)** and scans from the **[Vesuvius Challenge open-data collection](https://vesuvius-challenge-open-data.s3.amazonaws.com/index.html)**.
|
| 164 |
+
|
| 165 |
+
Hecate is released for experimentation and evaluation. It is a step toward finding writing in depth, not a finished solution to reliable 3D ink localization.
|
|
@@ -1,473 +1,476 @@
|
|
| 1 |
-
"""Standalone Hecate inference; architecture derived from scrollprize/villa's
|
| 2 |
-
canonical ResNet-152 3D decoder and CanonicalLogitProjection.
|
| 3 |
-
Only the two released Hecate EMA architectures are supported.
|
| 4 |
-
"""
|
| 5 |
-
import argparse
|
| 6 |
-
import json
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
import tempfile
|
| 9 |
-
import struct
|
| 10 |
-
import zlib
|
| 11 |
-
|
| 12 |
-
import numpy as np
|
| 13 |
-
import torch
|
| 14 |
-
from torch import nn
|
| 15 |
-
import torch.nn.functional as F
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def conv3x3x3(in_planes, out_planes, stride=1):
|
| 19 |
-
return nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def conv1x1x1(in_planes, out_planes, stride=1):
|
| 23 |
-
return nn.Conv3d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
class Bottleneck(nn.Module):
|
| 27 |
-
expansion = 4
|
| 28 |
-
|
| 29 |
-
def __init__(self, in_planes, planes, stride=1, downsample=None):
|
| 30 |
-
super().__init__()
|
| 31 |
-
self.conv1 = conv1x1x1(in_planes, planes)
|
| 32 |
-
self.bn1 = nn.BatchNorm3d(planes)
|
| 33 |
-
self.conv2 = conv3x3x3(planes, planes, stride)
|
| 34 |
-
self.bn2 = nn.BatchNorm3d(planes)
|
| 35 |
-
self.conv3 = conv1x1x1(planes, planes * self.expansion)
|
| 36 |
-
self.bn3 = nn.BatchNorm3d(planes * self.expansion)
|
| 37 |
-
self.relu = nn.ReLU(inplace=True)
|
| 38 |
-
self.downsample = downsample
|
| 39 |
-
self.stride = stride
|
| 40 |
-
|
| 41 |
-
def forward(self, x):
|
| 42 |
-
residual = x
|
| 43 |
-
out = self.conv1(x)
|
| 44 |
-
out = self.bn1(out)
|
| 45 |
-
out = self.relu(out)
|
| 46 |
-
out = self.conv2(out)
|
| 47 |
-
out = self.bn2(out)
|
| 48 |
-
out = self.relu(out)
|
| 49 |
-
out = self.conv3(out)
|
| 50 |
-
out = self.bn3(out)
|
| 51 |
-
if self.downsample is not None:
|
| 52 |
-
residual = self.downsample(x)
|
| 53 |
-
out += residual
|
| 54 |
-
out = self.relu(out)
|
| 55 |
-
return out
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
class ResNet(nn.Module):
|
| 59 |
-
|
| 60 |
-
def __init__(self, block, layers, block_inplanes, n_input_channels=3, conv1_t_size=7, conv1_t_stride=1, no_max_pool=False, shortcut_type='B', widen_factor=1.0, n_classes=400, forward_features=False):
|
| 61 |
-
super().__init__()
|
| 62 |
-
self.forward_features = forward_features
|
| 63 |
-
block_inplanes = [int(x * widen_factor) for x in block_inplanes]
|
| 64 |
-
self.in_planes = block_inplanes[0]
|
| 65 |
-
self.no_max_pool = no_max_pool
|
| 66 |
-
self.conv1 = nn.Conv3d(n_input_channels, self.in_planes, kernel_size=(conv1_t_size, 7, 7), stride=(conv1_t_stride, 2, 2), padding=(conv1_t_size // 2, 3, 3), bias=False)
|
| 67 |
-
self.bn1 = nn.BatchNorm3d(self.in_planes)
|
| 68 |
-
self.relu = nn.ReLU(inplace=True)
|
| 69 |
-
self.maxpool = nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))
|
| 70 |
-
self.layer1 = self._make_layer(block, block_inplanes[0], layers[0], shortcut_type)
|
| 71 |
-
self.layer2 = self._make_layer(block, block_inplanes[1], layers[1], shortcut_type, stride=2)
|
| 72 |
-
self.layer3 = self._make_layer(block, block_inplanes[2], layers[2], shortcut_type, stride=2)
|
| 73 |
-
self.layer4 = self._make_layer(block, block_inplanes[3], layers[3], shortcut_type, stride=2)
|
| 74 |
-
self.avgpool = nn.AdaptiveMaxPool3d((1, 1, 1))
|
| 75 |
-
self.fc = nn.Linear(block_inplanes[3] * block.expansion, n_classes)
|
| 76 |
-
for m in self.modules():
|
| 77 |
-
if isinstance(m, nn.Conv3d):
|
| 78 |
-
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 79 |
-
elif isinstance(m, nn.BatchNorm3d):
|
| 80 |
-
nn.init.constant_(m.weight, 1)
|
| 81 |
-
nn.init.constant_(m.bias, 0)
|
| 82 |
-
|
| 83 |
-
def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):
|
| 84 |
-
downsample = None
|
| 85 |
-
if stride != 1 or self.in_planes != planes * block.expansion:
|
| 86 |
-
if False:
|
| 87 |
-
raise ValueError('Only shortcut B is supported')
|
| 88 |
-
else:
|
| 89 |
-
downsample = nn.Sequential(conv1x1x1(self.in_planes, planes * block.expansion, stride), nn.BatchNorm3d(planes * block.expansion))
|
| 90 |
-
layers = []
|
| 91 |
-
layers.append(block(in_planes=self.in_planes, planes=planes, stride=stride, downsample=downsample))
|
| 92 |
-
self.in_planes = planes * block.expansion
|
| 93 |
-
for i in range(1, blocks):
|
| 94 |
-
layers.append(block(self.in_planes, planes))
|
| 95 |
-
return nn.Sequential(*layers)
|
| 96 |
-
|
| 97 |
-
def forward(self, x):
|
| 98 |
-
x = self.conv1(x)
|
| 99 |
-
x = self.bn1(x)
|
| 100 |
-
x = self.relu(x)
|
| 101 |
-
if not self.no_max_pool:
|
| 102 |
-
x = self.maxpool(x)
|
| 103 |
-
x1 = self.layer1(x)
|
| 104 |
-
x2 = self.layer2(x1)
|
| 105 |
-
x3 = self.layer3(x2)
|
| 106 |
-
x4 = self.layer4(x3)
|
| 107 |
-
if self.forward_features:
|
| 108 |
-
return [x1, x2, x3, x4]
|
| 109 |
-
else:
|
| 110 |
-
x = self.avgpool(x4)
|
| 111 |
-
x = x.view(x.size(0), -1)
|
| 112 |
-
x = self.fc(x)
|
| 113 |
-
return x
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
class ResConvBlock3D(nn.Module):
|
| 117 |
-
|
| 118 |
-
def __init__(self, in_ch, out_ch):
|
| 119 |
-
super().__init__()
|
| 120 |
-
self.conv1 = nn.Conv3d(in_ch, out_ch, 3, padding=1, bias=False)
|
| 121 |
-
self.gn1 = nn.GroupNorm(min(32, out_ch), out_ch)
|
| 122 |
-
self.conv2 = nn.Conv3d(out_ch, out_ch, 3, padding=1, bias=False)
|
| 123 |
-
self.gn2 = nn.GroupNorm(min(32, out_ch), out_ch)
|
| 124 |
-
self.shortcut = nn.Conv3d(in_ch, out_ch, 1, bias=False) if in_ch != out_ch else nn.Identity()
|
| 125 |
-
|
| 126 |
-
def forward(self, x):
|
| 127 |
-
identity = self.shortcut(x)
|
| 128 |
-
x = F.relu(self.gn1(self.conv1(x)), inplace=True)
|
| 129 |
-
x = self.gn2(self.conv2(x))
|
| 130 |
-
x = F.relu(x + identity, inplace=True)
|
| 131 |
-
return x
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
class DepthAttentionCollapse(nn.Module):
|
| 135 |
-
|
| 136 |
-
def __init__(self, in_ch):
|
| 137 |
-
super().__init__()
|
| 138 |
-
self.attn_conv = nn.Conv3d(in_ch, 1, 1)
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
class AuxHead(nn.Module):
|
| 142 |
-
|
| 143 |
-
def __init__(self, in_ch, target_size=64):
|
| 144 |
-
super().__init__()
|
| 145 |
-
self.pool = nn.AdaptiveAvgPool3d((1, None, None))
|
| 146 |
-
self.conv = nn.Conv2d(in_ch, 1, 1)
|
| 147 |
-
self.target_size = target_size
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
class Decoder3DUNet(nn.Module):
|
| 151 |
-
|
| 152 |
-
def __init__(self, encoder_dims=(256, 512, 1024, 2048), decoder_dims=(64, 128, 256, 512), deep_supervision=True):
|
| 153 |
-
super().__init__()
|
| 154 |
-
self.deep_supervision = deep_supervision
|
| 155 |
-
self.channel_reduce = nn.ModuleList([nn.Sequential(nn.Conv3d(enc_d, dec_d, 1, bias=False), nn.GroupNorm(min(32, dec_d), dec_d), nn.ReLU(inplace=True)) for enc_d, dec_d in zip(encoder_dims, decoder_dims)])
|
| 156 |
-
self.decoder_blocks = nn.ModuleList([ResConvBlock3D(decoder_dims[i] + decoder_dims[i - 1], decoder_dims[i - 1]) for i in range(len(decoder_dims) - 1, 0, -1)])
|
| 157 |
-
self.depth_collapse = DepthAttentionCollapse(decoder_dims[0])
|
| 158 |
-
self.logit = nn.Conv2d(decoder_dims[0], 1, 1)
|
| 159 |
-
if deep_supervision:
|
| 160 |
-
self.aux_head_s2 = AuxHead(decoder_dims[2])
|
| 161 |
-
self.aux_head_s1 = AuxHead(decoder_dims[1])
|
| 162 |
-
|
| 163 |
-
def forward_features(self, feat_maps):
|
| 164 |
-
"""Decode once, retaining the feature volume before depth collapse."""
|
| 165 |
-
feats = [self.channel_reduce[i](feat_maps[i]) for i in range(4)]
|
| 166 |
-
aux_outputs = []
|
| 167 |
-
x = feats[3]
|
| 168 |
-
x = F.interpolate(x, size=feats[2].shape[2:], mode='trilinear', align_corners=False)
|
| 169 |
-
x = torch.cat([x, feats[2]], dim=1)
|
| 170 |
-
x = self.decoder_blocks[0](x)
|
| 171 |
-
if self.deep_supervision and self.training:
|
| 172 |
-
aux_outputs.append(self.aux_head_s2(x))
|
| 173 |
-
x = F.interpolate(x, size=feats[1].shape[2:], mode='trilinear', align_corners=False)
|
| 174 |
-
x = torch.cat([x, feats[1]], dim=1)
|
| 175 |
-
x = self.decoder_blocks[1](x)
|
| 176 |
-
if self.deep_supervision and self.training:
|
| 177 |
-
aux_outputs.append(self.aux_head_s1(x))
|
| 178 |
-
x = F.interpolate(x, size=feats[0].shape[2:], mode='trilinear', align_corners=False)
|
| 179 |
-
x = torch.cat([x, feats[0]], dim=1)
|
| 180 |
-
x = self.decoder_blocks[2](x)
|
| 181 |
-
return (x, aux_outputs)
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
class RegressionModel(nn.Module):
|
| 185 |
-
|
| 186 |
-
def __init__(self, with_norm=False):
|
| 187 |
-
super().__init__()
|
| 188 |
-
self.backbone = ResNet(Bottleneck, [3, 8, 36, 3], [64, 128, 256, 512], n_input_channels=1, forward_features=True, n_classes=1039)
|
| 189 |
-
self.decoder = Decoder3DUNet(encoder_dims=(256, 512, 1024, 2048), decoder_dims=(64, 128, 256, 512), deep_supervision=True)
|
| 190 |
-
self.normalization = nn.BatchNorm3d(num_features=1) if with_norm else None
|
| 191 |
-
|
| 192 |
-
def encode(self, x: torch.Tensor):
|
| 193 |
-
if x.ndim == 4:
|
| 194 |
-
x = x[:, None]
|
| 195 |
-
if self.normalization is not None:
|
| 196 |
-
x = self.normalization(x)
|
| 197 |
-
return self.backbone(x)
|
| 198 |
-
|
| 199 |
-
def forward_features(self, x: torch.Tensor):
|
| 200 |
-
return self.decoder.forward_features(self.encode(x))
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
class SpatialMaxPool3d(nn.Module):
|
| 204 |
-
def forward(self, x):
|
| 205 |
-
b, c, d, h, w = x.shape
|
| 206 |
-
out = F.max_pool2d(x.reshape(b*c*d, 1, h, w), 3, 2, 1)
|
| 207 |
-
return out.reshape(b, c, d, *out.shape[-2:])
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
class Hecate(nn.Module):
|
| 211 |
-
def __init__(self, patch_size, sampling_um):
|
| 212 |
-
super().__init__()
|
| 213 |
-
self.patch_size = tuple(patch_size)
|
| 214 |
-
if (sampling_um, self.patch_size) not in (
|
| 215 |
-
(2.4, (64, 256, 256)), (9.6, (16, 64, 64))):
|
| 216 |
-
raise ValueError('Unsupported Hecate sampling/patch geometry')
|
| 217 |
-
self.sampling_um = sampling_um
|
| 218 |
-
self.margin = 1 if sampling_um == 2.4 else 0
|
| 219 |
-
self.xy_stride = 4 if sampling_um == 2.4 else 1
|
| 220 |
-
self.divisor = 200. if sampling_um == 2.4 else 255.
|
| 221 |
-
self.canonical = RegressionModel(with_norm=True)
|
| 222 |
-
self.canonical.decoder.deep_supervision = False
|
| 223 |
-
self.canonical.backbone.maxpool = SpatialMaxPool3d()
|
| 224 |
-
if self.xy_stride == 1:
|
| 225 |
-
self.canonical.backbone.conv1 = nn.Conv3d(1, 64, 3, padding=1, bias=False)
|
| 226 |
-
self.canonical.backbone.maxpool = nn.Identity()
|
| 227 |
-
self.depth_coordinate_scale = nn.Parameter(torch.zeros(()))
|
| 228 |
-
|
| 229 |
-
def features_logits(self, image):
|
| 230 |
-
if tuple(image.shape[1:]) != (1, *self.patch_size):
|
| 231 |
-
raise ValueError(f'Expected B,1,{self.patch_size}, got {tuple(image.shape)}')
|
| 232 |
-
d = self.patch_size[0]
|
| 233 |
-
features, _ = self.canonical.forward_features(image[:, :, self.margin:d-self.margin])
|
| 234 |
-
head = self.canonical.decoder.logit
|
| 235 |
-
logits = F.conv3d(features.float(), head.weight.float().unsqueeze(2), head.bias.float())
|
| 236 |
-
return features, logits.float()
|
| 237 |
-
|
| 238 |
-
def forward_3d(self, image):
|
| 239 |
-
"""3D logits on the input grid; image is already normalized, B1ZYX.
|
| 240 |
-
|
| 241 |
-
This path does not execute attention or the 2D projection.
|
| 242 |
-
The 2.4um model's outermost planes are untrained and padded with -20.
|
| 243 |
-
"""
|
| 244 |
-
_, logits = self.features_logits(image)
|
| 245 |
-
full = F.interpolate(logits, size=(self.patch_size[0]-2*self.margin, *image.shape[-2:]),
|
| 246 |
-
mode='trilinear', align_corners=False)
|
| 247 |
-
return F.pad(full, (0, 0, 0, 0, self.margin, self.margin), value=-20.)
|
| 248 |
-
|
| 249 |
-
def forward(self, image, valid=None):
|
| 250 |
-
"""2D logits; image is already normalized, B1ZYX; valid is optional B1ZYX."""
|
| 251 |
-
features, logits = self.features_logits(image)
|
| 252 |
-
scores = self.canonical.decoder.depth_collapse.attn_conv(features).float()
|
| 253 |
-
half = scores.shape[2] // 2
|
| 254 |
-
z = (torch.arange(scores.shape[2], device=scores.device, dtype=torch.float32)-half)/half
|
| 255 |
-
scores = scores + self.depth_coordinate_scale*z.view(1, 1, -1, 1, 1)
|
| 256 |
-
if valid is None:
|
| 257 |
-
support = torch.ones_like(logits, dtype=torch.bool)
|
| 258 |
-
else:
|
| 259 |
-
support = F.max_pool3d(valid[:, :, self.margin:self.patch_size[0]-self.margin].float(),
|
| 260 |
-
(1, self.xy_stride, self.xy_stride)).bool()
|
| 261 |
-
weights = scores.masked_fill(~support, -1e4).softmax(2)*support
|
| 262 |
-
weights = weights/weights.sum(2, keepdim=True).clamp_min(1e-8)
|
| 263 |
-
probability = F.interpolate((weights*logits).sum(2).sigmoid(), size=image.shape[-2:],
|
| 264 |
-
mode='bilinear', align_corners=False)
|
| 265 |
-
eps = torch.finfo(torch.float32).eps
|
| 266 |
-
return torch.logit(probability.clamp(eps, 1-eps))
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
def load_model(checkpoint, device='cpu'):
|
| 270 |
-
"""Strictly load a released inference-only EMA checkpoint."""
|
| 271 |
-
payload = torch.load(checkpoint, map_location='cpu', weights_only=True, mmap=True)
|
| 272 |
-
if payload.get('architecture_family') != 'hecate' or payload.get('weight_source') != 'ema_model':
|
| 273 |
-
raise ValueError('Use a released Hecate inference checkpoint')
|
| 274 |
-
model = Hecate(payload['config']['patch_size'], payload['sampling_um'])
|
| 275 |
-
config = payload['config']
|
| 276 |
-
canonical = config['model_config']['canonical']
|
| 277 |
-
if (config['image_normalization'] != {'mode': 'divide', 'divisor': model.divisor}
|
| 278 |
-
or canonical.get('native_refinement', False)
|
| 279 |
-
or canonical['native_xy_stride'] != model.xy_stride
|
| 280 |
-
or canonical['depth_margin'] != model.margin
|
| 281 |
-
or not canonical['with_norm']):
|
| 282 |
-
raise ValueError('Checkpoint configuration does not match the released architecture')
|
| 283 |
-
model.load_state_dict(payload['ema_model'], strict=True)
|
| 284 |
-
return model.requires_grad_(False).eval().to(device)
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
def axis_starts(length, patch, stride):
|
| 288 |
-
return list(range(0, max(0, length-patch), stride)) + [max(0, length-patch)]
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
def open_volume(path, array='0'):
|
| 292 |
-
if str(path).endswith('.npy'):
|
| 293 |
-
volume = np.load(path, mmap_mode='r', allow_pickle=False)
|
| 294 |
-
else:
|
| 295 |
-
import zarr
|
| 296 |
-
volume = zarr.open(str(path), mode='r')
|
| 297 |
-
if not hasattr(volume, 'shape'):
|
| 298 |
-
volume = volume[array]
|
| 299 |
-
if len(volume.shape) != 3 or np.dtype(volume.dtype) != np.dtype('uint8'):
|
| 300 |
-
raise ValueError('Input must be an unnormalized uint8 Z,Y,X surface volume')
|
| 301 |
-
return volume
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
@torch.inference_mode()
|
| 305 |
-
def predict(model, volume, output, reverse=False, stride=None, batch_size=1, precision='fp32', three_d=False):
|
| 306 |
-
"""Tiled 2D or 3D uint8 probabilities into a writable HxW array (can be a memmap).
|
| 307 |
-
|
| 308 |
-
Reads only individual CT patches. Accumulators use temporary disk-backed
|
| 309 |
-
arrays, so a full surface volume never needs to fit in RAM or GPU memory.
|
| 310 |
-
"""
|
| 311 |
-
d, p, _ = model.patch_size
|
| 312 |
-
depth, h, w = volume.shape
|
| 313 |
-
stride = p//2 if stride is None else stride
|
| 314 |
-
if depth < d or not 0 < stride <= p or batch_size < 1:
|
| 315 |
-
raise ValueError('Insufficient depth, invalid stride, or invalid batch size')
|
| 316 |
-
expected_shape = (depth,h,w) if three_d else (h,w)
|
| 317 |
-
if tuple(output.shape) != expected_shape or output.dtype != np.uint8:
|
| 318 |
-
raise ValueError(f'Output must be a uint8 array of shape {expected_shape}')
|
| 319 |
-
if three_d:
|
| 320 |
-
output[:] = 0
|
| 321 |
-
device = next(model.parameters()).device
|
| 322 |
-
if precision not in ('fp32', 'bf16') or (precision =
|
| 323 |
-
raise ValueError('bf16
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
win =
|
| 329 |
-
|
| 330 |
-
win = win.
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
if
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
output[y:y+128,x:x+256] = values
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
parser
|
| 405 |
-
parser.add_argument('--
|
| 406 |
-
parser.add_argument('--
|
| 407 |
-
parser.add_argument('--
|
| 408 |
-
parser.add_argument('--
|
| 409 |
-
parser.add_argument('--
|
| 410 |
-
parser.add_argument('--
|
| 411 |
-
parser.add_argument('--
|
| 412 |
-
parser.add_argument('--
|
| 413 |
-
parser.add_argument('--
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
if
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
'
|
| 440 |
-
'
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
if
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
'
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Standalone Hecate inference; architecture derived from scrollprize/villa's
|
| 2 |
+
canonical ResNet-152 3D decoder and CanonicalLogitProjection.
|
| 3 |
+
Only the two released Hecate EMA architectures are supported.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import tempfile
|
| 9 |
+
import struct
|
| 10 |
+
import zlib
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
from torch import nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def conv3x3x3(in_planes, out_planes, stride=1):
|
| 19 |
+
return nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def conv1x1x1(in_planes, out_planes, stride=1):
|
| 23 |
+
return nn.Conv3d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Bottleneck(nn.Module):
|
| 27 |
+
expansion = 4
|
| 28 |
+
|
| 29 |
+
def __init__(self, in_planes, planes, stride=1, downsample=None):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.conv1 = conv1x1x1(in_planes, planes)
|
| 32 |
+
self.bn1 = nn.BatchNorm3d(planes)
|
| 33 |
+
self.conv2 = conv3x3x3(planes, planes, stride)
|
| 34 |
+
self.bn2 = nn.BatchNorm3d(planes)
|
| 35 |
+
self.conv3 = conv1x1x1(planes, planes * self.expansion)
|
| 36 |
+
self.bn3 = nn.BatchNorm3d(planes * self.expansion)
|
| 37 |
+
self.relu = nn.ReLU(inplace=True)
|
| 38 |
+
self.downsample = downsample
|
| 39 |
+
self.stride = stride
|
| 40 |
+
|
| 41 |
+
def forward(self, x):
|
| 42 |
+
residual = x
|
| 43 |
+
out = self.conv1(x)
|
| 44 |
+
out = self.bn1(out)
|
| 45 |
+
out = self.relu(out)
|
| 46 |
+
out = self.conv2(out)
|
| 47 |
+
out = self.bn2(out)
|
| 48 |
+
out = self.relu(out)
|
| 49 |
+
out = self.conv3(out)
|
| 50 |
+
out = self.bn3(out)
|
| 51 |
+
if self.downsample is not None:
|
| 52 |
+
residual = self.downsample(x)
|
| 53 |
+
out += residual
|
| 54 |
+
out = self.relu(out)
|
| 55 |
+
return out
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ResNet(nn.Module):
|
| 59 |
+
|
| 60 |
+
def __init__(self, block, layers, block_inplanes, n_input_channels=3, conv1_t_size=7, conv1_t_stride=1, no_max_pool=False, shortcut_type='B', widen_factor=1.0, n_classes=400, forward_features=False):
|
| 61 |
+
super().__init__()
|
| 62 |
+
self.forward_features = forward_features
|
| 63 |
+
block_inplanes = [int(x * widen_factor) for x in block_inplanes]
|
| 64 |
+
self.in_planes = block_inplanes[0]
|
| 65 |
+
self.no_max_pool = no_max_pool
|
| 66 |
+
self.conv1 = nn.Conv3d(n_input_channels, self.in_planes, kernel_size=(conv1_t_size, 7, 7), stride=(conv1_t_stride, 2, 2), padding=(conv1_t_size // 2, 3, 3), bias=False)
|
| 67 |
+
self.bn1 = nn.BatchNorm3d(self.in_planes)
|
| 68 |
+
self.relu = nn.ReLU(inplace=True)
|
| 69 |
+
self.maxpool = nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))
|
| 70 |
+
self.layer1 = self._make_layer(block, block_inplanes[0], layers[0], shortcut_type)
|
| 71 |
+
self.layer2 = self._make_layer(block, block_inplanes[1], layers[1], shortcut_type, stride=2)
|
| 72 |
+
self.layer3 = self._make_layer(block, block_inplanes[2], layers[2], shortcut_type, stride=2)
|
| 73 |
+
self.layer4 = self._make_layer(block, block_inplanes[3], layers[3], shortcut_type, stride=2)
|
| 74 |
+
self.avgpool = nn.AdaptiveMaxPool3d((1, 1, 1))
|
| 75 |
+
self.fc = nn.Linear(block_inplanes[3] * block.expansion, n_classes)
|
| 76 |
+
for m in self.modules():
|
| 77 |
+
if isinstance(m, nn.Conv3d):
|
| 78 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 79 |
+
elif isinstance(m, nn.BatchNorm3d):
|
| 80 |
+
nn.init.constant_(m.weight, 1)
|
| 81 |
+
nn.init.constant_(m.bias, 0)
|
| 82 |
+
|
| 83 |
+
def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):
|
| 84 |
+
downsample = None
|
| 85 |
+
if stride != 1 or self.in_planes != planes * block.expansion:
|
| 86 |
+
if False:
|
| 87 |
+
raise ValueError('Only shortcut B is supported')
|
| 88 |
+
else:
|
| 89 |
+
downsample = nn.Sequential(conv1x1x1(self.in_planes, planes * block.expansion, stride), nn.BatchNorm3d(planes * block.expansion))
|
| 90 |
+
layers = []
|
| 91 |
+
layers.append(block(in_planes=self.in_planes, planes=planes, stride=stride, downsample=downsample))
|
| 92 |
+
self.in_planes = planes * block.expansion
|
| 93 |
+
for i in range(1, blocks):
|
| 94 |
+
layers.append(block(self.in_planes, planes))
|
| 95 |
+
return nn.Sequential(*layers)
|
| 96 |
+
|
| 97 |
+
def forward(self, x):
|
| 98 |
+
x = self.conv1(x)
|
| 99 |
+
x = self.bn1(x)
|
| 100 |
+
x = self.relu(x)
|
| 101 |
+
if not self.no_max_pool:
|
| 102 |
+
x = self.maxpool(x)
|
| 103 |
+
x1 = self.layer1(x)
|
| 104 |
+
x2 = self.layer2(x1)
|
| 105 |
+
x3 = self.layer3(x2)
|
| 106 |
+
x4 = self.layer4(x3)
|
| 107 |
+
if self.forward_features:
|
| 108 |
+
return [x1, x2, x3, x4]
|
| 109 |
+
else:
|
| 110 |
+
x = self.avgpool(x4)
|
| 111 |
+
x = x.view(x.size(0), -1)
|
| 112 |
+
x = self.fc(x)
|
| 113 |
+
return x
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class ResConvBlock3D(nn.Module):
|
| 117 |
+
|
| 118 |
+
def __init__(self, in_ch, out_ch):
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.conv1 = nn.Conv3d(in_ch, out_ch, 3, padding=1, bias=False)
|
| 121 |
+
self.gn1 = nn.GroupNorm(min(32, out_ch), out_ch)
|
| 122 |
+
self.conv2 = nn.Conv3d(out_ch, out_ch, 3, padding=1, bias=False)
|
| 123 |
+
self.gn2 = nn.GroupNorm(min(32, out_ch), out_ch)
|
| 124 |
+
self.shortcut = nn.Conv3d(in_ch, out_ch, 1, bias=False) if in_ch != out_ch else nn.Identity()
|
| 125 |
+
|
| 126 |
+
def forward(self, x):
|
| 127 |
+
identity = self.shortcut(x)
|
| 128 |
+
x = F.relu(self.gn1(self.conv1(x)), inplace=True)
|
| 129 |
+
x = self.gn2(self.conv2(x))
|
| 130 |
+
x = F.relu(x + identity, inplace=True)
|
| 131 |
+
return x
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class DepthAttentionCollapse(nn.Module):
|
| 135 |
+
|
| 136 |
+
def __init__(self, in_ch):
|
| 137 |
+
super().__init__()
|
| 138 |
+
self.attn_conv = nn.Conv3d(in_ch, 1, 1)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class AuxHead(nn.Module):
|
| 142 |
+
|
| 143 |
+
def __init__(self, in_ch, target_size=64):
|
| 144 |
+
super().__init__()
|
| 145 |
+
self.pool = nn.AdaptiveAvgPool3d((1, None, None))
|
| 146 |
+
self.conv = nn.Conv2d(in_ch, 1, 1)
|
| 147 |
+
self.target_size = target_size
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Decoder3DUNet(nn.Module):
|
| 151 |
+
|
| 152 |
+
def __init__(self, encoder_dims=(256, 512, 1024, 2048), decoder_dims=(64, 128, 256, 512), deep_supervision=True):
|
| 153 |
+
super().__init__()
|
| 154 |
+
self.deep_supervision = deep_supervision
|
| 155 |
+
self.channel_reduce = nn.ModuleList([nn.Sequential(nn.Conv3d(enc_d, dec_d, 1, bias=False), nn.GroupNorm(min(32, dec_d), dec_d), nn.ReLU(inplace=True)) for enc_d, dec_d in zip(encoder_dims, decoder_dims)])
|
| 156 |
+
self.decoder_blocks = nn.ModuleList([ResConvBlock3D(decoder_dims[i] + decoder_dims[i - 1], decoder_dims[i - 1]) for i in range(len(decoder_dims) - 1, 0, -1)])
|
| 157 |
+
self.depth_collapse = DepthAttentionCollapse(decoder_dims[0])
|
| 158 |
+
self.logit = nn.Conv2d(decoder_dims[0], 1, 1)
|
| 159 |
+
if deep_supervision:
|
| 160 |
+
self.aux_head_s2 = AuxHead(decoder_dims[2])
|
| 161 |
+
self.aux_head_s1 = AuxHead(decoder_dims[1])
|
| 162 |
+
|
| 163 |
+
def forward_features(self, feat_maps):
|
| 164 |
+
"""Decode once, retaining the feature volume before depth collapse."""
|
| 165 |
+
feats = [self.channel_reduce[i](feat_maps[i]) for i in range(4)]
|
| 166 |
+
aux_outputs = []
|
| 167 |
+
x = feats[3]
|
| 168 |
+
x = F.interpolate(x, size=feats[2].shape[2:], mode='trilinear', align_corners=False)
|
| 169 |
+
x = torch.cat([x, feats[2]], dim=1)
|
| 170 |
+
x = self.decoder_blocks[0](x)
|
| 171 |
+
if self.deep_supervision and self.training:
|
| 172 |
+
aux_outputs.append(self.aux_head_s2(x))
|
| 173 |
+
x = F.interpolate(x, size=feats[1].shape[2:], mode='trilinear', align_corners=False)
|
| 174 |
+
x = torch.cat([x, feats[1]], dim=1)
|
| 175 |
+
x = self.decoder_blocks[1](x)
|
| 176 |
+
if self.deep_supervision and self.training:
|
| 177 |
+
aux_outputs.append(self.aux_head_s1(x))
|
| 178 |
+
x = F.interpolate(x, size=feats[0].shape[2:], mode='trilinear', align_corners=False)
|
| 179 |
+
x = torch.cat([x, feats[0]], dim=1)
|
| 180 |
+
x = self.decoder_blocks[2](x)
|
| 181 |
+
return (x, aux_outputs)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class RegressionModel(nn.Module):
|
| 185 |
+
|
| 186 |
+
def __init__(self, with_norm=False):
|
| 187 |
+
super().__init__()
|
| 188 |
+
self.backbone = ResNet(Bottleneck, [3, 8, 36, 3], [64, 128, 256, 512], n_input_channels=1, forward_features=True, n_classes=1039)
|
| 189 |
+
self.decoder = Decoder3DUNet(encoder_dims=(256, 512, 1024, 2048), decoder_dims=(64, 128, 256, 512), deep_supervision=True)
|
| 190 |
+
self.normalization = nn.BatchNorm3d(num_features=1) if with_norm else None
|
| 191 |
+
|
| 192 |
+
def encode(self, x: torch.Tensor):
|
| 193 |
+
if x.ndim == 4:
|
| 194 |
+
x = x[:, None]
|
| 195 |
+
if self.normalization is not None:
|
| 196 |
+
x = self.normalization(x)
|
| 197 |
+
return self.backbone(x)
|
| 198 |
+
|
| 199 |
+
def forward_features(self, x: torch.Tensor):
|
| 200 |
+
return self.decoder.forward_features(self.encode(x))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class SpatialMaxPool3d(nn.Module):
|
| 204 |
+
def forward(self, x):
|
| 205 |
+
b, c, d, h, w = x.shape
|
| 206 |
+
out = F.max_pool2d(x.reshape(b*c*d, 1, h, w), 3, 2, 1)
|
| 207 |
+
return out.reshape(b, c, d, *out.shape[-2:])
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class Hecate(nn.Module):
|
| 211 |
+
def __init__(self, patch_size, sampling_um):
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.patch_size = tuple(patch_size)
|
| 214 |
+
if (sampling_um, self.patch_size) not in (
|
| 215 |
+
(2.4, (64, 256, 256)), (9.6, (16, 64, 64))):
|
| 216 |
+
raise ValueError('Unsupported Hecate sampling/patch geometry')
|
| 217 |
+
self.sampling_um = sampling_um
|
| 218 |
+
self.margin = 1 if sampling_um == 2.4 else 0
|
| 219 |
+
self.xy_stride = 4 if sampling_um == 2.4 else 1
|
| 220 |
+
self.divisor = 200. if sampling_um == 2.4 else 255.
|
| 221 |
+
self.canonical = RegressionModel(with_norm=True)
|
| 222 |
+
self.canonical.decoder.deep_supervision = False
|
| 223 |
+
self.canonical.backbone.maxpool = SpatialMaxPool3d()
|
| 224 |
+
if self.xy_stride == 1:
|
| 225 |
+
self.canonical.backbone.conv1 = nn.Conv3d(1, 64, 3, padding=1, bias=False)
|
| 226 |
+
self.canonical.backbone.maxpool = nn.Identity()
|
| 227 |
+
self.depth_coordinate_scale = nn.Parameter(torch.zeros(()))
|
| 228 |
+
|
| 229 |
+
def features_logits(self, image):
|
| 230 |
+
if tuple(image.shape[1:]) != (1, *self.patch_size):
|
| 231 |
+
raise ValueError(f'Expected B,1,{self.patch_size}, got {tuple(image.shape)}')
|
| 232 |
+
d = self.patch_size[0]
|
| 233 |
+
features, _ = self.canonical.forward_features(image[:, :, self.margin:d-self.margin])
|
| 234 |
+
head = self.canonical.decoder.logit
|
| 235 |
+
logits = F.conv3d(features.float(), head.weight.float().unsqueeze(2), head.bias.float())
|
| 236 |
+
return features, logits.float()
|
| 237 |
+
|
| 238 |
+
def forward_3d(self, image):
|
| 239 |
+
"""3D logits on the input grid; image is already normalized, B1ZYX.
|
| 240 |
+
|
| 241 |
+
This path does not execute attention or the 2D projection.
|
| 242 |
+
The 2.4um model's outermost planes are untrained and padded with -20.
|
| 243 |
+
"""
|
| 244 |
+
_, logits = self.features_logits(image)
|
| 245 |
+
full = F.interpolate(logits, size=(self.patch_size[0]-2*self.margin, *image.shape[-2:]),
|
| 246 |
+
mode='trilinear', align_corners=False)
|
| 247 |
+
return F.pad(full, (0, 0, 0, 0, self.margin, self.margin), value=-20.)
|
| 248 |
+
|
| 249 |
+
def forward(self, image, valid=None):
|
| 250 |
+
"""2D logits; image is already normalized, B1ZYX; valid is optional B1ZYX."""
|
| 251 |
+
features, logits = self.features_logits(image)
|
| 252 |
+
scores = self.canonical.decoder.depth_collapse.attn_conv(features).float()
|
| 253 |
+
half = scores.shape[2] // 2
|
| 254 |
+
z = (torch.arange(scores.shape[2], device=scores.device, dtype=torch.float32)-half)/half
|
| 255 |
+
scores = scores + self.depth_coordinate_scale*z.view(1, 1, -1, 1, 1)
|
| 256 |
+
if valid is None:
|
| 257 |
+
support = torch.ones_like(logits, dtype=torch.bool)
|
| 258 |
+
else:
|
| 259 |
+
support = F.max_pool3d(valid[:, :, self.margin:self.patch_size[0]-self.margin].float(),
|
| 260 |
+
(1, self.xy_stride, self.xy_stride)).bool()
|
| 261 |
+
weights = scores.masked_fill(~support, -1e4).softmax(2)*support
|
| 262 |
+
weights = weights/weights.sum(2, keepdim=True).clamp_min(1e-8)
|
| 263 |
+
probability = F.interpolate((weights*logits).sum(2).sigmoid(), size=image.shape[-2:],
|
| 264 |
+
mode='bilinear', align_corners=False)
|
| 265 |
+
eps = torch.finfo(torch.float32).eps
|
| 266 |
+
return torch.logit(probability.clamp(eps, 1-eps))
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def load_model(checkpoint, device='cpu'):
|
| 270 |
+
"""Strictly load a released inference-only EMA checkpoint."""
|
| 271 |
+
payload = torch.load(checkpoint, map_location='cpu', weights_only=True, mmap=True)
|
| 272 |
+
if payload.get('architecture_family') != 'hecate' or payload.get('weight_source') != 'ema_model':
|
| 273 |
+
raise ValueError('Use a released Hecate inference checkpoint')
|
| 274 |
+
model = Hecate(payload['config']['patch_size'], payload['sampling_um'])
|
| 275 |
+
config = payload['config']
|
| 276 |
+
canonical = config['model_config']['canonical']
|
| 277 |
+
if (config['image_normalization'] != {'mode': 'divide', 'divisor': model.divisor}
|
| 278 |
+
or canonical.get('native_refinement', False)
|
| 279 |
+
or canonical['native_xy_stride'] != model.xy_stride
|
| 280 |
+
or canonical['depth_margin'] != model.margin
|
| 281 |
+
or not canonical['with_norm']):
|
| 282 |
+
raise ValueError('Checkpoint configuration does not match the released architecture')
|
| 283 |
+
model.load_state_dict(payload['ema_model'], strict=True)
|
| 284 |
+
return model.requires_grad_(False).eval().to(device)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def axis_starts(length, patch, stride):
|
| 288 |
+
return list(range(0, max(0, length-patch), stride)) + [max(0, length-patch)]
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def open_volume(path, array='0'):
|
| 292 |
+
if str(path).endswith('.npy'):
|
| 293 |
+
volume = np.load(path, mmap_mode='r', allow_pickle=False)
|
| 294 |
+
else:
|
| 295 |
+
import zarr
|
| 296 |
+
volume = zarr.open(str(path), mode='r')
|
| 297 |
+
if not hasattr(volume, 'shape'):
|
| 298 |
+
volume = volume[array]
|
| 299 |
+
if len(volume.shape) != 3 or np.dtype(volume.dtype) != np.dtype('uint8'):
|
| 300 |
+
raise ValueError('Input must be an unnormalized uint8 Z,Y,X surface volume')
|
| 301 |
+
return volume
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
@torch.inference_mode()
|
| 305 |
+
def predict(model, volume, output, reverse=False, stride=None, batch_size=1, precision='fp32', three_d=False):
|
| 306 |
+
"""Tiled 2D or 3D uint8 probabilities into a writable HxW array (can be a memmap).
|
| 307 |
+
|
| 308 |
+
Reads only individual CT patches. Accumulators use temporary disk-backed
|
| 309 |
+
arrays, so a full surface volume never needs to fit in RAM or GPU memory.
|
| 310 |
+
"""
|
| 311 |
+
d, p, _ = model.patch_size
|
| 312 |
+
depth, h, w = volume.shape
|
| 313 |
+
stride = p//2 if stride is None else stride
|
| 314 |
+
if depth < d or not 0 < stride <= p or batch_size < 1:
|
| 315 |
+
raise ValueError('Insufficient depth, invalid stride, or invalid batch size')
|
| 316 |
+
expected_shape = (depth,h,w) if three_d else (h,w)
|
| 317 |
+
if tuple(output.shape) != expected_shape or output.dtype != np.uint8:
|
| 318 |
+
raise ValueError(f'Output must be a uint8 array of shape {expected_shape}')
|
| 319 |
+
if three_d:
|
| 320 |
+
output[:] = 0
|
| 321 |
+
device = next(model.parameters()).device
|
| 322 |
+
if precision not in ('fp32', 'bf16', 'fp16') or (precision != 'fp32' and device.type != 'cuda'):
|
| 323 |
+
raise ValueError('bf16 and fp16 require CUDA; otherwise use fp32')
|
| 324 |
+
# fp16 autocast for GPUs without fast bf16 (pre-Ampere, e.g. the T4 of free Colab sessions)
|
| 325 |
+
amp_dtype = torch.float16 if precision == 'fp16' else torch.bfloat16
|
| 326 |
+
z0 = depth//2-d//2
|
| 327 |
+
zs = slice(depth-z0-d, depth-z0) if reverse else slice(z0, z0+d)
|
| 328 |
+
win = torch.hann_window(p, periodic=False)
|
| 329 |
+
win = win[:, None]*win[None, :]
|
| 330 |
+
win = (win/win.max().clamp_min(torch.finfo(torch.float32).eps)).clamp_min(.001)
|
| 331 |
+
window = win.numpy()
|
| 332 |
+
win = win.to(device)
|
| 333 |
+
origins = [(y, x) for y in axis_starts(h,p,stride) for x in axis_starts(w,p,stride)]
|
| 334 |
+
with tempfile.TemporaryDirectory(prefix='hecate-') as tmp:
|
| 335 |
+
numerator = np.memmap(Path(tmp)/'sum', mode='w+', dtype='float32', shape=(d,h,w) if three_d else (h,w))
|
| 336 |
+
denominator = np.memmap(Path(tmp)/'weight', mode='w+', dtype='float32', shape=(h,w))
|
| 337 |
+
for start in range(0, len(origins), batch_size):
|
| 338 |
+
active, patches = [], []
|
| 339 |
+
for y, x in origins[start:start+batch_size]:
|
| 340 |
+
ph, pw = min(p,h-y), min(p,w-x)
|
| 341 |
+
denominator[y:y+ph,x:x+pw] += window[:ph,:pw]
|
| 342 |
+
raw = np.asarray(volume[zs,y:y+ph,x:x+pw])
|
| 343 |
+
if reverse:
|
| 344 |
+
raw = raw[::-1]
|
| 345 |
+
if not raw.any():
|
| 346 |
+
continue
|
| 347 |
+
patch = np.zeros((d,p,p), dtype=np.uint8)
|
| 348 |
+
patch[:,:ph,:pw] = raw
|
| 349 |
+
patches.append(patch)
|
| 350 |
+
active.append((y,x,ph,pw))
|
| 351 |
+
if patches:
|
| 352 |
+
raw = torch.from_numpy(np.stack(patches)).to(device)
|
| 353 |
+
support = raw.any(1)
|
| 354 |
+
normalized = np.stack(patches).astype(np.float32)
|
| 355 |
+
normalized /= model.divisor # Match original CPU division; no clipping.
|
| 356 |
+
image = torch.from_numpy(normalized[:,None]).to(device)
|
| 357 |
+
valid = support[:,None,None].expand(-1,1,d,-1,-1)
|
| 358 |
+
with torch.autocast(device_type=device.type, dtype=amp_dtype, enabled=precision!='fp32'):
|
| 359 |
+
logits = model.forward_3d(image) if three_d else model(image, valid)
|
| 360 |
+
probability = logits.float().sigmoid()[:,0]
|
| 361 |
+
if three_d:
|
| 362 |
+
support = support[:,None]
|
| 363 |
+
weighted = (probability*support*win).cpu().numpy()
|
| 364 |
+
for pred,(y,x,ph,pw) in zip(weighted,active):
|
| 365 |
+
numerator[...,y:y+ph,x:x+pw] += pred[..., :ph,:pw]
|
| 366 |
+
if start == 0 or start+batch_size >= len(origins) or start % 100 == 0:
|
| 367 |
+
print(f'{min(start+batch_size,len(origins))}/{len(origins)} patches', flush=True)
|
| 368 |
+
if three_d and model.margin:
|
| 369 |
+
numerator[:model.margin] = 0
|
| 370 |
+
numerator[-model.margin:] = 0
|
| 371 |
+
for y in range(0,h,128):
|
| 372 |
+
for x in range(0,w,256):
|
| 373 |
+
prob = numerator[...,y:y+128,x:x+256]/denominator[y:y+128,x:x+256]
|
| 374 |
+
if not np.isfinite(prob).all():
|
| 375 |
+
raise FloatingPointError('Non-finite inference output')
|
| 376 |
+
values = np.rint(prob.clip(0,1)*255).astype(np.uint8)
|
| 377 |
+
if three_d:
|
| 378 |
+
output[zs,y:y+128,x:x+256] = values[::-1] if reverse else values
|
| 379 |
+
else:
|
| 380 |
+
output[y:y+128,x:x+256] = values
|
| 381 |
+
del numerator, denominator
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def write_png(array, path):
|
| 385 |
+
"""Losslessly compressed grayscale PNG; streamed to avoid full-image copies."""
|
| 386 |
+
with Path(path).open('wb') as stream:
|
| 387 |
+
def chunk(kind, data):
|
| 388 |
+
stream.write(struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)&0xffffffff))
|
| 389 |
+
stream.write(b'\x89PNG\r\n\x1a\n')
|
| 390 |
+
h,w = array.shape
|
| 391 |
+
chunk(b'IHDR',struct.pack('!2I5B',w,h,8,0,0,0,0))
|
| 392 |
+
compressor = zlib.compressobj(9)
|
| 393 |
+
for row in array:
|
| 394 |
+
filtered = row.copy()
|
| 395 |
+
filtered[1:] = row[1:]-row[:-1]
|
| 396 |
+
data = compressor.compress(b'\x01'+filtered.tobytes())
|
| 397 |
+
if data:
|
| 398 |
+
chunk(b'IDAT',data)
|
| 399 |
+
chunk(b'IDAT',compressor.flush())
|
| 400 |
+
chunk(b'IEND',b'')
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def main():
|
| 404 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 405 |
+
parser.add_argument('--checkpoint', required=True)
|
| 406 |
+
parser.add_argument('--input', required=True, help='uint8 ZYX .npy or local Zarr')
|
| 407 |
+
parser.add_argument('--array', default='0', help='Array within a Zarr group')
|
| 408 |
+
parser.add_argument('--output', help='2D probability PNG (optional with --output-3d)')
|
| 409 |
+
parser.add_argument('--output-3d', help='Compressed uint8 3D probability Zarr')
|
| 410 |
+
parser.add_argument('--spacing-um', type=float, required=True, help='Actual isotropic render spacing, not raw scan spacing')
|
| 411 |
+
parser.add_argument('--reverse', action='store_true', help='Reverse full Z before selecting the central input planes')
|
| 412 |
+
parser.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu')
|
| 413 |
+
parser.add_argument('--batch-size', type=int, default=1)
|
| 414 |
+
parser.add_argument('--stride', type=int, help='XY stride; default half the trained patch width')
|
| 415 |
+
parser.add_argument('--precision', choices=('fp32','bf16','fp16'), default='fp32',
|
| 416 |
+
help='CUDA autocast: bf16 on Ampere or newer; fp16 on older GPUs such as the T4')
|
| 417 |
+
args = parser.parse_args()
|
| 418 |
+
if not args.output and not args.output_3d:
|
| 419 |
+
parser.error('Specify --output and/or --output-3d')
|
| 420 |
+
output = Path(args.output) if args.output else None
|
| 421 |
+
output3d = Path(args.output_3d) if args.output_3d else None
|
| 422 |
+
for path,suffix in ((output,'.png'),(output3d,'.zarr')):
|
| 423 |
+
if path is not None and (path.suffix.lower()!=suffix or path.exists()):
|
| 424 |
+
parser.error(f'Choose a new output filename ending in {suffix}: {path}')
|
| 425 |
+
model = load_model(args.checkpoint,args.device)
|
| 426 |
+
if abs(args.spacing_um/model.sampling_um-1) > .02:
|
| 427 |
+
parser.error(f'Resample the render to {model.sampling_um} um first (no automatic resampling)')
|
| 428 |
+
volume = open_volume(args.input,args.array)
|
| 429 |
+
if output is not None:
|
| 430 |
+
output.parent.mkdir(parents=True,exist_ok=True)
|
| 431 |
+
with tempfile.TemporaryDirectory(prefix='hecate-') as tmp:
|
| 432 |
+
result = np.memmap(Path(tmp)/'prediction',mode='w+',dtype='uint8',shape=volume.shape[-2:])
|
| 433 |
+
predict(model,volume,result,args.reverse,args.stride,args.batch_size,args.precision)
|
| 434 |
+
partial = output.with_suffix('.partial')
|
| 435 |
+
write_png(result,partial)
|
| 436 |
+
partial.replace(output)
|
| 437 |
+
del result
|
| 438 |
+
metadata = {
|
| 439 |
+
'checkpoint':Path(args.checkpoint).name,'sampling_um':args.spacing_um,
|
| 440 |
+
'shape_yx':list(volume.shape[-2:]),'reverse_z':args.reverse,
|
| 441 |
+
'central_depth':model.patch_size[0],'precision':args.precision,
|
| 442 |
+
'stride':args.stride or model.patch_size[1]//2,
|
| 443 |
+
'probabilities':'uint8 = round(255 * probability); no min-max scaling'
|
| 444 |
+
}
|
| 445 |
+
if output is not None:
|
| 446 |
+
output.with_suffix('.json').write_text(json.dumps(metadata,indent=2)+'\n')
|
| 447 |
+
print(output)
|
| 448 |
+
if output3d is not None:
|
| 449 |
+
import zarr
|
| 450 |
+
from numcodecs import Blosc
|
| 451 |
+
output3d.parent.mkdir(parents=True,exist_ok=True)
|
| 452 |
+
partial = output3d.with_name(output3d.name+'.partial')
|
| 453 |
+
if partial.exists():
|
| 454 |
+
parser.error(f'Incomplete output exists: {partial}; remove it or choose another output')
|
| 455 |
+
options = {'zarr_format':2} if int(zarr.__version__.split('.')[0])>=3 else {}
|
| 456 |
+
result = zarr.open_array(str(partial),mode='w',shape=volume.shape,
|
| 457 |
+
chunks=(1,256,256),dtype='uint8',fill_value=0,
|
| 458 |
+
compressor=Blosc(cname='zstd',clevel=3,shuffle=Blosc.BITSHUFFLE),**options)
|
| 459 |
+
predict(model,volume,result,args.reverse,args.stride,args.batch_size,args.precision,three_d=True)
|
| 460 |
+
depth = volume.shape[0]
|
| 461 |
+
d = model.patch_size[0]
|
| 462 |
+
start = depth//2-d//2
|
| 463 |
+
if args.reverse:
|
| 464 |
+
start = depth-start-d
|
| 465 |
+
result.attrs.update({**metadata,'axes':['z','y','x'],
|
| 466 |
+
'spacing_um':[args.spacing_um]*3,'z_order':'same as input',
|
| 467 |
+
'evaluated_z_interval':[start+model.margin,start+d-model.margin],
|
| 468 |
+
'outside_evaluated_z':'zero; not evaluated',
|
| 469 |
+
'background':'empty CT columns zeroed; no intensity threshold'})
|
| 470 |
+
partial.rename(output3d)
|
| 471 |
+
print(output3d)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
if __name__ == '__main__':
|
| 476 |
+
main()
|