GeoPOI / runtime /pre_adapter_gate.py
Tiga233's picture
Release complete GeoPOI model with shared regional basis and 500-entity public catalog
49d63ea verified
Raw History Blame Contribute Delete
12.7 kB
from __future__ import annotations
from dataclasses import dataclass, fields, is_dataclass
import hashlib, types
from threading import RLock
from typing import Any, Callable, Mapping, Protocol, Sequence
class PolicyHeads(Protocol):
def score_entry(self, features: Any) -> Any:
...
def entry_pass(self, probabilities: Any) -> Any:
...
def score_actions(self, features: Any) -> Mapping[str, Any]:
...
def _immutable(value: Any) -> Any:
if value is None or type(value) in (str, bytes, int, float, bool):
return value
if isinstance(value, Mapping):
return types.MappingProxyType({key: _immutable(item) for key, item in value.items()})
if isinstance(value, (list, tuple)):
items = tuple((_immutable(item) for item in value))
if isinstance(value, tuple) and hasattr(value, '_fields'):
return type(value)(*items)
return items
if is_dataclass(value) and value.__dataclass_params__.frozen:
if all((_unchangeable(getattr(value, f.name)) for f in fields(value))):
return value
raise TypeError('native route must contain immutable metadata, not mutable objects or tensors')
def _unchangeable(value: Any) -> bool:
if value is None or type(value) in (str, bytes, int, float, bool):
return True
return isinstance(value, tuple) and all((_unchangeable(item) for item in value))
def _identifier(value: str, name: str) -> None:
if not isinstance(value, str) or not value:
raise ValueError(name + ' must be a nonempty string')
def _index(value: int, name: str) -> None:
if type(value) is not int or value < 0:
raise ValueError(name + ' must be a nonnegative integer')
@dataclass(frozen=True)
class RawPartial:
request_id: str
context_key: str
segment_id: int
version: int
text: str
audio_time_us: int
received_audio_time_us: int
is_final: bool = False
eos_observed: bool = False
text_origin: str = 'asr_raw'
@dataclass(frozen=True)
class GateFeatures:
request_id: str
context_key: str
segment_id: int
entry_F32: Any
gate_F32: Any
action_cells: tuple[str, ...]
observed_version: int
raw_partial_text_sha256: str
audio_time_us: int
received_audio_time_us: int
@classmethod
def from_original_snapshot(cls, partial: RawPartial, entry: Any, gate: Any, actions: Sequence[Mapping[str, Any]]) -> GateFeatures:
import numpy as np
return cls(partial.request_id, partial.context_key, partial.segment_id, np.asarray([entry], dtype=np.float32), np.asarray(gate, dtype=np.float32).reshape((-1, 46)), tuple((action['candidate']['cell'] for action in actions)), partial.version, hashlib.sha256(partial.text.encode('utf-8')).hexdigest(), partial.audio_time_us, partial.received_audio_time_us)
@dataclass(frozen=True)
class GateDecision:
request_id: str
context_key: str
sequence: int
source_segment_id: int
valid_for_segment_id: int
entry_probability: float | None
entry_pass: bool
action_count: int
passing_action_indices: tuple[int, ...]
passing_candidate_cells: tuple[str, ...]
allow_adapter_next_input: bool
reason: str
@dataclass(frozen=True)
class InputRoute:
request_id: str
context_key: str
segment_id: int
enabled: bool
native_route: Any
reason: str
permission_sequence: int | None = None
passing_candidate_cells: tuple[str, ...] = ()
@dataclass
class _Request:
context_key: str
cells: frozenset[str]
last_input: int = -1
next_version: int = 0
last_partial_segment: int = -1
last_audio_us: int = -1
last_received_us: int = -1
sequence: int = 0
consumed_sequence: int = -1
permission: GateDecision | None = None
active_route: InputRoute | None = None
class PreAdapterGate:
def __init__(self, heads: PolicyHeads):
self.heads = heads
self._requests: dict[str, _Request] = {}
self._lock = RLock()
def begin_request(self, request_id: str, *, context_key: str, allowed_cells: Sequence[str]) -> None:
_identifier(request_id, 'request_id')
_identifier(context_key, 'context_key')
if isinstance(allowed_cells, (str, bytes)):
raise TypeError('allowed_cells must be a sequence of GPS cell strings')
cells = tuple(allowed_cells)
if len(cells) > 9 or len(set(cells)) != len(cells):
raise ValueError('original request scope requires at most nine distinct GPS cells')
for cell in cells:
_identifier(cell, 'GPS cell')
with self._lock:
if request_id in self._requests:
raise ValueError('request is already active')
self._requests[request_id] = _Request(context_key, frozenset(cells))
def _request(self, request_id: str, context_key: str) -> _Request:
state = self._requests.get(request_id)
if state is None:
raise ValueError('request is not active')
if state.context_key != context_key:
raise ValueError('request context binding differs')
return state
def observe_partial(self, partial: RawPartial, feature_builder: Callable[[RawPartial], GateFeatures]) -> GateDecision:
with self._lock:
state = self._request(partial.request_id, partial.context_key)
for name in ('segment_id', 'version', 'audio_time_us', 'received_audio_time_us'):
_index(getattr(partial, name), name)
if type(partial.is_final) is not bool or type(partial.eos_observed) is not bool:
raise TypeError('final and EOF flags must be Boolean')
if partial.is_final or partial.eos_observed or partial.text_origin != 'asr_raw':
raise ValueError('only a nonfinal, pre-EOF ASR raw partial may grant permission')
if not isinstance(partial.text, str):
raise TypeError('raw partial text must be Unicode')
partial.text.encode('utf-8', errors='strict')
if partial.segment_id != state.last_input or partial.segment_id <= state.last_partial_segment or partial.version != state.next_version:
raise ValueError('partial must bind once to the current INPUT and next version')
if partial.audio_time_us > partial.received_audio_time_us or partial.audio_time_us < state.last_audio_us or partial.received_audio_time_us < state.last_received_us:
raise ValueError('partial audio must already have arrived; clocks must be monotone')
probability, entry_pass, count, passing, cells = (None, False, 0, (), ())
if state.cells:
import numpy as np
from threadpoolctl import threadpool_limits
features = feature_builder(partial)
if (features.request_id, features.context_key, features.segment_id) != (partial.request_id, partial.context_key, partial.segment_id):
raise ValueError('features must come from this request/context/segment')
if (features.observed_version, features.raw_partial_text_sha256, features.audio_time_us, features.received_audio_time_us) != (partial.version, hashlib.sha256(partial.text.encode('utf-8')).hexdigest(), partial.audio_time_us, partial.received_audio_time_us):
raise ValueError('features must bind the current raw partial version/text/clocks')
entry, gate = (np.asarray(features.entry_F32), np.asarray(features.gate_F32))
count = len(features.action_cells)
if entry.dtype != np.float32 or entry.shape != (1, 18) or gate.dtype != np.float32 or (gate.shape != (count, 46)) or (not np.isfinite(entry).all()) or (not np.isfinite(gate).all()):
raise ValueError('expected finite unnormalized original F32[1,18] and F32[A,46]')
with threadpool_limits(limits=1):
ep = np.asarray(self.heads.score_entry(entry))
scores = self.heads.score_actions(gate)
entry_flags = np.asarray(self.heads.entry_pass(ep))
flags = np.asarray(scores['passing'])
if ep.dtype != np.float32 or ep.shape != (1,) or (not np.isfinite(ep).all()) or (not ((ep >= 0) & (ep <= 1)).all()) or (entry_flags.dtype != np.bool_) or (entry_flags.shape != (1,)) or (flags.dtype != np.bool_) or (flags.shape != (count,)):
raise ValueError('original heads returned incompatible probability/pass arrays')
probability, entry_pass = (float(ep[0]), bool(entry_flags[0]))
passing = tuple((int(i) for i in np.flatnonzero(flags)))
if entry_pass and passing:
cells = tuple(sorted({features.action_cells[i] for i in passing}))
if not set(cells).issubset(state.cells):
raise ValueError('passing candidate cells exceed the request GPS scope')
allowed = entry_pass and bool(passing)
reason = 'MISSING_GEOGRAPHY_NO_GATE_SCORING' if not state.cells else 'CURRENT_GATE_ALLOW' if allowed else 'CURRENT_GATE_REJECT'
decision = GateDecision(partial.request_id, partial.context_key, state.sequence, partial.segment_id, partial.segment_id + 1, probability, entry_pass, count, passing, cells, allowed, reason)
state.permission = decision
state.sequence += 1
state.next_version += 1
state.last_partial_segment = partial.segment_id
state.last_audio_us = partial.audio_time_us
state.last_received_us = partial.received_audio_time_us
return decision
def begin_input(self, request_id: str, *, context_key: str, segment_id: int, current_shortlist: Sequence[Mapping[str, Any]], route_builder: Callable[[list[Mapping[str, Any]]], Any]) -> InputRoute:
_index(segment_id, 'segment_id')
with self._lock:
state = self._request(request_id, context_key)
if segment_id <= state.last_input:
raise ValueError('begin_input must advance once; token hooks use route_for_token')
state.last_input = segment_id
permission = state.permission
reason, sequence, cells, route = ('NO_PRIOR_NONFINAL_PARTIAL', None, (), None)
state.active_route = InputRoute(request_id, context_key, segment_id, False, None, reason)
if not state.cells:
reason = 'MISSING_GEOGRAPHY_NO_GATE_SCORING'
elif permission is not None:
sequence = permission.sequence
if permission.valid_for_segment_id != segment_id:
reason = 'STALE_PERMISSION_NOT_NEXT_INPUT'
elif sequence <= state.consumed_sequence:
reason = 'PERMISSION_ALREADY_CONSUMED'
else:
state.consumed_sequence = sequence
reason = 'CURRENT_GATE_REJECT'
if permission.allow_adapter_next_input:
cells = permission.passing_candidate_cells
filtered = [row for row in current_shortlist if row['cell'] in cells]
route = route_builder(filtered) if filtered else None
present = route.get('present') if isinstance(route, Mapping) else getattr(route, 'present', False)
if type(present) is not bool:
raise ValueError('original native route must expose a Boolean present')
if not present:
route = None
elif route is not None:
route = _immutable(route)
reason = 'CURRENT_GATE_ALLOW' if route is not None else 'NO_PASSING_CELL_IN_CURRENT_ACOUSTIC_EVIDENCE'
result = InputRoute(request_id, context_key, segment_id, route is not None, route, reason, sequence, cells)
state.active_route = result
return result
def route_for_token(self, request_id: str, *, context_key: str, segment_id: int) -> InputRoute:
with self._lock:
state = self._request(request_id, context_key)
if state.active_route is None or state.active_route.segment_id != segment_id:
raise ValueError('token must belong to the current begun INPUT')
return state.active_route
def end_request(self, request_id: str, *, context_key: str) -> None:
with self._lock:
self._request(request_id, context_key)
del self._requests[request_id]