yongkytristan's picture
download
raw
21.1 kB
"""Arsitektur model Phase 3 (encoder Phase 2 + decoder Attention U-Net / U-Mamba) untuk inferensi.
Disalin dari notebook Phase 3 terbaru (phase_3_final, nama atribut identik, checkpoint `_best.pth` termuat
strict). Checkpoint lama (decoder4..decoder1, bottleneck grid 8) tetap bisa dimuat lewat convert_state_dict.
Bongkar pasang: encoder (EfficientNet-B3 / ResNet-50 / Swin V2 Tiny) dan decoder (attention / umamba)
dibaca otomatis dari `config` di dalam checkpoint, jadi cukup taruh file .pth baru di folder weights/.
Decoder U-Mamba punya dua implementasi Mamba dengan bobot yang sama: 'cuda' (paket mamba-ssm, butuh GPU CUDA,
sama dengan training) dan 'torch' (MambaTorch, PyTorch murni, jalan di CPU). Decoder attention jalan di mana saja.
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
# ------------------------------------------------------------------ tabel channel per grid (sama dengan notebook)
STUDENT_CHANNELS = {
'resnet50': {128: 64, 64: 256, 32: 512, 16: 1024},
'efficientnetb3': {128: 40, 64: 32, 32: 48, 16: 136},
'swinv2tiny': {128: 0, 64: 96, 32: 192, 16: 384},
}
STUDENT_SKIP_ORDER = {
'resnet50': (128, 64, 32, 16),
'efficientnetb3': (128, 64, 32, 16),
'swinv2tiny': (64, 32, 16),
}
STUDENT_OUT_CHANNELS = {
'resnet50': 2048,
'efficientnetb3': 1536,
'swinv2tiny': 768,
}
SWIN_STEM_CHANNELS = 32
STUDENT_NAMES = {
'efficientnetb3': 'EfficientNet-B3',
'resnet50': 'ResNet-50',
'swinv2tiny': 'Swin V2 Tiny',
}
# ------------------------------------------------------------------ konversi conv pertama ke N channel
def _convert_to_1ch(conv):
new = nn.Conv2d(1, conv.out_channels, conv.kernel_size, conv.stride,
conv.padding, bias=conv.bias is not None)
with torch.no_grad():
new.weight.copy_(conv.weight.sum(dim=1, keepdim=True))
if conv.bias is not None:
new.bias.copy_(conv.bias)
return new
def _convert_to_nch(conv, n):
if n == 1:
return _convert_to_1ch(conv)
single = _convert_to_1ch(conv)
new = nn.Conv2d(n, conv.out_channels, conv.kernel_size, conv.stride,
conv.padding, bias=conv.bias is not None)
with torch.no_grad():
new.weight.copy_(single.weight.repeat(1, n, 1, 1) / float(n))
if conv.bias is not None:
new.bias.copy_(single.bias)
return new
# ------------------------------------------------------------------ encoder (bobot ditimpa checkpoint)
# [P3-OUTGRID] out_grid = grid tempat bottleneck diambil. 8 = e4@8 (run lama), 16 = e3@16 (pipeline terbaru,
# ENCODER_OUT_GRID 16): stage terakhir encoder tidak dieksekusi, decoder punya 3 blok.
class ResNet50Encoder(nn.Module):
GRID_STAGE = {128: 0, 64: 1, 32: 2, 16: 3, 8: 4}
def __init__(self, in_channels=3, out_grid=8):
super().__init__()
trunk = models.resnet50(weights=None)
trunk.fc = nn.Identity()
trunk.conv1 = _convert_to_nch(trunk.conv1, in_channels)
self.in_channels = in_channels
self.out_grid = int(out_grid)
self.stop_stage = self.GRID_STAGE[self.out_grid]
self.conv1 = trunk.conv1
self.bn1 = trunk.bn1
self.relu = trunk.relu
self.maxpool = trunk.maxpool
self.layer1 = trunk.layer1
self.layer2 = trunk.layer2
self.layer3 = trunk.layer3
self.layer4 = trunk.layer4
def forward(self, x):
taps = []
x = self.relu(self.bn1(self.conv1(x)))
taps.append(x) # 64 @ 128
if self.stop_stage == 0:
return taps[0], []
x = self.layer1(self.maxpool(x))
taps.append(x) # 256 @ 64
if self.stop_stage == 1:
return taps[1], taps[:1]
x = self.layer2(x)
taps.append(x) # 512 @ 32
if self.stop_stage == 2:
return taps[2], taps[:2]
x = self.layer3(x)
taps.append(x) # 1024 @ 16
if self.stop_stage == 3:
return taps[3], taps[:3]
x = self.layer4(x)
taps.append(x) # 2048 @ 8
return taps[4], taps[:4]
class EfficientNetB3Encoder(nn.Module):
GRID_STAGE = {128: 0, 64: 2, 32: 3, 16: 5, 8: 8}
def __init__(self, in_channels=3, out_grid=8):
super().__init__()
base = models.efficientnet_b3(weights=None)
base.features[0][0] = _convert_to_nch(base.features[0][0], in_channels)
self.in_channels = in_channels
self.out_grid = int(out_grid)
self.stop_index = self.GRID_STAGE[self.out_grid]
self.features = base.features
def forward(self, x):
by_index = {}
for index, layer in enumerate(self.features):
x = layer(x)
if index in self.GRID_STAGE.values():
by_index[index] = x
if index >= self.stop_index:
break
deep = by_index[self.stop_index]
skips = [by_index[self.GRID_STAGE[g]] for g in (128, 64, 32, 16)
if g in self.GRID_STAGE and g > self.out_grid]
return deep, skips
class SwinV2TinyEncoder(nn.Module):
GRID_STAGE = {64: 1, 32: 3, 16: 5, 8: 7}
def __init__(self, in_channels=3, out_grid=8):
super().__init__()
base = models.swin_v2_t(weights=None)
base.features[0][0] = _convert_to_nch(base.features[0][0], in_channels)
self.in_channels = in_channels
self.out_grid = int(out_grid)
self.stop_index = self.GRID_STAGE[self.out_grid]
self.features = base.features
self.norm = base.norm
def forward(self, x):
by_index = {}
for index, layer in enumerate(self.features):
x = layer(x)
if index in self.GRID_STAGE.values():
by_index[index] = x
if index >= self.stop_index:
break
raw = by_index[self.stop_index]
deep = self.norm(raw) if self.stop_index == 7 else raw
to_nchw = lambda t: t.permute(0, 3, 1, 2).contiguous()
skips = [to_nchw(by_index[self.GRID_STAGE[g]]) for g in (64, 32, 16) if g > self.out_grid]
return to_nchw(deep), skips
ENCODER_REGISTRY = {
'resnet50': ResNet50Encoder,
'efficientnetb3': EfficientNetB3Encoder,
'swinv2tiny': SwinV2TinyEncoder,
}
class EncoderModule(nn.Module):
def __init__(self, model, in_ch=3, out_grid=8):
super().__init__()
if model not in ENCODER_REGISTRY:
raise ValueError('encoder %r tidak dikenal; pilihan: %s' % (model, tuple(ENCODER_REGISTRY)))
stage_channels = {**STUDENT_CHANNELS[model], 8: STUDENT_OUT_CHANNELS[model]}
self.model = model
self.in_channels = int(in_ch)
self.out_grid = int(out_grid)
if self.out_grid not in stage_channels or stage_channels[self.out_grid] == 0:
raise ValueError('%s tidak punya grid %d' % (model, self.out_grid))
self.out_channels = int(stage_channels[self.out_grid])
self.skip_grids = tuple(g for g in STUDENT_SKIP_ORDER[model] if g > self.out_grid)
self.grid_channels = {g: int(STUDENT_CHANNELS[model][g]) for g in self.skip_grids}
self.body = ENCODER_REGISTRY[model](in_channels=self.in_channels, out_grid=self.out_grid)
def forward(self, x):
return self.body(x)
class ConvStem(nn.Module):
"""Skip 128x128 untuk Swin (fitur pertama Swin baru 64x64)."""
def __init__(self, in_channels, out_channels=SWIN_STEM_CHANNELS):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, stride=2, padding=1, bias=False),
nn.InstanceNorm2d(out_channels, affine=True),
nn.LeakyReLU(0.01, inplace=True),
nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
nn.InstanceNorm2d(out_channels, affine=True),
nn.LeakyReLU(0.01, inplace=True),
)
self.out_channels = out_channels
def forward(self, x):
return self.block(x)
# ------------------------------------------------------------------ decoder Attention U-Net
class AttentionGate(nn.Module):
def __init__(self, g_ch, x_ch, out_ch):
super().__init__()
self.Wx = nn.Sequential(nn.Conv2d(x_ch, out_ch, kernel_size=1, bias=False))
self.Wg = nn.Sequential(nn.Conv2d(g_ch, out_ch, kernel_size=1))
self.psi = nn.Sequential(nn.Conv2d(out_ch, 1, kernel_size=1, bias=True), nn.Sigmoid())
self.W = nn.Sequential(nn.Conv2d(x_ch, x_ch, kernel_size=1), nn.BatchNorm2d(x_ch))
self.relu = nn.ReLU(inplace=True)
def forward(self, g, x):
return self.W(x * self.psi(self.relu(self.Wg(g) + self.Wx(x))))
class AttentionConvBlock(nn.Module):
def __init__(self, in_ch, out_ch, dropout=0.0):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1, bias=False),
nn.BatchNorm2d(out_ch),
nn.LeakyReLU(0.01, inplace=True),
nn.Dropout2d(dropout) if dropout > 0 else nn.Identity(),
nn.Conv2d(out_ch, out_ch, 3, padding=1, bias=False),
nn.BatchNorm2d(out_ch),
nn.LeakyReLU(0.01, inplace=True),
)
def forward(self, x):
return self.conv(x)
class AttentionDecoderBlock(nn.Module):
def __init__(self, in_ch, skip_ch, out_ch, dropout=0.0):
super().__init__()
self.gate = AttentionGate(in_ch, skip_ch, out_ch)
self.conv = AttentionConvBlock(in_ch + skip_ch, out_ch, dropout)
def forward(self, x, skip):
if x.shape[2:] != skip.shape[2:]:
x = F.interpolate(x, size=skip.shape[2:], mode='bilinear', align_corners=False)
return self.conv(torch.cat([x, self.gate(x, skip)], dim=1))
# ------------------------------------------------------------------ decoder U-Mamba (adaptasi, sama dengan notebook)
MAMBA_IMPLS = ('cuda', 'torch')
def mamba_status():
"""(bisa_dipakai, alasan) untuk implementasi 'cuda': butuh mamba-ssm terpasang DAN GPU CUDA."""
if not torch.cuda.is_available():
return False, 'tidak ada GPU CUDA'
try:
import mamba_ssm # noqa: F401
except Exception as error: # noqa: BLE001 - pesan apa adanya
return False, 'mamba-ssm tidak terpasang (%s)' % type(error).__name__
return True, 'ok'
class MambaTorch(nn.Module):
"""mamba_ssm.Mamba (v2.2.6) dalam PyTorch murni, untuk inferensi tanpa GPU.
Nama dan bentuk parameter identik dengan mamba_ssm.Mamba (bias=False, conv_bias=True, dt_rank='auto'), jadi
state_dict checkpoint termuat strict. Rumus = jalur referensi mamba-ssm (Mamba.forward tanpa fast path +
selective_scan_ref, fp32). Scan dihitung per potongan `chunk` langkah agar memori tetap kecil untuk
sekuens panjang (128 x 128 = 16384 token).
"""
def __init__(self, d_model, d_state=16, d_conv=4, expand=2, chunk=256):
super().__init__()
d_inner = int(expand * d_model)
self.dt_rank = math.ceil(d_model / 16)
self.d_state = d_state
self.chunk = chunk
self.in_proj = nn.Linear(d_model, d_inner * 2, bias=False)
self.conv1d = nn.Conv1d(d_inner, d_inner, d_conv, groups=d_inner, padding=d_conv - 1, bias=True)
self.x_proj = nn.Linear(d_inner, self.dt_rank + d_state * 2, bias=False)
self.dt_proj = nn.Linear(self.dt_rank, d_inner, bias=True)
self.A_log = nn.Parameter(torch.zeros(d_inner, d_state))
self.D = nn.Parameter(torch.ones(d_inner))
self.out_proj = nn.Linear(d_inner, d_model, bias=False)
def forward(self, hidden):
"""hidden (B, L, d_model) -> (B, L, d_model)."""
length = hidden.shape[1]
x, z = self.in_proj(hidden).chunk(2, dim=-1) # (B, L, d_inner)
x = F.silu(self.conv1d(x.transpose(1, 2))[..., :length]) # (B, d_inner, L), conv kausal
dt, B, C = torch.split(self.x_proj(x.transpose(1, 2)),
[self.dt_rank, self.d_state, self.d_state], dim=-1)
delta = F.softplus(self.dt_proj(dt)).transpose(1, 2) # softplus(W dt + bias)
A = -torch.exp(self.A_log.float()) # (d_inner, d_state)
y = self._scan(x, delta, A, B, C)
y = (y + x * self.D[:, None]) * F.silu(z.transpose(1, 2))
return self.out_proj(y.transpose(1, 2))
def _scan(self, u, delta, A, B, C):
"""h_t = exp(delta_t A) h_{t-1} + delta_t B_t u_t ; y_t = C_t . h_t.
u, delta (b, d, L); A (d, n); B, C (b, L, n) -> y (b, d, L)."""
batch, dim, length = u.shape
state = u.new_zeros(batch, dim, A.shape[1])
y = torch.empty_like(u)
for start in range(0, length, self.chunk):
stop = min(start + self.chunk, length)
dl = delta[:, :, start:stop].permute(2, 0, 1).unsqueeze(-1) # (T, b, d, 1)
dA = torch.exp(dl * A) # (T, b, d, n)
dBu = dl * u[:, :, start:stop].permute(2, 0, 1).unsqueeze(-1) \
* B[:, start:stop].transpose(0, 1).unsqueeze(2) # (T, b, d, n)
hs = torch.empty_like(dA)
for t in range(stop - start):
state = torch.addcmul(dBu[t], dA[t], state, out=hs[t])
y[:, :, start:stop] = torch.einsum('tbdn,btn->bdt', hs, C[:, start:stop])
return y
class ResidualConvBlock(nn.Module):
def __init__(self, in_ch, out_ch, dropout):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1, bias=False),
nn.InstanceNorm2d(out_ch),
nn.LeakyReLU(0.01, inplace=True),
nn.Dropout2d(dropout),
nn.Conv2d(out_ch, out_ch, 3, padding=1, bias=False),
nn.InstanceNorm2d(out_ch),
)
self.shortcut = nn.Identity() if in_ch == out_ch else nn.Conv2d(in_ch, out_ch, 1, bias=False)
self.activation = nn.LeakyReLU(0.01, inplace=True)
def forward(self, x):
return self.activation(self.block(x) + self.shortcut(x))
class MambaLayer2D(nn.Module):
def __init__(self, dim, impl='cuda'):
super().__init__()
self.dim = dim
self.norm = nn.LayerNorm(dim)
if impl == 'torch':
self.mamba = MambaTorch(d_model=dim, d_state=16, d_conv=4, expand=2)
else:
from mamba_ssm import Mamba
self.mamba = Mamba(d_model=dim, d_state=16, d_conv=4, expand=2)
def forward(self, x):
batch, channels, height, width = x.shape
tokens = self.mamba(self.norm(x.flatten(2).transpose(1, 2)))
return tokens.transpose(1, 2).reshape(batch, channels, height, width)
class UMambaDecoderBlock(nn.Module):
"""ResConv (lokal) + gamma x Mamba (global). gamma = ReZero, tersimpan di checkpoint."""
def __init__(self, in_ch, skip_ch, out_ch, dropout, mamba_impl='cuda'):
super().__init__()
self.local = ResidualConvBlock(in_ch + skip_ch, out_ch, dropout)
self.global_context = MambaLayer2D(out_ch, mamba_impl)
self.gamma = nn.Parameter(torch.zeros(1))
def forward(self, x, skip):
x = F.interpolate(x, size=skip.shape[2:], mode='bilinear', align_corners=False)
local = self.local(torch.cat([x, skip], dim=1))
return local + self.gamma * self.global_context(local)
# ------------------------------------------------------------------ model segmentasi
class SegmentationModel(nn.Module):
"""Encoder (pilihan) + decoder (attention | umamba), sama dengan notebook Phase 3 terbaru.
Decoder dibangun dari daftar skip (kasar -> halus, satu blok per grid) di `self.decoders`.
out_grid 8 -> skip (128, 64, 32, 16), 4 blok; out_grid 16 -> skip (128, 64, 32), 3 blok.
Decoder U-Mamba: mamba_impl 'cuda' (mamba-ssm) atau 'torch' (MambaTorch, CPU); bobotnya sama.
"""
def __init__(self, student='efficientnetb3', decoder='attention', width=1, in_ch=3, dropout=0.4,
logit_clamp=200.0, out_grid=8, mamba_impl='cuda'):
super().__init__()
if decoder not in ('attention', 'umamba'):
raise ValueError('decoder %r tidak dikenal (attention | umamba)' % (decoder,))
if mamba_impl not in MAMBA_IMPLS:
raise ValueError('mamba_impl %r tidak dikenal %s' % (mamba_impl, MAMBA_IMPLS))
self.student = student
self.decoder_type = decoder
self.logit_clamp = float(logit_clamp)
self.encoder = EncoderModule(student, in_ch, out_grid)
self.stem = ConvStem(in_ch) if student == 'swinv2tiny' else None
grid_channels = dict(self.encoder.grid_channels)
if self.stem is not None:
grid_channels[128] = self.stem.out_channels
self.out_grid = int(self.encoder.out_grid)
self.skip_grids = tuple(sorted(grid_channels, reverse=True))
self.grid_channels = {g: grid_channels[g] for g in self.skip_grids}
self.decoder_grids = tuple(reversed(self.skip_grids))
widths = [max(int(round(base * width)), 8) for base in (256, 128, 64, 32)]
drop = [max(float(dropout) * (0.5 ** i), 0.0) for i in range(4)]
blocks, in_ch_dec, level_channels = [], int(self.encoder.out_channels), {}
for level, grid in enumerate(self.decoder_grids):
if decoder == 'umamba':
blocks.append(UMambaDecoderBlock(in_ch_dec, self.grid_channels[grid], widths[level], drop[level],
mamba_impl))
else:
blocks.append(AttentionDecoderBlock(in_ch_dec, self.grid_channels[grid], widths[level],
drop[level]))
level_channels[grid] = widths[level]
in_ch_dec = widths[level]
self.decoders = nn.ModuleList(blocks)
if decoder == 'umamba':
self.final_up = nn.Identity()
self.output = nn.Conv2d(in_ch_dec, 1, 1)
else:
head = max(in_ch_dec // 2, 8)
self.final_up = nn.Sequential(
nn.Conv2d(in_ch_dec, head, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(head),
nn.LeakyReLU(0.01, inplace=True),
)
self.output = nn.Conv2d(head, 1, 1)
# aux head deep supervision (hanya agar state_dict cocok; tidak dipakai saat inferensi)
self.aux3 = nn.Conv2d(level_channels[32], 1, kernel_size=1)
self.aux2 = nn.Conv2d(level_channels[64], 1, kernel_size=1)
self.aux1 = nn.Conv2d(level_channels[128], 1, kernel_size=1)
def forward(self, x):
deep, skips = self.encoder(x)
if self.stem is not None:
skips = [self.stem(x), *skips]
by_grid = dict(zip(self.skip_grids, skips))
y = deep
for grid, block in zip(self.decoder_grids, self.decoders):
y = block(y, by_grid[grid])
y = F.interpolate(y, size=x.shape[2:], mode='bilinear', align_corners=False)
logits = self.output(self.final_up(y))
return logits.clamp(-self.logit_clamp, self.logit_clamp)
_OLD_DECODER_KEYS = {'decoder4.': 'decoders.0.', 'decoder3.': 'decoders.1.',
'decoder2.': 'decoders.2.', 'decoder1.': 'decoders.3.'}
def convert_state_dict(state):
"""Checkpoint lama (decoder4..decoder1, out_grid 8) -> nama baru (decoders.0..3)."""
if not any(k.startswith('decoder4.') for k in state):
return state
out = {}
for key, value in state.items():
for old, new in _OLD_DECODER_KEYS.items():
if key.startswith(old):
key = new + key[len(old):]
break
out[key] = value
return out
def build_model(config, mamba_impl='cuda'):
"""Bangun model dari CONFIG yang tersimpan di checkpoint Phase 3.
mamba_impl hanya berlaku untuk decoder U-Mamba: 'cuda' (mamba-ssm, butuh GPU) atau 'torch' (CPU).
"""
decoder = config.get('DECODER', 'attention')
if decoder == 'umamba' and mamba_impl == 'cuda':
ok, why = mamba_status()
if not ok:
raise RuntimeError('U-Mamba versi GPU butuh mamba-ssm + GPU CUDA (%s). Pilih U-Mamba versi CPU, '
'atau jalankan app di Vast.' % why)
return SegmentationModel(student=config['STUDENT'], decoder=decoder,
width=config.get('DECODER_WIDTH', 1),
in_ch=config.get('SLICE_CONTEXT', 3),
dropout=config.get('DROPOUT', 0.4),
logit_clamp=config.get('LOGIT_CLAMP', 200.0),
out_grid=int(config.get('ENCODER_OUT_GRID', 8)),
mamba_impl=mamba_impl)

Xet Storage Details

Size:
21.1 kB
·
Xet hash:
06738eb0eeb14a728ed83c7a3a2b3f437bf1061dca8668d4e879390a669e1148

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