SammySnake commited on
Commit
bf99854
·
verified ·
1 Parent(s): 10d226e

Connect real BEV features to semantic-map matching with bounded NPZ inputs

Browse files
Files changed (4) hide show
  1. MAP_MATCHING.md +87 -0
  2. README.md +2 -1
  3. app.py +27 -3
  4. bev_matching.py +242 -0
MAP_MATCHING.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Real BEV-to-semantic-map matching API
2
+
3
+ `/match_bev(features_npz, maps_npz)` returns `(JSON receipt, diagnostics NPZ)`.
4
+ This is **OrienterNet-MGL pretrained map encoding + exhaustive BEV voting + the
5
+ trained map unary prior**. It is not an image-generation step or a satellite
6
+ encoder, and does not apply a supplied GPS/heading prior.
7
+
8
+ ## Inputs
9
+
10
+ All archives must be NPZ, compressed size <=10 MiB, uncompressed size <=32 MiB.
11
+ Only named NPY v1/v2 arrays, no objects/pickle/structured arrays/duplicate members.
12
+ Metadata is one scalar UTF-8 JSON string <=128 KiB. All numeric values must be
13
+ finite. Files are validated **before** the trained model is loaded.
14
+
15
+ ### `features_npz`
16
+
17
+ Pass the NPZ produced by `/bev` unchanged:
18
+
19
+ - `features`: float `[1,8,64,129]` (absolute values <=1e6).
20
+ - `confidence`: numeric `[1,64,129]` in [0,1].
21
+ - `valid`: bool or integer 0/1 `[1,64,129]`, at least one valid cell.
22
+ - Optional `camera`: finite `[1,6]` pinhole tensor, positive dimensions/focals.
23
+ - Optional `metadata`: scalar JSON, preserved in the output manifest.
24
+
25
+ ### `maps_npz`
26
+
27
+ - `raster`: integer `[N,3,256,256]`, N=1..12. Channel classes must use the exact
28
+ upstream OrienterNet semantic encoding: areas 0..7, ways 0..10, nodes 0..33.
29
+ An ordinary RGB map screenshot is **not** compatible.
30
+ - `metadata`: scalar JSON with this schema (extra provenance keys are retained):
31
+
32
+ ```json
33
+ {
34
+ "schema_version": 1,
35
+ "pixels_per_meter": 2,
36
+ "candidates": [{
37
+ "id": "candidate-001",
38
+ "center_wgs84_latlon": [31.5, 120.3],
39
+ "projection": {
40
+ "type": "caller-supplied local metric projection",
41
+ "definition": "retain the exact map rasterizer projection parameters here"
42
+ },
43
+ "bbox_xy_m": {"min": [-64, -64], "max": [64, 64]}
44
+ }]
45
+ }
46
+ ```
47
+
48
+ `id` is unique, ASCII `[A-Za-z0-9][A-Za-z0-9._:-]{0,95}`. The local XY extent
49
+ must be 128×128 meters. The service preserves this manifest and the input SHA256
50
+ hashes, **does not interpret the projection, and does not invent WGS84 positions**.
51
+ Caller must convert returned `(u,v)` with its actual rasterizer's pixel-center
52
+ and local projection conventions. Camera/centers/projection are caller data,
53
+ not server-verified geographic facts.
54
+
55
+ ## Outputs
56
+
57
+ The JSON lists each candidate in input order with three separated `(u,v,yaw)`
58
+ modes, raw combined score, visual correlation, map unary prior, raw peak/mean/std,
59
+ top1/top2 separated-mode margin, class counts/nonzero fractions, and latency.
60
+ Modes use u=column/right, v=row/down and upstream yaw conventions. Yaw step is
61
+ 5.625 degrees (64 rotations); suppression radius is 8 pixels and 2 yaw bins.
62
+
63
+ The NPZ stores finite arrays `combined_heatmaps`, `visual_heatmaps`,
64
+ `unary_priors` of shape `[N,256,256]`, `best_yaw_indices` uint8 of that shape,
65
+ and the JSON receipt as `metadata`. Heatmaps take max over yaw, not softmax;
66
+ full rotation volumes are not retained to bound disk/memory.
67
+
68
+ `target_presence="unassessed"`, `coordinates_verified=false`,
69
+ `calibrated_probability=false` always. A wrong map can outscore the true map.
70
+ No exact-location winner flag is returned. Map nonzero coverage measures label
71
+ content, **not map completeness**. Pose modes must be checked against independent
72
+ ground-level evidence before any precise geographic conclusion.
73
+
74
+ ```python
75
+ from gradio_client import Client, handle_file
76
+ client = Client("SammySnake/BEV")
77
+ receipt, diagnostics = client.predict(
78
+ handle_file("orienternet-bev.npz"),
79
+ handle_file("semantic-map-pack.npz"),
80
+ api_name="/match_bev",
81
+ )
82
+ ```
83
+
84
+ This endpoint uses a lazy CPU instance of the existing full hosted checkpoint.
85
+ Existing `/bev`, `/embed`, `/rank` APIs and their numerical/device policies are
86
+ unchanged. All inference endpoints share concurrency=1. No new model weights,
87
+ map credentials, or photos are included in this patch.
README.md CHANGED
@@ -17,6 +17,7 @@ This research Space runs real pretrained **OrienterNet-MGL** and **Sample4Geo-CV
17
  ## Endpoints
18
 
19
  - `/bev`: image, assumed horizontal FOV/pitch/roll, compute mode → learned BEV feature visualization, raw NPZ, runtime receipt. **Not a reconstructed aerial photograph.**
 
20
  - `/embed`: image, `ground` or `satellite`, compute mode → L2-normalized 1024D Sample4Geo vector and NPZ.
21
  - `/rank`: ground image and 1–12 satellite candidate files, compute mode → cosine ranking and NPZ. **No automatic global search. Scores are not probabilities or verified coordinates.**
22
  - `/status`: actual runtime/backend, observed process/cgroup limits and model provenance.
@@ -27,6 +28,6 @@ API example: `API_EXAMPLE.py`. Use original photographs, not hallucination-prone
27
 
28
  ## Accuracy boundary
29
 
30
- BEV camera parameters are explicit assumptions, not recovered calibration. The OrienterNet endpoint does not perform 2D semantic-map matching; Sample4Geo embeddings are separate from BEV features and cannot be directly interchanged. Cross-view retrieval requires a geographically appropriate candidate gallery and independent final scene/pose verification. Narrow-FOV/night Chinese photos are unvalidated domain shifts. No target-absent detector or coordinate accuracy is claimed.
31
 
32
  See `ATTRIBUTION.md`, `UPSTREAM_LICENSE.txt` and `MODEL_PROVENANCE.json` for author checkpoints, hashes and restrictions. OrienterNet is CC-BY-NC. Sample4Geo has no clearly declared upstream license; this demo grants no commercial rights.
 
17
  ## Endpoints
18
 
19
  - `/bev`: image, assumed horizontal FOV/pitch/roll, compute mode → learned BEV feature visualization, raw NPZ, runtime receipt. **Not a reconstructed aerial photograph.**
20
+ - `/match_bev`: existing BEV NPZ + 1–12 caller-supplied semantic-map raster crops → pretrained OrienterNet map encoding, exhaustive pose voting and unary prior; raw pose modes and heatmaps. CPU only. See `MAP_MATCHING.md` for the strict archive format. **Wrong maps can score higher; no target-presence or coordinate-verification claim.**
21
  - `/embed`: image, `ground` or `satellite`, compute mode → L2-normalized 1024D Sample4Geo vector and NPZ.
22
  - `/rank`: ground image and 1–12 satellite candidate files, compute mode → cosine ranking and NPZ. **No automatic global search. Scores are not probabilities or verified coordinates.**
23
  - `/status`: actual runtime/backend, observed process/cgroup limits and model provenance.
 
28
 
29
  ## Accuracy boundary
30
 
31
+ BEV camera parameters are explicit assumptions, not recovered calibration. `/bev` only extracts features; the separate `/match_bev` performs actual 2D semantic-map pose matching, with caller-supplied maps and projection metadata. No GPS or heading prior is injected. Its map-label coverage is not a completeness measurement, and raw peaks are not calibrated cross-map probabilities. Sample4Geo embeddings are separate from BEV features and cannot be directly interchanged. Cross-view retrieval requires a geographically appropriate candidate gallery and independent final scene/pose verification. Narrow-FOV/night Chinese photos are unvalidated domain shifts. No target-absent detector or coordinate accuracy is claimed.
32
 
33
  See `ATTRIBUTION.md`, `UPSTREAM_LICENSE.txt` and `MODEL_PROVENANCE.json` for author checkpoints, hashes and restrictions. OrienterNet is CC-BY-NC. Sample4Geo has no clearly declared upstream license; this demo grants no commercial rights.
app.py CHANGED
@@ -17,6 +17,7 @@ from inference_core import (
17
  ROOT, MODEL_DIR, sample_model, infer_bev_cpu,
18
  infer_embedding_cpu, prepare_bev, prepare_embedding, visualize_bev,
19
  )
 
20
 
21
  ZERO_GPU = bool(Config.zero_gpu)
22
  OUTPUT_ROOT = Path(tempfile.gettempdir()) / "geo-bev-outputs"
@@ -149,6 +150,16 @@ def rank(image, candidates, compute="auto"):
149
  return metadata, file
150
 
151
 
 
 
 
 
 
 
 
 
 
 
152
  def status():
153
  """Observed process/container limits, not an advertised hardware guarantee."""
154
  limits = {}
@@ -163,13 +174,17 @@ def status():
163
  manifest = json.loads((ROOT / "MODEL_PROVENANCE.json").read_text())
164
  return {"service": "single-photo-geolocation-features", "zerogpu": ZERO_GPU,
165
  "gpu_models_initialized": SAMPLE_GPU is not None,
166
- "model_backends": {"bev": ["onnxruntime-cpu"], "embedding_and_rank": ["onnxruntime-cpu", "pytorch-cuda-zerogpu"]},
 
 
 
 
167
  "bev_gpu_policy": "Disabled after strict numeric gate failure, including with TF32 off; auto BEV uses verified CPU. Failed route evidence retained in the deployment report.",
168
  "cpu_backend": "onnxruntime", "torch_threads": torch.get_num_threads(),
169
  "os_cpu_count": os.cpu_count(), "process_peak_rss_mib": round(peak_mib, 1), "observed_cgroup_limits": limits,
170
  "models": manifest, "location_verified": False,
171
  "privacy": "Public research service; do not upload sensitive photos. Results expire from the app cache after about one hour; hosting provider retention is separate.",
172
- "limits": "Queue 8, concurrency 1, max upload 10MB/file, 16MP/image, 12 gallery images/request. Free service may sleep or be unavailable."}
173
 
174
 
175
  with gr.Blocks(analytics_enabled=False, delete_cache=(600, 3600), title="BEV + CVGL research inference") as demo:
@@ -186,6 +201,15 @@ with gr.Blocks(analytics_enabled=False, delete_cache=(600, 3600), title="BEV + C
186
  bev_file = gr.File(label="原始 BEV 张量 NPZ")
187
  bev_meta = gr.JSON(label="推理与相机假设收据")
188
  button_bev.click(bev, [photo, hfov, pitch, roll, compute_bev], [preview, bev_file, bev_meta], api_name="bev", concurrency_id="inference")
 
 
 
 
 
 
 
 
 
189
  with gr.Tab("CVGL 向量"):
190
  embed_photo = gr.Image(type="pil", label="图片")
191
  embed_view = gr.Radio(["ground", "satellite"], value="ground", label="图片视角")
@@ -206,7 +230,7 @@ with gr.Blocks(analytics_enabled=False, delete_cache=(600, 3600), title="BEV + C
206
  status_button = gr.Button("读取实际运行状态")
207
  status_json = gr.JSON()
208
  status_button.click(status, [], status_json, api_name="status")
209
- gr.Markdown("API: `/bev`、`/embed`、`/rank`、`/status`。使用 `gradio_client.Client('SammySnake/BEV')`。\n\nOrienterNet 原始代码/权重为 CC-BY-NC;Sample4Geo 未声明清晰许可,不能视作商业授权。详见仓库归属说明。")
210
 
211
  demo.queue(max_size=8, default_concurrency_limit=1)
212
 
 
17
  ROOT, MODEL_DIR, sample_model, infer_bev_cpu,
18
  infer_embedding_cpu, prepare_bev, prepare_embedding, visualize_bev,
19
  )
20
+ from bev_matching import match_features
21
 
22
  ZERO_GPU = bool(Config.zero_gpu)
23
  OUTPUT_ROOT = Path(tempfile.gettempdir()) / "geo-bev-outputs"
 
150
  return metadata, file
151
 
152
 
153
+ def match_bev(features_npz, maps_npz):
154
+ """Match one existing BEV against 1..12 caller-supplied semantic map crops."""
155
+ if not features_npz or not maps_npz:
156
+ raise ValueError("BEV features and a semantic-map NPZ pack are required")
157
+ metadata, arrays = match_features(features_npz, maps_npz)
158
+ file = artifact("orienternet-map-matching.npz", **arrays,
159
+ metadata=np.array(json.dumps(metadata, allow_nan=False)))
160
+ return metadata, file
161
+
162
+
163
  def status():
164
  """Observed process/container limits, not an advertised hardware guarantee."""
165
  limits = {}
 
174
  manifest = json.loads((ROOT / "MODEL_PROVENANCE.json").read_text())
175
  return {"service": "single-photo-geolocation-features", "zerogpu": ZERO_GPU,
176
  "gpu_models_initialized": SAMPLE_GPU is not None,
177
+ "model_backends": {"bev": ["onnxruntime-cpu"], "embedding_and_rank": ["onnxruntime-cpu", "pytorch-cuda-zerogpu"],
178
+ "match_bev": ["pytorch-cpu-pretrained-map-encoder-and-voting"]},
179
+ "semantic_map_matching": {"endpoint": "/match_bev", "pretrained_weights": "OrienterNet-MGL",
180
+ "map_limit": "1..12 integer [3,256,256] semantic rasters, 2 pixels/meter",
181
+ "target_presence": "unassessed", "coordinates_verified": False},
182
  "bev_gpu_policy": "Disabled after strict numeric gate failure, including with TF32 off; auto BEV uses verified CPU. Failed route evidence retained in the deployment report.",
183
  "cpu_backend": "onnxruntime", "torch_threads": torch.get_num_threads(),
184
  "os_cpu_count": os.cpu_count(), "process_peak_rss_mib": round(peak_mib, 1), "observed_cgroup_limits": limits,
185
  "models": manifest, "location_verified": False,
186
  "privacy": "Public research service; do not upload sensitive photos. Results expire from the app cache after about one hour; hosting provider retention is separate.",
187
+ "limits": "Queue 8, inference concurrency 1, max upload 10MB/file, 16MP/image, 12 gallery images/maps per request; NPZ uncompressed <=32MiB. Free service may sleep or be unavailable."}
188
 
189
 
190
  with gr.Blocks(analytics_enabled=False, delete_cache=(600, 3600), title="BEV + CVGL research inference") as demo:
 
201
  bev_file = gr.File(label="原始 BEV 张量 NPZ")
202
  bev_meta = gr.JSON(label="推理与相机假设收据")
203
  button_bev.click(bev, [photo, hfov, pitch, roll, compute_bev], [preview, bev_file, bev_meta], api_name="bev", concurrency_id="inference")
204
+ with gr.Tab("BEV 与语义地图匹配"):
205
+ gr.Markdown("使用 `/bev` 的真实特征与调用者准备的 OSM 语义地图匹配。每个候选返回局部位置/朝向假设;**错误地图也可能得高分,不能据此确认地点。** 输入规范见 `MAP_MATCHING.md`。")
206
+ match_features_file = gr.File(file_types=[".npz"], label="BEV 特征 NPZ(/bev 输出)")
207
+ match_maps_file = gr.File(file_types=[".npz"], label="1–12 个 256×256 三通道语义地图 NPZ")
208
+ match_button = gr.Button("真实 BEV → 语义地图匹配(CPU)")
209
+ match_meta = gr.JSON(label="候选姿态与非校准原始分数;经纬度未验证")
210
+ match_output_file = gr.File(label="逐候选相关性热图 NPZ")
211
+ match_button.click(match_bev, [match_features_file, match_maps_file], [match_meta, match_output_file],
212
+ api_name="match_bev", concurrency_id="inference")
213
  with gr.Tab("CVGL 向量"):
214
  embed_photo = gr.Image(type="pil", label="图片")
215
  embed_view = gr.Radio(["ground", "satellite"], value="ground", label="图片视角")
 
230
  status_button = gr.Button("读取实际运行状态")
231
  status_json = gr.JSON()
232
  status_button.click(status, [], status_json, api_name="status")
233
+ gr.Markdown("API: `/bev`、`/match_bev`、`/embed`、`/rank`、`/status`。使用 `gradio_client.Client('SammySnake/BEV')`。\n\nOrienterNet 原始代码/权重为 CC-BY-NC;Sample4Geo 未声明清晰许可,不能视作商业授权。详见仓库归属说明。")
234
 
235
  demo.queue(max_size=8, default_concurrency_limit=1)
236
 
bev_matching.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded pretrained OrienterNet BEV-to-semantic-map matching.
2
+
3
+ Input validation is deliberately independent of model construction. This module
4
+ never downloads weights, guesses map coordinates, or asserts target presence.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import io
10
+ import json
11
+ import math
12
+ from pathlib import Path
13
+ import re
14
+ import time
15
+ import zipfile
16
+
17
+ import numpy as np
18
+
19
+ MAX_COMPRESSED_BYTES = 10 * 1024 * 1024
20
+ MAX_UNCOMPRESSED_BYTES = 32 * 1024 * 1024
21
+ MAX_METADATA_BYTES = 128 * 1024
22
+ EXPECTED_FEATURE_KEYS = {"features", "confidence", "valid", "camera", "metadata"}
23
+ WARNING = (
24
+ "Uncalibrated semantic-map pose hypotheses, not verified coordinates or target presence. "
25
+ "A wrong map may score higher than the correct map. BEV camera parameters may be assumed; "
26
+ "missing OSM features and night/narrow-FOV domain shift can invalidate ranking. "
27
+ "Map label coverage is not map completeness. Independent ground-scene verification is required."
28
+ )
29
+
30
+
31
+ def read_npz(path, allowed, required):
32
+ """Reject excessive archives and object/oversized arrays before NumPy allocation."""
33
+ path = Path(path)
34
+ if not path.is_file() or path.stat().st_size > MAX_COMPRESSED_BYTES:
35
+ raise ValueError("NPZ must be a file <=10 MiB")
36
+ arrays = {}
37
+ with zipfile.ZipFile(path) as archive:
38
+ members = archive.infolist()
39
+ names = [entry.filename for entry in members]
40
+ if len(names) != len(set(names)) or len(names) > len(allowed):
41
+ raise ValueError("Duplicate or excessive NPZ members")
42
+ if sum(entry.file_size for entry in members) > MAX_UNCOMPRESSED_BYTES:
43
+ raise ValueError("NPZ uncompressed size exceeds 32 MiB")
44
+ for entry in members:
45
+ key = entry.filename.removesuffix(".npy")
46
+ if entry.filename != key + ".npy" or key not in allowed:
47
+ raise ValueError("Unexpected NPZ member")
48
+ if entry.flag_bits & 1 or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
49
+ raise ValueError("Unsupported or encrypted NPZ member")
50
+ # Read only a bounded member. Inspect its declared shape before np.load:
51
+ # a tiny malicious .npy can otherwise request a huge allocation.
52
+ with archive.open(entry) as source:
53
+ payload = source.read(MAX_UNCOMPRESSED_BYTES + 1)
54
+ if len(payload) != entry.file_size or len(payload) > MAX_UNCOMPRESSED_BYTES:
55
+ raise ValueError("Invalid NPZ member size")
56
+ stream = io.BytesIO(payload)
57
+ version = np.lib.format.read_magic(stream)
58
+ if version == (1, 0):
59
+ shape, _, dtype = np.lib.format.read_array_header_1_0(stream, max_header_size=8192)
60
+ elif version == (2, 0):
61
+ shape, _, dtype = np.lib.format.read_array_header_2_0(stream, max_header_size=8192)
62
+ else:
63
+ raise ValueError("Only NPY v1/v2 arrays are accepted")
64
+ if dtype.hasobject or dtype.fields or dtype.kind not in "biufUS":
65
+ raise ValueError("Object, structured, or unsupported arrays are forbidden")
66
+ if len(shape) > 5 or any(not isinstance(x, int) or x < 0 for x in shape):
67
+ raise ValueError("Invalid array dimensions")
68
+ size = math.prod(shape) * dtype.itemsize
69
+ if size > MAX_UNCOMPRESSED_BYTES or stream.tell() + size != len(payload):
70
+ raise ValueError("Array size disagrees with archive or exceeds limit")
71
+ arrays[key] = np.load(io.BytesIO(payload), allow_pickle=False, max_header_size=8192)
72
+ if not required <= arrays.keys():
73
+ raise ValueError("Missing required NPZ arrays")
74
+ return arrays, hashlib.sha256(path.read_bytes()).hexdigest()
75
+
76
+
77
+ def parse_metadata(array):
78
+ if array.shape != () or array.dtype.kind not in "US":
79
+ raise ValueError("metadata must be one scalar JSON string")
80
+ raw = array.item()
81
+ if isinstance(raw, bytes):
82
+ raw = raw.decode("utf-8")
83
+ if len(raw.encode("utf-8")) > MAX_METADATA_BYTES:
84
+ raise ValueError("Metadata exceeds 128 KiB")
85
+
86
+ def reject_constant(value):
87
+ raise ValueError("Non-finite JSON constant")
88
+
89
+ data = json.loads(raw, parse_constant=reject_constant)
90
+ if not isinstance(data, dict):
91
+ raise ValueError("Metadata must be a JSON object")
92
+ # json.loads permits finite literal syntax that overflows to infinity (1e999).
93
+ json.dumps(data, allow_nan=False)
94
+ return data
95
+
96
+
97
+ def finite_array(value, shape, name):
98
+ if value.shape != shape or value.dtype.kind not in "fiu" or not np.isfinite(value).all():
99
+ raise ValueError(f"{name} must be finite numeric {shape}")
100
+ return value
101
+
102
+
103
+ def latlon(value):
104
+ try:
105
+ array = np.asarray(value, dtype=np.float64)
106
+ except (ValueError, TypeError) as exc:
107
+ raise ValueError("Invalid WGS84 latlon") from exc
108
+ if array.shape != (2,) or not np.isfinite(array).all() or abs(array[0]) > 90 or abs(array[1]) > 180:
109
+ raise ValueError("Invalid WGS84 latlon")
110
+
111
+
112
+ def load_inputs(features_path, maps_path):
113
+ features, feature_hash = read_npz(features_path, EXPECTED_FEATURE_KEYS, {"features", "confidence", "valid"})
114
+ finite_array(features["features"], (1, 8, 64, 129), "features")
115
+ finite_array(features["confidence"], (1, 64, 129), "confidence")
116
+ if np.abs(features["features"]).max() > 1e6:
117
+ raise ValueError("Unreasonable feature magnitude")
118
+ confidence = features["confidence"]
119
+ if np.any(confidence < 0) or np.any(confidence > 1):
120
+ raise ValueError("Confidence must be in [0,1]")
121
+ valid = features["valid"]
122
+ if valid.shape != (1, 64, 129) or valid.dtype.kind not in "biu" or not np.isin(valid, (0, 1)).all():
123
+ raise ValueError("valid must be a boolean/0-or-1 array [1,64,129]")
124
+ if not valid.any():
125
+ raise ValueError("BEV has no valid cells")
126
+ if "camera" in features:
127
+ finite_array(features["camera"], (1, 6), "camera")
128
+ if np.any(features["camera"][0, :4] <= 0):
129
+ raise ValueError("Camera dimensions/focal lengths must be positive")
130
+ feature_metadata = parse_metadata(features["metadata"]) if "metadata" in features else None
131
+ maps, map_hash = read_npz(maps_path, {"raster", "metadata"}, {"raster", "metadata"})
132
+ raster = maps["raster"]
133
+ if raster.ndim != 4 or raster.shape[1:] != (3, 256, 256) or not 1 <= raster.shape[0] <= 12 or raster.dtype.kind not in "iu":
134
+ raise ValueError("raster must be integer [N,3,256,256], 1<=N<=12")
135
+ for channel, limit in enumerate((7, 10, 33)):
136
+ if (raster[:, channel] < 0).any() or (raster[:, channel] > limit).any():
137
+ raise ValueError("Semantic class range exceeded: areas 0..7, ways 0..10, nodes 0..33")
138
+ metadata = parse_metadata(maps["metadata"])
139
+ if metadata.get("schema_version") != 1 or metadata.get("pixels_per_meter") != 2:
140
+ raise ValueError("Map schema_version=1 and pixels_per_meter=2 are required")
141
+ candidates = metadata.get("candidates")
142
+ if not isinstance(candidates, list) or len(candidates) != len(raster):
143
+ raise ValueError("Candidate metadata count must match raster batch")
144
+ ids = set()
145
+ for item in candidates:
146
+ if not isinstance(item, dict) or not isinstance(item.get("id"), str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,95}", item["id"]):
147
+ raise ValueError("Candidate id must be a bounded ASCII identifier")
148
+ if item["id"] in ids:
149
+ raise ValueError("Duplicate candidate id")
150
+ ids.add(item["id"])
151
+ latlon(item.get("center_wgs84_latlon"))
152
+ if not isinstance(item.get("projection"), dict) or not item["projection"]:
153
+ raise ValueError("Caller-supplied local projection descriptor is required")
154
+ box = item.get("bbox_xy_m", {})
155
+ if not isinstance(box, dict):
156
+ raise ValueError("bbox_xy_m must be an object with min/max pairs")
157
+ lower = np.asarray(box.get("min"), dtype=np.float64)
158
+ upper = np.asarray(box.get("max"), dtype=np.float64)
159
+ if lower.shape != (2,) or upper.shape != (2,) or not np.isfinite([lower, upper]).all() or not np.allclose(upper - lower, 128, atol=1e-4, rtol=0):
160
+ raise ValueError("Local XY bbox must have 128x128 meter extent")
161
+ manifest = {"features_sha256": feature_hash, "maps_sha256": map_hash,
162
+ "feature_metadata": feature_metadata, "map_metadata": metadata,
163
+ "camera_tensor": features["camera"].tolist() if "camera" in features else None}
164
+ return features, raster, manifest
165
+
166
+
167
+ def top_modes(scores, correlation, prior, count=3):
168
+ """Distinct spatial/yaw modes; no softmax masquerading as confidence."""
169
+ work = scores.copy()
170
+ modes = []
171
+ height, width, rotations = work.shape
172
+ for _ in range(count):
173
+ flat = int(work.argmax())
174
+ v, u, r = np.unravel_index(flat, work.shape)
175
+ if not np.isfinite(work[v, u, r]):
176
+ break
177
+ modes.append({"u": int(u), "v": int(v), "yaw_index": int(r),
178
+ "yaw_deg": float(r * 360 / rotations),
179
+ "raw_combined_score": float(scores[v, u, r]),
180
+ "visual_correlation": float(correlation[v, u, r]),
181
+ "map_unary_prior": float(prior[v, u]),
182
+ "boundary_distance_px": int(min(u, v, width - 1 - u, height - 1 - v))})
183
+ # Suppress nearby pose bins, retaining genuinely different orientations.
184
+ yaw_bins = [(int(r) + offset) % rotations for offset in range(-2, 3)]
185
+ work[max(0, v - 8):min(height, v + 9), max(0, u - 8):min(width, u + 9), yaw_bins] = -np.inf
186
+ return modes
187
+
188
+
189
+ def match_features(features_path, maps_path):
190
+ """Use the full hosted pretrained map encoder, exact upstream voting and prior."""
191
+ features, rasters, manifest = load_inputs(features_path, maps_path)
192
+ # Lazy and CPU-only. The weights already belong to the deployed Space.
193
+ # No model creation occurs during archive-validation-only tests.
194
+ import torch
195
+ from inference_core import bev_model
196
+
197
+ started = time.perf_counter()
198
+ model = bev_model("cpu").model
199
+ f_bev = torch.from_numpy(features["features"].astype(np.float32, copy=True))
200
+ confidence = torch.from_numpy(features["confidence"].astype(np.float32, copy=True))
201
+ valid = torch.from_numpy(features["valid"].astype(bool, copy=True))
202
+ rows, combined_heatmaps, visual_heatmaps, prior_maps, yaw_maps = [], [], [], [], []
203
+ with torch.inference_mode():
204
+ for index, raster in enumerate(rasters):
205
+ tick = time.perf_counter()
206
+ pred_map = model.map_encoder({"map": torch.from_numpy(raster.astype(np.int64, copy=True))[None]})
207
+ corr = model.exhaustive_voting(f_bev, pred_map["map_features"][0], valid, confidence).moveaxis(1, -1)
208
+ applied_prior = "log_prior" in pred_map and model.conf.apply_map_prior
209
+ prior = pred_map["log_prior"][0] if applied_prior else torch.zeros_like(corr[..., 0])
210
+ scores = corr + prior.unsqueeze(-1)
211
+ if scores.shape != (1, 256, 256, 64) or not all(torch.isfinite(x).all() for x in (scores, corr, prior)):
212
+ raise ValueError("Unexpected/non-finite matching output; no pose can be reported")
213
+ scores_np, corr_np, prior_np = (x[0].cpu().numpy() for x in (scores, corr, prior))
214
+ modes = top_modes(scores_np, corr_np, prior_np)
215
+ coverage = {name: {"nonzero_fraction": float(np.mean(raster[channel] != 0)),
216
+ "class_counts": {str(int(v)): int(n) for v, n in zip(*np.unique(raster[channel], return_counts=True))}}
217
+ for channel, name in enumerate(("areas", "ways", "nodes"))}
218
+ rows.append({"candidate_index": index, "id": manifest["map_metadata"]["candidates"][index]["id"],
219
+ "top_modes": modes, "raw_score_peak": float(scores_np.max()),
220
+ "top1_top2_separated_mode_margin": float(modes[0]["raw_combined_score"] - modes[1]["raw_combined_score"]) if len(modes) > 1 else None,
221
+ "visual_correlation_peak": float(corr_np.max()),
222
+ "raw_score_mean": float(scores_np.mean()), "raw_score_std": float(scores_np.std()),
223
+ "map_prior_range": [float(prior_np.min()), float(prior_np.max())],
224
+ "map_prior_applied": bool(applied_prior), "map_label_coverage": coverage,
225
+ "any_label_fraction": float(np.mean(np.any(raster != 0, axis=0))),
226
+ "matching_seconds": round(time.perf_counter() - tick, 4)})
227
+ combined_heatmaps.append(scores_np.max(axis=-1).copy())
228
+ visual_heatmaps.append(corr_np.max(axis=-1).copy())
229
+ prior_maps.append(prior_np.copy())
230
+ yaw_maps.append(scores_np.argmax(axis=-1).astype(np.uint8))
231
+ del pred_map, corr, prior, scores, scores_np, corr_np, prior_np
232
+ metadata = {"model": "OrienterNet-MGL", "backend": "pytorch-cpu-pretrained-map-encoder-and-voting",
233
+ "candidate_count": len(rows), "candidates": rows, "input_manifest": manifest,
234
+ "inference_seconds": round(time.perf_counter() - started, 4),
235
+ "gps_or_heading_prior_supplied": False,
236
+ "pose_convention": {"u": "column/right", "v": "row/down", "yaw": "OrienterNet clockwise from local map north", "yaw_step_deg": 5.625,
237
+ "spatial_nms_radius_px": 8, "yaw_nms_radius_bins": 2},
238
+ "target_presence": "unassessed", "coordinates_verified": False, "location_verified": False,
239
+ "calibrated_probability": False, "coordinates": None, "warning": WARNING}
240
+ arrays = {"combined_heatmaps": np.stack(combined_heatmaps), "visual_heatmaps": np.stack(visual_heatmaps),
241
+ "unary_priors": np.stack(prior_maps), "best_yaw_indices": np.stack(yaw_maps)}
242
+ return metadata, arrays