forked from violetljj/blind-assist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_model_matrix.py
More file actions
2002 lines (1850 loc) · 76.9 KB
/
Copy pathrun_model_matrix.py
File metadata and controls
2002 lines (1850 loc) · 76.9 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Manifest-driven offline model matrix runner.
The runner owns the common contract: frame identity, model/config hashes,
streaming JSONL traces, progress and resume. Adapters return any subset of
the common outputs. Missing output is recorded as ``not_provided`` and is
never silently changed into zero, negative, or UNKNOWN truth.
The core uses only the Python standard library. TFLite and Depth-Anything
adapters import optional dependencies only when selected.
"""
from __future__ import annotations
import copy
import hashlib
import importlib
import importlib.util
import json
import math
import os
import sys
import tempfile
import time
from argparse import ArgumentParser
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Mapping, Sequence
MODULE_ROOT = Path(__file__).resolve().parent
REPO_ROOT = MODULE_ROOT.parents[2]
DEFAULT_MANIFEST = MODULE_ROOT / "matrix_manifest.json"
TRACE_SCHEMA_VERSION = "blindassist.model_matrix.frame_trace.v1"
RECEIPT_SCHEMA_VERSION = "blindassist.model_matrix.receipt.v1"
RESUME_SCHEMA_VERSION = "blindassist.model_matrix.resume_state.v1"
OUTPUT_KEYS = (
"detections",
"segmentation_logits",
"mask",
"depth",
"risk_output",
"clearance",
)
ENVELOPE_STATUSES = {
"present",
"partial",
"not_provided",
"not_evaluable",
"error",
}
ROW_STATUSES = {"OK", "ERROR", "NOT_EVALUABLE"}
class ConfigurationError(ValueError):
"""Raised when a manifest or registry is not safe to execute."""
class NotEvaluable(RuntimeError):
"""Raised when an adapter cannot run without changing the experiment."""
@dataclass(frozen=True)
class ArtifactPayload:
path: Path
sha256: str | None = None
encoding: str = "source_artifact"
origin: str = "dataset"
@dataclass(frozen=True)
class TensorPayload:
value: Any
encoding: str = "npy"
dtype: str | None = None
shape: tuple[int, ...] | None = None
@dataclass(frozen=True)
class Frame:
dataset_id: str
dataset_root: Path
raw: dict[str, Any]
source_id: str
sequence_id: str
frame_id: str
frame_index: int
source_frame_index: int
timestamp_ms: int | float | None
image_path: Path | None
source_sha256: str | None
event_id: str | None = None
@property
def key(self) -> str:
return "|".join(
(
self.source_id,
self.sequence_id,
self.frame_id,
str(self.frame_index),
str(self.source_frame_index),
self.source_sha256 or "",
)
)
def public_input(self, truth_fields: set[str]) -> dict[str, Any]:
"""Return a truth-sanitized adapter input."""
payload = {
key: copy.deepcopy(value)
for key, value in self.raw.items()
if key not in truth_fields
}
payload.update(
{
"dataset_id": self.dataset_id,
"source_id": self.source_id,
"sequence_id": self.sequence_id,
"frame_id": self.frame_id,
"frame_index": self.frame_index,
"source_frame_index": self.source_frame_index,
"timestamp_ms": self.timestamp_ms,
"image_path": str(self.image_path) if self.image_path else None,
"image_sha256": self.source_sha256,
}
)
return payload
def oracle_input(self) -> dict[str, Any]:
payload = copy.deepcopy(self.raw)
payload.update(
{
"dataset_id": self.dataset_id,
"source_id": self.source_id,
"sequence_id": self.sequence_id,
"frame_id": self.frame_id,
"frame_index": self.frame_index,
"source_frame_index": self.source_frame_index,
"timestamp_ms": self.timestamp_ms,
"image_path": str(self.image_path) if self.image_path else None,
"image_sha256": self.source_sha256,
}
)
return payload
@dataclass(frozen=True)
class AdapterContext:
repo_root: Path
output_root: Path
job_root: Path
model: dict[str, Any]
dataset: dict[str, Any]
job: dict[str, Any]
resolution: dict[str, int]
model_hash: str | None
model_hash_kind: str
config_hash: str
class Adapter:
truth_fields_read: tuple[str, ...] = ()
def infer(self, frame: Frame, input_row: dict[str, Any]) -> dict[str, Any]:
raise NotImplementedError
def close(self) -> None:
return None
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def canonical_json_bytes(value: Any) -> bytes:
return json.dumps(
value,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
allow_nan=False,
).encode("utf-8")
def sha256_bytes(value: bytes) -> str:
return hashlib.sha256(value).hexdigest()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def read_json(path: Path) -> dict[str, Any]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise ConfigurationError(f"Missing JSON file: {path}") from exc
except json.JSONDecodeError as exc:
raise ConfigurationError(f"Invalid JSON at {path}: {exc}") from exc
if not isinstance(value, dict):
raise ConfigurationError(f"JSON root must be an object: {path}")
return value
def read_jsonl(path: Path) -> list[dict[str, Any]]:
try:
stream = path.open("r", encoding="utf-8")
except FileNotFoundError as exc:
raise ConfigurationError(f"Missing JSONL file: {path}") from exc
rows: list[dict[str, Any]] = []
with stream:
for line_number, raw in enumerate(stream, start=1):
if not raw.strip():
continue
try:
value = json.loads(raw)
except json.JSONDecodeError as exc:
raise ConfigurationError(
f"Invalid JSONL at {path}:{line_number}: {exc}"
) from exc
if not isinstance(value, dict):
raise ConfigurationError(
f"JSONL row is not an object: {path}:{line_number}"
)
rows.append(value)
return rows
def write_json_atomic(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary_name = tempfile.mkstemp(
prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent)
)
temporary = Path(temporary_name)
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream:
json.dump(value, stream, ensure_ascii=False, indent=2, sort_keys=True)
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
if temporary.exists():
temporary.unlink()
def resolve_declared_path(
repo_root: Path, value: str | Path, anchor: Path | None = None
) -> Path:
path = Path(value)
if path.is_absolute():
return path.resolve()
candidates: list[Path] = []
if anchor is not None:
candidates.append((anchor / path).resolve())
candidates.append((repo_root / path).resolve())
for candidate in candidates:
if candidate.exists():
return candidate
return candidates[0]
def require_list(value: Any, label: str) -> list[Any]:
if not isinstance(value, list):
raise ConfigurationError(f"{label} must be a list")
return value
def load_configuration(
manifest_path: Path, repo_root: Path
) -> tuple[
dict[str, Any],
dict[str, dict[str, Any]],
dict[str, dict[str, Any]],
dict[str, Any],
dict[str, str],
]:
manifest_path = manifest_path.resolve()
manifest = read_json(manifest_path)
if manifest.get("schema_version") != "blindassist.model_matrix.manifest.v1":
raise ConfigurationError(f"Unsupported matrix manifest schema: {manifest_path}")
model_registry_path = resolve_declared_path(
repo_root,
str(manifest.get("model_registry", "model_registry.json")),
manifest_path.parent,
)
dataset_registry_path = resolve_declared_path(
repo_root,
str(manifest.get("dataset_registry", "dataset_registry.json")),
manifest_path.parent,
)
trace_schema_path = resolve_declared_path(
repo_root,
str(manifest.get("trace_schema", "trace_schema.json")),
manifest_path.parent,
)
model_registry = read_json(model_registry_path)
dataset_registry = read_json(dataset_registry_path)
trace_schema = read_json(trace_schema_path)
if model_registry.get("schema_version") != "blindassist.model_matrix.model_registry.v1":
raise ConfigurationError(f"Unsupported model registry schema: {model_registry_path}")
if dataset_registry.get("schema_version") != "blindassist.model_matrix.dataset_registry.v1":
raise ConfigurationError(f"Unsupported dataset registry schema: {dataset_registry_path}")
if trace_schema.get("schema_version") != TRACE_SCHEMA_VERSION:
raise ConfigurationError(f"Unsupported trace schema: {trace_schema_path}")
models: dict[str, dict[str, Any]] = {}
for index, item in enumerate(
require_list(model_registry.get("models"), "model registry models")
):
if not isinstance(item, dict) or not isinstance(item.get("model_id"), str):
raise ConfigurationError(f"model registry models[{index}] must have model_id")
model_id = str(item["model_id"])
if model_id in models:
raise ConfigurationError(f"Duplicate model_id: {model_id}")
models[model_id] = item
datasets: dict[str, dict[str, Any]] = {}
for index, item in enumerate(
require_list(dataset_registry.get("datasets"), "dataset registry datasets")
):
if not isinstance(item, dict) or not isinstance(item.get("dataset_id"), str):
raise ConfigurationError(
f"dataset registry datasets[{index}] must have dataset_id"
)
dataset_id = str(item["dataset_id"])
if dataset_id in datasets:
raise ConfigurationError(f"Duplicate dataset_id: {dataset_id}")
datasets[dataset_id] = item
jobs = require_list(manifest.get("jobs"), "matrix manifest jobs")
seen_jobs: set[str] = set()
for index, job in enumerate(jobs):
if not isinstance(job, dict):
raise ConfigurationError(f"jobs[{index}] must be an object")
job_id = job.get("job_id")
if not isinstance(job_id, str) or not job_id:
raise ConfigurationError(f"jobs[{index}] must have a non-empty job_id")
if job_id in seen_jobs:
raise ConfigurationError(f"Duplicate job_id: {job_id}")
seen_jobs.add(job_id)
if job.get("model_id") not in models:
raise ConfigurationError(f"{job_id}: unknown model_id {job.get('model_id')}")
if job.get("dataset_id") not in datasets:
raise ConfigurationError(f"{job_id}: unknown dataset_id {job.get('dataset_id')}")
if job.get("mode", "run") not in {"run", "preflight_only"}:
raise ConfigurationError(f"{job_id}: unsupported mode {job.get('mode')}")
resolution = job.get("resolution") or manifest.get("default_resolution")
if not isinstance(resolution, dict) or not all(
isinstance(resolution.get(key), int) and resolution[key] > 0
for key in ("width", "height")
):
raise ConfigurationError(
f"{job_id}: resolution must contain positive width/height"
)
file_hashes = {
"manifest_sha256": sha256_file(manifest_path),
"model_registry_sha256": sha256_file(model_registry_path),
"dataset_registry_sha256": sha256_file(dataset_registry_path),
"trace_schema_sha256": sha256_file(trace_schema_path),
}
manifest["_manifest_path"] = str(manifest_path)
manifest["_model_registry_path"] = str(model_registry_path)
manifest["_dataset_registry_path"] = str(dataset_registry_path)
manifest["_trace_schema_path"] = str(trace_schema_path)
return manifest, models, datasets, trace_schema, file_hashes
def load_dataset_frames(repo_root: Path, dataset: dict[str, Any]) -> list[Frame]:
dataset_id = str(dataset["dataset_id"])
root = resolve_declared_path(repo_root, str(dataset.get("root", ".")), repo_root)
manifest_value = dataset.get("manifest_path")
if manifest_value:
manifest_path = resolve_declared_path(repo_root, str(manifest_value), root)
try:
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise ConfigurationError(f"Missing dataset manifest: {manifest_path}") from exc
else:
payload = {"frames": dataset.get("frames", [])}
fmt = str(dataset.get("format", "jsonl"))
raw_frames: list[tuple[dict[str, Any], dict[str, Any]]] = []
if fmt == "nested_event_json":
if not isinstance(payload, dict):
raise ConfigurationError(f"{dataset_id}: nested event manifest must be an object")
for event in require_list(payload.get("events"), f"{dataset_id}.events"):
if not isinstance(event, dict):
raise ConfigurationError(f"{dataset_id}: event is not an object")
for frame in require_list(event.get("frames"), f"{dataset_id}.event.frames"):
if not isinstance(frame, dict):
raise ConfigurationError(f"{dataset_id}: frame is not an object")
raw_frames.append((frame, event))
elif fmt == "jsonl":
if manifest_value:
rows = read_jsonl(resolve_declared_path(repo_root, str(manifest_value), root))
else:
rows = require_list(payload.get("frames"), f"{dataset_id}.frames")
raw_frames = [(row, {}) for row in rows if isinstance(row, dict)]
elif fmt == "json_frames":
rows = payload.get("frames") if isinstance(payload, dict) else payload
raw_frames = [
(row, {}) for row in require_list(rows, f"{dataset_id}.frames") if isinstance(row, dict)
]
else:
raise ConfigurationError(f"{dataset_id}: unsupported dataset format {fmt}")
frames: list[Frame] = []
for ordinal, (raw, event) in enumerate(raw_frames):
frame_index = int(raw.get("frame_index", ordinal))
source_frame_index = int(raw.get("source_frame_index", frame_index))
source_id = str(
raw.get("source_id")
or raw.get("source_session_id")
or event.get("source_session_id")
or dataset.get("source_id")
or dataset_id
)
sequence_id = str(
raw.get("sequence_id")
or event.get("sequence_id")
or raw.get("session_id")
or source_id
)
event_id_value = (
raw.get("event_id")
or raw.get("parent_event_id")
or event.get("parent_event_id")
)
event_id = str(event_id_value) if event_id_value is not None else None
frame_id = str(raw.get("frame_id") or raw.get("id") or f"{sequence_id}:{frame_index}")
image_value = raw.get("image_path") or raw.get("image") or raw.get("file_name")
image_path = resolve_declared_path(repo_root, str(image_value), root) if image_value else None
source_sha256 = raw.get("image_sha256") or raw.get("source_rgb_sha256")
if source_sha256 is None and image_path is not None and image_path.is_file():
source_sha256 = sha256_file(image_path)
timestamp = raw.get("timestamp_ms")
if timestamp is not None and not isinstance(timestamp, (int, float)):
raise ConfigurationError(f"{dataset_id}/{frame_id}: timestamp_ms must be numeric or null")
merged_raw = copy.deepcopy(raw)
for key in ("event_candidate_id", "parent_event_id", "source_session_id", "sequence_id"):
if key not in merged_raw and key in event:
merged_raw[key] = event[key]
frames.append(
Frame(
dataset_id=dataset_id,
dataset_root=root,
raw=merged_raw,
source_id=source_id,
sequence_id=sequence_id,
frame_id=frame_id,
frame_index=frame_index,
source_frame_index=source_frame_index,
timestamp_ms=timestamp,
image_path=image_path,
source_sha256=str(source_sha256) if source_sha256 is not None else None,
event_id=event_id,
)
)
if not frames:
raise ConfigurationError(f"{dataset_id}: dataset contains no frames")
keys = [frame.key for frame in frames]
if len(keys) != len(set(keys)):
raise ConfigurationError(f"{dataset_id}: duplicate frame identity")
return frames
def logical_model_hash(model: dict[str, Any]) -> str:
return sha256_bytes(
canonical_json_bytes(
{
"model_id": model.get("model_id"),
"adapter": model.get("adapter"),
"config": model.get("config", {}),
}
)
)
def model_identity(
repo_root: Path, model: dict[str, Any]
) -> tuple[str | None, str, list[dict[str, Any]]]:
assets: list[str] = []
if isinstance(model.get("asset"), str):
assets.append(str(model["asset"]))
assets.extend(str(value) for value in model.get("assets", []) if isinstance(value, str))
if not assets:
return logical_model_hash(model), "logical", []
inventory: list[dict[str, Any]] = []
missing = False
for declared in assets:
path = resolve_declared_path(repo_root, declared, repo_root)
if path.is_file():
inventory.append(
{"path": declared, "sha256": sha256_file(path), "size": path.stat().st_size}
)
else:
inventory.append({"path": declared, "sha256": None, "size": None})
missing = True
if missing:
return None, "missing", inventory
if len(inventory) == 1:
return inventory[0]["sha256"], "asset", inventory
return sha256_bytes(canonical_json_bytes(inventory)), "asset_set", inventory
def config_identity(
model: dict[str, Any], dataset: dict[str, Any], job: dict[str, Any], resolution: dict[str, int]
) -> str:
return sha256_bytes(
canonical_json_bytes(
{
"model_id": model.get("model_id"),
"model_adapter": model.get("adapter"),
"model_config": model.get("config", {}),
"dataset_id": dataset.get("dataset_id"),
"dataset_input_contract": dataset.get("input_contract", {}),
"job": {
key: value
for key, value in job.items()
if key not in {"job_id", "mode", "frame_limit"}
},
"resolution": resolution,
}
)
)
def declared_manifest_hash(repo_root: Path, dataset: dict[str, Any]) -> str | None:
value = dataset.get("manifest_path")
if not value:
return None
root = resolve_declared_path(repo_root, str(dataset.get("root", ".")), repo_root)
path = resolve_declared_path(repo_root, str(value), root)
return sha256_file(path) if path.is_file() else None
def job_fingerprint(
manifest: dict[str, Any],
model: dict[str, Any],
dataset: dict[str, Any],
job: dict[str, Any],
model_hash: str | None,
config_hash: str,
dataset_manifest_hash: str | None,
trace_schema_version: str,
) -> str:
return sha256_bytes(
canonical_json_bytes(
{
"run_id": manifest.get("run_id"),
"job_id": job.get("job_id"),
"model_id": model.get("model_id"),
"dataset_id": dataset.get("dataset_id"),
"model_hash": model_hash,
"config_hash": config_hash,
"dataset_manifest_hash": dataset_manifest_hash,
"trace_schema_version": trace_schema_version,
"mode": job.get("mode", "run"),
"adapter_override": job.get("adapter_override"),
"model_override": job.get("model_override"),
}
)
)
def empty_output(reason: str = "adapter_did_not_provide_output") -> dict[str, Any]:
return {"status": "not_provided", "reason": reason}
def ensure_finite(value: Any, label: str) -> None:
if isinstance(value, bool):
return
if isinstance(value, (int, float)):
if not math.isfinite(float(value)):
raise ValueError(f"{label} must be finite")
elif isinstance(value, list):
for index, item in enumerate(value):
ensure_finite(item, f"{label}[{index}]")
elif isinstance(value, dict):
for key, item in value.items():
ensure_finite(item, f"{label}.{key}")
def jsonable(value: Any) -> Any:
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, Path):
return str(value)
if isinstance(value, Mapping):
return {str(key): jsonable(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [jsonable(item) for item in value]
tolist = getattr(value, "tolist", None)
if callable(tolist):
return jsonable(tolist())
return str(value)
def safe_output_relative(path: Path | None, base: Path) -> str | None:
if path is None:
return None
try:
return path.resolve().relative_to(base.resolve()).as_posix()
except ValueError:
return str(path.resolve()).replace("\\", "/")
def write_tensor_payload(
payload: TensorPayload,
job_root: Path,
ordinal: int,
output_name: str,
) -> dict[str, Any]:
target_dir = job_root / "artifacts" / f"frame-{ordinal:06d}"
target_dir.mkdir(parents=True, exist_ok=True)
value = payload.value
shape = list(payload.shape) if payload.shape is not None else None
dtype = payload.dtype
if shape is None:
raw_shape = getattr(value, "shape", None)
if raw_shape is not None:
try:
shape = [int(item) for item in raw_shape]
except (TypeError, ValueError):
shape = None
if dtype is None:
raw_dtype = getattr(value, "dtype", None)
dtype = str(raw_dtype) if raw_dtype is not None else None
encoding = payload.encoding
if encoding == "npy":
try:
import numpy as np # type: ignore
target = target_dir / f"{output_name}.npy"
np.save(target, np.asarray(value), allow_pickle=False)
except Exception:
encoding = "json"
if encoding == "json":
target = target_dir / f"{output_name}.json"
target.write_text(
json.dumps(jsonable(value), ensure_ascii=False, separators=(",", ":")) + "\n",
encoding="utf-8",
)
return {
"path_scope": "job",
"artifact_path": safe_output_relative(target, job_root),
"sha256": sha256_file(target),
"encoding": encoding,
"dtype": dtype,
"shape": shape,
}
def artifact_reference(payload: ArtifactPayload, repo_root: Path) -> dict[str, Any]:
if not payload.path.is_file():
raise NotEvaluable(f"artifact_missing:{payload.path}")
digest = payload.sha256 or sha256_file(payload.path)
return {
"path_scope": "repo",
"artifact_path": safe_output_relative(payload.path, repo_root),
"sha256": digest,
"encoding": payload.encoding,
"origin": payload.origin,
}
def normalize_artifact_value(
value: Any,
*,
output_name: str,
ordinal: int,
job_root: Path,
repo_root: Path,
) -> Any:
if isinstance(value, TensorPayload):
return write_tensor_payload(value, job_root, ordinal, output_name)
if isinstance(value, ArtifactPayload):
return artifact_reference(value, repo_root)
if isinstance(value, dict):
result = dict(value)
if "value" in result:
result["artifact"] = normalize_artifact_value(
result.pop("value"),
output_name=output_name,
ordinal=ordinal,
job_root=job_root,
repo_root=repo_root,
)
elif "artifact" in result:
result["artifact"] = normalize_artifact_value(
result["artifact"],
output_name=output_name,
ordinal=ordinal,
job_root=job_root,
repo_root=repo_root,
)
return result
return value
def normalize_output(
output_name: str,
raw_value: Any,
*,
ordinal: int,
job_root: Path,
repo_root: Path,
) -> dict[str, Any]:
if raw_value is None:
return empty_output()
if isinstance(raw_value, dict) and "status" in raw_value:
value = normalize_artifact_value(
raw_value,
output_name=output_name,
ordinal=ordinal,
job_root=job_root,
repo_root=repo_root,
)
if value.get("status") not in ENVELOPE_STATUSES:
raise ValueError(f"{output_name}: unsupported output status {value.get('status')}")
return value
if output_name == "detections":
if isinstance(raw_value, list):
return {"status": "present", "items": jsonable(raw_value), "count": len(raw_value)}
if isinstance(raw_value, dict):
items = raw_value.get("items", [])
return {
"status": "present",
"items": jsonable(items),
"count": int(raw_value.get("count", len(items))),
}
if output_name in {"segmentation_logits", "mask", "depth"}:
artifact = normalize_artifact_value(
raw_value,
output_name=output_name,
ordinal=ordinal,
job_root=job_root,
repo_root=repo_root,
)
return {"status": "present", "artifact": artifact}
if isinstance(raw_value, dict):
return {"status": "present", **jsonable(raw_value)}
return {"status": "present", "value": jsonable(raw_value)}
def normalize_known(value: Any) -> str:
if isinstance(value, bool):
return "KNOWN" if value else "UNKNOWN"
if isinstance(value, str) and value.upper() in {"KNOWN", "UNKNOWN"}:
return value.upper()
return "UNKNOWN"
class FixtureAdapter(Adapter):
def infer(self, frame: Frame, input_row: dict[str, Any]) -> dict[str, Any]:
value = input_row.get("fixture_output") or input_row.get("model_output") or {}
if not isinstance(value, dict):
raise NotEvaluable("fixture_output_must_be_object")
return copy.deepcopy(value)
class FixedRuleAdapter(Adapter):
def __init__(self, model: dict[str, Any]) -> None:
self.rule = str(model.get("config", {}).get("rule", "no_alert"))
def infer(self, frame: Frame, input_row: dict[str, Any]) -> dict[str, Any]:
if self.rule == "no_alert":
return {
"risk_output": {
"status": "present",
"raw_level": "NONE",
"stable_level": "NONE",
"active": False,
"direction": "NONE",
"rule_id": self.rule,
},
"known": "UNKNOWN",
}
if self.rule == "always_unknown":
return {
"risk_output": {
"status": "present",
"raw_level": "UNKNOWN",
"stable_level": "UNKNOWN",
"active": False,
"direction": "NONE",
"rule_id": self.rule,
},
"known": "UNKNOWN",
}
if self.rule == "frame_metadata":
level = str(input_row.get("fixed_risk_level", "UNKNOWN")).upper()
active = bool(input_row.get("fixed_alert", False))
return {
"risk_output": {
"status": "present",
"raw_level": level,
"stable_level": level,
"active": active,
"direction": str(input_row.get("fixed_direction", "NONE")),
"rule_id": self.rule,
},
"known": "KNOWN" if level not in {"UNKNOWN", "NONE"} else "UNKNOWN",
}
raise NotEvaluable(f"unknown_fixed_rule:{self.rule}")
class TruthMaskAdapter(Adapter):
truth_fields_read = ("oracle_mask_path", "oracle_mask_sha256")
def __init__(self, repo_root: Path) -> None:
self.repo_root = repo_root
def infer(self, frame: Frame, input_row: dict[str, Any]) -> dict[str, Any]:
mask_value = input_row.get("oracle_mask_path") or input_row.get("mask_path")
if not mask_value:
raise NotEvaluable("truth_mask_path_missing")
path = resolve_declared_path(self.repo_root, str(mask_value), frame.dataset_root)
digest = input_row.get("oracle_mask_sha256") or input_row.get("mask_sha256")
return {
"mask": {
"status": "present",
"encoding": "png_class_id",
"artifact": ArtifactPayload(
path=path,
sha256=str(digest) if digest else None,
encoding="png_class_id",
origin="dataset_oracle",
),
},
"known": "KNOWN",
"adapter_metadata": {
"evidence_role": "oracle_reference",
"drives_alerts": False,
},
}
class LegacyTraceReplayAdapter(Adapter):
def __init__(self, model: dict[str, Any], repo_root: Path) -> None:
spec = model.get("adapter", {})
config = model.get("config", {})
self.repo_root = repo_root
declared = spec.get("trace_path") or config.get("trace_path")
if not isinstance(declared, str):
raise NotEvaluable("legacy_trace_path_missing")
trace_path = resolve_declared_path(repo_root, declared, repo_root)
if not trace_path.is_file():
raise NotEvaluable(f"legacy_trace_missing:{trace_path}")
arm = spec.get("arm") or config.get("arm")
self.rows: dict[tuple[str, int, str | None], dict[str, Any]] = {}
for row in read_jsonl(trace_path):
event_id = str(row.get("event_candidate_id") or row.get("parent_event_id") or "")
frame_index = int(row.get("frame_index", -1))
row_arm = str(row.get("arm")) if row.get("arm") is not None else None
key = (event_id, frame_index, row_arm)
if key in self.rows:
raise NotEvaluable(f"legacy_trace_duplicate:{trace_path}:{key}")
self.rows[key] = row
self.arm = str(arm) if arm is not None else None
self.trace_path = trace_path
def infer(self, frame: Frame, input_row: dict[str, Any]) -> dict[str, Any]:
event_id = str(
frame.raw.get("event_candidate_id")
or frame.raw.get("parent_event_id")
or frame.event_id
or ""
)
if self.arm is not None:
legacy = self.rows.get((event_id, frame.frame_index, self.arm))
else:
candidates = [
row
for (row_event, row_frame, _), row in self.rows.items()
if row_event == event_id and row_frame == frame.frame_index
]
legacy = candidates[0] if candidates else None
if legacy is None:
raise NotEvaluable(f"legacy_trace_frame_missing:{event_id}:{frame.frame_index}")
detection_count = legacy.get("detection_count")
detections = None
if detection_count is not None:
detections = {
"status": "partial",
"count": int(detection_count),
"items": [],
"reason": "legacy_trace_contains_count_without_boxes",
}
risk = {
"status": "present",
"raw_level": legacy.get("raw_risk_level"),
"stable_level": legacy.get("stable_risk_level"),
"active": legacy.get("risk_event_active"),
"direction": legacy.get("risk_direction"),
"event_id": legacy.get("risk_event_id"),
"event_state": legacy.get("risk_event_state"),
"clear_reason": legacy.get("risk_event_clear_reason"),
"actual_alert": legacy.get("actual_alert"),
}
return {
"detections": detections,
"risk_output": risk,
"known": "UNKNOWN",
"latency_ms": {"inference": legacy.get("perception_ms")},
"adapter_metadata": {
"source_trace": safe_output_relative(self.trace_path, self.repo_root),
"source_trace_schema": legacy.get("schema_version"),
"legacy_model_sha256": legacy.get("model_sha256"),
"reused_without_rerun": True,
},
}
class TFLiteAdapter(Adapter):
def __init__(self, model: dict[str, Any], repo_root: Path, resolution: dict[str, int]) -> None:
try:
import numpy as np # type: ignore
except Exception as exc:
raise NotEvaluable("numpy_not_installed") from exc
self.np = np
asset = model.get("asset")
if not isinstance(asset, str):
raise NotEvaluable("tflite_asset_missing")
model_path = resolve_declared_path(repo_root, asset, repo_root)
if not model_path.is_file():
raise NotEvaluable(f"tflite_asset_not_found:{model_path}")
self.model = model
self.config = model.get("config", {})
self.resolution = resolution
try:
from ai_edge_litert.interpreter import Interpreter # type: ignore
self.interpreter = Interpreter(model_path=str(model_path))
except Exception:
try:
import tensorflow as tf # type: ignore
self.interpreter = tf.lite.Interpreter(model_path=str(model_path))
except Exception as exc:
raise NotEvaluable("no_tflite_interpreter") from exc
self.interpreter.allocate_tensors()
self.input_detail = self.interpreter.get_input_details()[0]
self.output_details = self.interpreter.get_output_details()
def _shape(self, detail: dict[str, Any]) -> list[int]:
shape = detail.get("shape")
if hasattr(shape, "tolist"):
shape = shape.tolist()
return [int(value) for value in shape]
def _prepare_image(self, frame: Frame) -> Any:
if frame.image_path is None or not frame.image_path.is_file():
raise NotEvaluable(f"image_missing:{frame.image_path}")
try:
from PIL import Image # type: ignore
except Exception as exc:
raise NotEvaluable("pillow_not_installed") from exc
shape = self._shape(self.input_detail)
if len(shape) != 4 or shape[0] != 1 or shape[3] != 3:
raise NotEvaluable(f"unsupported_tflite_input_shape:{shape}")
height = shape[1] if shape[1] > 0 else self.resolution["height"]
width = shape[2] if shape[2] > 0 else self.resolution["width"]
with Image.open(frame.image_path) as image:
image = image.convert("RGB").resize((width, height))
array = self.np.asarray(image, dtype=self.np.float32) / self.np.float32(255.0)
dtype = self.input_detail.get("dtype")
if dtype == self.np.uint8 or dtype == self.np.int8:
scale, zero_point = self.input_detail.get("quantization", (0.0, 0))
if scale:
array = self.np.round(array / float(scale) + float(zero_point))
array = array.clip(self.np.iinfo(dtype).min, self.np.iinfo(dtype).max).astype(dtype)
else:
array = array.astype(dtype or self.np.float32)
return self.np.expand_dims(array, axis=0)
def _read_outputs(self) -> list[Any]:
values = []
for detail in self.output_details:
value = self.interpreter.get_tensor(detail["index"])
dtype = detail.get("dtype")
if dtype is not None and dtype != self.np.float32:
scale, zero_point = detail.get("quantization", (0.0, 0))
if scale:
value = (value.astype(self.np.float32) - float(zero_point)) * float(scale)
values.append(value)
return values
def _decode_segmentation(self, values: list[Any]) -> dict[str, Any]:
index = int(self.config.get("output_index", 0))