File size: 3,849 Bytes
49d63ea | 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 | """The deliberately restricted public POI directory, separate from all weights."""
from pathlib import Path
import hashlib
import json
import numpy as np
import torch
CANONICAL_KEYS = ('candidate_id', 'variant_id', 'lexical_id', 'lexical_entity_id',
'cell', 'surface_id', 'canonical', 'decoder_token_ids')
def digest(value):
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
separators=(',', ':'), allow_nan=False).encode()).hexdigest()
class PublicCatalog:
def __init__(self, root):
root = Path(root)
self.rows = [json.loads(line) for line in (root / 'assets/catalog.jsonl').read_text().splitlines() if line]
self.embeddings = np.load(root / 'assets/embeddings.npy', allow_pickle=False)
if self.embeddings.dtype != np.float32 or self.embeddings.ndim != 2 or self.embeddings.shape[1] != 128:
raise ValueError('Expected the released FP32 name embedding matrix')
self.pois = {row['id']: row for row in json.loads((root / 'pois.json').read_text())}
if len(self.rows) != 500 or len(self.pois) != 500:
raise ValueError('This release contains exactly 500 public entities')
self.by_region = {}
self.route_order = {}
for row in self.rows:
for key in CANONICAL_KEYS:
if key not in row:
raise ValueError('Incomplete public candidate: ' + key)
if row['surface_id'] != '-'.join(map(str, row['decoder_token_ids'])):
raise ValueError('Surface IDs must encode decoder token IDs')
self.by_region.setdefault(row['cell'], []).append(row)
self.route_order[row['cell']] = row['route_tiebreak']
def pool(self, cells):
rows = sorted((dict(row) for row in self.rows if row['cell'] in cells), key=lambda row: (row['variant_tiebreak'], row['candidate_tiebreak']))
embeddings = torch.from_numpy(np.ascontiguousarray(
self.embeddings[[row['variant_id'] for row in rows]]))
keys = dict(surface_ids='surface_id', candidate_cells='cell', variant_ids='variant_id',
candidate_ids='candidate_id', lexical_ids='lexical_id',
lexical_entity_ids='lexical_entity_id', decoder_token_ids='decoder_token_ids',
canonical_names='canonical')
pool = {plural: [row[singular] for row in rows] for plural, singular in keys.items()}
pool['embeddings'] = embeddings
ref = dict(sha256=digest(dict(rows=rows, cells=list(cells),
embedding_SHA256=hashlib.sha256(embeddings.numpy().tobytes()).hexdigest())),
size=len(rows))
minimum = {}
for i, row in enumerate(rows):
row['index'] = i
identity = {key: row[key] for key in CANONICAL_KEYS}
row['candidate_identity_sha256'] = digest(identity)
row['candidate_binding_sha256'] = digest(dict(original_pool=ref, original_pool_row=i, identity=identity))
minimum.setdefault(row['canonical'], row)
metadata = dict(rows=rows, minimum_row_per_canonical=minimum,
unique_surfaces=len(set(pool['surface_ids'])))
return pool, ref, metadata
def route(self, candidates, region_to_id):
support = {}
for row in candidates:
cell, score = row['cell'], row['acoustic_score']
if not np.isfinite(score):
raise ValueError('Nonfinite acoustic route evidence')
if cell in region_to_id:
support[cell] = max(score, support.get(cell, -float('inf')))
if not support:
return None
cell = max(support, key=lambda value: (support[value], self.route_order[value]))
return dict(present=True, region_ids=[region_to_id[cell]], weights=[1.0])
|