vilhess's picture
model.py: remove unused variate attention, ano_head and ano_logits_variate
720dc5b verified
Raw History Blame Contribute Delete
19.8 kB
import math
from dataclasses import asdict, dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from rotary_embedding_torch import RotaryEmbedding
@dataclass
class ModelConfig:
patch_len: int = 16
d_model: int = 256
n_heads: int = 8
n_layers_encoder: int = 8
input_diffs: int = 2
local_stats: tuple[int, ...] = (9, 33)
nn_dist: tuple[int, ...] = (32, 128)
revin_asinh: bool = True
head_skip: bool = True
mask_ratio_min: float = 0.05
mask_ratio_max: float = 0.5
ano_pos_weight: float = 2.0
segment_balanced_bce: bool = True
segment_ref_len: int = 32
local_std_eps: float = 1e-2
nn_dist_eps: float = 1e-2
max_infer_len: int = 10_192
def __post_init__(self):
self.local_stats = tuple(int(w) for w in self.local_stats)
self.nn_dist = tuple(int(L) for L in self.nn_dist)
assert 0.0 <= self.mask_ratio_min <= self.mask_ratio_max <= 1.0
assert self.input_diffs in (0, 1, 2)
assert all(w >= 3 and w % 2 == 1 for w in self.local_stats), "local_stats windows must be odd and >= 3"
assert all(L >= 2 for L in self.nn_dist), "nn_dist lengths must be >= 2"
@property
def n_channels(self):
return 1 + self.input_diffs + 2 * len(self.local_stats) + len(self.nn_dist) + 1
def to_dict(self):
return asdict(self)
class RevIN(nn.Module):
def __init__(self, use_asinh=True, eps=1e-5, min_std_ratio=0.1):
super().__init__()
self.use_asinh = use_asinh
self.eps = eps
self.min_std_ratio = min_std_ratio
def get_statistics(self, x, mask=None):
assert x.dim() == 3, "Input tensor must be (batch, signal_len, n_variate)"
x = x.float()
if mask is not None:
x = x.masked_fill(~mask[..., None], float("nan"))
centre = torch.nanmedian(x, dim=1, keepdim=True).values
quartiles = torch.nanquantile(x, torch.tensor([0.25, 0.75], device=x.device), dim=1, keepdim=True)
iqr = quartiles[1] - quartiles[0]
mean = torch.nanmean(x, dim=1, keepdim=True)
std = torch.sqrt(torch.nanmean((x - mean) ** 2, dim=1, keepdim=True))
scale = torch.maximum(iqr / 1.349, self.min_std_ratio * std).clamp_min(self.eps)
return centre, scale
def normalize(self, x, stats):
centre, scale = stats
out = (x.float() - centre) / scale
if self.use_asinh:
out = torch.asinh(out)
return out
def forward(self, x, mode="norm", mask=None):
if mode != "norm":
raise NotImplementedError(f"Mode '{mode}' not implemented.")
return self.normalize(x, self.get_statistics(x, mask))
class ResidualBlock(nn.Module):
def __init__(self, in_dim, hid_dim, out_dim):
super().__init__()
self.hidden_layer = nn.Linear(in_dim, hid_dim)
self.output_layer = nn.Linear(hid_dim, out_dim)
self.residual_layer = nn.Linear(in_dim, out_dim)
self.act = nn.SiLU()
def forward(self, x):
hid = self.act(self.hidden_layer(x))
out = self.output_layer(hid)
res = self.residual_layer(x)
return out + res
class PerDimScale(nn.Module):
def __init__(self, num_dims: int):
super().__init__()
self.num_dims = num_dims
self.per_dim_scale = nn.Parameter(torch.zeros(num_dims))
self._RECIPROCAL_OF_SOFTPLUS_0 = 1.442695041
def forward(self, x: torch.Tensor) -> torch.Tensor:
return (
x
* self._RECIPROCAL_OF_SOFTPLUS_0
/ math.sqrt(self.num_dims)
* torch.nn.functional.softplus(self.per_dim_scale)
)
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
assert (
d_model % n_heads == 0
), f"d_model ({d_model}) must be divisible by n_heads ({n_heads})"
self.WQ = nn.Linear(d_model, d_model, bias=False)
self.WK = nn.Linear(d_model, d_model, bias=False)
self.WV = nn.Linear(d_model, d_model, bias=False)
self.gate = nn.Linear(d_model, d_model, bias=False)
self.out_proj = nn.Linear(d_model, d_model)
self.head_dim = d_model // n_heads
self.n_heads = n_heads
self.rope = RotaryEmbedding(dim=self.head_dim // 2)
self.q_norm = nn.RMSNorm(self.head_dim)
self.k_norm = nn.RMSNorm(self.head_dim)
self.per_dim_scale = PerDimScale(self.head_dim)
def forward(self, q, key_padding_mask=None):
bs, batch_dim, context, dim = q.size()
k = q
v = q
gated = self.gate(q)
q = self.WQ(q).reshape(bs, batch_dim, -1, self.n_heads, self.head_dim).transpose(2, 3)
k = self.WK(k).reshape(bs, batch_dim, -1, self.n_heads, self.head_dim).transpose(2, 3)
v = self.WV(v).reshape(bs, batch_dim, -1, self.n_heads, self.head_dim).transpose(2, 3)
q = self.q_norm(q)
k = self.k_norm(k)
q = self.rope.rotate_queries_or_keys(q)
k = self.rope.rotate_queries_or_keys(k)
q = self.per_dim_scale(q)
attn_mask = None
if key_padding_mask is not None:
attn_mask = key_padding_mask[:, None, None, None, :]
values = nn.functional.scaled_dot_product_attention(
q, k, v, attn_mask=attn_mask, is_causal=False, scale=1.0
)
values = values.transpose(2, 3).reshape(bs, batch_dim, -1, dim)
values = gated.sigmoid() * values
return self.out_proj(values)
class FeedForward(nn.Module):
def __init__(self, d_model, multiple_of=256):
super().__init__()
hidden_dim = d_model * 4
hidden_dim = int(2 * hidden_dim / 3)
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
self.w1 = nn.Linear(d_model, hidden_dim, bias=False)
self.w2 = nn.Linear(hidden_dim, d_model, bias=False)
self.w3 = nn.Linear(d_model, hidden_dim, bias=False)
self.act = nn.SiLU()
def forward(self, x):
return self.w2(self.act(self.w1(x)) * self.w3(x))
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.ln1 = nn.RMSNorm(d_model)
self.attn = MultiHeadAttention(d_model=d_model, n_heads=n_heads)
self.ln2 = nn.RMSNorm(d_model)
self.ff = FeedForward(d_model=d_model)
def forward(self, x, key_padding_mask=None):
x = x + self.attn(self.ln1(x), key_padding_mask=key_padding_mask)
return x + self.ff(self.ln2(x))
class TransformerEncoder(nn.Module):
def __init__(self, d_model, n_heads, n_layers):
super().__init__()
self.layers = nn.ModuleList([TransformerEncoderLayer(d_model=d_model, n_heads=n_heads) for _ in range(n_layers)])
self.norm = nn.RMSNorm(d_model)
def forward(self, x, key_padding_mask=None):
for layer in self.layers:
x = layer(x, key_padding_mask=key_padding_mask)
return self.norm(x)
class Model(nn.Module):
def __init__(self, config=None):
super().__init__()
cfg = config if isinstance(config, ModelConfig) else ModelConfig(**(config or {}))
self.cfg = cfg
self.patch_len = cfg.patch_len
self.d_model = cfg.d_model
self.n_heads = cfg.n_heads
self.n_layers_encoder = cfg.n_layers_encoder
self.mask_ratio_min = cfg.mask_ratio_min
self.mask_ratio_max = cfg.mask_ratio_max
self.ano_pos_weight = cfg.ano_pos_weight
self.head_skip = cfg.head_skip
self.segment_balanced_bce = cfg.segment_balanced_bce
self.segment_ref_len = cfg.segment_ref_len
self.input_diffs = cfg.input_diffs
self.local_stats = cfg.local_stats
self.nn_dist = cfg.nn_dist
self.patch_in_dim = cfg.n_channels * cfg.patch_len
self.revin = RevIN(use_asinh=cfg.revin_asinh)
self.proj_embedding = ResidualBlock(
in_dim=self.patch_in_dim, hid_dim=2 * self.d_model, out_dim=self.d_model
)
self.transformer_encoder = TransformerEncoder(d_model=self.d_model, n_heads=self.n_heads, n_layers=self.n_layers_encoder)
ano_in = self.d_model + (self.patch_in_dim if self.head_skip else 0)
self.ano_proj = ResidualBlock(in_dim=ano_in, hid_dim=2 * self.d_model, out_dim=self.patch_len)
self.reco_proj = ResidualBlock(in_dim=self.d_model, hid_dim=2 * self.d_model, out_dim=self.patch_len)
self.mask_token = nn.Parameter(torch.zeros(self.d_model))
@staticmethod
def local_statistics(x, visible, w, eps):
# return x_t - mean(x_{t-w/2:t+w/2} \ x_t) and log(std(x_{t-w/2:t+w/2}))
B, T, V = x.shape
m = visible.float()
xv = x.float() * m
ones = torch.ones(1, 1, w, device=x.device)
def window_sum(z):
z = rearrange(z, "b t v -> (b v) 1 t")
return rearrange(F.conv1d(z, ones, padding=w // 2), "(b v) 1 t -> b t v", b=B, v=V)
n, s1, s2 = window_sum(m), window_sum(xv), window_sum(xv * xv)
n_loo = n - m
mean_loo = (s1 - xv) / n_loo.clamp_min(1.0)
residual = torch.where(visible & (n_loo >= 1), x.float() - mean_loo, torch.zeros_like(mean_loo))
mean = s1 / n.clamp_min(1.0)
var = (s2 / n.clamp_min(1.0) - mean ** 2).clamp_min(0.0)
log_std = torch.where(visible & (n >= 2), torch.log(var.sqrt() + eps), torch.zeros_like(var))
return residual.to(x.dtype), log_std.to(x.dtype)
@staticmethod
@torch.no_grad()
def nearest_neighbour_distance(x, visible, L, eps, max_block=2 ** 25):
# return the distance to the nearest neighbour for each point spaced at least L apart.
B, T, V = x.shape
n = B * V
feat = torch.zeros(n, T, device=x.device)
if T < 2 * L + 1:
return rearrange(feat, "(b v) t -> b t v", b=B, v=V).to(x.dtype)
m = rearrange(visible, "b t v -> (b v) t")
z = rearrange(x.float(), "b t v -> (b v) t").masked_fill(~m, 0.0)
left = L // 2
S = T - L + 1
sub = z.unfold(-1, L, 1)
ok = m.float().unfold(-1, L, 1).sum(-1) >= L - 0.5
norms = (sub * sub).sum(-1)
bias = norms.masked_fill(~ok, float("inf"))[:, None, :]
sub_t = sub.transpose(1, 2).contiguous()
idx = torch.arange(S, device=x.device)
best = torch.empty(n, S, device=x.device)
rows = max(1, max_block // max(1, n * S))
for r0 in range(0, S, rows):
r1 = min(S, r0 + rows)
d = torch.baddbmm(bias, sub[:, r0:r1], sub_t, alpha=-2.0)
trivial = (idx[r0:r1, None] - idx[None, :]).abs() < L
d += torch.zeros(trivial.shape, device=x.device).masked_fill_(trivial, float("inf"))[None]
best[:, r0:r1] = d.min(dim=-1).values
d2 = (best + norms).clamp_min(0.0) / L
valid = ok & torch.isfinite(best)
log_d = torch.log(d2.sqrt() + eps).masked_fill(~valid, float("nan"))
log_d = log_d - torch.nanmedian(log_d, dim=1, keepdim=True).values
feat[:, left:left + S] = torch.nan_to_num(log_d, nan=0.0)
return rearrange(feat, "(b v) t -> b t v", b=B, v=V).to(x.dtype)
def preprocess(self, x, mask=None, hidden=None):
B, T, V = x.size()
if mask is None:
mask = torch.ones(B, T, dtype=torch.bool, device=x.device)
mask = mask.bool()
stats = self.revin.get_statistics(x, mask)
x_norm = self.revin.normalize(x, stats).masked_fill(~mask[..., None], 0.0)
visible = mask[..., None].expand(B, T, V)
if hidden is not None:
visible = visible & ~hidden.bool()
x_norm = x_norm.masked_fill(hidden.bool(), 0.0)
channels = [x_norm]
prev, prev_mask = x_norm, visible
for _ in range(self.input_diffs):
diff = prev - F.pad(prev, (0, 0, 1, 0))[:, :-1]
diff_mask = prev_mask & F.pad(prev_mask, (0, 0, 1, 0))[:, :-1]
diff = diff.masked_fill(~diff_mask, 0.0)
channels.append(diff)
prev, prev_mask = diff, diff_mask
for w in self.local_stats:
channels.extend(self.local_statistics(x_norm, visible, w, self.cfg.local_std_eps))
for L in self.nn_dist:
channels.append(self.nearest_neighbour_distance(x_norm, visible, L, self.cfg.nn_dist_eps))
pad = (-T) % self.patch_len
if pad:
channels = [F.pad(c, (0, 0, 0, pad)) for c in channels]
mask = F.pad(mask, (0, pad), value=False)
patched = [rearrange(c, "b (pn pl) v -> b v pn pl", pl=self.patch_len) for c in channels]
observed = rearrange(mask, "b (pn pl) -> b pn pl", pl=self.patch_len)
observed_v = observed[:, None].expand(-1, V, -1, -1).to(patched[0].dtype)
patch_input = torch.cat(patched + [observed_v], dim=-1)
tokens = self.proj_embedding(patch_input)
patch_valid = observed.any(dim=-1)
return tokens, patch_valid, stats, patch_input
def sample_patch_mask(self, patch_valid, n_variate):
B, PN = patch_valid.shape
device = patch_valid.device
ratio = torch.empty(B, 1, 1, device=device).uniform_(self.mask_ratio_min, self.mask_ratio_max)
valid = patch_valid[:, None, :].expand(B, n_variate, PN)
n_valid = valid.sum(dim=-1, keepdim=True)
n_masked = (ratio * n_valid).round().clamp(min=1).minimum(n_valid)
scores = torch.rand(B, n_variate, PN, device=device).masked_fill(~valid, 2.0)
ranks = scores.argsort(dim=-1).argsort(dim=-1)
return (ranks < n_masked) & valid
def _unpatch(self, out, T):
return rearrange(out, "b v pn pl -> b (pn pl) v")[:, :T]
def forward(self, x, mask=None, patch_mask=None):
B, T, V = x.size()
hidden = None
if patch_mask is not None:
hidden = patch_mask.repeat_interleave(self.patch_len, dim=-1)[..., :T].transpose(1, 2)
tokens, patch_valid, stats, patch_input = self.preprocess(x, mask, hidden=hidden)
if patch_mask is not None:
tokens = torch.where(patch_mask[..., None], self.mask_token.to(tokens.dtype), tokens)
hidden = self.transformer_encoder(tokens, key_padding_mask=patch_valid)
ano_in = hidden
if self.head_skip:
if patch_mask is not None:
patch_input = patch_input.masked_fill(patch_mask[..., None], 0.0)
ano_in = torch.cat([hidden, patch_input.to(hidden.dtype)], dim=-1)
ano_variate = self._unpatch(self.ano_proj(ano_in), T)
reco = self._unpatch(self.reco_proj(hidden), T)
ano_logits = torch.logsumexp(ano_variate.float(), dim=-1) - math.log(V)
return {
"ano_logits": ano_logits,
"reco": reco,
"stats": stats,
"patch_valid": patch_valid,
}
@torch.no_grad()
def _predict_full(self, x, mask=None):
out = self.forward(x, mask)
x_norm = self.revin.normalize(x, out["stats"])
reco_error = ((out["reco"].float() - x_norm) ** 2).mean(dim=-1)
return out["ano_logits"].float(), reco_error
@torch.no_grad()
def _predict_windows(self, x, max_len, stride, windows_per_batch):
T = x.shape[0]
starts = list(range(0, T - max_len + 1, stride))
if starts[-1] != T - max_len:
starts.append(T - max_len)
pos = torch.arange(max_len, device=x.device, dtype=torch.float32)
weight = torch.minimum(pos + 1, max_len - pos)
logit_sum = torch.zeros(T, device=x.device)
reco_sum = torch.zeros(T, device=x.device)
weight_sum = torch.zeros(T, device=x.device)
for i in range(0, len(starts), windows_per_batch):
chunk = starts[i:i + windows_per_batch]
windows = torch.stack([x[s:s + max_len] for s in chunk])
logits, reco_error = self._predict_full(windows)
for k, s in enumerate(chunk):
logit_sum[s:s + max_len] += weight * logits[k]
reco_sum[s:s + max_len] += weight * reco_error[k]
weight_sum[s:s + max_len] += weight
return logit_sum / weight_sum, reco_sum / weight_sum
@torch.no_grad()
def predict(self, x, mask=None, max_len=..., stride=None, windows_per_batch=8):
# score windows of length max_len with stride if needed, then merge the scores with a weighted average (triangular weights for the overlapping regions: anomalies in the middle of a window are more likely to be detected than anomalies at the edges)
was_training = self.training
if max_len is ...:
max_len = self.cfg.max_infer_len
self.eval()
B, T, V = x.size()
if max_len is None or T <= max_len:
logits, reco_error = self._predict_full(x, mask)
else:
stride = stride or max(1, max_len // 2)
assert 1 <= stride <= max_len, "stride must be in [1, max_len]"
lengths = mask.bool().sum(dim=1).tolist() if mask is not None else [T] * B
logits = torch.zeros(B, T, device=x.device)
reco_error = torch.zeros(B, T, device=x.device)
for b, length in enumerate(lengths):
if length <= max_len:
lg, re = self._predict_full(x[b:b + 1, :length])
lg, re = lg[0], re[0]
else:
lg, re = self._predict_windows(x[b, :length], max_len, stride, windows_per_batch)
logits[b, :length], reco_error[b, :length] = lg, re
self.train(was_training)
return {"scores": torch.sigmoid(logits), "reco_error": reco_error}
def anomaly_point_weights(self, y):
weights = torch.full_like(y, float(self.ano_pos_weight))
if not self.segment_balanced_bce:
return weights
is_ano = y > 0.5
starts = is_ano & ~F.pad(is_ano, (1, 0))[:, :-1]
run_id = torch.cumsum(starts.flatten().long(), dim=0) * is_ano.flatten().long()
run_len = torch.bincount(run_id)[run_id].view_as(y).float()
balanced = self.ano_pos_weight * torch.sqrt(self.segment_ref_len / run_len.clamp_min(1.0))
return torch.where(is_ano, balanced, weights)
def train_step(self, x, y, x_normal=None, mask=None, label_mask=None):
B, T, V = x.size()
if mask is None:
mask = torch.ones(B, T, dtype=torch.bool, device=x.device)
mask = mask.bool()
y = y.float()
valid = mask.float()
labelled = (mask & label_mask.bool()).float() if label_mask is not None else valid
out = self.forward(x, mask)
bce = F.binary_cross_entropy_with_logits(out["ano_logits"], y, reduction="none")
weights = labelled * (1.0 + (self.anomaly_point_weights(y) - 1.0) * y)
bce = (bce * weights).sum() / labelled.sum().clamp_min(1.0)
target = x if x_normal is None else torch.where(y[..., None].bool(), x_normal, x)
target_norm = self.revin.normalize(target, out["stats"])
err_full = ((out["reco"].float() - target_norm) ** 2).mean(dim=-1)
mse_full = (err_full * valid).sum() / valid.sum().clamp_min(1.0)
patch_mask = self.sample_patch_mask(out["patch_valid"], V)
out_masked = self.forward(x, mask, patch_mask=patch_mask)
point_mask = patch_mask.repeat_interleave(self.patch_len, dim=-1)[..., :T]
point_mask = point_mask.transpose(1, 2).float() * valid[..., None]
err_masked = (out_masked["reco"].float() - target_norm) ** 2
mse_masked = (err_masked * point_mask).sum() / point_mask.sum().clamp_min(1.0)
mse = 0.5 * (mse_full + mse_masked)
return bce, mse