File size: 14,967 Bytes
fe8202e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#!/usr/bin/env python3
"""
SAM3 + LoRA 推理脚本 - 与 SegMamba 的 4_predict.py 保持一致的评估流程

读取 SegMamba 格式的预处理数据 (.npz),使用 SAM3 + LoRA + decoder 进行推理,
输出与 SegMamba 相同格式的预测结果。
"""

import argparse
import glob
import os
import sys
from pathlib import Path

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import SimpleITK as sitk
from tqdm import tqdm
import random

sys.path.insert(0, "/root/githubs/sam3")
sys.path.insert(0, "/root/githubs/SegMamba")

# Set determinism
random.seed(123)
np.random.seed(123)
torch.manual_seed(123)


def dice(pred, gt):
    """计算 Dice 系数"""
    pred = pred.astype(bool)
    gt = gt.astype(bool)
    intersection = np.sum(pred & gt)
    union = np.sum(pred) + np.sum(gt)
    if union == 0:
        return 1.0 if np.sum(pred) == 0 else 0.0
    return 2.0 * intersection / union


class MedSAM3DetectorSeg(nn.Module):
    """
    与训练时相同的模型结构:SAM3 detector backbone -> lightweight decoder -> mask logits
    4 类分割: 0=背景, 1=NCR, 2=ED, 3=ET
    """

    def __init__(self, sam3_detector: nn.Module, image_size: int = 1008, num_classes: int = 4):
        super().__init__()
        self.detector = sam3_detector
        self.image_size = int(image_size)
        self.num_classes = num_classes
        self.register_buffer("mean", torch.tensor([0.5, 0.5, 0.5]).view(1, 3, 1, 1))
        self.register_buffer("std", torch.tensor([0.5, 0.5, 0.5]).view(1, 3, 1, 1))

        # lightweight decoder; expects a 256-channel feature map from SAM3 backbone
        # 输出 num_classes 通道 (4 类分割)
        self.decoder = nn.Sequential(
            nn.Conv2d(256, 128, 3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
            nn.Conv2d(128, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
            nn.Conv2d(64, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
            nn.Conv2d(32, num_classes, 1),  # 4 类输出
        )

    def _preprocess(self, images: torch.Tensor) -> torch.Tensor:
        _, _, h, w = images.shape
        if h != self.image_size or w != self.image_size:
            images = F.interpolate(
                images, size=(self.image_size, self.image_size), mode="bilinear", align_corners=False
            )
        images = (images - self.mean.to(images.device)) / self.std.to(images.device)
        return images

    def _pick_feat(self, backbone_out) -> torch.Tensor:
        feat = None
        if isinstance(backbone_out, dict):
            if "sam3_features" in backbone_out:
                feat = backbone_out["sam3_features"]
            elif "features" in backbone_out:
                feat = backbone_out["features"]
            else:
                for _, v in backbone_out.items():
                    if isinstance(v, torch.Tensor) and v.ndim == 4:
                        feat = v
                        break
        elif isinstance(backbone_out, torch.Tensor):
            feat = backbone_out
        if feat is None or not isinstance(feat, torch.Tensor) or feat.ndim != 4:
            raise RuntimeError("Could not find a 4D feature map in SAM3 backbone output")
        return feat

    def forward(self, images: torch.Tensor) -> torch.Tensor:
        orig_h, orig_w = images.shape[-2:]
        x = self._preprocess(images)
        backbone_out = self.detector.backbone.forward_image(x)
        feat = self._pick_feat(backbone_out)
        logits = self.decoder(feat)  # (B, num_classes, ?, ?)
        if logits.shape[-2:] != (orig_h, orig_w):
            logits = F.interpolate(logits, size=(orig_h, orig_w), mode="bilinear", align_corners=False)
        return logits  # (B, num_classes, H, W)


def load_model(checkpoint_path: str, lora_weights: str, decoder_weights: str = None, device: str = "cuda"):
    """加载 SAM3 + LoRA 模型"""
    from sam3.model_builder import build_sam3_video_model
    from lora import apply_lora_to_model, load_lora_weights

    print(f"Loading SAM3 from: {checkpoint_path}")
    sam3 = build_sam3_video_model(
        checkpoint_path=checkpoint_path,
        load_from_HF=False,
        device=device,
        apply_temporal_disambiguation=True,
    )

    # 创建分割模型 (4 类: 背景 + 3 类肿瘤)
    model = MedSAM3DetectorSeg(sam3.detector, image_size=1008, num_classes=4)

    # 注入 LoRA
    target_modules = ["q_proj", "k_proj", "v_proj", "out_proj", "qkv", "proj"]
    print(f"Applying LoRA to detector...")
    apply_lora_to_model(
        model.detector,
        rank=8,
        alpha=16.0,
        dropout=0.0,
        target_modules=target_modules,
        exclude_modules=[],
    )

    # 加载 LoRA 权重
    print(f"Loading LoRA weights from: {lora_weights}")
    load_lora_weights(model.detector, lora_weights)

    # 加载 decoder 权重
    if decoder_weights is not None:
        decoder_path = Path(decoder_weights)
    else:
        decoder_path = Path(lora_weights).parent / "best_decoder_weights.pt"
    
    if decoder_path.exists():
        print(f"Loading decoder weights from: {decoder_path}")
        decoder_state = torch.load(decoder_path, map_location="cpu")
        model.decoder.load_state_dict(decoder_state)
    else:
        print(f"WARNING: Decoder weights not found at {decoder_path}")
        print("The model will use randomly initialized decoder - predictions will be wrong!")
        print("Please retrain with the updated training script that saves decoder weights.")

    model = model.to(device)
    model.eval()
    return model


def convert_labels(labels):
    """
    转换标签为 3 通道 (TC, WT, ET)
    - TC (Tumor Core): label==1 或 label==3
    - WT (Whole Tumor): label==1 或 label==2 或 label==3
    - ET (Enhancing Tumor): label==3
    """
    result = [
        (labels == 1) | (labels == 3),  # TC
        (labels == 1) | (labels == 2) | (labels == 3),  # WT
        labels == 3,  # ET
    ]
    return np.stack(result, axis=0).astype(np.float32)


def predict_volume(model, volume_4d: np.ndarray, modality: int = 0, 
                   target_size: int = 512, device: str = "cuda") -> np.ndarray:
    """
    对 4D volume 进行 4 类分割预测
    
    Args:
        model: 分割模型 (输出 4 类)
        volume_4d: (4, D, H, W) 的 4 模态 3D volume
        modality: 使用的模态索引(0=T1, 1=T1ce, 2=T2, 3=FLAIR)
        target_size: 目标尺寸
        device: 计算设备
    
    Returns:
        pred_3d: (D, H, W) 的类别预测 (0=背景, 1=NCR, 2=ED, 3=ET)
    """
    # 提取指定模态
    volume = volume_4d[modality]  # (D, H, W)
    D, H, W = volume.shape
    
    pred_3d = np.zeros((D, H, W), dtype=np.uint8)
    
    with torch.no_grad():
        for z in range(D):
            slice_2d = volume[z]  # (H, W)
            
            # 归一化到 [0, 1]
            v_min, v_max = slice_2d.min(), slice_2d.max()
            if v_max > v_min:
                slice_2d = (slice_2d - v_min) / (v_max - v_min)
            else:
                slice_2d = np.zeros_like(slice_2d)
            
            # 转为 3 通道 RGB
            slice_rgb = np.stack([slice_2d] * 3, axis=0)  # (3, H, W)
            
            # Resize to target size
            slice_tensor = torch.from_numpy(slice_rgb).float().unsqueeze(0)  # (1, 3, H, W)
            if H != target_size or W != target_size:
                slice_tensor = F.interpolate(slice_tensor, size=(target_size, target_size), 
                                            mode="bilinear", align_corners=False)
            
            slice_tensor = slice_tensor.to(device)
            
            # 推理 - 4 类输出
            logits = model(slice_tensor)  # (1, 4, H, W)
            pred_class = logits.argmax(dim=1)  # (1, H, W)
            
            # Resize back to original size
            if H != target_size or W != target_size:
                pred_class = F.interpolate(pred_class.unsqueeze(1).float(), size=(H, W), 
                                          mode="nearest").squeeze(1).long()
            
            pred_3d[z] = pred_class[0].cpu().numpy()
    
    return pred_3d


def labels_to_regions(pred_3d: np.ndarray) -> dict:
    """
    将 4 类预测转换为 TC/WT/ET 区域
    
    BraTS 标签:
        0: 背景
        1: NCR (Necrotic tumor core)
        2: ED (Peritumoral Edema)
        3: ET (Enhancing tumor)
    
    区域定义:
        TC (Tumor Core) = NCR + ET = label 1 + label 3
        WT (Whole Tumor) = NCR + ED + ET = label 1 + label 2 + label 3
        ET (Enhancing Tumor) = label 3
    """
    tc = ((pred_3d == 1) | (pred_3d == 3)).astype(np.uint8)
    wt = ((pred_3d == 1) | (pred_3d == 2) | (pred_3d == 3)).astype(np.uint8)
    et = (pred_3d == 3).astype(np.uint8)
    return {"TC": tc, "WT": wt, "ET": et}


def main():
    parser = argparse.ArgumentParser(description="SAM3+LoRA inference for BraTS2023 (SegMamba-compatible)")
    
    # 数据参数
    parser.add_argument("--data_dir", type=str, default="/data/yty/brats23_processed",
                        help="Preprocessed data directory (contains *.npz)")
    parser.add_argument("--split", type=str, default="test", choices=["train", "val", "test", "all"])
    parser.add_argument("--train_rate", type=float, default=0.7)
    parser.add_argument("--val_rate", type=float, default=0.1)
    parser.add_argument("--test_rate", type=float, default=0.2)
    parser.add_argument("--seed", type=int, default=42)
    
    # 模型参数
    parser.add_argument("--checkpoint", type=str, default="/data/yty/sam3/sam3.pt",
                        help="SAM3 checkpoint path")
    parser.add_argument("--lora_weights", type=str, 
                        default="/data/yty/brats23_sam3_video_lora_bestonly_122/checkpoints/best_lora_weights.pt",
                        help="LoRA weights path")
    parser.add_argument("--decoder_weights", type=str, default=None,
                        help="Decoder weights path (default: auto-detect from lora_weights dir)")
    parser.add_argument("--modality", type=int, default=0,
                        help="Which modality to use (0=T1, 1=T1ce, 2=T2, 3=FLAIR)")
    parser.add_argument("--target_size", type=int, default=512,
                        help="Target image size for inference")
    
    # 输出参数
    parser.add_argument("--save_dir", type=str, default="/data/yty/brats23_sam3_predictions",
                        help="Directory to save predictions")
    parser.add_argument("--device", type=str, default="cuda:0")
    parser.add_argument("--raw_spacing", type=str, default="1,1,1")
    parser.add_argument("--print_dice", action="store_true", help="Print dice for each case")
    
    args = parser.parse_args()
    
    raw_spacing = [float(x) for x in args.raw_spacing.split(",")]
    
    # 加载模型
    model = load_model(args.checkpoint, args.lora_weights, args.decoder_weights, args.device)
    
    # 获取数据集
    all_paths = sorted(glob.glob(os.path.join(args.data_dir, "*.npz")))
    all_names = [os.path.splitext(os.path.basename(p))[0] for p in all_paths]
    
    if args.split == "all":
        cases = list(zip(all_names, all_paths))
    else:
        # 按比例划分
        n = len(all_names)
        indices = list(range(n))
        rng = np.random.RandomState(args.seed)
        rng.shuffle(indices)
        
        n_train = int(n * args.train_rate)
        n_val = int(n * args.val_rate)
        
        train_idx = indices[:n_train]
        val_idx = indices[n_train:n_train + n_val]
        test_idx = indices[n_train + n_val:]
        
        split_map = {"train": train_idx, "val": val_idx, "test": test_idx}
        selected_idx = split_map[args.split]
        
        cases = [(all_names[i], all_paths[i]) for i in selected_idx]
    
    print(f"Found {len(cases)} cases for split '{args.split}'")
    
    os.makedirs(args.save_dir, exist_ok=True)
    
    all_dices = []
    
    for case_name, npz_path in tqdm(cases, desc="Predicting"):
        # 加载数据
        data = np.load(npz_path)
        image_4d = data["data"]  # (4, D, H, W)
        seg = data.get("seg", None)  # (1, D, H, W) or None
        
        # 预测 - 4 类分割
        pred_classes = predict_volume(model, image_4d, modality=args.modality, 
                                      target_size=args.target_size, device=args.device)
        
        # 转换为 TC/WT/ET 区域
        pred_regions = labels_to_regions(pred_classes)
        D, H, W = pred_classes.shape
        pred_3c = np.stack([pred_regions["TC"], pred_regions["WT"], pred_regions["ET"]], axis=0)
        
        # 计算 dice(如果有 GT)
        if seg is not None and args.print_dice:
            gt = seg[0]  # (D, H, W)
            gt_3c = convert_labels(gt)
            
            dices = []
            for i, name in enumerate(["TC", "WT", "ET"]):
                d = dice(pred_3c[i], gt_3c[i])
                dices.append(d)
            
            # 也计算整体 tumor 的 dice
            gt_binary = (gt > 0).astype(np.float32)
            pred_binary = (pred_classes > 0).astype(np.float32)
            overall_dice = dice(pred_binary, gt_binary)
            
            print(f"{case_name}: TC={dices[0]:.4f}, WT={dices[1]:.4f}, ET={dices[2]:.4f}, Overall={overall_dice:.4f}")
            all_dices.append({
                "case": case_name,
                "TC": dices[0],
                "WT": dices[1],
                "ET": dices[2],
                "Overall": overall_dice,
            })
        
        # 保存预测
        out_path = os.path.join(args.save_dir, f"{case_name}.nii.gz")
        pred_itk = sitk.GetImageFromArray(pred_3c, isVector=False)
        pred_itk.SetSpacing((raw_spacing[0], raw_spacing[1], raw_spacing[2], 1.0))
        sitk.WriteImage(pred_itk, out_path)
    
    # 汇总结果
    if all_dices:
        print("\n" + "=" * 60)
        print(f"Results Summary ({len(all_dices)} cases):")
        avg_tc = np.mean([d["TC"] for d in all_dices])
        avg_wt = np.mean([d["WT"] for d in all_dices])
        avg_et = np.mean([d["ET"] for d in all_dices])
        avg_overall = np.mean([d["Overall"] for d in all_dices])
        print(f"  Average TC Dice:      {avg_tc:.4f}")
        print(f"  Average WT Dice:      {avg_wt:.4f}")
        print(f"  Average ET Dice:      {avg_et:.4f}")
        print(f"  Average Overall Dice: {avg_overall:.4f}")
        print("=" * 60)
        
        # 保存结果
        np.save(os.path.join(args.save_dir, "metrics.npy"), all_dices, allow_pickle=True)


if __name__ == "__main__":
    main()