seriffic Claude Opus 4.7 (1M context) commited on
Commit
052e77a
·
1 Parent(s): c368c91

fix(specialists): never fall through to broken local terratorch

Browse files

The Sat May 9 trace surfaced two regressions on the lablab UI Space:

prithvi_nyc_pluvial: RuntimeError: operator torchvision::nms does
not exist
terramind.lulc: deps unavailable on this deployment:
terratorch (RuntimeError), peft
terramind.buildings: deps unavailable on this deployment:
terratorch (RuntimeError), peft

Root cause in both: the specialist tries the configured remote
inference service, the call fails (RemoteUnreachable, ok=False, or
generic exception), and the code silently falls through to the local
terratorch path. Local on the cpu-basic UI Space has a torch /
torchvision binary mismatch (torchvision::nms not registered), so
either we crash with that RuntimeError or — for terramind_nyc, where
_DEPS_OK is False at import time — we surface a misleading "deps
unavailable" message that hides the real (remote) failure.

Fix: when remote was attempted, never fall through to local. Return
a clean ok=False with the remote failure reason on the trace.

prithvi_live: gate the local fallback on `not remote_attempted`
(was: only the generic Exception path was guarded; RemoteUnreachable
fell through unguarded).

terramind_nyc._try_remote: return a {"ok": False, "skipped": "..."}
sentinel on RemoteUnreachable / ok=False / generic Exception. None
is reserved for "remote not configured" (the legitimate try-local
case). Caller _run() treats the sentinel as a final outcome instead
of falling through to _DEPS_OK / local terratorch.

Adds scripts/probe_stones_fire.py — programmatic check that all 5
Stones fire on the canonical address and no step result contains
the dep-regression patterns. Run against the lablab UI to verify
before each demo.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

app/context/terramind_nyc.py CHANGED
@@ -305,9 +305,18 @@ def _summarize_buildings(pred, class_labels: list[str]) -> dict[str, Any]:
305
 
306
 
307
  def _try_remote(adapter_name: str, modality_chips: dict) -> dict | None:
308
- """v0.4.5 — POST to MI300X riprap-models if configured. Returns the
309
- parsed result on success; None on RemoteUnreachable so the caller
310
- falls through to the local terratorch path."""
 
 
 
 
 
 
 
 
 
311
  try:
312
  from app import inference as _inf
313
  if not _inf.remote_enabled():
@@ -320,7 +329,9 @@ def _try_remote(adapter_name: str, modality_chips: dict) -> dict | None:
320
  # service rebuilds the temporal stack on its end.
321
  result = _inf.terramind(adapter_name, s2, s1, dem)
322
  if not result.get("ok"):
323
- return None
 
 
324
  result.setdefault("adapter", adapter_name)
325
  result.setdefault("repo", ADAPTERS_REPO)
326
  result["compute"] = f"remote · {result.get('device', 'gpu')}"
@@ -354,13 +365,14 @@ def _try_remote(adapter_name: str, modality_chips: dict) -> dict | None:
354
  result["polygons_geojson"] = None
355
  return result
356
  except _inf.RemoteUnreachable as e:
357
- log.info("terramind/%s: remote unreachable (%s); local fallback",
358
- adapter_name, e)
359
- return None
360
- except Exception:
361
- log.exception("terramind/%s: remote call failed; local fallback",
362
- adapter_name)
363
- return None
 
364
 
365
 
366
  def _run(adapter_name: str, modality_chips: dict, summarizer):
 
305
 
306
 
307
  def _try_remote(adapter_name: str, modality_chips: dict) -> dict | None:
308
+ """POST to the riprap-models inference service if configured.
309
+
310
+ Returns:
311
+ - successful result dict on a 200/ok=True remote response
312
+ - {"ok": False, "skipped": "<reason>"} when remote was attempted
313
+ but failed (RemoteUnreachable, ok=False, or other error). The
314
+ caller MUST NOT fall through to local terratorch in this case
315
+ — local has been broken on the CPU-tier UI Spaces since the
316
+ torchvision binary mismatch landed, and we'd rather show a
317
+ clean "remote unreachable" reason than a noisy crash.
318
+ - None ONLY when remote isn't configured at all (caller may
319
+ legitimately try local then)."""
320
  try:
321
  from app import inference as _inf
322
  if not _inf.remote_enabled():
 
329
  # service rebuilds the temporal stack on its end.
330
  result = _inf.terramind(adapter_name, s2, s1, dem)
331
  if not result.get("ok"):
332
+ err = result.get("error") or result.get("err") or "unknown"
333
+ return {"ok": False,
334
+ "skipped": f"remote terramind/{adapter_name} non-ok: {err}"}
335
  result.setdefault("adapter", adapter_name)
336
  result.setdefault("repo", ADAPTERS_REPO)
337
  result["compute"] = f"remote · {result.get('device', 'gpu')}"
 
365
  result["polygons_geojson"] = None
366
  return result
367
  except _inf.RemoteUnreachable as e:
368
+ log.info("terramind/%s: remote unreachable (%s)", adapter_name, e)
369
+ return {"ok": False,
370
+ "skipped": f"remote terramind/{adapter_name} unreachable: {e}"}
371
+ except Exception as e:
372
+ log.exception("terramind/%s: remote call failed", adapter_name)
373
+ return {"ok": False,
374
+ "skipped": f"remote terramind/{adapter_name} error: "
375
+ f"{type(e).__name__}: {e}"}
376
 
377
 
378
  def _run(adapter_name: str, modality_chips: dict, summarizer):
app/flood_layers/prithvi_live.py CHANGED
@@ -450,7 +450,15 @@ def _fetch_inner(lat: float, lon: float, timeout_s: float) -> dict[str, Any]:
450
  f"{remote.get('error') or 'unknown'}",
451
  "elapsed_s": round(time.time() - t0, 2)}
452
  except _inf.RemoteUnreachable as e:
453
- log.info("prithvi_live: remote unreachable (%s); falling back to local", e)
 
 
 
 
 
 
 
 
454
  except Exception as e:
455
  log.exception("prithvi_live: remote call failed")
456
  if remote_attempted:
@@ -460,6 +468,8 @@ def _fetch_inner(lat: float, lon: float, timeout_s: float) -> dict[str, Any]:
460
  "elapsed_s": round(time.time() - t0, 2)}
461
 
462
  # Local fallback — the path that's been live since v0.4.4.
 
 
463
  model, run_model = _ensure_model()
464
  x = img[None, :, None, :, :] # (1, 6, 1, H, W)
465
  pred_t = run_model(x, None, None, model.model, model.datamodule, IMG_SIZE)
 
450
  f"{remote.get('error') or 'unknown'}",
451
  "elapsed_s": round(time.time() - t0, 2)}
452
  except _inf.RemoteUnreachable as e:
453
+ log.info("prithvi_live: remote unreachable (%s)", e)
454
+ if remote_attempted:
455
+ # Don't fall to local — torchvision::nms is broken on the
456
+ # CPU-tier UI Spaces and crashes the FSM specialist with
457
+ # a confusing RuntimeError. Return a clean skipped row so
458
+ # the trace says "remote unreachable" instead.
459
+ return {"ok": False,
460
+ "skipped": f"remote prithvi-pluvial unreachable: {e}",
461
+ "elapsed_s": round(time.time() - t0, 2)}
462
  except Exception as e:
463
  log.exception("prithvi_live: remote call failed")
464
  if remote_attempted:
 
468
  "elapsed_s": round(time.time() - t0, 2)}
469
 
470
  # Local fallback — the path that's been live since v0.4.4.
471
+ # Reached only when remote_attempted is False (i.e. remote
472
+ # backend not configured at all).
473
  model, run_model = _ensure_model()
474
  x = img[None, :, None, :, :] # (1, 6, 1, H, W)
475
  pred_t = run_model(x, None, None, model.model, model.datamodule, IMG_SIZE)
scripts/probe_stones_fire.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Probe the lablab UI: does every Stone fire on the canonical address,
2
+ and is the dep-availability regression that the SAT_MAY_9 run hit
3
+ (`RuntimeError: operator torchvision::nms does not exist` on the local
4
+ fallback path; `deps unavailable on this deployment: terratorch
5
+ (RuntimeError), peft` on TerraMind LULC + Buildings) gone?
6
+
7
+ This consumes /api/agent/stream as a curl-style SSE client (no
8
+ EventSource needed) and asserts:
9
+ 1. Every step event has a Stone mapping (per web/main.py:_STEP_TO_STONE)
10
+ 2. All five Stones (Cornerstone, Keystone, Touchstone, Lodestone,
11
+ Capstone) emit at least one fired step
12
+ 3. No step result mentions:
13
+ - "torchvision::nms"
14
+ - "deps unavailable on this deployment: terratorch"
15
+ - "peft (RuntimeError)"
16
+ 4. Final emissions block carries L4 hardware + non-zero tokens
17
+
18
+ Usage:
19
+ PYTHONPATH=. uv run python scripts/probe_stones_fire.py
20
+ PYTHONPATH=. uv run python scripts/probe_stones_fire.py \\
21
+ --base http://127.0.0.1:8000 \\
22
+ --query "Carleton Manor Houses, Queens"
23
+
24
+ Exit 0 on success, 1 on any failure. Prints a per-Stone summary.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import sys
31
+ import time
32
+ from urllib.parse import quote
33
+
34
+ import httpx
35
+
36
+ DEFAULT_BASE = "https://lablab-ai-amd-developer-hackathon-riprap-nyc.hf.space"
37
+ DEFAULT_QUERY = "80 Pioneer Street, Brooklyn"
38
+
39
+ EXPECTED_STONES = {"Cornerstone", "Keystone", "Touchstone",
40
+ "Lodestone", "Capstone"}
41
+
42
+ # Step name → Stone, mirrored from web/main.py:_STEP_TO_STONE so this
43
+ # script can be run without importing the app package.
44
+ STEP_TO_STONE: dict[str, str] = {
45
+ "sandy_inundation": "Cornerstone",
46
+ "dep_stormwater": "Cornerstone",
47
+ "ida_hwm_2021": "Cornerstone",
48
+ "prithvi_eo_v2": "Cornerstone",
49
+ "microtopo_lidar": "Cornerstone",
50
+ "sandy_nta": "Cornerstone",
51
+ "dep_extreme_2080_nta": "Cornerstone",
52
+ "dep_moderate_2050_nta": "Cornerstone",
53
+ "dep_moderate_current_nta": "Cornerstone",
54
+ "microtopo_nta": "Cornerstone",
55
+ "mta_entrance_exposure": "Keystone",
56
+ "nycha_development_exposure": "Keystone",
57
+ "doe_school_exposure": "Keystone",
58
+ "doh_hospital_exposure": "Keystone",
59
+ "terramind_synthesis": "Keystone",
60
+ "eo_chip_fetch": "Keystone",
61
+ "terramind_buildings": "Keystone",
62
+ "floodnet": "Touchstone",
63
+ "nyc311": "Touchstone",
64
+ "nws_obs": "Touchstone",
65
+ "noaa_tides": "Touchstone",
66
+ "prithvi_eo_live": "Touchstone",
67
+ "terramind_lulc": "Touchstone",
68
+ "nyc311_nta": "Touchstone",
69
+ "nws_alerts": "Lodestone",
70
+ "ttm_forecast": "Lodestone",
71
+ "ttm_311_forecast": "Lodestone",
72
+ "floodnet_forecast": "Lodestone",
73
+ "ttm_battery_surge": "Lodestone",
74
+ "reconcile_granite41": "Capstone",
75
+ "mellea_reconcile_address": "Capstone",
76
+ "reconcile_neighborhood": "Capstone",
77
+ "reconcile_development": "Capstone",
78
+ "reconcile_live_now": "Capstone",
79
+ }
80
+
81
+ DEP_REGRESSION_PATTERNS = [
82
+ "torchvision::nms",
83
+ "deps unavailable on this deployment: terratorch",
84
+ "peft (RuntimeError)",
85
+ ]
86
+
87
+
88
+ def stream_events(base: str, q: str, timeout_s: float = 360.0):
89
+ """Yield (event, data_dict) for each SSE record."""
90
+ url = f"{base.rstrip('/')}/api/agent/stream?q={quote(q)}"
91
+ with httpx.Client(timeout=timeout_s) as client:
92
+ with client.stream("GET", url) as r:
93
+ r.raise_for_status()
94
+ event = None
95
+ for line in r.iter_lines():
96
+ if not line:
97
+ event = None
98
+ continue
99
+ if line.startswith("event:"):
100
+ event = line.removeprefix("event:").strip()
101
+ elif line.startswith("data:") and event:
102
+ body = line.removeprefix("data:").strip()
103
+ try:
104
+ yield event, json.loads(body)
105
+ except Exception:
106
+ yield event, {"_raw": body}
107
+
108
+
109
+ def main() -> int:
110
+ p = argparse.ArgumentParser()
111
+ p.add_argument("--base", default=DEFAULT_BASE)
112
+ p.add_argument("--query", default=DEFAULT_QUERY)
113
+ p.add_argument("--timeout", type=float, default=360.0)
114
+ args = p.parse_args()
115
+
116
+ print(f"== probe_stones_fire ==")
117
+ print(f" base : {args.base}")
118
+ print(f" query: {args.query}\n")
119
+
120
+ t0 = time.time()
121
+ fired: dict[str, list[dict]] = {s: [] for s in EXPECTED_STONES}
122
+ errored: list[dict] = []
123
+ dep_regressions: list[dict] = []
124
+ final: dict | None = None
125
+
126
+ for event, payload in stream_events(args.base, args.query, args.timeout):
127
+ if event == "step":
128
+ step = payload.get("step", "")
129
+ ok = bool(payload.get("ok"))
130
+ stone = STEP_TO_STONE.get(step)
131
+ if stone:
132
+ if ok:
133
+ fired[stone].append(payload)
134
+ else:
135
+ errored.append(payload)
136
+ # Check the result + err strings against regression patterns.
137
+ blob = json.dumps(payload, default=str).lower()
138
+ for pat in DEP_REGRESSION_PATTERNS:
139
+ if pat.lower() in blob:
140
+ dep_regressions.append({"pattern": pat,
141
+ "step": step,
142
+ "payload": payload})
143
+ break
144
+ elif event == "final":
145
+ final = payload
146
+
147
+ elapsed = time.time() - t0
148
+
149
+ # ---- assertions
150
+ failures: list[str] = []
151
+
152
+ missing_stones = [s for s in EXPECTED_STONES if not fired[s]]
153
+ if missing_stones:
154
+ failures.append(f"Stones with no fired step: {missing_stones}")
155
+
156
+ if dep_regressions:
157
+ for d in dep_regressions[:10]:
158
+ failures.append(
159
+ f"dep regression in step '{d['step']}': matched '{d['pattern']}'"
160
+ )
161
+
162
+ if final is None:
163
+ failures.append("no `final` event received")
164
+ else:
165
+ em = final.get("emissions") or {}
166
+ n_calls = em.get("n_calls", 0)
167
+ if n_calls == 0:
168
+ failures.append("emissions ledger is empty (n_calls=0)")
169
+ hw_keys = list((em.get("by_hardware") or {}).keys())
170
+ if hw_keys and "nvidia_l4" not in hw_keys:
171
+ failures.append(f"expected nvidia_l4 in emissions; got {hw_keys}")
172
+
173
+ # ---- print summary
174
+ print(f"-- step events --")
175
+ for s in ("Cornerstone", "Keystone", "Touchstone", "Lodestone", "Capstone"):
176
+ steps = [p.get("step") for p in fired[s]]
177
+ print(f" {s:11s} fired={len(fired[s]):2d} {steps}")
178
+ if errored:
179
+ print(f"\n-- {len(errored)} step events with ok=False --")
180
+ for p in errored[:8]:
181
+ err = (p.get("err") or
182
+ (p.get("result") or {}).get("err") or
183
+ (p.get("result") or {}).get("skipped") or "?")
184
+ print(f" {p.get('step'):28s} {err[:140]}")
185
+
186
+ if final and (em := final.get("emissions")):
187
+ print(f"\n-- emissions --")
188
+ print(f" n_calls = {em.get('n_calls')}")
189
+ print(f" n_measured = {em.get('n_measured')}")
190
+ print(f" total_wh = {em.get('total_wh')}")
191
+ print(f" total_joules = {em.get('total_joules')}")
192
+ print(f" tokens.total = {(em.get('tokens') or {}).get('total')}")
193
+ print(f" by_hardware = {list((em.get('by_hardware') or {}).keys())}")
194
+
195
+ print(f"\nelapsed: {elapsed:.1f}s")
196
+
197
+ if failures:
198
+ print(f"\nFAIL ({len(failures)} issue{'s' if len(failures) != 1 else ''}):")
199
+ for f in failures:
200
+ print(f" - {f}")
201
+ return 1
202
+ print("\nPASS — all 5 Stones fired, no torchvision/terratorch dep regression.")
203
+ return 0
204
+
205
+
206
+ if __name__ == "__main__":
207
+ sys.exit(main())