File size: 7,010 Bytes
0d8aa44 acb2ce3 0d8aa44 acb2ce3 0d8aa44 acb2ce3 0d8aa44 acb2ce3 0d8aa44 acb2ce3 | 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 | """Compose independent token augmentation, transformation and MIL pooling stages."""
from __future__ import annotations
import inspect
from typing import Any, Dict, Optional, Set, Tuple, Union
import torch
import torch.nn as nn
from .cross_shuffle import CrossTokenShuffle
from .mil_head_beta import MILHead
def _forward_param_names(module: nn.Module) -> Set[str]:
try:
return set(inspect.signature(module.forward).parameters.keys())
except (TypeError, ValueError):
return set()
class CrossShuffleStage(nn.Module):
"""Optional cross-batch token replacement; disabled stages act as the identity."""
def __init__(self, use: bool = True) -> None:
super().__init__()
self._use = use
self.op: Optional[CrossTokenShuffle]
if use:
self.op = CrossTokenShuffle()
else:
self.op = None
def forward(
self,
x: torch.Tensor,
y: Optional[torch.Tensor],
*,
apply: bool,
replace_ratio: float = 0.5,
with_replacement: bool = False,
detach_inserted: bool = True,
min_keep_original: int = 0,
) -> torch.Tensor:
if not self._use or not apply or self.op is None or y is None:
return x
if y.dim() != 1 or y.shape[0] != x.shape[0]:
raise ValueError(
f"y must be 1D [B], got {tuple(y.shape)} for B={x.shape[0]}"
)
return self.op(
x, y,
replace_ratio=replace_ratio,
with_replacement=with_replacement,
detach_inserted=detach_inserted,
min_keep_original=min_keep_original,
)
class TransStage(nn.Module):
"""Apply an optional token transformation with supported keyword arguments.
A missing core acts as the identity. Fixed-length masking can be passed
through key_padding_mask without dropping tokens.
"""
def __init__(self, core: Optional[nn.Module] = None) -> None:
super().__init__()
self.core = core
self._params = _forward_param_names(core) if core is not None else set()
def forward(
self,
x: torch.Tensor,
*,
p_shuffle: float = 0.0,
p_drop: float = 0.0,
key_padding_mask: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
if self.core is None:
return x
if "p_shuffle" in self._params:
call_kw: Dict[str, Any] = {}
for name, val in (
("p_shuffle", p_shuffle),
("p_drop", p_drop),
("key_padding_mask", key_padding_mask),
):
if name in self._params:
call_kw[name] = val
for k, v in kwargs.items():
if k in self._params:
call_kw[k] = v
return self.core(x, **call_kw)
kw2: Dict[str, Any] = {}
if key_padding_mask is not None and "src_key_padding_mask" in self._params:
kw2["src_key_padding_mask"] = key_padding_mask
for k, v in kwargs.items():
if k in self._params:
kw2[k] = v
return self.core(x, **kw2) if kw2 else self.core(x)
class MILHeadStage(nn.Module):
"""Classify instances and pool tokens [B, N, D] using the wrapped MIL head."""
def __init__(self, **mil_kw: Any) -> None:
super().__init__()
self.head = MILHead(**mil_kw)
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Dict[str, Any]:
return self.head(x, mask=mask)
class MILCore(nn.Module):
"""Compose Cross-Shuffle, token transformation and MIL head stages.
Fixed-length bags can use attention masks instead of token dropping.
Optional masks and transformation arguments are forwarded to supported stages.
"""
def __init__(
self,
d_in: int,
num_classes: int = 2,
mil_head_pooling: str = "attn",
mil_head_kwargs: Optional[Dict[str, Any]] = None,
*,
use_cross_shuffle: bool = True,
trans: Optional[nn.Module] = None,
allow_trans_token_drop: bool = False,
) -> None:
super().__init__()
self.allow_trans_token_drop = bool(allow_trans_token_drop)
self.shuffle = CrossShuffleStage(use=use_cross_shuffle)
self.trans = TransStage(core=trans)
mil_kw: Dict[str, Any] = {"d_in": d_in, "num_classes": num_classes, "pooling": mil_head_pooling}
if mil_head_kwargs:
mil_kw.update(mil_head_kwargs)
self.head = MILHeadStage(**mil_kw)
def forward(
self,
tokens: torch.Tensor,
y: Optional[torch.Tensor] = None,
mask: Optional[torch.Tensor] = None,
*,
do_cross_shuffle: bool = False,
replace_ratio: float = 0.5,
with_replacement: bool = False,
detach_inserted: bool = True,
cross_shuffle_min_keep: int = 0,
p_shuffle: float = 0.0,
p_drop: float = 0.0,
trans_key_padding_mask: Optional[torch.Tensor] = None,
trans_extra: Optional[Dict[str, Any]] = None,
return_dict: bool = False,
):
x = self.shuffle(
tokens, y,
apply=do_cross_shuffle,
replace_ratio=replace_ratio,
with_replacement=with_replacement,
detach_inserted=detach_inserted,
min_keep_original=cross_shuffle_min_keep,
)
trans_p_drop = float(p_drop) if self.allow_trans_token_drop else 0.0
tex = dict(trans_extra or {})
trans_out = self.trans(
x,
p_shuffle=p_shuffle,
p_drop=trans_p_drop,
key_padding_mask=trans_key_padding_mask,
**tex,
)
if isinstance(trans_out, tuple) and len(trans_out) == 2:
x, trans_mil_mask = trans_out
if mask is not None:
raise ValueError(
"MILCore: `trans` returned (x, mil_valid); omit `mask` and use the trans-stage mask."
)
mask = trans_mil_mask
else:
x = trans_out # type: ignore[assignment]
if mask is not None and mask.shape != x.shape[:2]:
raise ValueError(
f"mask must be [B,N], got {tuple(mask.shape)} vs x {tuple(x.shape[:2])}"
)
mil_out = self.head(x, mask=mask)
if not return_dict:
return mil_out["bag_logits"]
return {"bag_logits": mil_out["bag_logits"], "mil_head": mil_out, "features": x}
def forward_logits(
self,
tokens: torch.Tensor,
y: Optional[torch.Tensor] = None,
mask: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> torch.Tensor:
extra = dict(kwargs)
extra.pop("return_dict", None)
return self.forward(tokens, y, mask, return_dict=False, **extra)
CrossShuffleTransMIL = MILCore
|