Download components/router.py from guga-guga/GeoPOI: direct link, hf CLI and curl.
- Browser
- Download file 8.09 kB
-
https://huggingface.co/guga-guga/GeoPOI/resolve/main/components/router.py
- Command line
-
hf download hf://guga-guga/GeoPOI/components/router.py
-
curl -L -o router.py https://huggingface.co/guga-guga/GeoPOI/resolve/main/components/router.py
8.09 kB
| """Single trained audio-semantic Near/Far/NONE inference head.""" | |
| from __future__ import annotations | |
| import json | |
| import math | |
| from pathlib import Path | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from safetensors.torch import load_file | |
| LABELS = ('Near', 'Far', 'NONE') | |
| DEFAULT_ARCHITECTURE = dict(input_dim=2048, frames=96, width=192, heads=4, layers=2, ff_width=384, dropout=0.1) | |
| DEFAULT_POLICY = dict(min_far_probability=0.6, min_none_probability=0.9, min_margin=0.1, fallback='Near') | |
| def configure_numeric(): | |
| torch.set_float32_matmul_precision('highest') | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch.backends.cudnn.allow_tf32 = False | |
| torch.backends.cudnn.benchmark = False | |
| def normalize_time(h2, frames=96): | |
| """The identical CPU FP32 preprocessing for cache and native inference. | |
| Every utterance has exactly `frames` output positions. Original frame count | |
| is audit metadata only, never a classifier input or a padding mask. | |
| """ | |
| x = torch.as_tensor(h2).detach().to(device='cpu', dtype=torch.float32) | |
| if x.ndim != 2 or x.shape[1] != 2048 or x.shape[0] == 0: | |
| raise ValueError('Expected nonempty complete-audio H2[T,2048]') | |
| if frames < 2 or not bool(torch.isfinite(x).all()): | |
| raise ValueError('Finite H2 and at least two normalized frames required') | |
| return F.interpolate(x.T[None], size=frames, mode='linear', align_corners=False)[0].T.contiguous() | |
| class TemporalBlock(nn.Module): | |
| """Explicit FP32 attention avoids version-specific MHA fast paths.""" | |
| def __init__(self, width, heads, ff_width, dropout): | |
| super().__init__() | |
| if width % heads: | |
| raise ValueError('Width must be divisible by heads') | |
| self.heads, self.head_dim = (heads, width // heads) | |
| self.norm1 = nn.LayerNorm(width) | |
| self.qkv = nn.Linear(width, width * 3) | |
| self.attention_projection = nn.Linear(width, width) | |
| self.norm2 = nn.LayerNorm(width) | |
| self.ff = nn.Sequential(nn.Linear(width, ff_width), nn.GELU(), nn.Dropout(dropout), nn.Linear(ff_width, width)) | |
| self.dropout = nn.Dropout(dropout) | |
| def forward(self, x): | |
| batch, steps, width = x.shape | |
| qkv = self.qkv(self.norm1(x)).reshape(batch, steps, 3, self.heads, self.head_dim) | |
| q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0) | |
| attention = (q @ k.transpose(-2, -1) / math.sqrt(self.head_dim)).softmax(dim=-1) | |
| value = (self.dropout(attention) @ v).transpose(1, 2).reshape(batch, steps, width) | |
| x = x + self.dropout(self.attention_projection(value)) | |
| return x + self.dropout(self.ff(self.norm2(x))) | |
| class AudioSemanticNetwork(nn.Module): | |
| def __init__(self, **architecture): | |
| super().__init__() | |
| architecture = {**DEFAULT_ARCHITECTURE, **architecture} | |
| self.architecture = architecture | |
| if architecture['input_dim'] != 2048: | |
| raise ValueError('Frozen V8 H2 dimension must remain 2048') | |
| d, width = (architecture['input_dim'], architecture['width']) | |
| self.register_buffer('train_mean', torch.zeros(d)) | |
| self.register_buffer('train_scale', torch.ones(d)) | |
| self.input_norm = nn.LayerNorm(d) | |
| self.input_projection = nn.Linear(d, width) | |
| self.position = nn.Parameter(torch.zeros(1, architecture['frames'], width)) | |
| nn.init.normal_(self.position, std=0.02) | |
| self.blocks = nn.ModuleList([TemporalBlock(width, architecture['heads'], architecture['ff_width'], architecture['dropout']) for _ in range(architecture['layers'])]) | |
| self.output_norm = nn.LayerNorm(width) | |
| self.pool_projection = nn.Sequential(nn.LayerNorm(width * 2), nn.Linear(width * 2, width), nn.GELU(), nn.Dropout(architecture['dropout'])) | |
| self.classifier = nn.Linear(width, 3) | |
| def forward(self, normalized_h2): | |
| x = normalized_h2 | |
| if x.ndim != 3 or tuple(x.shape[1:]) != (self.architecture['frames'], 2048): | |
| raise ValueError('Expected fixed-frame normalized H2 batch') | |
| x = ((x - self.train_mean) / self.train_scale).clamp(-12, 12) | |
| x = F.gelu(self.input_projection(self.input_norm(x))) + self.position | |
| for block in self.blocks: | |
| x = block(x) | |
| x = self.output_norm(x) | |
| pooled = torch.cat((x.mean(dim=1), x.amax(dim=1)), dim=-1) | |
| return self.classifier(self.pool_projection(pooled)) | |
| def apply_policy(probability, policy): | |
| """Only confident non-Near decisions override the requested Near fallback.""" | |
| p = torch.as_tensor(probability, dtype=torch.float32, device='cpu') | |
| if p.shape != (3,) or not bool(torch.isfinite(p).all()) or bool((p < 0).any()) or (abs(float(p.sum()) - 1) > 0.0001): | |
| raise ValueError('Three finite normalized probabilities required') | |
| order = p.argsort(descending=True) | |
| raw, second = (int(order[0]), int(order[1])) | |
| margin = float(p[raw] - p[second]) | |
| chosen = 0 | |
| if raw == 1 and float(p[1]) > policy['min_far_probability'] and (margin >= policy['min_margin']): | |
| chosen = 1 | |
| if raw == 2 and float(p[2]) > policy['min_none_probability'] and (margin >= policy['min_margin']): | |
| chosen = 2 | |
| return dict(label=LABELS[chosen], label_lower=LABELS[chosen].lower(), raw_label=LABELS[raw], probabilities={name: float(value) for name, value in zip(LABELS, p)}, confidence=float(p[raw]), margin=margin, near_fallback=chosen == 0 and raw != 0) | |
| def check_policy(policy): | |
| if set(policy) != set(DEFAULT_POLICY) or policy['fallback'] != 'Near': | |
| raise ValueError('Explicit Near fallback policy required') | |
| for key in ('min_far_probability', 'min_none_probability', 'min_margin'): | |
| if not 0 <= float(policy[key]) <= 1: | |
| raise ValueError('Invalid confidence threshold') | |
| if policy['min_none_probability'] < 0.5: | |
| raise ValueError('NONE requires an explicit confidence majority') | |
| class AudioSemanticRouter: | |
| def __init__(self, directory, device="cpu"): | |
| directory = Path(directory) | |
| self.config = json.loads((directory/"config.json").read_text()) | |
| if self.config["labels"] != list(LABELS) or self.config["classifier_heads"] != 1: | |
| raise ValueError("Exactly one trained three-logit router is required") | |
| check_policy(self.config["policy"]) | |
| self.device = torch.device(device) | |
| self.network = AudioSemanticNetwork(**self.config["architecture"]) | |
| self.network.load_state_dict(load_file(str(directory/"model.safetensors")), strict=True) | |
| self.network.to(self.device).eval().requires_grad_(False) | |
| def predict(self, h2): | |
| normalized = normalize_time(h2, self.config["architecture"]["frames"]) | |
| logits = self.network(normalized[None].to(self.device))[0].float().cpu() | |
| result = apply_policy(logits.softmax(-1), self.config["policy"]) | |
| result.update(policy="audio_semantic_near_far_none_v1", classifier_heads=1, | |
| gate_modified=False, transcript_input=False, catalog_score_input=False) | |
| return result | |
| def select(self, frames, cells, center_cell=None): | |
| original = list(cells) | |
| if len(original) != len(set(original)) or len(original) > 9: | |
| raise ValueError("A context must contain at most nine distinct region IDs") | |
| if not original: | |
| return dict(cells=[], action="missing_geography", policy="audio_semantic_near_far_none_v1", gate_modified=False) | |
| if center_cell not in original: | |
| raise ValueError("The supplied center must belong to the supplied context") | |
| prediction = self.predict(frames) | |
| label = prediction["label"] | |
| selected = [center_cell] if label == "Near" else original if label == "Far" else [] | |
| return dict(prediction, cells=selected, action={"Near":"semantic_near","Far":"semantic_far","NONE":"semantic_none"}[label], | |
| center_cell=center_cell, recall_disabled=(label == "NONE")) | |
| select_top = select | |
| def load_router(directory, package_override=None): | |
| return AudioSemanticRouter(directory) | |