Explore 给我仔细讲一讲这个代码 %%writefile infer.py #!/usr/bin/env python3 """ Kaggle Inference - Optimized… Save Share Download ▾ Report给我仔细讲一讲这个代码 %%writefile infer.py
#!/usr/bin/env python3
"""
Kaggle Inference - Optimized 5-Fold Ensemble (Volume-wise, Dual-GPU)
Multiprocessing (spawn) version:
2 processes, each bound to one GPU
torch.compile (cudagraph) is stable across processes
volume is shared via CPU shared_memory once per volume
each process copies volume to its GPU once, slices patches on GPU
each process handles half patches by (patch_index % 2 == rank)
each process writes weighted_sum back to shared_memory; parent merges and normalizes
Fixes applied:
FP32 ensemble accumulation: softmax + prob_sum + mean are forced to float32.
Postprocess: clear3 -> hyst(0.90/0.50) -> z_close(1) -> rm(100) -> clear3 (final clear3 added).
Removed try/except error captures (errors will raise directly).
"""
import os
import time
import zipfile
from pathlib import Path
from typing import List, Tuple, Optional, Dict, Any
import numpy as np
import torch
import torch.multiprocessing as mp
from multiprocessing import shared_memory
from scipy import ndimage
from scipy.ndimage import generate_binary_structure
from skimage.morphology import remove_small_objects as skimage_remove_small
from tqdm import tqdm
import tifffile
from monai.networks.nets import SegResNetDS
==================== Fixed Config (DO NOT CHANGE) ====================
USE_TRAIN_FOR_TEST = True
TRAIN_TEST_LIMIT = 50
PATCH_SIZE = 160
STRIDE = 80
BATCH_SIZE = 8
USE_AMP = True
AMP_DTYPE = torch.float16
USE_PINNED_MEMORY = True
ENABLE_TF32 = True
CUDNN_BENCHMARK = True
torch.compile acceleration
USE_TORCH_COMPILE = False
COMPILE_MODE = "reduce-overhead" # "default", "reduce-overhead", "max-autotune"
Postprocess: clear3 -> hyst(0.90/0.50) -> z_close(1) -> rm(100)
CLEAR_BOUNDARY_WIDTH = 3
HYSTERESIS_HIGH = 0.90
HYSTERESIS_LOW = 0.50
Z_CLOSE_RADIUS = 1
RM_SMALL_MIN_SIZE = 100
=======================================================
5-fold checkpoints (fixed)
CHECKPOINTS = [
"/kaggle/input/segresnetds-patch/pytorch/default/11/best_checkpoints/fold0.ckpt",
"/kaggle/input/segresnetds-patch/pytorch/default/11/best_checkpoints/fold1.ckpt",
"/kaggle/input/segresnetds-patch/pytorch/default/11/best_checkpoints/fold2.ckpt",
"/kaggle/input/segresnetds-patch/pytorch/default/11/best_checkpoints/fold3.ckpt",
"/kaggle/input/segresnetds-patch/pytorch/default/11/best_checkpoints/fold4.ckpt",
]
NUM_FOLDS = 5
DATA_DIR = Path("/kaggle/input/vesuvius-challenge-surface-detection")
OUTPUT_DIR = Path("/kaggle/working")
TEST_DIR = DATA_DIR / ("train_images" if USE_TRAIN_FOR_TEST else "test_images")
DELETE_TIFS_AFTER_ZIP = True
Show full message · 547 lines AssistantCopy response Copy first prompt
Details Provider moonshot
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language Not recorded
Conversation date Feb 22, 2026
Added to archive Nov 22, 2026
ID 01m80erry9p5jm1w5z6k9wc5yzSource & license Imported from Zhiyaowang DataClaw Conversations (source ). Imported records earn no Research Points.
Upstream record: c827695a-4253-4337-bc86-cebe4b64c0ce
zhiyaowang/dataclaw-zhiyaowang, revision f5157333cbc22489661122a9bc5347b137144900. See upstream dataset card for attribution.
License: MIT
Cite this conversation “给我仔细讲一讲这个代码 %%writefile infer.py #!/usr/bin/env python3 """ Kaggle Inference - Optimized….” Conversation with kimi-k2.5, from the Zhiyaowang DataClaw Conversations dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m80erry9p5jm1w5z6k9wc5yz
==================== Utilities ==================== def make_starts(dim: int, patch_size: int, stride: int) -> List[int]:
if dim <= patch_size:
return [0]
starts = list(range(0, dim - patch_size + 1, stride))
if starts[-1] != dim - patch_size:
starts.append(dim - patch_size)
return starts
def get_gaussian_weight(size: int, sigma_scale: float = 0.125) -> torch.Tensor:
"""Return gaussian weight as CPU tensor (float32)."""
center = size // 2
sigma = size * sigma_scale
coords = torch.arange(size, dtype=torch.float32) - center
g1d = torch.exp(-(coords ** 2) / (2 * sigma ** 2))
return torch.einsum("i,j,k->ijk", g1d, g1d, g1d)
def clear_boundary(arr: np.ndarray, width: int) -> np.ndarray:
result = arr.copy()
result[:width, :, :] = 0
result[-width:, :, :] = 0
result[:, :width, :] = 0
result[:, -width:, :] = 0
result[:, :, :width] = 0
result[:, :, -width:] = 0
return result
def build_anisotropic_struct(z_radius: int, xy_radius: int):
z, r = z_radius, xy_radius
if z == 0 and r == 0:
return None
if z > 0 and r == 0:
struct = np.zeros((2 * z + 1, 1, 1), dtype=bool)
struct[:, 0, 0] = True
return struct
if z == 0 and r > 0:
size = 2 * r + 1
struct = np.zeros((1, size, size), dtype=bool)
cy, cx = r, r
for dy in range(-r, r + 1):
for dx in range(-r, r + 1):
if dy * dy + dx * dx <= r * r:
struct[0, cy + dy, cx + dx] = True
return struct
depth, size = 2 * z + 1, 2 * r + 1
struct = np.zeros((depth, size, size), dtype=bool)
cz, cy, cx = z, r, r
for dz in range(-z, z + 1):
for dy in range(-r, r + 1):
for dx in range(-r, r + 1):
if dy * dy + dx * dx <= r * r:
struct[cz + dz, cy + dy, cx + dx] = True
return struct
def apply_hysteresis(prob: np.ndarray, t_high: float, t_low: float) -> np.ndarray:
strong = prob >= t_high
weak = prob >= t_low
if not strong.any():
return np.zeros_like(prob, dtype=np.uint8)
struct = generate_binary_structure(3, 3)
mask = ndimage.binary_propagation(strong, mask=weak, structure=struct)
return mask.astype(np.uint8)
def apply_z_close(mask: np.ndarray, z_radius: int) -> np.ndarray:
if z_radius <= 0:
return mask
struct = build_anisotropic_struct(z_radius, 0)
if struct is not None:
mask = ndimage.binary_closing(mask.astype(bool), structure=struct)
return mask.astype(np.uint8)
def remove_small(mask: np.ndarray, min_size: int) -> np.ndarray:
return skimage_remove_small(mask.astype(bool), min_size=min_size).astype(np.uint8)
def postprocess_pipeline(prob: np.ndarray) -> np.ndarray:
# clear3 -> hyst -> z_close -> rm -> clear3
prob = clear_boundary(prob, CLEAR_BOUNDARY_WIDTH)
mask = apply_hysteresis(prob, HYSTERESIS_HIGH, HYSTERESIS_LOW)
mask = apply_z_close(mask, Z_CLOSE_RADIUS)
mask = remove_small(mask, RM_SMALL_MIN_SIZE)
mask = clear_boundary(mask, CLEAR_BOUNDARY_WIDTH) # final clear3
return mask
def load_volume(path: Path) -> np.ndarray:
vol = tifffile.imread(path)
if vol.ndim == 4:
vol = vol[0]
if vol.dtype == np.uint8:
vol = vol.astype(np.float32) / 255.0
else:
vol = vol.astype(np.float32)
return vol
def load_ckpt_state_and_init_filters(ckpt_path: str) -> Tuple[dict, int]:
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
state_dict = {k.replace("model.", ""): v for k, v in ckpt["state_dict"].items() if k.startswith("model.")}
init_filters = ckpt.get("hyper_parameters", {}).get("init_filters")
if init_filters is None:
w = state_dict.get("encoder.conv_init.weight")
init_filters = int(w.shape[0]) if w is not None else 32
return state_dict, int(init_filters)
def build_model(ckpt_path: str, device: str, use_compile: bool) -> torch.nn.Module:
state_dict, init_filters = load_ckpt_state_and_init_filters(ckpt_path)
code Copy code
model = SegResNetDS(
spatial_dims=3,
in_channels=1,
out_channels=2,
init_filters=init_filters,
dsdepth=3,
)
model.load_state_dict(state_dict)
model = model.to(device).eval()
if use_compile:
model = torch.compile(model, mode=COMPILE_MODE)
return model
def compute_weight_sum(shape: Tuple[int, int, int], ps: int, stride: int, g_np: np.ndarray) -> np.ndarray:
d, h, w = shape
starts_z = make_starts(d, ps, stride)
starts_y = make_starts(h, ps, stride)
starts_x = make_starts(w, ps, stride)
code Copy code
weight_sum = np.zeros((d, h, w), dtype=np.float32)
for z in starts_z:
for y in starts_y:
for x in starts_x:
weight_sum[z:z + ps, y:y + ps, x:x + ps] += g_np
return weight_sum
==================== SharedMemory helpers ==================== def shm_put_array(arr: np.ndarray, name: Optional[str] = None) -> Tuple[str, Tuple[int, ...], str]:
"""
Create shared memory and copy numpy array into it.
Returns (shm_name, shape, dtype_str)
"""
arr_c = np.ascontiguousarray(arr)
shm = shared_memory.SharedMemory(create=True, size=arr_c.nbytes, name=name)
buf = np.ndarray(arr_c.shape, dtype=arr_c.dtype, buffer=shm.buf)
buf[...] = arr_c
shm.close()
return shm.name, arr_c.shape, str(arr_c.dtype)
def shm_get_array(shm_name: str, shape: Tuple[int, ...], dtype_str: str) -> Tuple[shared_memory.SharedMemory, np.ndarray]:
shm = shared_memory.SharedMemory(name=shm_name, create=False)
arr = np.ndarray(shape, dtype=np.dtype(dtype_str), buffer=shm.buf)
return shm, arr
def shm_free(shm_name: str):
shm = shared_memory.SharedMemory(name=shm_name, create=False)
shm.close()
shm.unlink()
==================== Worker (spawn entry) ==================== def worker_main(
rank: int,
task_q: "mp.Queue",
result_q: "mp.Queue",
cfg: Dict[str, Any],
):
"""
rank 0 -> cuda:0
rank 1 -> cuda:1
Persistent worker loop until receives None.
"""
gpu_id = rank
torch.cuda.set_device(gpu_id)
device = torch.device(f"cuda:{gpu_id}")
code Copy code
# Backend flags (each process independently)
if cfg["CUDNN_BENCHMARK"]:
torch.backends.cudnn.benchmark = True
if cfg["ENABLE_TF32"]:
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
if hasattr(torch, "set_float32_matmul_precision"):
torch.set_float32_matmul_precision("high")
ps = cfg["PATCH_SIZE"]
stride = cfg["STRIDE"]
bs = cfg["BATCH_SIZE"]
use_amp = cfg["USE_AMP"]
amp_dtype = cfg["AMP_DTYPE"]
use_compile = cfg["USE_TORCH_COMPILE"]
# Load all fold models on this GPU
models: List[torch.nn.Module] = []
for ckpt in cfg["CHECKPOINTS"]:
m = build_model(ckpt, str(device), use_compile=use_compile)
models.append(m)
# Warmup compile
if use_compile:
dummy = torch.randn(1, 1, ps, ps, ps, device=device)
with torch.inference_mode():
for m in models:
if use_amp:
with torch.amp.autocast("cuda", dtype=amp_dtype):
_ = m(dummy)
else:
_ = m(dummy)
del dummy
torch.cuda.empty_cache()
# Gaussian weight
gaussian_cpu = cfg["GAUSSIAN_CPU"] # numpy array
g = torch.from_numpy(gaussian_cpu).to(device=device, dtype=torch.float32)
# Pre-alloc input buffer
inp_buf = torch.empty((bs, 1, ps, ps, ps), dtype=torch.float32, device=device)
# Pre-alloc fp32 prob_sum buffer (for max batch size)
prob_sum_buf = torch.empty((bs, ps, ps, ps), dtype=torch.float32, device=device)
while True:
task = task_q.get()
if task is None:
break
vol_id = task["vol_id"]
vol_shm_name = task["vol_shm_name"]
vol_shape = tuple(task["vol_shape"])
vol_dtype = task["vol_dtype"]
starts_z = task["starts_z"]
starts_y = task["starts_y"]
starts_x = task["starts_x"]
# Attach shared volume (CPU) and copy once to GPU
vol_shm, vol_np_view = shm_get_array(vol_shm_name, vol_shape, vol_dtype)
vol_tensor_cpu = torch.from_numpy(np.asarray(vol_np_view)) # view on shm
if cfg["USE_PINNED_MEMORY"]:
vol_tensor_cpu = vol_tensor_cpu.pin_memory()
vol_gpu = vol_tensor_cpu.to(device, non_blocking=True)
vol_shm.close()
d, h, w = vol_shape
weighted_sum_gpu = torch.zeros((d, h, w), dtype=torch.float32, device=device)
batch_coords: List[Tuple[int, int, int]] = []
patch_idx = 0
def run_batch(coords: List[Tuple[int, int, int]]):
b = len(coords)
if b == 0:
return
for i, (z, y, x) in enumerate(coords):
inp_buf[i, 0] = vol_gpu[z:z + ps, y:y + ps, x:x + ps]
inp = inp_buf[:b]
# -------- FP32 ensemble accumulation fix --------
prob_sum = prob_sum_buf[:b]
prob_sum.zero_()
with torch.inference_mode():
for m in models:
if use_amp:
with torch.amp.autocast("cuda", dtype=amp_dtype):
logits = m(inp)
else:
logits = m(inp)
if isinstance(logits, list):
logits = logits[0]
# softmax in fp32, accumulate in fp32
prob = torch.softmax(logits.float(), dim=1)[:, 1].to(torch.float32)
prob_sum.add_(prob)
prob_mean = prob_sum.mul_(1.0 / float(len(models))) # fp32
# ----------------------------------------------
for i, (z, y, x) in enumerate(coords):
weighted_sum_gpu[z:z + ps, y:y + ps, x:x + ps] += prob_mean[i] * g
for z in starts_z:
for y in starts_y:
for x in starts_x:
if (patch_idx % 2) == rank:
batch_coords.append((z, y, x))
if len(batch_coords) == bs:
run_batch(batch_coords)
batch_coords = []
patch_idx += 1
if batch_coords:
run_batch(batch_coords)
ws_cpu = weighted_sum_gpu.detach().cpu().numpy().astype(np.float32, copy=False)
ws_shm_name, ws_shape, ws_dtype = shm_put_array(ws_cpu)
del vol_gpu, weighted_sum_gpu, ws_cpu
torch.cuda.empty_cache()
result_q.put(
{
"vol_id": vol_id,
"rank": rank,
"ws_shm_name": ws_shm_name,
"ws_shape": ws_shape,
"ws_dtype": ws_dtype,
}
)
for m in models:
del m
torch.cuda.empty_cache()
==================== Main ==================== def main():
if torch.cuda.device_count() < 2:
raise RuntimeError("This script requires 2 GPUs.")
code Copy code
files = sorted(list(TEST_DIR.glob("*.tif")))
if USE_TRAIN_FOR_TEST and len(files) > TRAIN_TEST_LIMIT:
files = files[:TRAIN_TEST_LIMIT]
if not files:
raise RuntimeError(f"No tif files found in {TEST_DIR}")
stems = [p.stem for p in files]
print("=" * 70)
print("Optimized 5-Fold Ensemble Inference (spawn multi-process, dual-GPU)")
print("=" * 70)
print(f"USE_TRAIN_FOR_TEST={USE_TRAIN_FOR_TEST} files={len(files)} dir={TEST_DIR}")
print(f"PATCH_SIZE={PATCH_SIZE} STRIDE={STRIDE} BATCH_SIZE={BATCH_SIZE}")
print(f"AMP={USE_AMP} dtype={AMP_DTYPE} TF32={ENABLE_TF32}")
print(f"torch.compile={USE_TORCH_COMPILE} mode={COMPILE_MODE}")
print(
f"Postprocess: clear3 -> hyst({HYSTERESIS_HIGH}/{HYSTERESIS_LOW}) -> z_close({Z_CLOSE_RADIUS}) -> rm({RM_SMALL_MIN_SIZE}) -> clear3"
)
print("=" * 70)
gaussian_t = get_gaussian_weight(PATCH_SIZE)
gaussian_np = gaussian_t.numpy().astype(np.float32, copy=False)
ctx = mp.get_context("spawn")
task_q = ctx.Queue()
result_q = ctx.Queue()
cfg: Dict[str, Any] = {
"PATCH_SIZE": PATCH_SIZE,
"STRIDE": STRIDE,
"BATCH_SIZE": BATCH_SIZE,
"USE_AMP": USE_AMP,
"AMP_DTYPE": AMP_DTYPE,
"USE_PINNED_MEMORY": USE_PINNED_MEMORY,
"ENABLE_TF32": ENABLE_TF32,
"CUDNN_BENCHMARK": CUDNN_BENCHMARK,
"USE_TORCH_COMPILE": USE_TORCH_COMPILE,
"CHECKPOINTS": CHECKPOINTS,
"GAUSSIAN_CPU": gaussian_np,
}
print("\n[Init] Spawning 2 worker processes (each loads 5-fold models on its GPU)...")
spawn_ctx = mp.spawn(
worker_main,
args=(task_q, result_q, cfg),
nprocs=2,
join=False,
daemon=False,
)
t0_all = time.time()
out_names: List[str] = []
print(f"\n[Inference] Processing {len(files)} volumes ...")
for vol_id, path in enumerate(tqdm(files, desc="Volumes")):
vol = load_volume(path)
d, h, w = vol.shape
starts_z = make_starts(d, PATCH_SIZE, STRIDE)
starts_y = make_starts(h, PATCH_SIZE, STRIDE)
starts_x = make_starts(w, PATCH_SIZE, STRIDE)
weight_sum = compute_weight_sum((d, h, w), PATCH_SIZE, STRIDE, gaussian_np)
vol_shm_name, vol_shape, vol_dtype = shm_put_array(vol.astype(np.float32, copy=False))
del vol
task = {
"vol_id": vol_id,
"vol_shm_name": vol_shm_name,
"vol_shape": vol_shape,
"vol_dtype": vol_dtype,
"starts_z": starts_z,
"starts_y": starts_y,
"starts_x": starts_x,
}
task_q.put(task)
task_q.put(task)
res0 = result_q.get()
res1 = result_q.get()
if res0["vol_id"] != vol_id or res1["vol_id"] != vol_id:
raise RuntimeError("Result queue desync: volume id mismatch.")
if res0["rank"] == res1["rank"]:
raise RuntimeError("Both results came from the same rank; expected two ranks.")
ws_shm0, ws0_view = shm_get_array(res0["ws_shm_name"], tuple(res0["ws_shape"]), res0["ws_dtype"])
ws_shm1, ws1_view = shm_get_array(res1["ws_shm_name"], tuple(res1["ws_shape"]), res1["ws_dtype"])
ws0 = np.array(ws0_view, copy=True)
ws1 = np.array(ws1_view, copy=True)
ws_shm0.close()
ws_shm1.close()
shm_free(res0["ws_shm_name"])
shm_free(res1["ws_shm_name"])
shm_free(vol_shm_name)
weighted_sum_total = ws0 + ws1
prob_mean = weighted_sum_total / np.maximum(weight_sum, 1e-8)
prob_mean = prob_mean.astype(np.float32, copy=False)
pred = postprocess_pipeline(prob_mean)
out_path = OUTPUT_DIR / f"{stems[vol_id]}.tif"
tifffile.imwrite(str(out_path), pred.astype(np.uint8))
out_names.append(out_path.name)
del ws0, ws1, weighted_sum_total, weight_sum, prob_mean, pred
task_q.put(None)
task_q.put(None)
spawn_ctx.join()
print("\nZipping submission...")
zip_path = OUTPUT_DIR / "submission.zip"
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
for name in out_names:
fp = OUTPUT_DIR / name
zf.write(fp, name)
if DELETE_TIFS_AFTER_ZIP and fp.exists():
fp.unlink()
dt = time.time() - t0_all
print("=" * 70)
print(f"Submission: {zip_path}")
print(f"Inference Time: {dt:.1f}s")
print("=" * 70)
if name == "main ":
mp.set_start_method("spawn", force=True)
main()
这是一个用于 Kaggle Vesuvius Challenge 的3D体数据分割推理脚本。它采用了多进程双GPU并行、5-Fold模型集成、高斯加权融合等技术。让我详细拆解:
1. 整体架构
code Copy code
主进程 (Main) 工作进程 (Worker x2)
│ │
├── 加载体数据 -> SharedMemory ─>┤
├── 发送任务到 Queue ─────────>┤
│ ├── 加载5个fold模型到GPU
│ ├── 从SharedMemory读取体积
│ ├── GPU切片推理
│ └── 高斯加权累加
│<─ 从 Result Queue 接收结果 ──┘
├── 合并两个GPU的结果
├── 后处理 -> 保存TIF
2. 核心配置解析
python Copy code
PATCH_SIZE = 160 # 3D patch大小
STRIDE = 80 # 滑动窗口步长(50%重叠)
BATCH_SIZE = 8 # 每批次处理8个patch
USE_AMP = True # 使用FP16混合精度
USE_TORCH_COMPILE = False # torch.compile加速(spawn模式可能不稳定)
3. 关键函数详解
make_starts() - 计算滑动窗口起始位置
python Copy code
def make_starts(dim: int, patch_size: int, stride: int) -> List[int]:
if dim <= patch_size:
return [0]
starts = list(range(0, dim - patch_size + 1, stride))
if starts[-1] != dim - patch_size: # 确保覆盖边界
starts.append(dim - patch_size)
return starts
例如 dim=500, patch=160, stride=80:
code Copy code
starts = [0, 80, 160, 240, 320, 340] # 最后补充340确保覆盖边界
get_gaussian_weight() - 3D高斯权重
用于重叠区域融合,中心权重高,边缘权重低:
python Copy code
def get_gaussian_weight(size: int, sigma_scale: float = 0.125) -> torch.Tensor:
center = size // 2
sigma = size * sigma_scale # 默认 sigma = 160 * 0.125 = 20
coords = torch.arange(size, dtype=torch.float32) - center
g1d = torch.exp(-(coords ** 2) / (2 * sigma ** 2))
# 外积生成3D高斯核
return torch.einsum("i,j,k->ijk", g1d, g1d, g1d)
compute_weight_sum() - 计算归一化权重
python Copy code
def compute_weight_sum(shape, ps, stride, g_np):
weight_sum = np.zeros((d, h, w), dtype=np.float32)
for z, y, x in 所有patches:
weight_sum[z:z+ps, y:y+ps, x:x+ps] += g_np
return weight_sum
用于最终除以权重和,消除重叠区域的影响。
4. SharedMemory 机制
由于spawn模式无法共享全局变量,使用 multiprocessing.shared_memory:
python Copy code
def shm_put_array(arr):
# 创建共享内存,拷贝数组
shm = shared_memory.SharedMemory(create=True, size=arr.nbytes)
buf = np.ndarray(arr.shape, dtype=arr.dtype, buffer=shm.buf)
buf[...] = arr
return shm.name, arr.shape, str(arr.dtype)
def shm_get_array(shm_name, shape, dtype_str):
# 连接到已有共享内存
shm = shared_memory.SharedMemory(name=shm_name, create=False)
arr = np.ndarray(shape, dtype=np.dtype(dtype_str), buffer=shm.buf)
return shm, arr
5. Worker进程核心逻辑 (worker_main)
python Copy code
def worker_main(rank, task_q, result_q, cfg):
# rank 0 -> cuda:0, rank 1 -> cuda:1
torch.cuda.set_device(rank)
# 加载所有5个fold的模型到当前GPU
models = [build_model(ckpt, device, use_compile) for ckpt in cfg["CHECKPOINTS"]]
while True:
task = task_q.get()
if task is None: break
# 从SharedMemory读取体积
vol_shm, vol_view = shm_get_array(...)
vol_gpu = vol_view.to(device) # 一次性拷贝到GPU
# 只处理 patch_idx % 2 == rank 的patches
for patch_idx, (z,y,x) in enumerate(all_patches):
if patch_idx % 2 != rank:
continue
# 从GPU切片(避免CPU-GPU拷贝)
patch = vol_gpu[z:z+ps, y:y+ps, x:x+ps]
# 5-Fold推理
for model in models:
logits = model(patch)
prob_sum += softmax(logits)[:, 1]
prob_mean = prob_sum / 5
weighted_sum += prob_mean * gaussian_weight
# 结果写回SharedMemory
result_q.put({"ws_shm_name": ..., "ws_shape": ...})
6. 后处理流水线 (postprocess_pipeline)
python Copy code
def postprocess_pipeline(prob: np.ndarray) -> np.ndarray:
# 1. 清除边界3像素
prob = clear_boundary(prob, 3)
# 2. 滞后阈值 (高阈值0.9, 低阈值0.5)
mask = apply_hysteresis(prob, 0.90, 0.50)
# 3. Z轴闭运算 (连接相邻层)
mask = apply_z_close(mask, z_radius=1)
# 4. 移除小物体 (最小100体素)
mask = remove_small(mask, min_size=100)
# 5. 再次清除边界
mask = clear_boundary(mask, 3)
return mask
7. 主流程 (main)
python Copy code
def main():
# 1. 创建2个worker进程 (spawn模式)
mp.spawn(worker_main, nprocs=2, ...)
# 2. 遍历所有测试体积
for vol_id, path in enumerate(files):
# 加载体积 -> SharedMemory
vol = load_volume(path)
shm_put_array(vol)
# 发送相同任务到两个worker队列
task_q.put(task)
task_q.put(task)
# 收集两个GPU的结果
res0 = result_q.get()
res1 = result_q.get()
# 合并: 加权求和
weighted_sum = ws0 + ws1
prob_mean = weighted_sum / weight_sum
# 后处理 -> 保存
pred = postprocess_pipeline(prob_mean)
tifffile.imwrite(out_path, pred)
# 打包zip
with zipfile.ZipFile(...) as zf:
for name in out_names:
zf.write(name)
8. 关键技术点总结
技术 说明 Spawn多进程 每个进程独立CUDA上下文,避免GIL限制 SharedMemory 零拷贝共享大体积数据 GPU切片 体积一次性拷贝到GPU,后续纯GPU切片 奇偶分配 patch_idx % 2 == rank 实现负载均衡5-Fold集成 5个模型平均,FP32累加避免溢出 高斯加权 边缘渐变平滑融合重叠区 后处理链 边界清除→滞后阈值→Z闭运算→去噪
这个代码是一个高度优化的医学图像分割推理系统,充分利用了多GPU并行和内存优化技术。
Copy first response
Dataset releases Not yet included in a published release.