Spaces:
Running on Zero
Running on Zero
Upload folder using huggingface_hub
Browse files- .gitattributes +3 -0
- README.md +40 -7
- app.py +195 -0
- examples/2ch.png +3 -0
- examples/4ch.png +3 -0
- examples/psax.png +3 -0
- p2echo.pth +3 -0
- p2echo/__init__.py +4 -0
- p2echo/data.py +115 -0
- p2echo/dyita.py +176 -0
- p2echo/engine.py +35 -0
- p2echo/losses.py +59 -0
- p2echo/metrics.py +64 -0
- p2echo/model.py +141 -0
- p2echo/prompts.py +136 -0
- p2echo/pvtv2.py +150 -0
- p2echo/text_encoder.py +38 -0
- p2echo/transformer.py +62 -0
- requirements.txt +5 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
examples/2ch.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
examples/4ch.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
examples/psax.png filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,13 +1,46 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.32.0
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: P2Echo · Text-Prompted Echo Segmentation
|
| 3 |
+
emoji: 🫀
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.32.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
short_description: Text-prompted multi-view echocardiography segmentation
|
| 10 |
+
python_version: "3.12"
|
| 11 |
+
startup_duration_timeout: 30m
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# P2Echo · Text-Prompted Echocardiography Segmentation
|
| 15 |
+
|
| 16 |
+
**P2Echo** segments cardiac structures (LV, MYO, LA, RV, RA) across four echocardiography
|
| 17 |
+
views (2CH, 3CH, 4CH, PSAX) with a single 37.5M-parameter model controlled by structured
|
| 18 |
+
text prompts. Pick the view, select the structures to segment, and the demo builds the
|
| 19 |
+
paper's view-aware prompt (e.g. *"Apical 4-Chamber (4CH): … Segment the LV: The LV appears
|
| 20 |
+
as a bullet-shaped chamber forming the apex."*) and runs one forward pass.
|
| 21 |
+
|
| 22 |
+
- **Paper**: [Prompt2Echo (P2Echo): Text-Prompted Multi-View Echocardiography Segmentation with One Model](https://arxiv.org/abs/2611.13425)
|
| 23 |
+
- **Code**: [github.com/moeinheidari7829/P2Echo](https://github.com/moeinheidari7829/P2Echo)
|
| 24 |
+
- **Weights**: [moein99/P2Echo](https://huggingface.co/moein99/P2Echo)
|
| 25 |
+
|
| 26 |
+
## How it works
|
| 27 |
+
|
| 28 |
+
1. The requested structures are turned into the paper's view-aware text prompts.
|
| 29 |
+
2. A frozen **Qwen3-Embedding-0.6B** text encoder embeds each prompt.
|
| 30 |
+
3. The **P2Echo** segmentation network (PVTv2-B2 encoder + DyITA prompt decoder)
|
| 31 |
+
processes the frame with all structure prompts in one forward pass.
|
| 32 |
+
4. Each structure's logit map is thresholded and colour-blended over the input.
|
| 33 |
+
|
| 34 |
+
## Example images
|
| 35 |
+
|
| 36 |
+
The bundled example frames are from the Yale University echocardiography atlas
|
| 37 |
+
([four chamber](https://commons.wikimedia.org/wiki/File:Apical_4_chamber_view.png),
|
| 38 |
+
[two chamber](https://commons.wikimedia.org/wiki/File:Apical2Chamber.png),
|
| 39 |
+
[short axis](https://commons.wikimedia.org/wiki/File:LeftVentricleShortAxis.gif)),
|
| 40 |
+
via Wikimedia Commons, © Patrick J. Lynch and C. Carl Jaffe, Yale Center for Advanced
|
| 41 |
+
Instructional Media, licensed under [CC BY 2.5](https://creativecommons.org/licenses/by/2.5/).
|
| 42 |
+
|
| 43 |
+
## Disclaimer
|
| 44 |
+
|
| 45 |
+
P2Echo is a research prototype. It has **not** been validated for clinical use and must
|
| 46 |
+
not be used for diagnosis or any clinical decision-making.
|
app.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""P2Echo: text-prompted multi-view echocardiography segmentation demo.
|
| 2 |
+
|
| 3 |
+
Upload an echocardiography frame, pick the view and the cardiac structures to
|
| 4 |
+
segment, and P2Echo returns a colour-coded segmentation mask following the
|
| 5 |
+
structured text prompt built from your selection.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 11 |
+
|
| 12 |
+
import spaces # noqa: E402 (must precede torch)
|
| 13 |
+
import torch # noqa: E402
|
| 14 |
+
import gradio as gr # noqa: E402
|
| 15 |
+
import numpy as np # noqa: E402
|
| 16 |
+
from PIL import Image # noqa: E402
|
| 17 |
+
|
| 18 |
+
from p2echo import P2Echo, TextEncoder # noqa: E402
|
| 19 |
+
from p2echo.data import normalize_image # noqa: E402
|
| 20 |
+
from p2echo.prompts import VIEW_STRUCTURES, structure_prompt # noqa: E402
|
| 21 |
+
|
| 22 |
+
DEVICE = "cuda"
|
| 23 |
+
IMAGE_SIZE = 256
|
| 24 |
+
TEXT_MODEL = "Qwen/Qwen3-Embedding-0.6B"
|
| 25 |
+
|
| 26 |
+
CHECKPOINT = "p2echo.pth" # shipped in the Space repo
|
| 27 |
+
|
| 28 |
+
# ---------------------------------------------------------------- model load
|
| 29 |
+
text_encoder = TextEncoder(TEXT_MODEL).to(DEVICE)
|
| 30 |
+
model = P2Echo(text_dim=text_encoder.dim).to(DEVICE).eval()
|
| 31 |
+
state = torch.load(CHECKPOINT, map_location="cpu", weights_only=True)["model"]
|
| 32 |
+
model.load_state_dict(state)
|
| 33 |
+
print("P2Echo loaded:", sum(p.numel() for p in model.parameters()) / 1e6, "M params")
|
| 34 |
+
|
| 35 |
+
STRUCTURE_COLORS = {
|
| 36 |
+
"LV": (255, 60, 60),
|
| 37 |
+
"MYO": (60, 200, 255),
|
| 38 |
+
"LA": (255, 220, 60),
|
| 39 |
+
"RV": (80, 130, 255),
|
| 40 |
+
"RA": (220, 80, 255),
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def preprocess(pil_image):
|
| 45 |
+
"""PIL -> normalized [1,3,256,256] tensor, exactly like p2echo.data.EchoDataset."""
|
| 46 |
+
img = pil_image.convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE), Image.BILINEAR)
|
| 47 |
+
arr = np.array(img).transpose(2, 0, 1)
|
| 48 |
+
tensor = torch.from_numpy(arr).float() / 255.0
|
| 49 |
+
return normalize_image(tensor).unsqueeze(0)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@torch.no_grad()
|
| 53 |
+
def _segment_impl(image, view, structures, threshold):
|
| 54 |
+
"""Reference implementation returning (overlay PIL, gallery list) as plain CPU objects."""
|
| 55 |
+
view = view.upper()
|
| 56 |
+
structures = [s for s in structures if s] or ["LV"]
|
| 57 |
+
requested = [s for s in structures if s in VIEW_STRUCTURES[view]]
|
| 58 |
+
if not requested:
|
| 59 |
+
raise gr.Error(f"None of {structures} is visualized in the {view} view. "
|
| 60 |
+
f"Choose one of: {', '.join(VIEW_STRUCTURES[view])}.")
|
| 61 |
+
prompts = [structure_prompt(view, s) for s in requested]
|
| 62 |
+
emb = text_encoder(prompts, DEVICE).unsqueeze(0) # [1, N, dim]
|
| 63 |
+
img_t = preprocess(image).to(DEVICE)
|
| 64 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 65 |
+
logits = model(img_t, emb)[0].float() # [1, N, H, W]
|
| 66 |
+
probs = torch.sigmoid(logits)[0].cpu().numpy() # [N, H, W]
|
| 67 |
+
|
| 68 |
+
n = len(requested)
|
| 69 |
+
base = image.convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE), Image.BILINEAR)
|
| 70 |
+
overlay = np.array(base, dtype=np.float32)
|
| 71 |
+
for i, s in enumerate(requested):
|
| 72 |
+
m = probs[i] >= threshold
|
| 73 |
+
color = np.array(STRUCTURE_COLORS[s], dtype=np.float32)
|
| 74 |
+
overlay[m] = overlay[m] * 0.45 + color * 0.55
|
| 75 |
+
overlay_img = Image.fromarray(overlay.clip(0, 255).astype(np.uint8))
|
| 76 |
+
|
| 77 |
+
gallery = [(base, "input"), (overlay_img, "overlay")]
|
| 78 |
+
for i, s in enumerate(requested):
|
| 79 |
+
m = probs[i] >= threshold
|
| 80 |
+
color = np.array(STRUCTURE_COLORS[s], dtype=np.float32)
|
| 81 |
+
tile = np.full((IMAGE_SIZE, IMAGE_SIZE, 3), 255, dtype=np.float32)
|
| 82 |
+
tile[m] = color
|
| 83 |
+
gallery.append((Image.fromarray(tile.clip(0, 255).astype(np.uint8)), f"{s} ({float(probs[i].max()):.2f} max)"))
|
| 84 |
+
return overlay_img, gallery
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@spaces.GPU(duration=90)
|
| 88 |
+
def segment(image, view, structures=("LV",), threshold=0.5):
|
| 89 |
+
"""Segment the selected cardiac structures in an echocardiography frame.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
image: input echocardiography image (any size; resized to 256x256).
|
| 93 |
+
view: echocardiographic view, one of 2CH / 3CH / 4CH / PSAX.
|
| 94 |
+
structures: list of structures to segment (LV, MYO, LA, RV, RA).
|
| 95 |
+
threshold: probability threshold binarising each structure's mask.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
(overlay image, gallery of input/overlay/per-structure colour masks).
|
| 99 |
+
"""
|
| 100 |
+
if image is None:
|
| 101 |
+
raise gr.Error("Please upload an echocardiography image first.")
|
| 102 |
+
return _segment_impl(image, view, structures, float(threshold))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
VIEW_DESCRIPTIONS = {
|
| 106 |
+
"4CH": "Apical 4-Chamber",
|
| 107 |
+
"2CH": "Apical 2-Chamber",
|
| 108 |
+
"3CH": "Apical 3-Chamber",
|
| 109 |
+
"PSAX": "Parasternal Short-Axis",
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def update_structures(view):
|
| 114 |
+
"""Restrict the structure checkboxes to those visible in the chosen view."""
|
| 115 |
+
return gr.update(choices=list(VIEW_STRUCTURES[view.upper()]),
|
| 116 |
+
value=["LV"] if "LV" in VIEW_STRUCTURES[view.upper()]
|
| 117 |
+
else list(VIEW_STRUCTURES[view.upper()])[:1])
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
CSS = """
|
| 121 |
+
#col-container { max-width: 1210px; margin: 0 auto; }
|
| 122 |
+
.dark .gradio-container { color: var(--body-text-color); }
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
with gr.Blocks(theme=gr.themes.Citrus(), css=CSS, title="P2Echo · Text-Prompted Echo Segmentation") as demo:
|
| 126 |
+
with gr.Column(elem_id="col-container"):
|
| 127 |
+
gr.Markdown(
|
| 128 |
+
"""
|
| 129 |
+
# 🫀 P2Echo · Text-Prompted Echocardiography Segmentation
|
| 130 |
+
|
| 131 |
+
**P2Echo** segments cardiac structures (LV, MYO, LA, RV, RA) across four echo views
|
| 132 |
+
(2CH, 3CH, 4CH, PSAX) with a single 37.5M-parameter model controlled by a structured
|
| 133 |
+
text prompt naming the view and the requested structure.
|
| 134 |
+
|
| 135 |
+
Upload a frame, pick the view, select the structures — the demo builds the paper's
|
| 136 |
+
view-aware prompt (e.g. *"Apical 4-Chamber (4CH): … Segment the LV: The LV appears as
|
| 137 |
+
a bullet-shaped chamber forming the apex."*) and runs one forward pass.
|
| 138 |
+
|
| 139 |
+
[Paper](https://arxiv.org/abs/2611.13425) · [Code](https://github.com/moeinheidari7829/P2Echo) ·
|
| 140 |
+
[Weights](https://huggingface.co/moein99/P2Echo) — research use only, not for clinical decisions.
|
| 141 |
+
"""
|
| 142 |
+
)
|
| 143 |
+
with gr.Row():
|
| 144 |
+
with gr.Column(scale=5):
|
| 145 |
+
input_img = gr.Image(type="pil", label="Echocardiography frame", height=320)
|
| 146 |
+
view = gr.Radio(list(VIEW_DESCRIPTIONS.keys()), value="4CH", label="View",
|
| 147 |
+
info="Standard echocardiographic view of the frame")
|
| 148 |
+
structures = gr.CheckboxGroup(list(VIEW_STRUCTURES["4CH"]), value=["LV"],
|
| 149 |
+
label="Structures to segment",
|
| 150 |
+
info="Restricted to structures visible in the view")
|
| 151 |
+
threshold = gr.Slider(0.1, 0.9, value=0.5, step=0.05, label="Threshold")
|
| 152 |
+
run_btn = gr.Button("Segment", variant="primary")
|
| 153 |
+
prompt_preview = gr.Textbox(label="Text prompt sent to the model", lines=4, interactive=False)
|
| 154 |
+
with gr.Column(scale=7):
|
| 155 |
+
overlay_out = gr.Image(type="pil", label="Prediction overlay", height=320)
|
| 156 |
+
gallery_out = gr.Gallery(label="Input · Overlay · Per-structure masks",
|
| 157 |
+
columns=4, height=300)
|
| 158 |
+
gr.Examples(
|
| 159 |
+
examples=[
|
| 160 |
+
["examples/4ch.png", "4CH"],
|
| 161 |
+
["examples/2ch.png", "2CH"],
|
| 162 |
+
["examples/psax.png", "PSAX"],
|
| 163 |
+
],
|
| 164 |
+
inputs=[input_img, view],
|
| 165 |
+
outputs=[overlay_out, gallery_out],
|
| 166 |
+
fn=segment,
|
| 167 |
+
cache_examples=True,
|
| 168 |
+
cache_mode="lazy",
|
| 169 |
+
label="Examples (click one, then Segment)",
|
| 170 |
+
)
|
| 171 |
+
gr.Markdown(
|
| 172 |
+
"""**Reference**: Heidari et al., *Prompt2Echo (P2Echo): Text-Prompted Multi-View
|
| 173 |
+
Echocardiography Segmentation with One Model*, arXiv:2611.13425. Text encoder:
|
| 174 |
+
frozen Qwen3-Embedding-0.6B."""
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
view.change(update_structures, inputs=view, outputs=structures)
|
| 178 |
+
|
| 179 |
+
def _preview(view, structures):
|
| 180 |
+
chosen = [s for s in structures if s in VIEW_STRUCTURES[view.upper()]][:1]
|
| 181 |
+
if not chosen:
|
| 182 |
+
return gr.update()
|
| 183 |
+
return structure_prompt(view.upper(), chosen[0])
|
| 184 |
+
|
| 185 |
+
structures.change(_preview, inputs=[view, structures], outputs=prompt_preview)
|
| 186 |
+
view.change(_preview, inputs=[view, structures], outputs=prompt_preview)
|
| 187 |
+
|
| 188 |
+
run_btn.click(
|
| 189 |
+
segment,
|
| 190 |
+
inputs=[input_img, view, structures, threshold],
|
| 191 |
+
outputs=[overlay_out, gallery_out],
|
| 192 |
+
api_name="segment",
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
demo.launch(mcp_server=True)
|
examples/2ch.png
ADDED
|
Git LFS Details
|
examples/4ch.png
ADDED
|
Git LFS Details
|
examples/psax.png
ADDED
|
Git LFS Details
|
p2echo.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2892bb52eb3011031217332a0614a87aae895e006850ec08187fcd95197fd16a
|
| 3 |
+
size 150455752
|
p2echo/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .model import P2Echo
|
| 2 |
+
from .text_encoder import TextEncoder
|
| 3 |
+
|
| 4 |
+
__all__ = ["P2Echo", "TextEncoder"]
|
p2echo/data.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Echocardiography dataset, split files and training augmentation."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from torch.utils.data import DataLoader, Dataset
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def normalize_image(img, eps=1e-8):
|
| 13 |
+
"""Z-score normalisation over non-zero (foreground) pixels; background stays 0."""
|
| 14 |
+
fg = img.ne(0).any(dim=0)
|
| 15 |
+
if not fg.any():
|
| 16 |
+
return (img - img.mean()) / img.std(unbiased=False).clamp_min(eps)
|
| 17 |
+
fg = fg.unsqueeze(0).expand_as(img)
|
| 18 |
+
out = img.clone()
|
| 19 |
+
out[fg] = (img[fg] - img[fg].mean()) / img[fg].std(unbiased=False).clamp_min(eps)
|
| 20 |
+
out[~fg] = 0
|
| 21 |
+
return out
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class EchoDataset(Dataset):
|
| 25 |
+
"""
|
| 26 |
+
Items are dicts with image_path, mask_path, view (2CH/3CH/4CH/PSAX) and dataset.
|
| 27 |
+
Masks are single-channel label maps: 0 BG, 1 LV, 2 MYO, 3 LA, 4 RV, 5 RA.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self, items, image_size=256):
|
| 31 |
+
self.items = items
|
| 32 |
+
self.size = (image_size, image_size)
|
| 33 |
+
|
| 34 |
+
def __len__(self):
|
| 35 |
+
return len(self.items)
|
| 36 |
+
|
| 37 |
+
def __getitem__(self, idx):
|
| 38 |
+
item = self.items[idx]
|
| 39 |
+
image = Image.open(item["image_path"]).convert("RGB").resize(self.size, Image.BILINEAR)
|
| 40 |
+
mask = Image.open(item["mask_path"]).convert("L").resize(self.size, Image.NEAREST)
|
| 41 |
+
image = torch.from_numpy(np.array(image).transpose(2, 0, 1)).float() / 255.0
|
| 42 |
+
return {
|
| 43 |
+
"image": normalize_image(image),
|
| 44 |
+
"mask": torch.from_numpy(np.array(mask)).long(),
|
| 45 |
+
"view": str(item["view"]).upper(),
|
| 46 |
+
"dataset": item["dataset"],
|
| 47 |
+
"name": os.path.basename(item["image_path"]),
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def load_split(splits_json, split, data_root=""):
|
| 52 |
+
"""Read one split ("train", "val", "test" or "external") of a split file; paths are relative to data_root."""
|
| 53 |
+
with open(splits_json) as f:
|
| 54 |
+
items = json.load(f)[split]
|
| 55 |
+
for item in items:
|
| 56 |
+
for key in ("image_path", "mask_path"):
|
| 57 |
+
item[key] = os.path.join(data_root, item[key])
|
| 58 |
+
return items
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def make_loader(items, batch_size, num_workers, shuffle=False, image_size=256):
|
| 62 |
+
return DataLoader(EchoDataset(items, image_size), batch_size=batch_size, shuffle=shuffle,
|
| 63 |
+
num_workers=num_workers, pin_memory=True, persistent_workers=num_workers > 0)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class SafeGammaTransform:
|
| 67 |
+
"""Per-channel gamma on min-max rescaled intensities (valid for negative inputs)."""
|
| 68 |
+
|
| 69 |
+
def __init__(self, gamma_range=(0.7, 1.5), p_per_sample=0.3):
|
| 70 |
+
self.gamma_range = gamma_range
|
| 71 |
+
self.p_per_sample = p_per_sample
|
| 72 |
+
|
| 73 |
+
def __call__(self, **data_dict):
|
| 74 |
+
data = data_dict["data"].astype(np.float32, copy=False)
|
| 75 |
+
for b in range(data.shape[0]):
|
| 76 |
+
if np.random.random() >= self.p_per_sample:
|
| 77 |
+
continue
|
| 78 |
+
for c in range(data.shape[1]):
|
| 79 |
+
gamma = np.random.uniform(*self.gamma_range)
|
| 80 |
+
x = data[b, c]
|
| 81 |
+
lo = float(np.min(x))
|
| 82 |
+
span = float(np.max(x - lo))
|
| 83 |
+
if span > 0:
|
| 84 |
+
data[b, c] = np.power((x - lo) / (span + 1e-8), gamma, dtype=np.float32) * span + lo
|
| 85 |
+
data_dict["data"] = data
|
| 86 |
+
return data_dict
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def build_train_transforms(image_size=256):
|
| 90 |
+
"""nnU-Net style 2D augmentation (batchgenerators)."""
|
| 91 |
+
from batchgenerators.transforms.abstract_transforms import Compose
|
| 92 |
+
from batchgenerators.transforms.color_transforms import (
|
| 93 |
+
BrightnessMultiplicativeTransform, ContrastAugmentationTransform)
|
| 94 |
+
from batchgenerators.transforms.noise_transforms import GaussianBlurTransform, GaussianNoiseTransform
|
| 95 |
+
from batchgenerators.transforms.resample_transforms import SimulateLowResolutionTransform
|
| 96 |
+
from batchgenerators.transforms.spatial_transforms import SpatialTransform
|
| 97 |
+
|
| 98 |
+
rotation = (-15.0 / 180.0 * np.pi, 15.0 / 180.0 * np.pi)
|
| 99 |
+
return Compose([
|
| 100 |
+
SpatialTransform(
|
| 101 |
+
patch_size=(image_size, image_size), patch_center_dist_from_border=None,
|
| 102 |
+
do_elastic_deform=False, alpha=(0.0, 0.0), sigma=(0.0, 0.0),
|
| 103 |
+
do_rotation=True, angle_x=rotation, angle_y=(0.0, 0.0), angle_z=(0.0, 0.0),
|
| 104 |
+
do_scale=True, scale=(0.7, 1.4), border_mode_data="constant", border_cval_data=0.0,
|
| 105 |
+
order_data=3, border_mode_seg="constant", border_cval_seg=0, order_seg=0,
|
| 106 |
+
random_crop=False, p_el_per_sample=0.0, p_scale_per_sample=0.2, p_rot_per_sample=0.2,
|
| 107 |
+
independent_scale_for_each_axis=False),
|
| 108 |
+
GaussianNoiseTransform(p_per_sample=0.1),
|
| 109 |
+
GaussianBlurTransform(blur_sigma=(0.5, 1.0), different_sigma_per_channel=True, p_per_sample=0.2),
|
| 110 |
+
BrightnessMultiplicativeTransform(multiplier_range=(0.7, 1.3), p_per_sample=0.15),
|
| 111 |
+
ContrastAugmentationTransform(contrast_range=(0.65, 1.5), p_per_sample=0.15),
|
| 112 |
+
SafeGammaTransform(gamma_range=(0.7, 1.5), p_per_sample=0.3),
|
| 113 |
+
SimulateLowResolutionTransform(zoom_range=(0.5, 1.0), per_channel=True, p_per_sample=0.25,
|
| 114 |
+
order_downsample=0, order_upsample=3),
|
| 115 |
+
])
|
p2echo/dyita.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dynamic Image-Text Alignment (DyITA) and the ITA decoder block."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from timm.layers import DropPath
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def ste_argmax(scores):
|
| 12 |
+
"""Hard one-hot routing in the forward pass, softmax gradient in the backward pass."""
|
| 13 |
+
one_hot = F.one_hot(scores.argmax(dim=-1), scores.shape[-1]).float()
|
| 14 |
+
soft = F.softmax(scores, dim=-1)
|
| 15 |
+
return one_hot + soft - soft.detach()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class DynamicProjection(nn.Module):
|
| 19 |
+
"""Q from image tokens, K/V from prompt tokens, plus routed redundancy projections Q', K'."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, img_dim, txt_dim, head_dim, n_heads, n_projectors=3):
|
| 22 |
+
super().__init__()
|
| 23 |
+
inner = head_dim * n_heads
|
| 24 |
+
self.n_heads = n_heads
|
| 25 |
+
self.head_dim = head_dim
|
| 26 |
+
|
| 27 |
+
self.q_proj = nn.Linear(img_dim, inner, bias=False)
|
| 28 |
+
self.k_proj = nn.Linear(txt_dim, inner, bias=False)
|
| 29 |
+
self.v_proj = nn.Linear(txt_dim, inner, bias=False)
|
| 30 |
+
self.q_prime_banks = nn.ModuleList(
|
| 31 |
+
[nn.Linear(img_dim, inner, bias=False) for _ in range(n_projectors)])
|
| 32 |
+
self.k_prime_banks = nn.ModuleList(
|
| 33 |
+
[nn.Linear(txt_dim, inner, bias=False) for _ in range(n_projectors)])
|
| 34 |
+
self.router_q = nn.Linear(img_dim, n_projectors, bias=False)
|
| 35 |
+
self.router_k = nn.Linear(txt_dim, n_projectors, bias=False)
|
| 36 |
+
|
| 37 |
+
for m in self.modules():
|
| 38 |
+
if isinstance(m, nn.Linear):
|
| 39 |
+
nn.init.xavier_uniform_(m.weight)
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
def _route(tokens, router, banks):
|
| 43 |
+
route = ste_argmax(router(tokens)) # [B, L, P]
|
| 44 |
+
candidates = torch.stack([bank(tokens) for bank in banks], dim=-1) # [B, L, C, P]
|
| 45 |
+
return (candidates * route.unsqueeze(2)).sum(dim=-1)
|
| 46 |
+
|
| 47 |
+
def _heads(self, x):
|
| 48 |
+
b, l, _ = x.shape
|
| 49 |
+
return x.view(b, l, self.n_heads, self.head_dim).transpose(1, 2)
|
| 50 |
+
|
| 51 |
+
def forward(self, img_tokens, txt_tokens):
|
| 52 |
+
q = self.q_proj(img_tokens)
|
| 53 |
+
k = self.k_proj(txt_tokens)
|
| 54 |
+
v = self.v_proj(txt_tokens)
|
| 55 |
+
q_prime = self._route(img_tokens, self.router_q, self.q_prime_banks)
|
| 56 |
+
k_prime = self._route(txt_tokens, self.router_k, self.k_prime_banks)
|
| 57 |
+
return tuple(self._heads(t) for t in (q, k, v, q_prime, k_prime))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class DynamicMeasureKernel(nn.Module):
|
| 61 |
+
"""Norm-preserving power map softplus(z)^gamma with a per-token routed exponent."""
|
| 62 |
+
|
| 63 |
+
def __init__(self, dim, n_factors=9, gamma_init=3.0):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.gammas = nn.Parameter(torch.full((n_factors,), float(gamma_init)))
|
| 66 |
+
self.router = nn.Linear(dim, n_factors, bias=False)
|
| 67 |
+
nn.init.xavier_uniform_(self.router.weight)
|
| 68 |
+
|
| 69 |
+
def forward(self, z):
|
| 70 |
+
route = ste_argmax(self.router(z.detach()))
|
| 71 |
+
gamma = (route * self.gammas.unsqueeze(0)).sum(dim=-1, keepdim=True).clamp(min=1.0)
|
| 72 |
+
z = F.softplus(z)
|
| 73 |
+
norm = z.norm(dim=-1, keepdim=True).clamp(min=1e-8)
|
| 74 |
+
z_pow = z.pow(gamma)
|
| 75 |
+
return z_pow / z_pow.norm(dim=-1, keepdim=True).clamp(min=1e-8) * norm
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class DifferentialOperator(nn.Module):
|
| 79 |
+
"""Subtract routed redundancy (Q - l_q Q', K - l_k K') and apply softmax cross-attention."""
|
| 80 |
+
|
| 81 |
+
def __init__(self, head_dim, n_factors=9, lambda_init=0.01):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.scale = head_dim ** -0.5
|
| 84 |
+
self.lambdas = nn.Parameter(torch.full((n_factors,), float(lambda_init)))
|
| 85 |
+
self.router_q = nn.Linear(2 * head_dim, n_factors, bias=False)
|
| 86 |
+
self.router_k = nn.Linear(2 * head_dim, n_factors, bias=False)
|
| 87 |
+
nn.init.xavier_uniform_(self.router_q.weight)
|
| 88 |
+
nn.init.xavier_uniform_(self.router_k.weight)
|
| 89 |
+
|
| 90 |
+
def forward(self, q, q_prime, k, k_prime, v):
|
| 91 |
+
route_q = ste_argmax(self.router_q(torch.cat([q, q_prime], dim=-1).detach()))
|
| 92 |
+
route_k = ste_argmax(self.router_k(torch.cat([k, k_prime], dim=-1).detach()))
|
| 93 |
+
lambda_q = (route_q * self.lambdas).sum(dim=-1, keepdim=True)
|
| 94 |
+
lambda_k = (route_k * self.lambdas).sum(dim=-1, keepdim=True)
|
| 95 |
+
q = q - lambda_q * q_prime
|
| 96 |
+
k = k - lambda_k * k_prime
|
| 97 |
+
attn = F.softmax(torch.matmul(q, k.transpose(-2, -1)) * self.scale, dim=-1)
|
| 98 |
+
return torch.matmul(attn, v)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class DyITA(nn.Module):
|
| 102 |
+
"""Image tokens attend to the stage prompt embeddings through the three DyITA operations."""
|
| 103 |
+
|
| 104 |
+
def __init__(self, dim, n_heads=2, n_projectors=3, n_kernel_factors=9, n_diff_factors=9,
|
| 105 |
+
gamma_init=3.0, lambda_init=0.01, dropout=0.0):
|
| 106 |
+
super().__init__()
|
| 107 |
+
head_dim = dim // n_heads
|
| 108 |
+
self.dyn_proj = DynamicProjection(dim, dim, head_dim, n_heads, n_projectors)
|
| 109 |
+
self.kernel_q = DynamicMeasureKernel(head_dim, n_kernel_factors, gamma_init)
|
| 110 |
+
self.kernel_k = DynamicMeasureKernel(head_dim, n_kernel_factors, gamma_init)
|
| 111 |
+
self.kernel_q_prime = DynamicMeasureKernel(head_dim, n_kernel_factors, gamma_init)
|
| 112 |
+
self.kernel_k_prime = DynamicMeasureKernel(head_dim, n_kernel_factors, gamma_init)
|
| 113 |
+
self.tdo = DifferentialOperator(head_dim, n_diff_factors, lambda_init)
|
| 114 |
+
self.local_residual = nn.Sequential(
|
| 115 |
+
nn.Conv2d(dim, dim, 3, padding=1, groups=dim, bias=False),
|
| 116 |
+
nn.BatchNorm2d(dim),
|
| 117 |
+
)
|
| 118 |
+
self.out_proj = nn.Linear(dim, dim, bias=False)
|
| 119 |
+
self.dropout = nn.Dropout(dropout)
|
| 120 |
+
|
| 121 |
+
def forward(self, x, prompts):
|
| 122 |
+
b, c, h, w = x.shape
|
| 123 |
+
local = self.local_residual(x)
|
| 124 |
+
q, k, v, q_prime, k_prime = self.dyn_proj(x.flatten(2).transpose(1, 2), prompts)
|
| 125 |
+
out = self.tdo(self.kernel_q(q), self.kernel_q_prime(q_prime),
|
| 126 |
+
self.kernel_k(k), self.kernel_k_prime(k_prime), v)
|
| 127 |
+
out = out.transpose(1, 2).contiguous().view(b, h * w, c)
|
| 128 |
+
out = self.dropout(self.out_proj(out))
|
| 129 |
+
return out.transpose(1, 2).view(b, c, h, w) + local
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class GatedConvFFN(nn.Module):
|
| 133 |
+
"""1x1 expand -> SiLU -> depth-wise 3x3 on the value half -> gating -> 1x1 project."""
|
| 134 |
+
|
| 135 |
+
def __init__(self, dim, hidden_ratio=4.0, drop=0.0):
|
| 136 |
+
super().__init__()
|
| 137 |
+
hidden = int(dim * hidden_ratio)
|
| 138 |
+
self.fc1 = nn.Conv2d(dim, 2 * hidden, 1, bias=False)
|
| 139 |
+
self.act = nn.SiLU()
|
| 140 |
+
self.dwconv = nn.Conv2d(hidden, hidden, 3, padding=1, groups=hidden, bias=False)
|
| 141 |
+
self.dwconv_bn = nn.BatchNorm2d(hidden)
|
| 142 |
+
self.act2 = nn.SiLU()
|
| 143 |
+
self.fc2 = nn.Conv2d(hidden, dim, 1, bias=False)
|
| 144 |
+
self.drop = nn.Dropout(drop)
|
| 145 |
+
|
| 146 |
+
for m in self.modules():
|
| 147 |
+
if isinstance(m, nn.Conv2d):
|
| 148 |
+
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels // m.groups
|
| 149 |
+
nn.init.normal_(m.weight, 0, math.sqrt(2.0 / fan_out))
|
| 150 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 151 |
+
nn.init.constant_(m.weight, 1)
|
| 152 |
+
nn.init.constant_(m.bias, 0)
|
| 153 |
+
|
| 154 |
+
def forward(self, x):
|
| 155 |
+
value, gate = self.fc1(x).chunk(2, dim=1)
|
| 156 |
+
value = self.act2(self.dwconv_bn(self.dwconv(self.act(value))))
|
| 157 |
+
x = self.drop(value * self.act(gate))
|
| 158 |
+
return self.drop(self.fc2(x))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class ITABlock(nn.Module):
|
| 162 |
+
"""x + LS1 * DyITA(BN(x), prompts), then x + LS2 * FFN(BN(x))."""
|
| 163 |
+
|
| 164 |
+
def __init__(self, dim, n_heads=2, ffn_ratio=4.0, drop_path=0.0, init_value=0.1, **dyita_kwargs):
|
| 165 |
+
super().__init__()
|
| 166 |
+
self.norm1 = nn.BatchNorm2d(dim)
|
| 167 |
+
self.dyita = DyITA(dim, n_heads, **dyita_kwargs)
|
| 168 |
+
self.norm2 = nn.BatchNorm2d(dim)
|
| 169 |
+
self.ffn = GatedConvFFN(dim, ffn_ratio)
|
| 170 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0 else nn.Identity()
|
| 171 |
+
self.layer_scale_1 = nn.Parameter(torch.full((1, dim, 1, 1), float(init_value)))
|
| 172 |
+
self.layer_scale_2 = nn.Parameter(torch.full((1, dim, 1, 1), float(init_value)))
|
| 173 |
+
|
| 174 |
+
def forward(self, x, prompts):
|
| 175 |
+
x = x + self.drop_path(self.layer_scale_1 * self.dyita(self.norm1(x), prompts))
|
| 176 |
+
return x + self.drop_path(self.layer_scale_2 * self.ffn(self.norm2(x)))
|
p2echo/engine.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference and evaluation loop shared by training (validation) and testing."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from .metrics import MetricTracker, decode, evaluated_labels
|
| 6 |
+
from .prompts import annotated_mask, prompt_texts
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def prompt_embeddings(text_encoder, views, active, device):
|
| 10 |
+
emb = text_encoder(prompt_texts(views, active.bool().cpu()), device)
|
| 11 |
+
return emb.view(len(views), active.shape[1], -1)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@torch.no_grad()
|
| 15 |
+
def evaluate(model, text_encoder, loader, device, amp=True, threshold=0.5):
|
| 16 |
+
"""
|
| 17 |
+
Every structure annotated by an image's dataset is prompted, the remaining slots get the
|
| 18 |
+
null prompt. Returns a MetricTracker with groups 'all', 'view/<view>' and 'dataset/<name>'.
|
| 19 |
+
"""
|
| 20 |
+
model.eval()
|
| 21 |
+
tracker = MetricTracker()
|
| 22 |
+
for batch in loader:
|
| 23 |
+
image = batch["image"].to(device, non_blocking=True)
|
| 24 |
+
views, datasets = batch["view"], batch["dataset"]
|
| 25 |
+
active = annotated_mask(datasets, device)
|
| 26 |
+
emb = prompt_embeddings(text_encoder, views, active, device)
|
| 27 |
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp and device.type == "cuda"):
|
| 28 |
+
probs = torch.sigmoid(model(image, emb)[0].float()).cpu().numpy()
|
| 29 |
+
masks = batch["mask"].numpy()
|
| 30 |
+
for i in range(len(views)):
|
| 31 |
+
labels = evaluated_labels(datasets[i], views[i])
|
| 32 |
+
if labels:
|
| 33 |
+
pred = decode(probs[i], labels, threshold)
|
| 34 |
+
tracker.update(pred, masks[i], labels, ["all", f"view/{views[i]}", f"dataset/{datasets[i]}"])
|
| 35 |
+
return tracker
|
p2echo/losses.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Boundary Difference over Union loss (Sun et al., MICCAI 2023) with deep supervision."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class BoundaryDoULoss(nn.Module):
|
| 9 |
+
"""Applied per sample and per prompt to sigmoid probabilities; empty targets use mean(p)."""
|
| 10 |
+
|
| 11 |
+
def __init__(self, smooth=1e-5):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.smooth = smooth
|
| 14 |
+
|
| 15 |
+
def _bdou(self, score, target):
|
| 16 |
+
kernel = torch.tensor([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], device=target.device)
|
| 17 |
+
boundary = torch.conv2d(target[None, None], kernel[None, None], padding=1).squeeze() * target
|
| 18 |
+
boundary[boundary == 5] = 0
|
| 19 |
+
c = torch.count_nonzero(boundary)
|
| 20 |
+
s = torch.count_nonzero(target)
|
| 21 |
+
alpha = min((2 * (1 - (c + self.smooth) / (s + self.smooth)) - 1).item(), 0.8)
|
| 22 |
+
intersect = torch.sum(score * target)
|
| 23 |
+
y_sum = torch.sum(target * target)
|
| 24 |
+
z_sum = torch.sum(score * score)
|
| 25 |
+
return (z_sum + y_sum - 2 * intersect + self.smooth) / \
|
| 26 |
+
(z_sum + y_sum - (1 + alpha) * intersect + self.smooth)
|
| 27 |
+
|
| 28 |
+
def forward(self, logits, targets, valid):
|
| 29 |
+
"""logits/targets: [B, N, H, W]; valid: [B, N], 0 where the prompt is not supervised."""
|
| 30 |
+
probs = torch.sigmoid(logits.float())
|
| 31 |
+
targets = targets.float()
|
| 32 |
+
losses = []
|
| 33 |
+
for b in range(logits.shape[0]):
|
| 34 |
+
for n in range(logits.shape[1]):
|
| 35 |
+
if valid[b, n] < 0.5:
|
| 36 |
+
continue
|
| 37 |
+
if targets[b, n].sum() > 0:
|
| 38 |
+
losses.append(self._bdou(probs[b, n], targets[b, n]))
|
| 39 |
+
else:
|
| 40 |
+
losses.append(probs[b, n].mean())
|
| 41 |
+
if not losses:
|
| 42 |
+
return logits.sum() * 0.0
|
| 43 |
+
return torch.stack(losses).mean()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class DeepSupervisionLoss(nn.Module):
|
| 47 |
+
"""Outputs ordered high to low resolution, weighted 4/7, 2/7, 1/7."""
|
| 48 |
+
|
| 49 |
+
def __init__(self):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.loss = BoundaryDoULoss()
|
| 52 |
+
|
| 53 |
+
def forward(self, outputs, targets, valid):
|
| 54 |
+
weights = [1.0 / 2 ** i for i in range(len(outputs))]
|
| 55 |
+
weights = [w / sum(weights) for w in weights]
|
| 56 |
+
total = 0.0
|
| 57 |
+
for w, out in zip(weights, outputs):
|
| 58 |
+
total = total + w * self.loss(out, F.interpolate(targets, size=out.shape[-2:], mode="nearest"), valid)
|
| 59 |
+
return total
|
p2echo/metrics.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-image Dice, IoU and HD95 (medpy), macro-averaged over structures."""
|
| 2 |
+
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
if not hasattr(np, "bool"): # older medpy releases use the removed np.bool alias
|
| 8 |
+
np.bool = np.bool_
|
| 9 |
+
from medpy.metric.binary import dc, hd95, jc # noqa: E402
|
| 10 |
+
|
| 11 |
+
from .prompts import DATASET_LABELS, LABEL_TO_ID, LABELS, VIEW_STRUCTURES
|
| 12 |
+
|
| 13 |
+
METRICS = ("dice", "iou", "hd95")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def evaluated_labels(dataset, view):
|
| 17 |
+
"""Structures that are both annotated by the dataset and visible in the view."""
|
| 18 |
+
return [l for l in LABELS if l in DATASET_LABELS[dataset] and l in VIEW_STRUCTURES[view]]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def decode(probs, labels, threshold=0.5):
|
| 22 |
+
"""[5, H, W] per-prompt probabilities -> label map, restricted to the given structures."""
|
| 23 |
+
probs = probs.copy()
|
| 24 |
+
for i, label in enumerate(LABELS):
|
| 25 |
+
if label not in labels:
|
| 26 |
+
probs[i] = 0.0
|
| 27 |
+
best = probs.max(axis=0)
|
| 28 |
+
pred = (probs.argmax(axis=0) + 1).astype(np.uint8)
|
| 29 |
+
pred[best < threshold] = 0
|
| 30 |
+
return pred
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def case_metrics(pred, gt, class_id):
|
| 34 |
+
p, g = pred == class_id, gt == class_id
|
| 35 |
+
if not p.any() and not g.any():
|
| 36 |
+
return {"dice": 1.0, "iou": 1.0, "hd95": 0.0}
|
| 37 |
+
if not p.any() or not g.any():
|
| 38 |
+
return {"dice": 0.0, "iou": 0.0, "hd95": float("inf")}
|
| 39 |
+
return {"dice": dc(p, g), "iou": jc(p, g), "hd95": hd95(p, g, voxelspacing=(1.0, 1.0))}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class MetricTracker:
|
| 43 |
+
"""Collects per-image, per-structure metrics under several groupings (e.g. view or dataset)."""
|
| 44 |
+
|
| 45 |
+
def __init__(self):
|
| 46 |
+
self.values = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
|
| 47 |
+
|
| 48 |
+
def update(self, pred, gt, labels, groups):
|
| 49 |
+
for label in labels:
|
| 50 |
+
m = case_metrics(pred, gt, LABEL_TO_ID[label])
|
| 51 |
+
for group in groups:
|
| 52 |
+
for key in METRICS:
|
| 53 |
+
if np.isfinite(m[key]): # images where a structure is missed count 0 Dice but no HD95
|
| 54 |
+
self.values[group][label][key].append(float(m[key]))
|
| 55 |
+
|
| 56 |
+
def summary(self, group):
|
| 57 |
+
"""{label: {metric: mean}} plus 'mean': macro average over structures."""
|
| 58 |
+
out = {label: {k: float(np.mean(v)) for k, v in metrics.items()}
|
| 59 |
+
for label, metrics in self.values[group].items()}
|
| 60 |
+
out["mean"] = {k: float(np.mean([out[l][k] for l in out if k in out[l]])) for k in METRICS}
|
| 61 |
+
return out
|
| 62 |
+
|
| 63 |
+
def groups(self):
|
| 64 |
+
return sorted(self.values)
|
p2echo/model.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""P2Echo: PVTv2-B2 encoder, prompt decoder, four ITA decoder stages and prompt-conditioned mask heads."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from .dyita import ITABlock
|
| 8 |
+
from .pvtv2 import pvt_v2_b2
|
| 9 |
+
from .transformer import PromptDecoder, sine_position_encoding_2d
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class EUCB(nn.Module):
|
| 13 |
+
"""Efficient up-convolution block: 2x upsample, depth-wise 3x3, BN, LeakyReLU, 1x1 projection."""
|
| 14 |
+
|
| 15 |
+
def __init__(self, in_channels, out_channels):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.up_dwc = nn.Sequential(
|
| 18 |
+
nn.Upsample(scale_factor=2),
|
| 19 |
+
nn.Conv2d(in_channels, in_channels, 3, padding=1, groups=in_channels, bias=False),
|
| 20 |
+
nn.BatchNorm2d(in_channels),
|
| 21 |
+
nn.LeakyReLU(0.2, inplace=True),
|
| 22 |
+
)
|
| 23 |
+
self.pwc = nn.Sequential(nn.Conv2d(in_channels, out_channels, 1))
|
| 24 |
+
for m in self.modules():
|
| 25 |
+
if isinstance(m, nn.Conv2d):
|
| 26 |
+
nn.init.normal_(m.weight, std=.02)
|
| 27 |
+
if m.bias is not None:
|
| 28 |
+
nn.init.zeros_(m.bias)
|
| 29 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 30 |
+
nn.init.constant_(m.weight, 1)
|
| 31 |
+
nn.init.constant_(m.bias, 0)
|
| 32 |
+
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
return self.pwc(self.up_dwc(x))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class MaskHead(nn.Module):
|
| 38 |
+
"""One logit map per prompt: scaled dot product between pixel and prompt embeddings."""
|
| 39 |
+
|
| 40 |
+
def __init__(self, image_dim, prompt_dim, mask_dim=64):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.scale = mask_dim ** -0.5
|
| 43 |
+
self.image_projection = nn.Conv2d(image_dim, mask_dim, 1, bias=False)
|
| 44 |
+
self.prompt_projection = nn.Linear(prompt_dim, mask_dim, bias=False)
|
| 45 |
+
nn.init.xavier_uniform_(self.image_projection.weight)
|
| 46 |
+
nn.init.xavier_uniform_(self.prompt_projection.weight)
|
| 47 |
+
|
| 48 |
+
def forward(self, x, prompts):
|
| 49 |
+
pixels = self.image_projection(x)
|
| 50 |
+
prompts = self.prompt_projection(prompts)
|
| 51 |
+
return torch.einsum("bmhw,bnm->bnhw", pixels, prompts) * self.scale
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class ITADecoder(nn.Module):
|
| 55 |
+
def __init__(self, channels=(512, 320, 128, 64), n_heads=(2, 2, 2, 2), mask_dim=64,
|
| 56 |
+
drop_path=0.1, **dyita_kwargs):
|
| 57 |
+
super().__init__()
|
| 58 |
+
c4, c3, c2, c1 = channels
|
| 59 |
+
block = lambda dim, heads: ITABlock(dim, heads, drop_path=drop_path, **dyita_kwargs)
|
| 60 |
+
self.dec4 = block(c4, n_heads[0])
|
| 61 |
+
self.up3 = EUCB(c4, c3)
|
| 62 |
+
self.dec3 = block(c3, n_heads[1])
|
| 63 |
+
self.up2 = EUCB(c3, c2)
|
| 64 |
+
self.dec2 = block(c2, n_heads[2])
|
| 65 |
+
self.up1 = EUCB(c2, c1)
|
| 66 |
+
self.dec1 = block(c1, n_heads[3])
|
| 67 |
+
self.output_head = MaskHead(c1, c1, mask_dim)
|
| 68 |
+
self.deep_supervision_heads = nn.ModuleList([MaskHead(c2, c2, mask_dim), MaskHead(c3, c3, mask_dim)])
|
| 69 |
+
|
| 70 |
+
def forward(self, features, prompts):
|
| 71 |
+
f1, f2, f3, f4 = features
|
| 72 |
+
p4, p3, p2, p1 = prompts
|
| 73 |
+
d4 = self.dec4(f4, p4)
|
| 74 |
+
d3 = self.dec3(self.up3(d4) + f3, p3)
|
| 75 |
+
ds3 = self.deep_supervision_heads[1](d3, p3)
|
| 76 |
+
d2 = self.dec2(self.up2(d3) + f2, p2)
|
| 77 |
+
ds2 = self.deep_supervision_heads[0](d2, p2)
|
| 78 |
+
d1 = self.dec1(self.up1(d2) + f1, p1)
|
| 79 |
+
logits = self.output_head(d1, p1)
|
| 80 |
+
logits = F.interpolate(logits, size=(4 * f1.shape[-2], 4 * f1.shape[-1]),
|
| 81 |
+
mode="bilinear", align_corners=False)
|
| 82 |
+
return logits, ds2, ds3
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class P2Echo(nn.Module):
|
| 86 |
+
"""
|
| 87 |
+
Args:
|
| 88 |
+
img_size: input resolution (square, divisible by 32).
|
| 89 |
+
text_dim: dimension of the frozen text-encoder embeddings.
|
| 90 |
+
pretrained_encoder: optional path to ImageNet PVTv2-B2 weights.
|
| 91 |
+
|
| 92 |
+
forward(image [B,3,H,W], prompt_embeddings [B,N,text_dim]) returns
|
| 93 |
+
(logits [B,N,H,W], aux [B,N,H/8,W/8], aux [B,N,H/16,W/16]); output n follows prompt n.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def __init__(self, img_size=256, text_dim=1024, query_dim=256, mask_dim=64,
|
| 97 |
+
prompt_layers=3, prompt_heads=8, prompt_ffn_dim=1024, drop_path=0.1,
|
| 98 |
+
ita_heads=(2, 2, 2, 2), n_projectors=3, n_kernel_factors=9, n_diff_factors=9,
|
| 99 |
+
gamma_init=3.0, lambda_init=0.01, pretrained_encoder=None):
|
| 100 |
+
super().__init__()
|
| 101 |
+
channels = (512, 320, 128, 64)
|
| 102 |
+
self.encoder = pvt_v2_b2()
|
| 103 |
+
if pretrained_encoder:
|
| 104 |
+
self._load_encoder(pretrained_encoder)
|
| 105 |
+
|
| 106 |
+
self.project_bottleneck = nn.Linear(channels[0], query_dim)
|
| 107 |
+
self.project_text = nn.Linear(text_dim, query_dim)
|
| 108 |
+
side = img_size // 32
|
| 109 |
+
self.register_buffer("pos_embed", sine_position_encoding_2d(side, side, query_dim))
|
| 110 |
+
self.prompt_decoder = PromptDecoder(query_dim, prompt_heads, prompt_ffn_dim, prompt_layers)
|
| 111 |
+
self.stage_prompt_projections = nn.ModuleList([
|
| 112 |
+
nn.Sequential(nn.Linear(query_dim, query_dim // 2), nn.GELU(), nn.Linear(query_dim // 2, c))
|
| 113 |
+
for c in channels])
|
| 114 |
+
self.decoder = ITADecoder(
|
| 115 |
+
channels, ita_heads, mask_dim, drop_path, n_projectors=n_projectors,
|
| 116 |
+
n_kernel_factors=n_kernel_factors, n_diff_factors=n_diff_factors,
|
| 117 |
+
gamma_init=gamma_init, lambda_init=lambda_init)
|
| 118 |
+
|
| 119 |
+
for module in [self.project_bottleneck, self.project_text, *self.stage_prompt_projections]:
|
| 120 |
+
for layer in module.modules():
|
| 121 |
+
if isinstance(layer, nn.Linear):
|
| 122 |
+
nn.init.xavier_uniform_(layer.weight)
|
| 123 |
+
nn.init.zeros_(layer.bias)
|
| 124 |
+
|
| 125 |
+
def _load_encoder(self, path):
|
| 126 |
+
state = torch.load(path, map_location="cpu", weights_only=True)
|
| 127 |
+
state = state.get("state_dict", state)
|
| 128 |
+
state = {k.removeprefix("module."): v for k, v in state.items()}
|
| 129 |
+
own = self.encoder.state_dict()
|
| 130 |
+
missing = [k for k in own if k not in state or state[k].shape != own[k].shape]
|
| 131 |
+
if missing:
|
| 132 |
+
raise RuntimeError(f"PVTv2-B2 weights at {path} are incomplete, e.g. {missing[:4]}")
|
| 133 |
+
self.encoder.load_state_dict({k: state[k] for k in own})
|
| 134 |
+
|
| 135 |
+
def forward(self, image, prompt_embeddings):
|
| 136 |
+
features = self.encoder(image)
|
| 137 |
+
memory = self.project_bottleneck(features[-1].flatten(2).permute(2, 0, 1)) # [HW, B, C]
|
| 138 |
+
prompts = self.project_text(prompt_embeddings.transpose(0, 1)) # [N, B, C]
|
| 139 |
+
prompts = self.prompt_decoder(prompts, memory, self.pos_embed).transpose(0, 1)
|
| 140 |
+
stage_prompts = [proj(prompts) for proj in self.stage_prompt_projections]
|
| 141 |
+
return self.decoder(features, stage_prompts)
|
p2echo/prompts.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""View-aware text prompts and per-sample prompt sampling."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
LABELS = ("LV", "MYO", "LA", "RV", "RA") # output classes 1..5, background is 0
|
| 6 |
+
LABEL_TO_ID = {name: i + 1 for i, name in enumerate(LABELS)}
|
| 7 |
+
|
| 8 |
+
VIEW_NAMES = {
|
| 9 |
+
"2CH": "Apical 2-Chamber (2CH)",
|
| 10 |
+
"3CH": "Apical 3-Chamber (3CH)",
|
| 11 |
+
"4CH": "Apical 4-Chamber (4CH)",
|
| 12 |
+
"PSAX": "Parasternal Short-Axis (PSAX)",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
# Structures anatomically visible in each view.
|
| 16 |
+
VIEW_STRUCTURES = {
|
| 17 |
+
"4CH": ("LV", "LA", "RA", "RV", "MYO"),
|
| 18 |
+
"2CH": ("LV", "LA", "MYO"),
|
| 19 |
+
"3CH": ("LV", "LA", "MYO"),
|
| 20 |
+
"PSAX": ("LV", "RV", "MYO"),
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
# Structures annotated by each dataset.
|
| 24 |
+
DATASET_LABELS = {
|
| 25 |
+
"Camus": ("LV", "MYO", "LA"),
|
| 26 |
+
"CardiacUDA": ("LV", "LA", "RV", "RA"),
|
| 27 |
+
"EchoCP": ("LV", "LA", "RV", "RA"),
|
| 28 |
+
"EchoNet-Pediatric": ("LV",),
|
| 29 |
+
"SegRWMA": ("LV",),
|
| 30 |
+
"CardiacNet": ("LV", "LA", "RV", "RA"),
|
| 31 |
+
"HMCQU": ("LV", "MYO"),
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
DESCRIPTIONS = {
|
| 35 |
+
"4CH": {
|
| 36 |
+
"LV": "The LV appears as a bullet-shaped chamber forming the apex.",
|
| 37 |
+
"LA": "The LA is located posterior to the LV.",
|
| 38 |
+
"RA": "The RA is located next to the LA and inferior to the RV.",
|
| 39 |
+
"RV": "The RV appears triangular and usually smaller than the LV.",
|
| 40 |
+
"MYO": "The LV myocardium includes inferoseptum, anterolateral, apical septal, and apical lateral segments.",
|
| 41 |
+
},
|
| 42 |
+
"2CH": {
|
| 43 |
+
"LV": "The LV is fully visualized from base to apex.",
|
| 44 |
+
"LA": "The LA is seen superior to the LV.",
|
| 45 |
+
"MYO": "The LV myocardium includes anterior and inferior wall segments (basal, mid, apical).",
|
| 46 |
+
},
|
| 47 |
+
"3CH": {
|
| 48 |
+
"LV": "The LV and LVOT are visible in long-axis.",
|
| 49 |
+
"LA": "The LA is visible in long-axis.",
|
| 50 |
+
"MYO": "The LV myocardium includes anteroseptum, inferolateral, apical septal, and apical lateral segments.",
|
| 51 |
+
},
|
| 52 |
+
"PSAX": {
|
| 53 |
+
"LV": "The LV appears circular at mid-ventricle.",
|
| 54 |
+
"RV": "The RV appears crescent-shaped, wrapping anteriorly around the LV.",
|
| 55 |
+
"MYO": "The LV myocardium shows all 6 radial segments.",
|
| 56 |
+
},
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
NULL_REQUEST = "No anatomical structure is requested. Return an empty segmentation mask."
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def view_header(view):
|
| 63 |
+
view = view.upper()
|
| 64 |
+
return f"{VIEW_NAMES[view]}: Structures visualized: {', '.join(sorted(VIEW_STRUCTURES[view]))}."
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def structure_prompt(view, label):
|
| 68 |
+
"""Prompt requesting one structure, e.g. view_header + ' Segment the LV: <description>'."""
|
| 69 |
+
view = view.upper()
|
| 70 |
+
if label in VIEW_STRUCTURES[view]:
|
| 71 |
+
request = f"Segment the {label}: {DESCRIPTIONS[view][label]}"
|
| 72 |
+
else:
|
| 73 |
+
request = f"The {label} is not visualized in this view; do not segment it. Background only."
|
| 74 |
+
return f"{view_header(view)} {request}"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def null_prompt(view):
|
| 78 |
+
"""Prompt for an output slot whose structure is not requested; its target is empty."""
|
| 79 |
+
return f"{view_header(view)} {NULL_REQUEST}"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def prompt_texts(views, active):
|
| 83 |
+
"""Prompt strings for a batch, ordered sample by sample. active: [B, 5] bool."""
|
| 84 |
+
return [structure_prompt(view, label) if active[b, i] else null_prompt(view)
|
| 85 |
+
for b, view in enumerate(views) for i, label in enumerate(LABELS)]
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def annotated_mask(datasets, device):
|
| 89 |
+
"""[B, 5] mask of structures annotated by each sample's dataset."""
|
| 90 |
+
mask = torch.zeros(len(datasets), len(LABELS), device=device)
|
| 91 |
+
for b, name in enumerate(datasets):
|
| 92 |
+
if name not in DATASET_LABELS:
|
| 93 |
+
raise KeyError(f"Unknown dataset '{name}'. Add its annotated labels to DATASET_LABELS.")
|
| 94 |
+
for label in DATASET_LABELS[name]:
|
| 95 |
+
mask[b, LABEL_TO_ID[label] - 1] = 1.0
|
| 96 |
+
return mask
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def sample_active_prompts(annotated, full_probability=0.25):
|
| 100 |
+
"""
|
| 101 |
+
Randomly choose which annotated structures are requested for each training sample.
|
| 102 |
+
With probability full_probability all of them are; otherwise a uniformly sized random
|
| 103 |
+
subset (possibly empty), so every structure is also seen with a null prompt.
|
| 104 |
+
"""
|
| 105 |
+
active = torch.zeros_like(annotated)
|
| 106 |
+
for b in range(annotated.shape[0]):
|
| 107 |
+
valid = torch.nonzero(annotated[b] >= 0.5).flatten()
|
| 108 |
+
n = valid.numel()
|
| 109 |
+
if n == 0:
|
| 110 |
+
continue
|
| 111 |
+
if torch.rand((), device=annotated.device).item() < full_probability:
|
| 112 |
+
chosen = valid
|
| 113 |
+
else:
|
| 114 |
+
k = int(torch.randint(0, n + 1, (), device=annotated.device).item())
|
| 115 |
+
chosen = valid[torch.randperm(n, device=annotated.device)[:k]]
|
| 116 |
+
active[b, chosen] = 1.0
|
| 117 |
+
return active
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def binary_targets(mask, active=None):
|
| 121 |
+
"""[B, H, W] label map -> [B, 5, H, W] per-structure targets, emptied where not requested."""
|
| 122 |
+
targets = torch.stack([(mask == i + 1) for i in range(len(LABELS))], dim=1).float()
|
| 123 |
+
if active is not None:
|
| 124 |
+
targets = targets * active[:, :, None, None]
|
| 125 |
+
return targets
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def shuffle_prompts(*tensors):
|
| 129 |
+
"""Apply the same random permutation of the prompt axis (dim 1) to every tensor, per sample."""
|
| 130 |
+
b, n = tensors[0].shape[:2]
|
| 131 |
+
perm = torch.stack([torch.randperm(n, device=tensors[0].device) for _ in range(b)])
|
| 132 |
+
out = []
|
| 133 |
+
for t in tensors:
|
| 134 |
+
index = perm.view(b, n, *([1] * (t.ndim - 2))).expand(b, n, *t.shape[2:])
|
| 135 |
+
out.append(t.gather(1, index))
|
| 136 |
+
return out
|
p2echo/pvtv2.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PVTv2-B2 backbone (Wang et al., "PVT v2: Improved Baselines with Pyramid Vision Transformer")."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from functools import partial
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from timm.layers import DropPath, to_2tuple, trunc_normal_
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _init_weights(m):
|
| 12 |
+
if isinstance(m, nn.Linear):
|
| 13 |
+
trunc_normal_(m.weight, std=.02)
|
| 14 |
+
if m.bias is not None:
|
| 15 |
+
nn.init.constant_(m.bias, 0)
|
| 16 |
+
elif isinstance(m, nn.LayerNorm):
|
| 17 |
+
nn.init.constant_(m.bias, 0)
|
| 18 |
+
nn.init.constant_(m.weight, 1.0)
|
| 19 |
+
elif isinstance(m, nn.Conv2d):
|
| 20 |
+
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels // m.groups
|
| 21 |
+
m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
|
| 22 |
+
if m.bias is not None:
|
| 23 |
+
m.bias.data.zero_()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DWConv(nn.Module):
|
| 27 |
+
def __init__(self, dim):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
|
| 30 |
+
|
| 31 |
+
def forward(self, x, H, W):
|
| 32 |
+
B, N, C = x.shape
|
| 33 |
+
x = self.dwconv(x.transpose(1, 2).view(B, C, H, W))
|
| 34 |
+
return x.flatten(2).transpose(1, 2)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Mlp(nn.Module):
|
| 38 |
+
def __init__(self, in_features, hidden_features, drop=0.):
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
| 41 |
+
self.dwconv = DWConv(hidden_features)
|
| 42 |
+
self.act = nn.GELU()
|
| 43 |
+
self.fc2 = nn.Linear(hidden_features, in_features)
|
| 44 |
+
self.drop = nn.Dropout(drop)
|
| 45 |
+
self.apply(_init_weights)
|
| 46 |
+
|
| 47 |
+
def forward(self, x, H, W):
|
| 48 |
+
x = self.drop(self.act(self.dwconv(self.fc1(x), H, W)))
|
| 49 |
+
return self.drop(self.fc2(x))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class Attention(nn.Module):
|
| 53 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., sr_ratio=1):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.num_heads = num_heads
|
| 56 |
+
self.scale = (dim // num_heads) ** -0.5
|
| 57 |
+
self.q = nn.Linear(dim, dim, bias=qkv_bias)
|
| 58 |
+
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
|
| 59 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 60 |
+
self.proj = nn.Linear(dim, dim)
|
| 61 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 62 |
+
self.sr_ratio = sr_ratio
|
| 63 |
+
if sr_ratio > 1:
|
| 64 |
+
self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
|
| 65 |
+
self.norm = nn.LayerNorm(dim)
|
| 66 |
+
self.apply(_init_weights)
|
| 67 |
+
|
| 68 |
+
def forward(self, x, H, W):
|
| 69 |
+
B, N, C = x.shape
|
| 70 |
+
q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
|
| 71 |
+
if self.sr_ratio > 1:
|
| 72 |
+
x = self.sr(x.permute(0, 2, 1).reshape(B, C, H, W)).reshape(B, C, -1).permute(0, 2, 1)
|
| 73 |
+
x = self.norm(x)
|
| 74 |
+
kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 75 |
+
k, v = kv[0], kv[1]
|
| 76 |
+
attn = self.attn_drop(((q @ k.transpose(-2, -1)) * self.scale).softmax(dim=-1))
|
| 77 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 78 |
+
return self.proj_drop(self.proj(x))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class Block(nn.Module):
|
| 82 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
|
| 83 |
+
drop_path=0., norm_layer=nn.LayerNorm, sr_ratio=1):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.norm1 = norm_layer(dim)
|
| 86 |
+
self.attn = Attention(dim, num_heads, qkv_bias, attn_drop, drop, sr_ratio)
|
| 87 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 88 |
+
self.norm2 = norm_layer(dim)
|
| 89 |
+
self.mlp = Mlp(dim, int(dim * mlp_ratio), drop)
|
| 90 |
+
self.apply(_init_weights)
|
| 91 |
+
|
| 92 |
+
def forward(self, x, H, W):
|
| 93 |
+
x = x + self.drop_path(self.attn(self.norm1(x), H, W))
|
| 94 |
+
return x + self.drop_path(self.mlp(self.norm2(x), H, W))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class OverlapPatchEmbed(nn.Module):
|
| 98 |
+
def __init__(self, patch_size=7, stride=4, in_chans=3, embed_dim=768):
|
| 99 |
+
super().__init__()
|
| 100 |
+
patch_size = to_2tuple(patch_size)
|
| 101 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride,
|
| 102 |
+
padding=(patch_size[0] // 2, patch_size[1] // 2))
|
| 103 |
+
self.norm = nn.LayerNorm(embed_dim)
|
| 104 |
+
self.apply(_init_weights)
|
| 105 |
+
|
| 106 |
+
def forward(self, x):
|
| 107 |
+
x = self.proj(x)
|
| 108 |
+
_, _, H, W = x.shape
|
| 109 |
+
return self.norm(x.flatten(2).transpose(1, 2)), H, W
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class PyramidVisionTransformerV2(nn.Module):
|
| 113 |
+
def __init__(self, in_chans=3, embed_dims=(64, 128, 320, 512), num_heads=(1, 2, 5, 8),
|
| 114 |
+
mlp_ratios=(8, 8, 4, 4), qkv_bias=True, drop_rate=0., attn_drop_rate=0.,
|
| 115 |
+
drop_path_rate=0.1, norm_layer=partial(nn.LayerNorm, eps=1e-6),
|
| 116 |
+
depths=(3, 4, 6, 3), sr_ratios=(8, 4, 2, 1)):
|
| 117 |
+
super().__init__()
|
| 118 |
+
self.depths = depths
|
| 119 |
+
self.patch_embed1 = OverlapPatchEmbed(7, 4, in_chans, embed_dims[0])
|
| 120 |
+
self.patch_embed2 = OverlapPatchEmbed(3, 2, embed_dims[0], embed_dims[1])
|
| 121 |
+
self.patch_embed3 = OverlapPatchEmbed(3, 2, embed_dims[1], embed_dims[2])
|
| 122 |
+
self.patch_embed4 = OverlapPatchEmbed(3, 2, embed_dims[2], embed_dims[3])
|
| 123 |
+
|
| 124 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
|
| 125 |
+
cur = 0
|
| 126 |
+
for i in range(4):
|
| 127 |
+
blocks = nn.ModuleList([
|
| 128 |
+
Block(embed_dims[i], num_heads[i], mlp_ratios[i], qkv_bias, drop_rate, attn_drop_rate,
|
| 129 |
+
dpr[cur + j], norm_layer, sr_ratios[i])
|
| 130 |
+
for j in range(depths[i])])
|
| 131 |
+
setattr(self, f"block{i + 1}", blocks)
|
| 132 |
+
setattr(self, f"norm{i + 1}", norm_layer(embed_dims[i]))
|
| 133 |
+
cur += depths[i]
|
| 134 |
+
self.apply(_init_weights)
|
| 135 |
+
|
| 136 |
+
def forward(self, x):
|
| 137 |
+
B = x.shape[0]
|
| 138 |
+
outs = []
|
| 139 |
+
for i in range(1, 5):
|
| 140 |
+
x, H, W = getattr(self, f"patch_embed{i}")(x)
|
| 141 |
+
for blk in getattr(self, f"block{i}"):
|
| 142 |
+
x = blk(x, H, W)
|
| 143 |
+
x = getattr(self, f"norm{i}")(x)
|
| 144 |
+
x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
|
| 145 |
+
outs.append(x)
|
| 146 |
+
return outs
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def pvt_v2_b2():
|
| 150 |
+
return PyramidVisionTransformerV2()
|
p2echo/text_encoder.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen Qwen3-Embedding text encoder with an in-memory cache of prompt embeddings."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from transformers import AutoModel, AutoTokenizer
|
| 7 |
+
|
| 8 |
+
INSTRUCTION = ("Instruct: Given an anatomical term query, retrieve the precise anatomical entity "
|
| 9 |
+
"and location it represents\nQuery: ")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TextEncoder(nn.Module):
|
| 13 |
+
def __init__(self, model_name="Qwen/Qwen3-Embedding-0.6B", max_length=128):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 16 |
+
self.model = AutoModel.from_pretrained(model_name).eval().requires_grad_(False)
|
| 17 |
+
self.max_length = max_length
|
| 18 |
+
self.dim = self.model.config.hidden_size
|
| 19 |
+
self.cache = {}
|
| 20 |
+
|
| 21 |
+
@torch.no_grad()
|
| 22 |
+
def forward(self, prompts, device):
|
| 23 |
+
"""Returns [len(prompts), dim] L2-normalised last-token embeddings."""
|
| 24 |
+
self.model.to(device)
|
| 25 |
+
new = [p for p in prompts if p not in self.cache]
|
| 26 |
+
if new:
|
| 27 |
+
tokens = self.tokenizer([INSTRUCTION + p for p in new], padding=True, truncation=True,
|
| 28 |
+
max_length=self.max_length, return_tensors="pt").to(device)
|
| 29 |
+
hidden = self.model(**tokens).last_hidden_state
|
| 30 |
+
mask = tokens["attention_mask"]
|
| 31 |
+
if mask[:, -1].sum() == mask.shape[0]: # left padding
|
| 32 |
+
pooled = hidden[:, -1]
|
| 33 |
+
else:
|
| 34 |
+
pooled = hidden[torch.arange(hidden.shape[0], device=device), mask.sum(dim=1) - 1]
|
| 35 |
+
pooled = F.normalize(pooled.float(), p=2, dim=-1)
|
| 36 |
+
for p, e in zip(new, pooled):
|
| 37 |
+
self.cache[p] = e.cpu()
|
| 38 |
+
return torch.stack([self.cache[p] for p in prompts]).to(device)
|
p2echo/transformer.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prompt decoder: prompt tokens self-attend, then cross-attend to the bottleneck image tokens."""
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def sine_position_encoding_2d(height, width, dim):
|
| 12 |
+
"""2D sinusoidal encoding, returned as [height * width, 1, dim]."""
|
| 13 |
+
channels = int(math.ceil(dim / 4) * 2)
|
| 14 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, channels, 2).float() / channels))
|
| 15 |
+
|
| 16 |
+
def embed(n):
|
| 17 |
+
angles = torch.einsum("i,j->ij", torch.arange(n, dtype=torch.float32), inv_freq)
|
| 18 |
+
return torch.stack((angles.sin(), angles.cos()), dim=-1).flatten(-2, -1)
|
| 19 |
+
|
| 20 |
+
emb = torch.zeros(height, width, 2 * channels)
|
| 21 |
+
emb[:, :, :channels] = embed(height).unsqueeze(1)
|
| 22 |
+
emb[:, :, channels:] = embed(width)
|
| 23 |
+
return emb[:, :, :dim].reshape(height * width, 1, dim)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PromptDecoderLayer(nn.Module):
|
| 27 |
+
"""Post-norm layer: self-attention, cross-attention to image tokens, GELU FFN."""
|
| 28 |
+
|
| 29 |
+
def __init__(self, d_model=256, nhead=8, dim_feedforward=1024, dropout=0.1):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 32 |
+
self.cross_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 33 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward)
|
| 34 |
+
self.dropout = nn.Dropout(dropout)
|
| 35 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 36 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 37 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 38 |
+
self.norm3 = nn.LayerNorm(d_model)
|
| 39 |
+
self.dropout_sa = nn.Dropout(dropout)
|
| 40 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 41 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 42 |
+
|
| 43 |
+
def forward(self, tgt, memory, pos):
|
| 44 |
+
tgt = self.norm1(tgt + self.dropout_sa(self.self_attn(tgt, tgt, value=tgt)[0]))
|
| 45 |
+
attended = self.cross_attn(query=tgt, key=memory + pos, value=memory)[0]
|
| 46 |
+
tgt = self.norm2(tgt + self.dropout1(attended))
|
| 47 |
+
ffn = self.linear2(self.dropout(F.gelu(self.linear1(tgt))))
|
| 48 |
+
return self.norm3(tgt + self.dropout2(ffn))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class PromptDecoder(nn.Module):
|
| 52 |
+
def __init__(self, d_model=256, nhead=8, dim_feedforward=1024, num_layers=3, dropout=0.1):
|
| 53 |
+
super().__init__()
|
| 54 |
+
layer = PromptDecoderLayer(d_model, nhead, dim_feedforward, dropout)
|
| 55 |
+
self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)])
|
| 56 |
+
self.norm = nn.LayerNorm(d_model)
|
| 57 |
+
|
| 58 |
+
def forward(self, prompts, memory, pos):
|
| 59 |
+
"""prompts: [N, B, C], memory: [HW, B, C], pos: [HW, 1, C]."""
|
| 60 |
+
for layer in self.layers:
|
| 61 |
+
prompts = layer(prompts, memory, pos)
|
| 62 |
+
return self.norm(prompts)
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torchvision
|
| 2 |
+
timm
|
| 3 |
+
transformers
|
| 4 |
+
numpy<2
|
| 5 |
+
pillow
|