yongkytristan/stroke-app / inference.py
yongkytristan's picture
download
raw
6.77 kB
"""Load checkpoint Phase 3 dan prediksi mask lesi (volume penuh atau satu slice) dari NCCT terpreproses."""
from pathlib import Path
import numpy as np
import torch
from model import STUDENT_NAMES, build_model, convert_state_dict
DECODER_NAMES = {'attention': 'Attention U-Net', 'umamba': 'U-Mamba'}
def default_device():
return 'cuda' if torch.cuda.is_available() else 'cpu'
def _torch_load(path, **kwargs):
try:
return torch.load(path, map_location='cpu', weights_only=False, **kwargs)
except TypeError: # torch lama tanpa argumen mmap
kwargs.pop('mmap', None)
return torch.load(path, map_location='cpu', weights_only=False, **kwargs)
def read_meta(path):
"""Info ringan tanpa membangun model (dipakai untuk daftar checkpoint di sidebar)."""
try:
ck = _torch_load(path, mmap=True)
except Exception: # noqa: BLE001 - file lama/zip non-standar
ck = _torch_load(path)
config = ck.get('config', {}) if isinstance(ck, dict) else {}
decoder = config.get('DECODER', 'attention')
return {
'student': config.get('STUDENT', '?'),
'student_name': STUDENT_NAMES.get(config.get('STUDENT'), config.get('STUDENT', '?')),
'decoder': decoder,
'decoder_name': DECODER_NAMES.get(decoder, decoder),
'kd': config.get('TEACHER') if config.get('USE_DISTILL') else None,
}
def load_checkpoint(path, device=None, mamba_impl='cuda'):
"""Kembalikan (model, info). Mendukung checkpoint penuh `_best.pth` maupun versi ramping.
mamba_impl (decoder U-Mamba saja): 'cuda' = mamba-ssm di GPU, 'torch' = MambaTorch, selalu di CPU.
"""
ck = _torch_load(path)
if 'model_state_dict' not in ck or 'config' not in ck:
raise KeyError('%s bukan checkpoint Phase 3 (butuh model_state_dict + config)' % Path(path).name)
config = ck['config']
decoder = config.get('DECODER', 'attention')
if decoder != 'umamba':
mamba_impl = None
device = 'cpu' if mamba_impl == 'torch' else (device or default_device())
model = build_model(config, mamba_impl or 'cuda')
model.load_state_dict(convert_state_dict(ck['model_state_dict']), strict=True)
model.to(device).eval()
threshold = ck.get('threshold')
info = {
'file': Path(path).name,
'student': config['STUDENT'],
'student_name': STUDENT_NAMES.get(config['STUDENT'], config['STUDENT']),
'decoder': decoder,
'decoder_name': DECODER_NAMES.get(decoder, decoder),
'mamba_impl': mamba_impl,
'kd': config.get('TEACHER') if config.get('USE_DISTILL') else None,
'slice_context': int(config.get('SLICE_CONTEXT', 3)),
'out_grid': int(config.get('ENCODER_OUT_GRID', 8)),
'run_tag': ck.get('run_tag'),
'val_dice': ck.get('val_dice_patient'),
'test_dice': ck.get('test_dice_patient'),
'threshold': float(threshold) if threshold is not None else 0.5,
'threshold_from_val': threshold is not None,
'epoch': ck.get('epoch'),
'weights': ck.get('weights', 'ema'),
'params': sum(p.numel() for p in model.parameters()),
'device': device,
}
return model, info
def slim_checkpoint(src, dst):
"""Simpan versi ramping (hanya bobot + threshold + config) supaya file kecil untuk deploy."""
ck = _torch_load(src)
torch.save({'model_state_dict': ck['model_state_dict'], 'threshold': ck.get('threshold'),
'config': ck['config'], 'epoch': ck.get('epoch'), 'weights': ck.get('weights', 'ema')}, dst)
def as_volume(array):
"""Terima array 2D (H, W) atau 3D (H, W, Z) -> float32 (H, W, Z)."""
array = np.asarray(array, dtype=np.float32)
array = np.squeeze(array) if array.ndim > 3 else array
if array.ndim == 2:
array = array[:, :, None]
if array.ndim != 3:
raise ValueError('volume harus 2D (H, W) atau 3D (H, W, Z), didapat bentuk %s' % (array.shape,))
return np.nan_to_num(array, nan=0.0, posinf=0.0, neginf=0.0)
def slice_stack(volume, z, channels=3, context='neighbors'):
"""Input model untuk slice z -> (H, W, channels).
context='neighbors': slice tetangga asli (z-1, z, z+1), tepi diulang. Sama dengan StrokeDataset Phase 3.
context='single' : slice z saja, diulang sebanyak channels (untuk input 1 slice / perbandingan).
"""
depth = volume.shape[2]
if context == 'single':
index = [z] * channels
else:
half = (channels - 1) // 2
index = [min(max(z + d, 0), depth - 1) for d in range(-half, half + 1)]
return volume[:, :, index]
@torch.no_grad()
def predict_slices(model, volume, zs, slice_context=3, context='neighbors', tta=True, batch_size=8,
device=None, progress=None):
"""Probabilitas lesi untuk slice-slice zs -> (H, W, len(zs)) di 0..1."""
device = device or next(model.parameters()).device
volume = as_volume(volume)
zs = list(zs)
H, W = volume.shape[:2]
probs = np.zeros((H, W, len(zs)), dtype=np.float32)
for start in range(0, len(zs), batch_size):
chunk = zs[start:start + batch_size]
x = np.stack([slice_stack(volume, z, slice_context, context) for z in chunk]) # (B, H, W, C)
x = torch.from_numpy(x).permute(0, 3, 1, 2).contiguous().to(device) # (B, C, H, W)
p = torch.sigmoid(model(x))
if tta:
pf = torch.sigmoid(model(torch.flip(x, dims=[3])))
p = 0.5 * (p + torch.flip(pf, dims=[3]))
probs[:, :, start:start + len(chunk)] = p[:, 0].permute(1, 2, 0).float().cpu().numpy()
if progress is not None:
progress(min(start + batch_size, len(zs)) / len(zs))
return probs
def predict_volume(model, volume, slice_context=3, tta=True, batch_size=8, device=None, progress=None):
"""Semua slice dengan tetangga asli -> (H, W, Z)."""
volume = as_volume(volume)
return predict_slices(model, volume, range(volume.shape[2]), slice_context, 'neighbors', tta,
batch_size, device, progress)
def dice(pred, gt):
"""Dice; None kalau prediksi dan ground truth sama-sama kosong (tidak terdefinisi)."""
pred, gt = pred.astype(bool), gt.astype(bool)
denom = pred.sum() + gt.sum()
return float(2.0 * (pred & gt).sum() / denom) if denom > 0 else None
if __name__ == '__main__':
# Rampingkan checkpoint: python inference.py slim <_best.pth asli> <weights/nama.pth>
import sys
if len(sys.argv) == 4 and sys.argv[1] == 'slim':
slim_checkpoint(sys.argv[2], sys.argv[3])
print('tersimpan:', sys.argv[3])
else:
print('pemakaian: python inference.py slim <checkpoint_asli.pth> <weights/hasil.pth>')

Xet Storage Details

Size:
6.77 kB
·
Xet hash:
986b02b6470714a9dc7fb2aba8fc67cb4ec02cbd4673c9a973b14215facb6039

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.