Download model.py from GokseninYuksel/array-tracker: direct link, hf CLI and curl.
- Browser
- Download file 43.1 kB
-
https://huggingface.co/GokseninYuksel/array-tracker/resolve/main/model.py
- Command line
-
hf download hf://GokseninYuksel/array-tracker/model.py
-
curl -L -o model.py https://huggingface.co/GokseninYuksel/array-tracker/resolve/main/model.py
43.1 kB
| """Causal, transformer-only source tracker for arbitrary microphone arrays. | |
| Signal path (shapes: N batch, T frames, M microphones, B bands, F bins, G grid | |
| directions, K track slots): | |
| STFT -> phase of every microphone relative to a reference microphone, PHAT-normalised. Nothing else | |
| of the signal enters: no magnitude, so the outputs do not depend on the level of the input | |
| or on the gain of any microphone | |
| -> band stage narrow tokens per (microphone, band, frame): microphone attention | |
| with a wavelength-aware geometry bias, and recursive smoothing over time | |
| -> merge the bands of each microphone become one token | |
| -> main stage microphone attention + causal ALiBi time attention with unbounded memory | |
| the same phases | |
| -> steered power per band on a fixed grid of directions (delay-and-sum, exact physics) | |
| -> map stage one token per direction, smoothed over time | |
| track slots read the microphone tokens and the direction tokens, and output per frame | |
| one vector each: its length is the activity, its direction is where the source is. | |
| Two ways to run it, tested to give the same outputs: | |
| forward(audio, pos) whole clip at once (training, FLOP counting) | |
| step(frame, state) one frame at a time with a fixed-size state (streaming) | |
| Three switches turn the signal-processing additions off for ablation: | |
| relative_phase, smooth, steered. | |
| A fourth, level, gives the inputs their log-magnitudes back: "relative" (to a running mean of what has been | |
| heard, so a gain on the whole input still changes nothing) or "absolute" (the design until 21 November 2026). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from dataclasses import dataclass | |
| import torch | |
| import torch.nn as nn | |
| SPEED_OF_SOUND = 343.0 | |
| UNIT_FLOOR = 1e-12 # a bin weaker than this (far below the last bit of 16-bit audio) counts as no signal | |
| SILENT_LEVEL = math.log(1e-10) # a frame whose mean log-magnitude is below this is digital silence | |
| LEVEL_RANGE = 10.0 # relative levels are kept within +-10 (87 dB) | |
| class TrackerConfig: | |
| fs: int = 16000 | |
| n_fft: int = 512 # 32 ms analysis window = algorithmic latency | |
| hop: int = 128 # 8 ms frame step, as in AGG-RL | |
| heads: int = 8 | |
| mlp_ratio: int = 2 | |
| # band stage: cheap, narrow tokens on fine bands | |
| bands: int = 16 # 500 Hz each | |
| band_width: int = 32 | |
| band_blocks: int = 2 | |
| # main stage: one token per microphone and frame | |
| width: int = 96 | |
| main_blocks: int = 4 | |
| window: int = 128 # frames attended exactly (about 1 s); older frames live in the memory | |
| slowest_slope: float = 1 / 4096 # longest memory time constant: 4096 frames, about 33 s | |
| # steered branch: direction tokens | |
| grid: int = 128 # directions, about 18 degrees apart | |
| grid_width: int = 32 | |
| grid_blocks: int = 2 | |
| smooth_slowest: float = 1 / 256 # slowest smoother: 256 frames, about 2 s | |
| # tracks | |
| slots: int = 4 # up to 3 sources plus one spare | |
| trk_blocks: int = 4 | |
| # ablation switches | |
| relative_phase: bool = True # inputs are phases relative to a reference microphone | |
| level: str = "none" # log-magnitudes in the inputs. "none": phases only. "absolute": also the difference | |
| # between microphones and their mean; the first design, kept for its checkpoints and | |
| # as an ablation: trained at one speech level, it answered quieter recordings as if | |
| # nothing were there. "relative": the same with the mean taken relative to a running | |
| # average of the level heard so far, which forgets at `level_slope`. | |
| level_slope: float = 1 / 256 # level="relative": the running average forgets by exp(-level_slope) per frame | |
| # (1 / 256: 256 frames, about 2 s, the slowest smoother's; 1 / 1000: 8 s) | |
| smooth: bool = True # recursive smoothing in the band stage | |
| steered: bool = True # direction tokens from steered power | |
| bias_offsets: bool = True # False: every bias head has a zero offset (plain ALiBi on distance) | |
| bias_wavelengths: bool = True # False: displacement in metres times one fixed wavenumber, the same for all bands and heads | |
| def bins(self) -> int: | |
| return self.n_fft // 2 # DC dropped | |
| def bins_per_band(self) -> int: | |
| assert self.bins % self.bands == 0 | |
| return self.bins // self.bands | |
| def frame_ms(self) -> float: | |
| return 1000.0 * self.hop / self.fs | |
| def latency_ms(self) -> float: | |
| return 1000.0 * self.n_fft / self.fs | |
| def time_slopes(heads: int, slowest: float, fastest: float = 0.5) -> torch.Tensor: | |
| """ALiBi-style geometric slopes per frame from `fastest` to `slowest`, one per head.""" | |
| if heads == 1: | |
| return torch.tensor([slowest]) | |
| ratio = (slowest / fastest) ** (1.0 / (heads - 1)) | |
| return torch.tensor([fastest * ratio ** i for i in range(heads)]) | |
| def fibonacci_directions(n: int) -> torch.Tensor: | |
| """n roughly even unit vectors; the six axis directions when n == 6.""" | |
| if n == 6: | |
| eye = torch.eye(3) | |
| return torch.cat([eye, -eye]) | |
| i = torch.arange(n, dtype=torch.float32) + 0.5 | |
| polar = torch.acos(1 - 2 * i / n) | |
| azim = math.pi * (1 + 5 ** 0.5) * i | |
| return torch.stack([polar.sin() * azim.cos(), polar.sin() * azim.sin(), polar.cos()], -1) | |
| def split_heads(t, heads): # [..., L, D] -> [..., H, L, d] | |
| return t.unflatten(-1, (heads, -1)).transpose(-3, -2) | |
| def merge_heads(t): # [..., H, L, d] -> [..., L, D] | |
| return t.transpose(-3, -2).flatten(-2) | |
| class Attention(nn.Module): | |
| """Multi-head attention written with explicit matmuls so FLOP counters see it.""" | |
| def __init__(self, dim: int, heads: int, kv_dim: int | None = None): | |
| super().__init__() | |
| self.heads = heads | |
| kv_dim = kv_dim or dim | |
| self.q, self.o = nn.Linear(dim, dim), nn.Linear(dim, dim) | |
| self.k, self.v = nn.Linear(kv_dim, dim), nn.Linear(kv_dim, dim) | |
| def forward(self, xq, xkv, bias=None): | |
| h = self.heads | |
| q, k, v = split_heads(self.q(xq), h), split_heads(self.k(xkv), h), split_heads(self.v(xkv), h) | |
| logits = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(q.shape[-1]) | |
| if bias is not None: | |
| logits = logits + bias | |
| return self.o(merge_heads(torch.matmul(logits.softmax(-1), v))) | |
| class SharedRead(nn.Module): | |
| """Cross-attention whose keys and values are prepared once and reused by every block. | |
| Each block keeps its own queries and output projection.""" | |
| def __init__(self, dim: int, heads: int): | |
| super().__init__() | |
| self.heads = heads | |
| self.q, self.o = nn.Linear(dim, dim), nn.Linear(dim, dim) | |
| def forward(self, xq, keys, values): # keys, values [..., H, L, d] | |
| q = split_heads(self.q(xq), self.heads) | |
| logits = torch.matmul(q, keys.transpose(-1, -2)) / math.sqrt(q.shape[-1]) | |
| return self.o(merge_heads(torch.matmul(logits.softmax(-1), values))) | |
| class TimeAttention(nn.Module): | |
| """Causal ALiBi attention over the whole past at a fixed cost per frame. | |
| logit(t -> j) = q_t . k_j / sqrt(d) - slope_h * (t - j) for the last W frames | |
| = c_h - slope_h * (t - j) for every older frame | |
| Older frames keep their ALiBi weight but lose the content term, so their total | |
| contribution is an exponentially decaying sum that can be updated recursively. | |
| `forward` evaluates the formula directly; `step` uses the recursion. | |
| """ | |
| def __init__(self, dim: int, heads: int, window: int, slowest_slope: float): | |
| super().__init__() | |
| self.heads, self.window = heads, window | |
| self.q, self.k, self.v, self.o = (nn.Linear(dim, dim) for _ in range(4)) | |
| self.register_buffer("slopes", time_slopes(heads, slowest_slope)) | |
| self.old_logit = nn.Parameter(torch.zeros(heads)) # c_h | |
| def qkv(self, x): | |
| h = self.heads | |
| return split_heads(self.q(x), h), split_heads(self.k(x), h), split_heads(self.v(x), h) | |
| def forward(self, x): # x [..., T, D] | |
| q, k, v = self.qkv(x) | |
| t = torch.arange(x.shape[-2], device=x.device) | |
| lag = t[:, None] - t[None, :] # query minus key | |
| content = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(q.shape[-1]) | |
| logits = torch.where(lag < self.window, content, self.old_logit[:, None, None].expand_as(content)) | |
| logits = logits - self.slopes[:, None, None] * lag.clamp(min=0) | |
| logits = logits.masked_fill(lag < 0, float("-inf")) | |
| return self.o(merge_heads(torch.matmul(logits.softmax(-1), v))) | |
| def step(self, x, state): # x [..., D]: one frame | |
| q, k, v = self.qkv(x.unsqueeze(-2)) # [..., H, 1, d] | |
| w = self.window | |
| if state is None: | |
| shape = (*k.shape[:-2], w, k.shape[-1]) | |
| state = {"keys": k.new_zeros(shape), "values": v.new_zeros(shape), | |
| "memory": torch.zeros_like(v[..., 0, :]), "mass": torch.zeros_like(self.slopes), "seen": 0} | |
| keys, values, memory, mass, seen = (state[n] for n in ("keys", "values", "memory", "mass", "seen")) | |
| slot = seen % w # holds the oldest frame once the buffer is full | |
| if seen >= w: | |
| decay = torch.exp(-self.slopes) | |
| memory = decay[:, None] * memory + values[..., slot, :] | |
| mass = decay * mass + 1.0 | |
| keys[..., slot, :], values[..., slot, :] = k[..., 0, :], v[..., 0, :] | |
| seen += 1 | |
| lag = (slot - torch.arange(w, device=x.device)) % w # age of each buffer slot in frames | |
| logits = torch.matmul(q, keys.transpose(-1, -2)) / math.sqrt(q.shape[-1]) - self.slopes[:, None, None] * lag | |
| if seen < w: | |
| logits = logits.masked_fill(lag >= seen, float("-inf")) # slots not written yet | |
| vals = values | |
| if seen > w: | |
| old = self.old_logit - self.slopes * w + torch.log(mass) # [H] | |
| logits = torch.cat([logits, old[:, None, None].expand(*logits.shape[:-1], 1)], -1) | |
| vals = torch.cat([values, (memory / mass[:, None]).unsqueeze(-2)], -2) | |
| out = self.o(merge_heads(torch.matmul(logits.softmax(-1), vals))).squeeze(-2) | |
| return out, {"keys": keys, "values": values, "memory": memory, "mass": mass, "seen": seen} | |
| def chunk(self, x, state): # x [..., T, D]: T consecutive frames | |
| """`forward` continued from a state (None, or the state `step` or `chunk` returned). | |
| The state has the same layout as in `step`, so the two can be mixed.""" | |
| q, k, v = self.qkv(x) # [..., H, T, d] | |
| w, frames, dev = self.window, x.shape[-2], x.device | |
| if state is None: | |
| seen, memory, mass = 0, torch.zeros_like(v[..., 0, :]), torch.zeros_like(self.slopes) | |
| keys, values = k, v | |
| else: | |
| seen, memory, mass = state["seen"], state["memory"], state["mass"] | |
| order = (torch.arange(min(seen, w), device=dev) + seen) % w if seen >= w else torch.arange(seen, device=dev) | |
| keys = torch.cat([state["keys"][..., order, :], k], -2) # oldest to newest | |
| values = torch.cat([state["values"][..., order, :], v], -2) | |
| held = keys.shape[-2] - frames # frames carried in from the state | |
| lag = (held + torch.arange(frames, device=dev))[:, None] - torch.arange(held + frames, device=dev)[None, :] | |
| content = torch.matmul(q, keys.transpose(-1, -2)) / math.sqrt(q.shape[-1]) | |
| logits = torch.where(lag < w, content, self.old_logit[:, None, None].expand_as(content)) | |
| logits = logits - self.slopes[:, None, None] * lag.clamp(min=0) | |
| logits = logits.masked_fill(lag < 0, float("-inf")) | |
| vals = values | |
| if seen > w: # frames older than everything held: the carried memory | |
| ahead = w + 1 + torch.arange(frames, device=dev) # its newest frame's lag | |
| old = self.old_logit[:, None] - self.slopes[:, None] * ahead + torch.log(mass)[:, None] # [H, T] | |
| logits = torch.cat([logits, old[..., None].expand(*logits.shape[:-1], 1)], -1) | |
| vals = torch.cat([values, (memory / mass[:, None]).unsqueeze(-2)], -2) | |
| out = self.o(merge_heads(torch.matmul(logits.softmax(-1), vals))) | |
| # new state: the last w frames in the ring layout `step` uses; everything older folds into the memory | |
| total, decay = held + frames, torch.exp(-self.slopes) | |
| leaving = max(total - w, 0) | |
| if leaving: | |
| weight = decay[:, None] ** torch.arange(leaving - 1, -1, -1, device=dev) # [H, leaving] | |
| memory = decay[:, None] ** frames * memory + (weight[..., None] * values[..., :leaving, :]).sum(-2) | |
| mass = decay ** frames * mass + weight.sum(-1) | |
| slots = (seen - held + torch.arange(leaving, total, device=dev)) % w | |
| new_keys = keys.new_zeros(*keys.shape[:-2], w, keys.shape[-1]).index_copy(-2, slots, keys[..., leaving:, :]) | |
| new_values = torch.zeros_like(new_keys).index_copy(-2, slots, values[..., leaving:, :]) | |
| return out, {"keys": new_keys, "values": new_values, "memory": memory, "mass": mass, "seen": seen + frames} | |
| class Smoothing(nn.Module): | |
| """ALiBi attention with the content term removed: logit(t -> j) = -slope_h * (t - j). | |
| That is a bank of exponential smoothers, one time constant per head: the recursive | |
| averaging used to estimate cross-spectra and spatial covariance. Short constants | |
| follow moving sources and onsets; long ones integrate a static source out of noise. | |
| memory <- exp(-slope_h) * memory + value; output = memory / mass | |
| """ | |
| def __init__(self, dim: int, heads: int, slowest_slope: float): | |
| super().__init__() | |
| self.heads = heads | |
| self.v, self.o = nn.Linear(dim, dim), nn.Linear(dim, dim) | |
| self.register_buffer("decay", torch.exp(-time_slopes(heads, slowest_slope))) | |
| def forward(self, x): # x [..., T, D] | |
| y = split_heads(self.v(x), self.heads) # [..., H, T, d] | |
| frames, shift = y.shape[-2], 1 | |
| g = self.decay[:, None, None] | |
| while shift < frames: # exact first-order recursion in log2(T) passes | |
| y = y + nn.functional.pad(g.pow(shift) * y[..., :-shift, :], (0, 0, shift, 0)) | |
| shift *= 2 | |
| t = torch.arange(1, frames + 1, device=x.device) | |
| mass = (1 - self.decay[:, None] ** t) / (1 - self.decay[:, None]) # [H, T] | |
| return self.o(merge_heads(y / mass[..., None])) | |
| def step(self, x, state): # x [..., D]: one frame | |
| v = split_heads(self.v(x.unsqueeze(-2)), self.heads)[..., 0, :] # [..., H, d] | |
| if state is None: | |
| memory, mass = v, torch.ones_like(self.decay) | |
| else: | |
| memory, mass = self.decay[:, None] * state["memory"] + v, self.decay * state["mass"] + 1.0 | |
| return self.o((memory / mass[:, None]).flatten(-2)), {"memory": memory, "mass": mass} | |
| def chunk(self, x, state): # x [..., T, D]: T consecutive frames | |
| """`forward` continued from a state (None, or the state `step` or `chunk` returned).""" | |
| y = split_heads(self.v(x), self.heads) # [..., H, T, d] | |
| frames, shift = y.shape[-2], 1 | |
| g = self.decay[:, None, None] | |
| while shift < frames: | |
| y = y + nn.functional.pad(g.pow(shift) * y[..., :-shift, :], (0, 0, shift, 0)) | |
| shift *= 2 | |
| fade = self.decay[:, None] ** torch.arange(1, frames + 1, device=x.device) # [H, T] | |
| mass = (1 - fade) / (1 - self.decay[:, None]) | |
| if state is not None: | |
| y = y + fade[..., None] * state["memory"].unsqueeze(-2) | |
| mass = mass + fade * state["mass"][:, None] | |
| return self.o(merge_heads(y / mass[..., None])), {"memory": y[..., -1, :], "mass": mass[:, -1]} | |
| class Mlp(nn.Module): | |
| def __init__(self, dim: int, ratio: int): | |
| super().__init__() | |
| self.net = nn.Sequential(nn.Linear(dim, ratio * dim), nn.GELU(), nn.Linear(ratio * dim, dim)) | |
| def forward(self, x): | |
| return self.net(x) | |
| class GeometryBias(nn.Module): | |
| """bias_h(i -> j) = -slope_h * || k (r_j - r_i) - offset_h ||, with k a wavenumber. | |
| offset_h = 0 is ALiBi on distance measured in wavelengths. A non-zero offset makes | |
| the head prefer microphones at one displacement. One extra learned key, "no | |
| microphone here", lets a head whose offset has no microphone nearby attend to nothing. | |
| per_band = True : tokens are per band, and k is that band's centre wavenumber. | |
| per_band = False: tokens hold all bands, and each head gets its own wavenumber. | |
| """ | |
| def __init__(self, cfg: TrackerConfig, radius: float, per_band: bool): | |
| super().__init__() | |
| heads = cfg.heads | |
| n_zero = 2 if heads >= 4 else 1 | |
| if cfg.bias_offsets: | |
| dirs = fibonacci_directions(heads - n_zero) | |
| self.offset = nn.Parameter(torch.cat([torch.zeros(n_zero, 3), radius * dirs])) | |
| slopes = torch.full((heads,), 2.0 / radius) | |
| slopes[0] = 0.5 / radius # one wide zero-offset head | |
| else: # ablation: ALiBi on distance only, nothing learned, | |
| self.register_buffer("offset", torch.zeros(heads, 3)) # slopes spread over the same range | |
| slopes = 0.5 / radius * 4.0 ** torch.linspace(0, 1, heads) | |
| self.register_buffer("slopes", slopes) | |
| self.sink_logit = nn.Parameter(torch.zeros(heads)) | |
| n = cfg.bands if per_band else heads | |
| hz = (torch.arange(n) + 0.5) * (cfg.fs / 2) / n | |
| if not cfg.bias_wavelengths: # ablation: metres, scaled by the mid-band wavenumber only | |
| hz = torch.full_like(hz, cfg.fs / 4) | |
| self.per_band = per_band | |
| self.register_buffer("wavenumber", 2 * math.pi * hz / SPEED_OF_SOUND) | |
| def forward(self, pos): # pos [N, M, 3] in metres | |
| disp = pos[:, None, :, :] - pos[:, :, None, :] # [N, M, M, 3], entry (i, j) = r_j - r_i | |
| kd = self.wavenumber[None, :, None, None, None] * disp[:, None] # [N, B or H, M, M, 3] | |
| if self.per_band: | |
| dist = (kd[:, :, None] - self.offset[None, None, :, None, None, :]).norm(dim=-1) # [N, B, H, M, M] | |
| else: | |
| dist = (kd - self.offset[None, :, None, None, :]).norm(dim=-1)[:, None] # [N, 1, H, M, M] | |
| bias = -self.slopes[None, None, :, None, None] * dist | |
| sink = self.sink_logit[None, None, :, None, None].expand(*bias.shape[:-1], 1) | |
| return torch.cat([bias, sink], -1)[:, None] # [N, 1, B or 1, H, M, M + 1] | |
| class MicAttention(nn.Module): | |
| """Attention across the microphones of one band and frame, with the geometry bias.""" | |
| def __init__(self, cfg: TrackerConfig, dim: int, radius: float, per_band: bool): | |
| super().__init__() | |
| self.norm = nn.LayerNorm(dim) | |
| self.attn = Attention(dim, cfg.heads) | |
| self.geometry = GeometryBias(cfg, radius, per_band) | |
| self.sink = nn.Parameter(torch.zeros(dim)) | |
| def forward(self, x, geometry): # x [N, T, M, B, D] | |
| y = self.norm(x).transpose(2, 3) # [N, T, B, M, D] | |
| sink = self.sink.expand(*y.shape[:3], 1, -1) | |
| return x + self.attn(y, torch.cat([y, sink], 3), geometry).transpose(2, 3) | |
| class BandBlock(nn.Module): | |
| """Band stage: compare microphones (geometry-aware), average over time, then mix.""" | |
| def __init__(self, cfg: TrackerConfig, radius: float): | |
| super().__init__() | |
| d = cfg.band_width | |
| self.mic = MicAttention(cfg, d, radius, per_band=True) | |
| self.smooth = Smoothing(d, cfg.heads, cfg.smooth_slowest) if cfg.smooth else None | |
| self.ns, self.nm = nn.LayerNorm(d), nn.LayerNorm(d) | |
| self.mlp = Mlp(d, cfg.mlp_ratio) | |
| def forward(self, x, geometry): # x [N, T, M, B, D] | |
| x = self.mic(x, geometry) | |
| if self.smooth is not None: | |
| x = x + self.smooth(self.ns(x).permute(0, 2, 3, 1, 4)).permute(0, 3, 1, 2, 4) | |
| return x + self.mlp(self.nm(x)) | |
| def step(self, x, geometry, state): # x [N, 1, M, B, D] | |
| x = self.mic(x, geometry) | |
| if self.smooth is not None: | |
| y, state = self.smooth.step(self.ns(x)[:, 0], state) | |
| x = x + y[:, None] | |
| return x + self.mlp(self.nm(x)), state | |
| def chunk(self, x, geometry, state): # x [N, T, M, B, D] | |
| x = self.mic(x, geometry) | |
| if self.smooth is not None: | |
| y, state = self.smooth.chunk(self.ns(x).permute(0, 2, 3, 1, 4), state) | |
| x = x + y.permute(0, 3, 1, 2, 4) | |
| return x + self.mlp(self.nm(x)), state | |
| class MainBlock(nn.Module): | |
| def __init__(self, cfg: TrackerConfig, radius: float): | |
| super().__init__() | |
| d = cfg.width | |
| self.mic = MicAttention(cfg, d, radius, per_band=False) | |
| self.nt, self.nm = nn.LayerNorm(d), nn.LayerNorm(d) | |
| self.time = TimeAttention(d, cfg.heads, cfg.window, cfg.slowest_slope) | |
| self.mlp = Mlp(d, cfg.mlp_ratio) | |
| def forward(self, x, geometry): # x [N, T, M, 1, D] | |
| x = self.mic(x, geometry) | |
| x = x + self.time(self.nt(x).permute(0, 2, 3, 1, 4)).permute(0, 3, 1, 2, 4) | |
| return x + self.mlp(self.nm(x)) | |
| def step(self, x, geometry, state): | |
| x = self.mic(x, geometry) | |
| y, state = self.time.step(self.nt(x)[:, 0], state) | |
| x = x + y[:, None] | |
| return x + self.mlp(self.nm(x)), state | |
| def chunk(self, x, geometry, state): # x [N, T, M, 1, D] | |
| x = self.mic(x, geometry) | |
| y, state = self.time.chunk(self.nt(x).permute(0, 2, 3, 1, 4), state) | |
| x = x + y.permute(0, 3, 1, 2, 4) | |
| return x + self.mlp(self.nm(x)), state | |
| class SteeredPower(nn.Module): | |
| """Delay-and-sum power of the PHAT-normalised phases toward each grid direction, per band. | |
| power(u, f) = | sum_i exp(j (phase_i(f) - k_f (r_i - r_ref) . u)) |^2 / M^2 | |
| This is SRP-PHAT over all microphone pairs. It uses the exact wavenumber of every | |
| bin and the exact geometry, so it is right for any array without being learned. | |
| """ | |
| def __init__(self, cfg: TrackerConfig): | |
| super().__init__() | |
| self.cfg = cfg | |
| self.register_buffer("grid", fibonacci_directions(cfg.grid)) # [G, 3] | |
| hz = torch.arange(1, cfg.bins + 1) * cfg.fs / cfg.n_fft | |
| self.register_buffer("wavenumber", 2 * math.pi * hz / SPEED_OF_SOUND) # [F] | |
| def steering(self, rel_pos): # rel_pos [N, M, 3] = r_i - r_ref | |
| theta = self.wavenumber[None, :, None, None] * torch.matmul(rel_pos, self.grid.T)[:, None] # [N, F, M, G] | |
| return theta.cos(), theta.sin() | |
| def forward(self, cos_phase, sin_phase, steering): # phases [N, F, T, M] | |
| cs, sn = steering | |
| re = torch.matmul(cos_phase, cs) + torch.matmul(sin_phase, sn) # [N, F, T, G] | |
| im = torch.matmul(sin_phase, cs) - torch.matmul(cos_phase, sn) | |
| power = (re.square() + im.square()) / cos_phase.shape[-1] ** 2 | |
| power = power.unflatten(1, (self.cfg.bands, self.cfg.bins_per_band)).mean(2) # [N, B, T, G] | |
| return power.permute(0, 2, 3, 1) # [N, T, G, B] | |
| class MapBlock(nn.Module): | |
| """Direction tokens: average the steered power over time, then mix.""" | |
| def __init__(self, cfg: TrackerConfig): | |
| super().__init__() | |
| d = cfg.grid_width | |
| self.ns, self.nm = nn.LayerNorm(d), nn.LayerNorm(d) | |
| self.smooth = Smoothing(d, cfg.heads, cfg.smooth_slowest) | |
| self.mlp = Mlp(d, cfg.mlp_ratio) | |
| def forward(self, g): # g [N, T, G, D] | |
| g = g + self.smooth(self.ns(g).transpose(1, 2)).transpose(1, 2) | |
| return g + self.mlp(self.nm(g)) | |
| def step(self, g, state): # g [N, 1, G, D] | |
| y, state = self.smooth.step(self.ns(g)[:, 0], state) | |
| g = g + y[:, None] | |
| return g + self.mlp(self.nm(g)), state | |
| def chunk(self, g, state): # g [N, T, G, D] | |
| y, state = self.smooth.chunk(self.ns(g).transpose(1, 2), state) | |
| g = g + y.transpose(1, 2) | |
| return g + self.mlp(self.nm(g)), state | |
| class TrackBlock(nn.Module): | |
| def __init__(self, cfg: TrackerConfig): | |
| super().__init__() | |
| d, h = cfg.width, cfg.heads | |
| self.n1, self.n2, self.n3, self.n4, self.nm = (nn.LayerNorm(d) for _ in range(5)) | |
| self.read_mics, self.among = Attention(d, h), Attention(d, h) | |
| if cfg.steered: | |
| self.read_map, self.n1g = SharedRead(d, h), nn.LayerNorm(d) | |
| self.steered = cfg.steered | |
| self.time = TimeAttention(d, h, cfg.window, cfg.slowest_slope) | |
| self.mlp = Mlp(d, cfg.mlp_ratio) | |
| def space(self, s, mics, directions): # s [N, T, K, D]; reads the current frame only | |
| s = s + self.read_mics(self.n1(s), self.nm(mics)) | |
| if self.steered: | |
| s = s + self.read_map(self.n1g(s), *directions) # directions = shared (keys, values) | |
| y = self.n2(s) | |
| return s + self.among(y, y) # slots see each other | |
| def forward(self, s, mics, directions): | |
| s = self.space(s, mics, directions) | |
| s = s + self.time(self.n3(s).transpose(1, 2)).transpose(1, 2) | |
| return s + self.mlp(self.n4(s)) | |
| def step(self, s, mics, directions, state): # s [N, 1, K, D] | |
| s = self.space(s, mics, directions) | |
| y, state = self.time.step(self.n3(s)[:, 0], state) | |
| s = s + y[:, None] | |
| return s + self.mlp(self.n4(s)), state | |
| def chunk(self, s, mics, directions, state): # s [N, T, K, D] | |
| s = self.space(s, mics, directions) | |
| y, state = self.time.chunk(self.n3(s).transpose(1, 2), state) | |
| s = s + y.transpose(1, 2) | |
| return s + self.mlp(self.n4(s)), state | |
| class Tracker(nn.Module): | |
| def __init__(self, cfg: TrackerConfig = TrackerConfig()): | |
| super().__init__() | |
| self.cfg = cfg | |
| d1, d, dg = cfg.band_width, cfg.width, cfg.grid_width | |
| self.register_buffer("window", torch.hann_window(cfg.n_fft)) | |
| assert cfg.level in ("none", "relative", "absolute") | |
| feats = 2 if cfg.level == "none" else 4 if cfg.relative_phase or cfg.level == "relative" else 3 | |
| self.embed = nn.Linear(feats * cfg.bins_per_band, d1, bias=False) # shared by all bands | |
| self.band_embedding = nn.Parameter(torch.zeros(cfg.bands, d1)) | |
| self.first_smooth = Smoothing(d1, cfg.heads, cfg.smooth_slowest) if cfg.smooth else None | |
| self.band_stage = nn.ModuleList(BandBlock(cfg, 0.5 * 2 ** i) for i in range(cfg.band_blocks)) | |
| self.merge = nn.Linear(cfg.bands * d1, d) | |
| self.main = nn.ModuleList(MainBlock(cfg, 0.5 * 2 ** i) for i in range(cfg.main_blocks)) | |
| if cfg.steered: | |
| self.power = SteeredPower(cfg) | |
| self.map_embed = nn.Linear(cfg.bands, dg) | |
| self.where = nn.Linear(3, dg, bias=False) # tells each token its direction | |
| self.map_stage = nn.ModuleList(MapBlock(cfg) for _ in range(cfg.grid_blocks)) | |
| self.map_norm = nn.LayerNorm(dg) | |
| self.map_keys, self.map_values = nn.Linear(dg, d), nn.Linear(dg, d) # projected once for all track blocks | |
| self.point_q, self.point_k = nn.Linear(d, dg), nn.Linear(dg, dg) # soft peak picking | |
| self.point_gate = nn.Linear(d, 1) # how much of the picked peak to use | |
| self.slots = nn.Parameter(torch.randn(cfg.slots, d) * 0.02) | |
| self.tracks = nn.ModuleList(TrackBlock(cfg) for _ in range(cfg.trk_blocks)) | |
| self.out_norm = nn.LayerNorm(d) | |
| self.vector = nn.Linear(d, 3) # one vector per output: length = activity, direction = where | |
| # ---- per-array quantities, computed once ---- | |
| def geometry(self, pos): # pos [N, M, 3] | |
| ref = (pos - pos.mean(1, keepdim=True)).norm(dim=-1).argmin(1) # microphone nearest the centroid | |
| geo = {"ref": ref, | |
| "band": [b.mic.geometry(pos) for b in self.band_stage], | |
| "main": [b.mic.geometry(pos) for b in self.main]} | |
| if self.cfg.steered: | |
| rel = pos - pos[torch.arange(pos.shape[0], device=pos.device), ref][:, None] | |
| geo["steering"] = self.power.steering(rel) | |
| return geo | |
| # ---- front end ---- | |
| def running_level(self, frame_level, state): # frame_level [N, T]: each frame's mean log-magnitude | |
| """The mean level of what has been heard up to and including each frame, with exponential forgetting: | |
| mean_t = sum_j g^(t-j) level_j / sum_j g^(t-j) over the frames j <= t that hold signal. Frames of digital | |
| silence (padding) are left out: they would pull the mean down and make what follows look loud. | |
| `state`: None (the clip starts here), or the dict this function fills, to continue from earlier frames.""" | |
| g, frames = math.exp(-self.cfg.level_slope), frame_level.shape[1] | |
| heard = (frame_level > SILENT_LEVEL).to(frame_level.dtype) | |
| sums = torch.stack([frame_level * heard, heard]) # [2, N, T]: weighted sum and weight | |
| shift = 1 | |
| while shift < frames: # exact first-order recursion, as Smoothing | |
| sums = sums + nn.functional.pad(g ** shift * sums[..., :-shift], (shift, 0)) | |
| shift *= 2 | |
| if state is not None and state.get("level") is not None: | |
| sums = sums + state["level"][..., None] * g ** torch.arange(1, frames + 1, device=sums.device, dtype=sums.dtype) | |
| if state is not None: | |
| state["level"] = sums[..., -1] | |
| return sums[0] / sums[1].clamp(min=1e-30) # nothing heard yet: 0 | |
| def features(self, audio, ref, state=None): # audio [N, M, samples]; state: only the running level uses it | |
| cfg = self.cfg | |
| n, m, _ = audio.shape | |
| spec = torch.stft(audio.flatten(0, 1), cfg.n_fft, cfg.hop, window=self.window, | |
| center=False, return_complex=True) # frame t ends at t*hop + n_fft | |
| spec = spec[:, 1:].unflatten(0, (n, m)).permute(0, 3, 1, 2) # [N, T, M, F], DC dropped | |
| if cfg.level != "absolute": | |
| # Every bin of every microphone at unit magnitude before anything else: what is left is phase, and a gain | |
| # on the input (one for all microphones, or one for each) changes nothing. A bin without signal stays zero. | |
| size = spec.abs().clamp(min=UNIT_FLOOR) | |
| unit = spec / size | |
| cross = unit * unit[torch.arange(n, device=audio.device), :, ref].conj().unsqueeze(2) | |
| c, s = cross.real, cross.imag # phase relative to the reference | |
| x = [c, s] if cfg.relative_phase else [unit.real, unit.imag] | |
| if cfg.level == "relative": | |
| # the level difference between microphones, and their mean level relative to the running mean of | |
| # what has been heard: one gain on the whole input cancels in both | |
| log_mag = torch.log(size) | |
| level = log_mag.mean(dim=2, keepdim=True) # [N, T, 1, F] | |
| heard = self.running_level(level.mean(dim=(2, 3)), state) # [N, T] | |
| x = x + [log_mag - level, (level - heard[:, :, None, None]).clamp(-LEVEL_RANGE, LEVEL_RANGE).expand_as(log_mag)] | |
| x = torch.stack(x, -1).unflatten(3, (cfg.bands, cfg.bins_per_band)).flatten(-2) # [N, T, M, B, features] | |
| return x, c.permute(0, 3, 1, 2), s.permute(0, 3, 1, 2) # phases as [N, F, T, M] | |
| log_mag = torch.log(spec.abs() + 1e-8) | |
| level = log_mag.mean(dim=2, keepdim=True) # [N, T, 1, F] | |
| cross = spec * spec[torch.arange(n, device=audio.device), :, ref].conj().unsqueeze(2) | |
| unit = cross / (cross.abs() + 1e-8) # phase relative to the reference | |
| c, s = unit.real, unit.imag | |
| if cfg.relative_phase: | |
| x = torch.stack([c, s, log_mag - level, level.expand_as(log_mag)], -1) | |
| else: | |
| own = torch.view_as_real(spec / torch.exp(level)) | |
| x = torch.stack([own[..., 0], own[..., 1], level.expand_as(log_mag)], -1) | |
| x = x.unflatten(3, (cfg.bands, cfg.bins_per_band)).flatten(-2) # [N, T, M, B, features] | |
| return x, c.permute(0, 3, 1, 2), s.permute(0, 3, 1, 2) # phases as [N, F, T, M] | |
| def map_tokens(self, c, s, geo): | |
| power = self.power(c, s, geo["steering"]) # [N, T, G, B] | |
| return self.map_embed(power) + self.where(self.power.grid) | |
| def map_memory(self, directions): | |
| """Keys and values of the direction tokens, shared by all track blocks.""" | |
| y, h = self.map_norm(directions), self.cfg.heads | |
| return split_heads(self.map_keys(y), h), split_heads(self.map_values(y), h) | |
| def heads_out(self, s, directions): | |
| """One vector per output and frame, as in ACCDOA: its length says whether a source is | |
| there (near 1) or not (near 0), and its direction says where.""" | |
| s = self.out_norm(s) | |
| vec = self.vector(s) | |
| if self.cfg.steered: | |
| logits = torch.matmul(self.point_q(s), self.point_k(directions).transpose(-1, -2)) / math.sqrt(self.cfg.grid_width) | |
| peak = torch.matmul(logits.softmax(-1), self.power.grid) # weighted mean of grid directions | |
| vec = vec + torch.sigmoid(self.point_gate(s)) * peak | |
| return {"vector": vec} # [N, T, K, 3] | |
| # ---- whole clip ---- | |
| def forward(self, audio, pos, every_block: bool = False): | |
| """audio [N, M, samples] at cfg.fs; pos [N, M, 3] in metres. | |
| every_block=True also returns the outputs after each track block, for deep supervision.""" | |
| cfg, geo = self.cfg, self.geometry(pos) | |
| feats, c, s = self.features(audio, geo["ref"]) | |
| x = self.embed(feats) + self.band_embedding | |
| if self.first_smooth is not None: # linear averaging before any non-linearity | |
| x = x + self.first_smooth(x.permute(0, 2, 3, 1, 4)).permute(0, 3, 1, 2, 4) | |
| for block, g in zip(self.band_stage, geo["band"]): | |
| x = block(x, g) | |
| x = self.merge(x.flatten(-2)).unsqueeze(3) # [N, T, M, 1, D] | |
| for block, g in zip(self.main, geo["main"]): | |
| x = block(x, g) | |
| mics = x.flatten(2, 3) | |
| directions = None | |
| if cfg.steered: | |
| directions = self.map_tokens(c, s, geo) | |
| for block in self.map_stage: | |
| directions = block(directions) | |
| memory = self.map_memory(directions) if cfg.steered else None | |
| slots = self.slots.expand(x.shape[0], x.shape[1], -1, -1) | |
| outs = [] | |
| for block in self.tracks: | |
| slots = block(slots, mics, memory) | |
| if every_block: | |
| outs.append(self.heads_out(slots, directions)) | |
| return outs if every_block else self.heads_out(slots, directions) | |
| # ---- streaming ---- | |
| def init_state(self, pos): | |
| """Streaming state. Its size stops growing once `window` frames have been seen.""" | |
| cfg = self.cfg | |
| return {"geometry": self.geometry(pos), "pos": pos, "level": None, "first": None, "band": [None] * cfg.band_blocks, | |
| "main": [None] * cfg.main_blocks, "map": [None] * cfg.grid_blocks, "tracks": [None] * cfg.trk_blocks} | |
| def step(self, frame, state): | |
| """One frame. frame [N, M, n_fft]: the newest n_fft samples. Returns outputs with T = 1.""" | |
| cfg, geo = self.cfg, state["geometry"] | |
| feats, c, s = self.features(frame, geo["ref"], state) | |
| x = self.embed(feats) + self.band_embedding | |
| if self.first_smooth is not None: | |
| y, state["first"] = self.first_smooth.step(x[:, 0], state["first"]) | |
| x = x + y[:, None] | |
| for i, block in enumerate(self.band_stage): | |
| x, state["band"][i] = block.step(x, geo["band"][i], state["band"][i]) | |
| x = self.merge(x.flatten(-2)).unsqueeze(3) | |
| for i, block in enumerate(self.main): | |
| x, state["main"][i] = block.step(x, geo["main"][i], state["main"][i]) | |
| mics = x.flatten(2, 3) | |
| directions = None | |
| if cfg.steered: | |
| directions = self.map_tokens(c, s, geo) | |
| for i, block in enumerate(self.map_stage): | |
| directions, state["map"][i] = block.step(directions, state["map"][i]) | |
| memory = self.map_memory(directions) if cfg.steered else None | |
| slots = self.slots.expand(x.shape[0], 1, -1, -1) | |
| for i, block in enumerate(self.tracks): | |
| slots, state["tracks"][i] = block.step(slots, mics, memory, state["tracks"][i]) | |
| return self.heads_out(slots, directions), state | |
| # ---- long clips: consecutive chunks that carry the state ---- | |
| def chunk(self, audio, state, every_block: bool = False): | |
| """A run of consecutive frames, continuing from `state` (from `init_state`, `step` or `chunk`). | |
| audio [N, M, n_fft + (T - 1) * hop]: exactly the samples those T frames cover, so consecutive | |
| chunks overlap by n_fft - hop samples. Outputs equal the same frames of `forward` on the whole clip.""" | |
| cfg, geo = self.cfg, state["geometry"] | |
| feats, c, s = self.features(audio, geo["ref"], state) | |
| x = self.embed(feats) + self.band_embedding | |
| if self.first_smooth is not None: | |
| y, state["first"] = self.first_smooth.chunk(x.permute(0, 2, 3, 1, 4), state["first"]) | |
| x = x + y.permute(0, 3, 1, 2, 4) | |
| for i, block in enumerate(self.band_stage): | |
| x, state["band"][i] = block.chunk(x, geo["band"][i], state["band"][i]) | |
| x = self.merge(x.flatten(-2)).unsqueeze(3) | |
| for i, block in enumerate(self.main): | |
| x, state["main"][i] = block.chunk(x, geo["main"][i], state["main"][i]) | |
| mics = x.flatten(2, 3) | |
| directions = None | |
| if cfg.steered: | |
| directions = self.map_tokens(c, s, geo) | |
| for i, block in enumerate(self.map_stage): | |
| directions, state["map"][i] = block.chunk(directions, state["map"][i]) | |
| memory = self.map_memory(directions) if cfg.steered else None | |
| slots = self.slots.expand(x.shape[0], x.shape[1], -1, -1) | |
| outs = [] | |
| for i, block in enumerate(self.tracks): | |
| slots, state["tracks"][i] = block.chunk(slots, mics, memory, state["tracks"][i]) | |
| if every_block: | |
| outs.append(self.heads_out(slots, directions)) | |
| return (outs if every_block else self.heads_out(slots, directions)), state | |
| def detach_state(self, state): | |
| """Cut the gradient path into the past (truncated back-propagation between chunks). The geometry | |
| bias has learned parameters, so it is rebuilt rather than detached.""" | |
| def cut(obj): | |
| if torch.is_tensor(obj): | |
| return obj.detach() | |
| if isinstance(obj, dict): | |
| return {k: cut(v) for k, v in obj.items()} | |
| if isinstance(obj, list): | |
| return [cut(v) for v in obj] | |
| return obj | |
| fresh = {k: cut(v) for k, v in state.items() if k != "geometry"} | |
| fresh["geometry"] = self.geometry(state["pos"]) | |
| return fresh | |
| def chunked(self, audio, pos, frames: int): | |
| """Whole clip in chunks of `frames` frames; gives the same outputs as `forward` at bounded memory.""" | |
| cfg, state, outs = self.cfg, self.init_state(pos), [] | |
| total = (audio.shape[-1] - cfg.n_fft) // cfg.hop + 1 | |
| for first in range(0, total, frames): | |
| last = min(first + frames, total) | |
| out, state = self.chunk(audio[..., first * cfg.hop:(last - 1) * cfg.hop + cfg.n_fft], state) | |
| outs.append(out) | |
| return {key: torch.cat([o[key] for o in outs], 1) for key in outs[0]} | |
| def stream(self, audio, pos): | |
| """Run `step` over a clip and stack the outputs; used to test against `forward`.""" | |
| cfg, state, outs = self.cfg, self.init_state(pos), [] | |
| for start in range(0, audio.shape[-1] - cfg.n_fft + 1, cfg.hop): | |
| out, state = self.step(audio[..., start:start + cfg.n_fft], state) | |
| outs.append(out) | |
| return {key: torch.cat([o[key] for o in outs], 1) for key in outs[0]} | |
| FULL = TrackerConfig() | |
| # ablations: one signal-processing addition removed at a time | |
| NO_STEERED = TrackerConfig(steered=False) | |
| NO_SMOOTH = TrackerConfig(smooth=False) | |
| NO_RELATIVE_PHASE = TrackerConfig(relative_phase=False) | |
| RELATIVE_LEVEL = TrackerConfig(level="relative") # levels relative to a running mean: no gain on the whole input matters | |
| RELATIVE_LEVEL_8S = TrackerConfig(level="relative", level_slope=1 / 1000) # the same with a running mean of 8 s instead of 2 | |
| ABSOLUTE_LEVEL = TrackerConfig(level="absolute") # the inputs with their log-magnitudes, as until 21 November 2026 | |
| PLAIN = TrackerConfig(steered=False, smooth=False, relative_phase=False, trk_blocks=2) # yesterday's two-stage model | |
| # does the attention bias add anything once the steered branch is there? (SPEC section 11) | |
| DISTANCE_BIAS = TrackerConfig(bias_offsets=False) # zero offsets only: ALiBi on distance in wavelengths | |
| METRE_BIAS = TrackerConfig(bias_wavelengths=False) # displacement in metres: no frequency dependence | |
| GRID_64 = TrackerConfig(grid=64) | |
| BANDS_8 = TrackerConfig(bands=8) | |
| PRESETS = {"full": FULL, "no_steered": NO_STEERED, "no_smooth": NO_SMOOTH, "no_relative_phase": NO_RELATIVE_PHASE, | |
| "relative_level": RELATIVE_LEVEL, "relative_level_8s": RELATIVE_LEVEL_8S, "absolute_level": ABSOLUTE_LEVEL, | |
| "plain": PLAIN, "distance_bias": DISTANCE_BIAS, "metre_bias": METRE_BIAS, "grid_64": GRID_64, "bands_8": BANDS_8} | |