Compare commits
5
Commits
1084984da2
...
15be698097
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15be698097 | ||
|
|
3679e43fe3 | ||
|
|
05590867b7 | ||
|
|
33cef2fdea | ||
|
|
6276bbf324 |
@@ -9,6 +9,10 @@ import {
|
||||
RecordedEvidenceSemanticMaskOverlay,
|
||||
type RecordedEvidenceSemanticOverlay,
|
||||
} from "./RecordedEvidenceSemanticMaskOverlay";
|
||||
import {
|
||||
RecordedEvidencePointCloudOverlay,
|
||||
type RecordedEvidencePointCloudOverlayData,
|
||||
} from "./RecordedEvidencePointCloudOverlay";
|
||||
|
||||
export function RecordedEvidenceImageScene({
|
||||
src,
|
||||
@@ -16,6 +20,7 @@ export function RecordedEvidenceImageScene({
|
||||
imageHeight,
|
||||
boxes,
|
||||
semanticOverlay,
|
||||
pointCloudOverlay,
|
||||
ariaLabel,
|
||||
}: {
|
||||
src: string;
|
||||
@@ -23,6 +28,7 @@ export function RecordedEvidenceImageScene({
|
||||
imageHeight: number;
|
||||
boxes: readonly RecordedEvidenceBox[];
|
||||
semanticOverlay?: RecordedEvidenceSemanticOverlay;
|
||||
pointCloudOverlay?: RecordedEvidencePointCloudOverlayData;
|
||||
ariaLabel: string;
|
||||
}) {
|
||||
const [state, setState] = useState<"loading" | "ready" | "error">("loading");
|
||||
@@ -47,6 +53,13 @@ export function RecordedEvidenceImageScene({
|
||||
imageHeight={imageHeight}
|
||||
/>
|
||||
) : null}
|
||||
{pointCloudOverlay ? (
|
||||
<RecordedEvidencePointCloudOverlay
|
||||
imageWidth={imageWidth}
|
||||
imageHeight={imageHeight}
|
||||
overlay={pointCloudOverlay}
|
||||
/>
|
||||
) : null}
|
||||
<RecordedEvidenceBoxOverlay
|
||||
imageWidth={imageWidth}
|
||||
imageHeight={imageHeight}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export type RecordedEvidenceProjectedPoint = readonly [number, number, number];
|
||||
|
||||
export interface RecordedEvidencePointCloudOverlayData {
|
||||
pointsXyd: readonly RecordedEvidenceProjectedPoint[];
|
||||
sourcePointCount: number;
|
||||
projectedPointCount: number;
|
||||
projection: "factory-kb4-exact";
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
const DEPTH_BUCKETS = 64;
|
||||
|
||||
function depthColor(depthM: number): string {
|
||||
const normalized = Math.max(0, Math.min(1, (depthM - 0.5) / 24));
|
||||
const bucket = Math.round(normalized * (DEPTH_BUCKETS - 1));
|
||||
const hue = 18 + bucket / (DEPTH_BUCKETS - 1) * 190;
|
||||
return `hsla(${hue}, 96%, 62%, 0.86)`;
|
||||
}
|
||||
|
||||
export function RecordedEvidencePointCloudOverlay({
|
||||
imageWidth,
|
||||
imageHeight,
|
||||
overlay,
|
||||
}: {
|
||||
imageWidth: number;
|
||||
imageHeight: number;
|
||||
overlay: RecordedEvidencePointCloudOverlayData;
|
||||
}) {
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const host = canvas?.parentElement;
|
||||
if (!canvas || !host) return;
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return;
|
||||
|
||||
const render = () => {
|
||||
const width = Math.max(host.clientWidth, 1);
|
||||
const height = Math.max(host.clientHeight, 1);
|
||||
const pixelRatio = Math.min(window.devicePixelRatio, 1.5);
|
||||
canvas.width = Math.round(width * pixelRatio);
|
||||
canvas.height = Math.round(height * pixelRatio);
|
||||
canvas.style.width = `${width}px`;
|
||||
canvas.style.height = `${height}px`;
|
||||
context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
|
||||
context.clearRect(0, 0, width, height);
|
||||
|
||||
const scale = Math.min(width / imageWidth, height / imageHeight);
|
||||
const offsetX = (width - imageWidth * scale) / 2;
|
||||
const offsetY = (height - imageHeight * scale) / 2;
|
||||
const radius = Math.max(0.8, Math.min(2.2, scale * 1.45));
|
||||
for (const [imageX, imageY, depthM] of overlay.pointsXyd) {
|
||||
context.beginPath();
|
||||
context.arc(
|
||||
offsetX + imageX * scale,
|
||||
offsetY + imageY * scale,
|
||||
radius,
|
||||
0,
|
||||
Math.PI * 2,
|
||||
);
|
||||
context.fillStyle = depthColor(depthM);
|
||||
context.fill();
|
||||
}
|
||||
};
|
||||
|
||||
const observer = new ResizeObserver(render);
|
||||
observer.observe(host);
|
||||
render();
|
||||
return () => observer.disconnect();
|
||||
}, [imageHeight, imageWidth, overlay]);
|
||||
|
||||
return <canvas ref={canvasRef} role="img" aria-label={overlay.ariaLabel} />;
|
||||
}
|
||||
@@ -12,6 +12,10 @@ import {
|
||||
RecordedEvidenceSemanticMaskOverlay,
|
||||
type RecordedEvidenceSemanticOverlay,
|
||||
} from "./RecordedEvidenceSemanticMaskOverlay";
|
||||
import {
|
||||
RecordedEvidencePointCloudOverlay,
|
||||
type RecordedEvidencePointCloudOverlayData,
|
||||
} from "./RecordedEvidencePointCloudOverlay";
|
||||
|
||||
export type { RecordedEvidenceBox, RecordedEvidenceBoxTone };
|
||||
|
||||
@@ -22,6 +26,7 @@ export function RecordedEvidenceVideoScene({
|
||||
imageHeight,
|
||||
boxes,
|
||||
semanticOverlay,
|
||||
pointCloudOverlay,
|
||||
ariaLabel,
|
||||
interactive = true,
|
||||
segmentSequence,
|
||||
@@ -35,6 +40,7 @@ export function RecordedEvidenceVideoScene({
|
||||
imageHeight: number;
|
||||
boxes: readonly RecordedEvidenceBox[];
|
||||
semanticOverlay?: RecordedEvidenceSemanticOverlay;
|
||||
pointCloudOverlay?: RecordedEvidencePointCloudOverlayData;
|
||||
ariaLabel: string;
|
||||
interactive?: boolean;
|
||||
segmentSequence?: number;
|
||||
@@ -61,6 +67,13 @@ export function RecordedEvidenceVideoScene({
|
||||
imageHeight={imageHeight}
|
||||
/>
|
||||
) : null}
|
||||
{pointCloudOverlay ? (
|
||||
<RecordedEvidencePointCloudOverlay
|
||||
imageWidth={imageWidth}
|
||||
imageHeight={imageHeight}
|
||||
overlay={pointCloudOverlay}
|
||||
/>
|
||||
) : null}
|
||||
<RecordedEvidenceBoxOverlay
|
||||
imageWidth={imageWidth}
|
||||
imageHeight={imageHeight}
|
||||
|
||||
@@ -42,10 +42,12 @@ import {
|
||||
fetchM48LifecycleResult,
|
||||
} from "./m48ObjectCentricQuality";
|
||||
import { fetchM48SmallStaticRegression } from "./m48SmallStaticRegression";
|
||||
import { fetchM48SFixedClassDetectorResult } from "./m48sFixedClassDetector";
|
||||
|
||||
export type AdvancedLaboratoryWorkId =
|
||||
| "m48-object-centric-quality"
|
||||
| "m48-small-static-passage-regression"
|
||||
| "m48s-fixed-class-detector"
|
||||
| "m47-reference-graph-shadow"
|
||||
| "m4-replay-threat"
|
||||
| "l3-pointpillars-visual-audit"
|
||||
@@ -90,6 +92,7 @@ export interface AdvancedLaboratoryIndexItem {
|
||||
const WORK_IDS: readonly AdvancedLaboratoryWorkId[] = [
|
||||
"m48-object-centric-quality",
|
||||
"m48-small-static-passage-regression",
|
||||
"m48s-fixed-class-detector",
|
||||
"m47-reference-graph-shadow",
|
||||
"m4-replay-threat",
|
||||
"l3-pointpillars-visual-audit",
|
||||
@@ -129,6 +132,7 @@ const WORK_IDS: readonly AdvancedLaboratoryWorkId[] = [
|
||||
const RESULT_PREFIX: Readonly<Record<AdvancedLaboratoryWorkId, string>> = {
|
||||
"m48-object-centric-quality": "m48-object-quality-(?:pack|result)",
|
||||
"m48-small-static-passage-regression": "m48-small-static-passage-regression",
|
||||
"m48s-fixed-class-detector": "m48s-fixed-class-detector-lab",
|
||||
"m47-reference-graph-shadow": "m47-reference-graph-lab",
|
||||
"m4-replay-threat": "m4-threat-replay",
|
||||
"l3-pointpillars-visual-audit": "l3-pointpillars-visual-audit",
|
||||
@@ -176,6 +180,7 @@ export function emptyAdvancedLaboratoryResults(): AdvancedLaboratoryResults {
|
||||
m47Graph: null,
|
||||
m48: null,
|
||||
m48SmallStatic: null,
|
||||
m48s: null,
|
||||
m4Threat: null,
|
||||
l3: null,
|
||||
l31: null,
|
||||
@@ -302,6 +307,7 @@ export function advancedLaboratoryResultAvailable(
|
||||
): boolean {
|
||||
return workId === "m48-object-centric-quality" ? results.m48 !== null
|
||||
: workId === "m48-small-static-passage-regression" ? results.m48SmallStatic !== null
|
||||
: workId === "m48s-fixed-class-detector" ? results.m48s !== null
|
||||
: workId === "m47-reference-graph-shadow" ? results.m47Graph !== null
|
||||
: workId === "m4-replay-threat" ? results.m4Threat !== null
|
||||
: workId === "l3-pointpillars-visual-audit" ? results.l3 !== null
|
||||
@@ -357,6 +363,9 @@ export async function fetchAdvancedLaboratoryResult(
|
||||
} else if (workId === "m48-small-static-passage-regression") {
|
||||
if (!resultId) throw new AdvancedLaboratoryContractError("M4.8R1 regression identity не выбрана.");
|
||||
results.m48SmallStatic = await fetchM48SmallStaticRegression(resultId, { fetcher, signal });
|
||||
} else if (workId === "m48s-fixed-class-detector") {
|
||||
if (!resultId) throw new AdvancedLaboratoryContractError("M4.8S LAB identity не выбрана.");
|
||||
results.m48s = await fetchM48SFixedClassDetectorResult(resultId, { fetcher, signal });
|
||||
} else if (workId === "m47-reference-graph-shadow") {
|
||||
if (!resultId) {
|
||||
throw new AdvancedLaboratoryContractError("M4.7 LAB identity не выбрана.");
|
||||
|
||||
@@ -36,11 +36,13 @@ import type { M4ThreatReplayResult } from "./m4ReplayThreat";
|
||||
import type { M47ReferenceGraphLabResult } from "./m47ReferenceGraph";
|
||||
import type { M48AdvancedResult } from "./m48ObjectCentricQuality";
|
||||
import type { M48SmallStaticRegressionResult } from "./m48SmallStaticRegression";
|
||||
import type { M48SFixedClassDetectorResult } from "./m48sFixedClassDetector";
|
||||
|
||||
export interface AdvancedLaboratoryResults {
|
||||
m47Graph: M47ReferenceGraphLabResult | null;
|
||||
m48: M48AdvancedResult | null;
|
||||
m48SmallStatic: M48SmallStaticRegressionResult | null;
|
||||
m48s: M48SFixedClassDetectorResult | null;
|
||||
m4Threat: M4ThreatReplayResult | null;
|
||||
l3: L3PointPillarsVisualAuditResult | null;
|
||||
l31: L31PointPillarsRavnovesResult | null;
|
||||
|
||||
@@ -967,7 +967,7 @@ export async function fetchAdvancedLaboratoryResults({
|
||||
const e39 = settledCatalogValue(settled[7]);
|
||||
const e40 = settledCatalogValue(settled[8]);
|
||||
return {
|
||||
m47Graph: null, m48: null, m48SmallStatic: null, m4Threat: null,
|
||||
m47Graph: null, m48: null, m48SmallStatic: null, m48s: null, m4Threat: null,
|
||||
l3: null, l31: null,
|
||||
l32: null,
|
||||
l33: null,
|
||||
|
||||
@@ -0,0 +1,569 @@
|
||||
import type { LaboratoryFetch } from "./advancedResults";
|
||||
|
||||
const RESULT_ID = /^m48s-fixed-class-detector-lab-[a-f0-9]{64}$/;
|
||||
const FRAME_ID = /^[0-9]{6}$/;
|
||||
const MODES = ["source", "yolox", "dfine", "rf-detr"] as const;
|
||||
const DETECTOR_MODES = ["yolox", "dfine", "rf-detr"] as const;
|
||||
const RESULT_STATUSES = [
|
||||
"detector-load-passed-reference-graph-shadow-only",
|
||||
"complete-reference-graph-shadow-passed-production-not-authorized",
|
||||
] as const;
|
||||
|
||||
export type M48SDetectorMode = typeof MODES[number];
|
||||
export type M48SDetectorModel = typeof DETECTOR_MODES[number];
|
||||
|
||||
export interface M48SAuthority {
|
||||
actuationAllowed: false;
|
||||
candidateAccepted: false;
|
||||
commandsEnabled: false;
|
||||
groundTruth: false;
|
||||
navigationOrSafetyAccepted: false;
|
||||
}
|
||||
|
||||
export interface M48SMethodComponent {
|
||||
kind: "source" | "tool" | "model" | "algorithm" | "runtime";
|
||||
name: string;
|
||||
version: string;
|
||||
role: string;
|
||||
identitySha256: string;
|
||||
}
|
||||
|
||||
export interface M48SMethod {
|
||||
completeness: "complete";
|
||||
executionClass: "ai-inference";
|
||||
pipelineId: string;
|
||||
components: readonly M48SMethodComponent[];
|
||||
}
|
||||
|
||||
export interface M48SDetectorCandidate {
|
||||
id: M48SDetectorModel;
|
||||
label: string;
|
||||
providerId: string;
|
||||
capacityFps: number;
|
||||
p95Ms: number;
|
||||
frame253DogDetected: boolean;
|
||||
frame253DogScore: number | null;
|
||||
selected: boolean;
|
||||
}
|
||||
|
||||
export interface M48SFrameDescriptor {
|
||||
frameId: string;
|
||||
sourceSequence: number;
|
||||
counts: Readonly<Record<M48SDetectorModel, number>>;
|
||||
}
|
||||
|
||||
export interface M48SIntegratedWorldState {
|
||||
durationSeconds: number;
|
||||
sourceFramesAdmitted: number;
|
||||
deliveredWorldStates: number;
|
||||
supersededFrames: number;
|
||||
effectiveWorldStateFps: number;
|
||||
worldStateCompletionAgeP95Ms: number;
|
||||
worldStateCompletionAgeP99Ms: number;
|
||||
worldStateCompletionAgeMaximumMs: number;
|
||||
localObstacleMapOutputAgeP95Ms: number;
|
||||
queueHighWatermarks: Readonly<Record<"detector" | "geometry" | "temporal" | "rolling" | "threat", number>>;
|
||||
queueCapacity: number;
|
||||
gpuUtilizationMeanPercent: number;
|
||||
gpuUtilizationMaximumPercent: number;
|
||||
gpuMemoryMaximumMib: number;
|
||||
gpuPowerMaximumW: number;
|
||||
gpuTemperatureMaximumC: number;
|
||||
uniqueComponentCount: number;
|
||||
multiFrameComponentCount: number;
|
||||
maximumComponentPublications: number;
|
||||
duplicateComponentIdsWithinFrame: number;
|
||||
advisoryFamilyCounts: Readonly<Record<"animal" | "generic-obstacle" | "light-road-user" | "person" | "vehicle", number>>;
|
||||
semanticHintCounts: Readonly<Record<string, number>>;
|
||||
motionCounts: Readonly<Record<"moving" | "stationary" | "unknown", number>>;
|
||||
additionalInferencePasses: number;
|
||||
failures: number;
|
||||
}
|
||||
|
||||
export interface M48SFixedClassDetectorResult {
|
||||
resultId: string;
|
||||
createdAtUtc: string;
|
||||
status: typeof RESULT_STATUSES[number];
|
||||
boundedQuestionAccepted: true;
|
||||
groundTruth: false;
|
||||
source: {
|
||||
sourceSessionId: "RAVNOVES00";
|
||||
cameraSourceId: "sensor.camera.right";
|
||||
cameraRaster: readonly [800, 600];
|
||||
evidenceFrameCount: number;
|
||||
};
|
||||
configuration: {
|
||||
comparisonThreshold: 0.5;
|
||||
displayModes: readonly M48SDetectorMode[];
|
||||
singleInferencePerFrame: true;
|
||||
geometryOwnsStaticOccupancy: true;
|
||||
unknownStationaryResponse: "route-around";
|
||||
unknownMovingResponse: "conservative-risk";
|
||||
};
|
||||
method: M48SMethod;
|
||||
metrics: {
|
||||
candidates: readonly M48SDetectorCandidate[];
|
||||
detectorLoad: {
|
||||
durationSeconds: number;
|
||||
sourceFramesConsumed: number;
|
||||
sourceFrameReplacements: number;
|
||||
effectiveConsumedFps: number;
|
||||
endToEndP95Ms: number;
|
||||
completionAgeP95Ms: number;
|
||||
gpuUtilizationMeanPercent: number;
|
||||
gpuUtilizationMaximumPercent: number;
|
||||
gpuMemoryMaximumMib: number;
|
||||
queueMaximumDepth: number;
|
||||
queueCapacity: number;
|
||||
failures: number;
|
||||
};
|
||||
integratedWorldState: M48SIntegratedWorldState | null;
|
||||
};
|
||||
decision: {
|
||||
selectedCandidate: "rf-detr";
|
||||
readyForReferenceGraphShadow: true;
|
||||
integratedWorldStateGateEvaluated: boolean;
|
||||
integratedWorldStateGatePassed: boolean;
|
||||
detectorReplacementAuthorized: false;
|
||||
productionAccepted: false;
|
||||
};
|
||||
limitations: readonly string[];
|
||||
authority: M48SAuthority;
|
||||
frames: readonly M48SFrameDescriptor[];
|
||||
}
|
||||
|
||||
export interface M48SDetection {
|
||||
label: string;
|
||||
score: number;
|
||||
bboxXyxy: readonly [number, number, number, number];
|
||||
}
|
||||
|
||||
export interface M48SDetectorFrame {
|
||||
resultId: string;
|
||||
frameId: string;
|
||||
sourceSequence: number;
|
||||
cameraUrl: string;
|
||||
imageWidth: 800;
|
||||
imageHeight: 600;
|
||||
comparisonThreshold: 0.5;
|
||||
detections: Readonly<Record<M48SDetectorModel, readonly M48SDetection[]>>;
|
||||
groundTruthAvailable: false;
|
||||
authority: M48SAuthority;
|
||||
}
|
||||
|
||||
export class M48SFixedClassDetectorContractError extends Error {}
|
||||
|
||||
function objectValue(value: unknown, label: string): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}: ожидался объект.`);
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function arrayValue(value: unknown, label: string): readonly unknown[] {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}: ожидался список.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function exact(value: unknown, expected: string | number | boolean, label: string): void {
|
||||
if (value !== expected) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}: нарушен контракт.`);
|
||||
}
|
||||
}
|
||||
|
||||
function textValue(value: unknown, label: string): string {
|
||||
if (typeof value !== "string" || !value.trim()) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}: ожидалась строка.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function numberValue(value: unknown, label: string): number {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}: ожидалось число.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function integerValue(value: unknown, label: string): number {
|
||||
const result = numberValue(value, label);
|
||||
if (!Number.isInteger(result) || result < 0) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}: ожидалось целое число.`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown, label: string): boolean {
|
||||
if (typeof value !== "boolean") {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}: ожидался флаг.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {
|
||||
if (typeof value !== "string" || !allowed.includes(value as T)) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}: неизвестное значение.`);
|
||||
}
|
||||
return value as T;
|
||||
}
|
||||
|
||||
function authorityValue(value: unknown, label: string): M48SAuthority {
|
||||
const authority = objectValue(value, label);
|
||||
exact(authority.actuation_allowed, false, `${label}.actuation_allowed`);
|
||||
exact(authority.candidate_accepted, false, `${label}.candidate_accepted`);
|
||||
exact(authority.commands_enabled, false, `${label}.commands_enabled`);
|
||||
exact(authority.ground_truth, false, `${label}.ground_truth`);
|
||||
exact(
|
||||
authority.navigation_or_safety_accepted,
|
||||
false,
|
||||
`${label}.navigation_or_safety_accepted`,
|
||||
);
|
||||
return {
|
||||
actuationAllowed: false,
|
||||
candidateAccepted: false,
|
||||
commandsEnabled: false,
|
||||
groundTruth: false,
|
||||
navigationOrSafetyAccepted: false,
|
||||
};
|
||||
}
|
||||
|
||||
function methodValue(value: unknown): M48SMethod {
|
||||
const method = objectValue(value, "M4.8S.method");
|
||||
exact(method.schema_version, "missioncore.laboratory-method/v1", "M4.8S.method.schema_version");
|
||||
exact(method.completeness, "complete", "M4.8S.method.completeness");
|
||||
exact(method.execution_class, "ai-inference", "M4.8S.method.execution_class");
|
||||
return {
|
||||
completeness: "complete",
|
||||
executionClass: "ai-inference",
|
||||
pipelineId: textValue(method.pipeline_id, "M4.8S.method.pipeline_id"),
|
||||
components: arrayValue(method.components, "M4.8S.method.components").map((value, index) => {
|
||||
const component = objectValue(value, `M4.8S.method.components[${index}]`);
|
||||
return {
|
||||
kind: enumValue(
|
||||
component.kind,
|
||||
["source", "tool", "model", "algorithm", "runtime"] as const,
|
||||
`M4.8S.method.components[${index}].kind`,
|
||||
),
|
||||
name: textValue(component.name, `M4.8S.method.components[${index}].name`),
|
||||
version: textValue(component.version, `M4.8S.method.components[${index}].version`),
|
||||
role: textValue(component.role, `M4.8S.method.components[${index}].role`),
|
||||
identitySha256: textValue(
|
||||
component.identity_sha256,
|
||||
`M4.8S.method.components[${index}].identity_sha256`,
|
||||
),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function countsValue(value: unknown, label: string): Readonly<Record<M48SDetectorModel, number>> {
|
||||
const counts = objectValue(value, label);
|
||||
return {
|
||||
yolox: integerValue(counts.yolox, `${label}.yolox`),
|
||||
dfine: integerValue(counts.dfine, `${label}.dfine`),
|
||||
"rf-detr": integerValue(counts["rf-detr"], `${label}.rf-detr`),
|
||||
};
|
||||
}
|
||||
|
||||
function descriptorValue(value: unknown): M48SFrameDescriptor {
|
||||
const frame = objectValue(value, "M4.8S.frame");
|
||||
const frameId = textValue(frame.frame_id, "M4.8S.frame.frame_id");
|
||||
if (!FRAME_ID.test(frameId)) {
|
||||
throw new M48SFixedClassDetectorContractError("M4.8S.frame.frame_id: нарушена идентичность.");
|
||||
}
|
||||
return {
|
||||
frameId,
|
||||
sourceSequence: integerValue(frame.source_sequence, "M4.8S.frame.source_sequence"),
|
||||
counts: countsValue(frame.counts, "M4.8S.frame.counts"),
|
||||
};
|
||||
}
|
||||
|
||||
function candidateValue(value: unknown): M48SDetectorCandidate {
|
||||
const candidate = objectValue(value, "M4.8S.candidate");
|
||||
const score = candidate.frame_253_dog_score;
|
||||
if (score !== null && (typeof score !== "number" || !Number.isFinite(score))) {
|
||||
throw new M48SFixedClassDetectorContractError("M4.8S.candidate.frame_253_dog_score: нарушен контракт.");
|
||||
}
|
||||
return {
|
||||
id: enumValue(candidate.id, DETECTOR_MODES, "M4.8S.candidate.id"),
|
||||
label: textValue(candidate.label, "M4.8S.candidate.label"),
|
||||
providerId: textValue(candidate.provider_id, "M4.8S.candidate.provider_id"),
|
||||
capacityFps: numberValue(candidate.capacity_fps, "M4.8S.candidate.capacity_fps"),
|
||||
p95Ms: numberValue(candidate.p95_ms, "M4.8S.candidate.p95_ms"),
|
||||
frame253DogDetected: booleanValue(
|
||||
candidate.frame_253_dog_detected,
|
||||
"M4.8S.candidate.frame_253_dog_detected",
|
||||
),
|
||||
frame253DogScore: score,
|
||||
selected: booleanValue(candidate.selected, "M4.8S.candidate.selected"),
|
||||
};
|
||||
}
|
||||
|
||||
function integerRecordValue(value: unknown, label: string): Readonly<Record<string, number>> {
|
||||
const record = objectValue(value, label);
|
||||
return Object.fromEntries(
|
||||
Object.entries(record).map(([key, item]) => [key, integerValue(item, `${label}.${key}`)]),
|
||||
);
|
||||
}
|
||||
|
||||
function integratedWorldStateValue(value: unknown): M48SIntegratedWorldState {
|
||||
const integrated = objectValue(value, "M4.8S.metrics.integrated_world_state");
|
||||
const queues = integerRecordValue(
|
||||
integrated.queue_high_watermarks,
|
||||
"M4.8S.integrated.queue_high_watermarks",
|
||||
);
|
||||
const advisory = integerRecordValue(
|
||||
integrated.advisory_family_counts,
|
||||
"M4.8S.integrated.advisory_family_counts",
|
||||
);
|
||||
const motion = integerRecordValue(
|
||||
integrated.motion_counts,
|
||||
"M4.8S.integrated.motion_counts",
|
||||
);
|
||||
for (const key of ["detector", "geometry", "temporal", "rolling", "threat"] as const) {
|
||||
if (!(key in queues)) {
|
||||
throw new M48SFixedClassDetectorContractError(`M4.8S.integrated.queue_high_watermarks.${key}: отсутствует.`);
|
||||
}
|
||||
}
|
||||
for (const key of ["animal", "generic-obstacle", "light-road-user", "person", "vehicle"] as const) {
|
||||
if (!(key in advisory)) {
|
||||
throw new M48SFixedClassDetectorContractError(`M4.8S.integrated.advisory_family_counts.${key}: отсутствует.`);
|
||||
}
|
||||
}
|
||||
for (const key of ["moving", "stationary", "unknown"] as const) {
|
||||
if (!(key in motion)) {
|
||||
throw new M48SFixedClassDetectorContractError(`M4.8S.integrated.motion_counts.${key}: отсутствует.`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
durationSeconds: numberValue(integrated.duration_seconds, "M4.8S.integrated.duration_seconds"),
|
||||
sourceFramesAdmitted: integerValue(integrated.source_frames_admitted, "M4.8S.integrated.source_frames_admitted"),
|
||||
deliveredWorldStates: integerValue(integrated.delivered_world_states, "M4.8S.integrated.delivered_world_states"),
|
||||
supersededFrames: integerValue(integrated.superseded_frames, "M4.8S.integrated.superseded_frames"),
|
||||
effectiveWorldStateFps: numberValue(integrated.effective_world_state_fps, "M4.8S.integrated.effective_world_state_fps"),
|
||||
worldStateCompletionAgeP95Ms: numberValue(integrated.world_state_completion_age_p95_ms, "M4.8S.integrated.world_state_completion_age_p95_ms"),
|
||||
worldStateCompletionAgeP99Ms: numberValue(integrated.world_state_completion_age_p99_ms, "M4.8S.integrated.world_state_completion_age_p99_ms"),
|
||||
worldStateCompletionAgeMaximumMs: numberValue(integrated.world_state_completion_age_maximum_ms, "M4.8S.integrated.world_state_completion_age_maximum_ms"),
|
||||
localObstacleMapOutputAgeP95Ms: numberValue(integrated.local_obstacle_map_output_age_p95_ms, "M4.8S.integrated.local_obstacle_map_output_age_p95_ms"),
|
||||
queueHighWatermarks: queues as M48SIntegratedWorldState["queueHighWatermarks"],
|
||||
queueCapacity: integerValue(integrated.queue_capacity, "M4.8S.integrated.queue_capacity"),
|
||||
gpuUtilizationMeanPercent: numberValue(integrated.gpu_utilization_mean_percent, "M4.8S.integrated.gpu_utilization_mean_percent"),
|
||||
gpuUtilizationMaximumPercent: numberValue(integrated.gpu_utilization_maximum_percent, "M4.8S.integrated.gpu_utilization_maximum_percent"),
|
||||
gpuMemoryMaximumMib: numberValue(integrated.gpu_memory_maximum_mib, "M4.8S.integrated.gpu_memory_maximum_mib"),
|
||||
gpuPowerMaximumW: numberValue(integrated.gpu_power_maximum_w, "M4.8S.integrated.gpu_power_maximum_w"),
|
||||
gpuTemperatureMaximumC: numberValue(integrated.gpu_temperature_maximum_c, "M4.8S.integrated.gpu_temperature_maximum_c"),
|
||||
uniqueComponentCount: integerValue(integrated.unique_component_count, "M4.8S.integrated.unique_component_count"),
|
||||
multiFrameComponentCount: integerValue(integrated.multi_frame_component_count, "M4.8S.integrated.multi_frame_component_count"),
|
||||
maximumComponentPublications: integerValue(integrated.maximum_component_publications, "M4.8S.integrated.maximum_component_publications"),
|
||||
duplicateComponentIdsWithinFrame: integerValue(integrated.duplicate_component_ids_within_frame, "M4.8S.integrated.duplicate_component_ids_within_frame"),
|
||||
advisoryFamilyCounts: advisory as M48SIntegratedWorldState["advisoryFamilyCounts"],
|
||||
semanticHintCounts: integerRecordValue(integrated.semantic_hint_counts, "M4.8S.integrated.semantic_hint_counts"),
|
||||
motionCounts: motion as M48SIntegratedWorldState["motionCounts"],
|
||||
additionalInferencePasses: integerValue(integrated.additional_inference_passes, "M4.8S.integrated.additional_inference_passes"),
|
||||
failures: integerValue(integrated.failures, "M4.8S.integrated.failures"),
|
||||
};
|
||||
}
|
||||
|
||||
function parseResult(value: unknown, resultId: string): M48SFixedClassDetectorResult {
|
||||
const payload = objectValue(value, "M4.8S");
|
||||
exact(
|
||||
payload.schema_version,
|
||||
"missioncore.m48s-fixed-class-detector-result-view/v1",
|
||||
"M4.8S.schema_version",
|
||||
);
|
||||
exact(payload.result_id, resultId, "M4.8S.result_id");
|
||||
const status = enumValue(payload.status, RESULT_STATUSES, "M4.8S.status");
|
||||
const integratedGate = status === "complete-reference-graph-shadow-passed-production-not-authorized";
|
||||
exact(payload.bounded_question_accepted, true, "M4.8S.bounded_question_accepted");
|
||||
exact(payload.ground_truth, false, "M4.8S.ground_truth");
|
||||
exact(payload.access, "read-only", "M4.8S.access");
|
||||
const source = objectValue(payload.source, "M4.8S.source");
|
||||
const configuration = objectValue(payload.configuration, "M4.8S.configuration");
|
||||
const metrics = objectValue(payload.metrics, "M4.8S.metrics");
|
||||
const load = objectValue(metrics.detector_load, "M4.8S.metrics.detector_load");
|
||||
const decision = objectValue(payload.decision, "M4.8S.decision");
|
||||
const cameraRaster = arrayValue(source.camera_raster, "M4.8S.source.camera_raster");
|
||||
if (cameraRaster.length !== 2) {
|
||||
throw new M48SFixedClassDetectorContractError("M4.8S.source.camera_raster: нарушен размер.");
|
||||
}
|
||||
exact(cameraRaster[0], 800, "M4.8S.source.camera_raster[0]");
|
||||
exact(cameraRaster[1], 600, "M4.8S.source.camera_raster[1]");
|
||||
const displayModes = arrayValue(
|
||||
configuration.display_modes,
|
||||
"M4.8S.configuration.display_modes",
|
||||
).map((mode, index) => enumValue(mode, MODES, `M4.8S.configuration.display_modes[${index}]`));
|
||||
if (displayModes.join(",") !== MODES.join(",")) {
|
||||
throw new M48SFixedClassDetectorContractError("M4.8S.configuration.display_modes: изменён контракт.");
|
||||
}
|
||||
exact(source.source_session_id, "RAVNOVES00", "M4.8S.source.source_session_id");
|
||||
exact(source.camera_source_id, "sensor.camera.right", "M4.8S.source.camera_source_id");
|
||||
exact(configuration.comparison_threshold, 0.5, "M4.8S.configuration.comparison_threshold");
|
||||
exact(configuration.single_inference_per_frame, true, "M4.8S.configuration.single_inference_per_frame");
|
||||
exact(configuration.geometry_owns_static_occupancy, true, "M4.8S.configuration.geometry_owns_static_occupancy");
|
||||
exact(configuration.unknown_stationary_response, "route-around", "M4.8S.configuration.unknown_stationary_response");
|
||||
exact(configuration.unknown_moving_response, "conservative-risk", "M4.8S.configuration.unknown_moving_response");
|
||||
exact(decision.selected_candidate, "rf-detr", "M4.8S.decision.selected_candidate");
|
||||
exact(decision.ready_for_reference_graph_shadow, true, "M4.8S.decision.ready_for_reference_graph_shadow");
|
||||
exact(decision.integrated_world_state_gate_evaluated, integratedGate, "M4.8S.decision.integrated_world_state_gate_evaluated");
|
||||
if (integratedGate) {
|
||||
exact(decision.integrated_world_state_gate_passed, true, "M4.8S.decision.integrated_world_state_gate_passed");
|
||||
exact(decision.detector_replacement_authorized, false, "M4.8S.decision.detector_replacement_authorized");
|
||||
}
|
||||
exact(decision.production_accepted, false, "M4.8S.decision.production_accepted");
|
||||
const frames = arrayValue(payload.frames, "M4.8S.frames").map(descriptorValue);
|
||||
const evidenceFrameCount = integerValue(source.evidence_frame_count, "M4.8S.source.evidence_frame_count");
|
||||
if (frames.length !== evidenceFrameCount || new Set(frames.map((frame) => frame.frameId)).size !== frames.length) {
|
||||
throw new M48SFixedClassDetectorContractError("M4.8S.frames: каталог изменён.");
|
||||
}
|
||||
return {
|
||||
resultId,
|
||||
createdAtUtc: textValue(payload.created_at_utc, "M4.8S.created_at_utc"),
|
||||
status,
|
||||
boundedQuestionAccepted: true,
|
||||
groundTruth: false,
|
||||
source: {
|
||||
sourceSessionId: "RAVNOVES00",
|
||||
cameraSourceId: "sensor.camera.right",
|
||||
cameraRaster: [800, 600],
|
||||
evidenceFrameCount,
|
||||
},
|
||||
configuration: {
|
||||
comparisonThreshold: 0.5,
|
||||
displayModes,
|
||||
singleInferencePerFrame: true,
|
||||
geometryOwnsStaticOccupancy: true,
|
||||
unknownStationaryResponse: "route-around",
|
||||
unknownMovingResponse: "conservative-risk",
|
||||
},
|
||||
method: methodValue(payload.method),
|
||||
metrics: {
|
||||
candidates: arrayValue(metrics.candidates, "M4.8S.metrics.candidates").map(candidateValue),
|
||||
detectorLoad: {
|
||||
durationSeconds: numberValue(load.duration_seconds, "M4.8S.load.duration_seconds"),
|
||||
sourceFramesConsumed: integerValue(load.source_frames_consumed, "M4.8S.load.source_frames_consumed"),
|
||||
sourceFrameReplacements: integerValue(load.source_frame_replacements, "M4.8S.load.source_frame_replacements"),
|
||||
effectiveConsumedFps: numberValue(load.effective_consumed_fps, "M4.8S.load.effective_consumed_fps"),
|
||||
endToEndP95Ms: numberValue(load.end_to_end_p95_ms, "M4.8S.load.end_to_end_p95_ms"),
|
||||
completionAgeP95Ms: numberValue(load.completion_age_p95_ms, "M4.8S.load.completion_age_p95_ms"),
|
||||
gpuUtilizationMeanPercent: numberValue(load.gpu_utilization_mean_percent, "M4.8S.load.gpu_utilization_mean_percent"),
|
||||
gpuUtilizationMaximumPercent: numberValue(load.gpu_utilization_maximum_percent, "M4.8S.load.gpu_utilization_maximum_percent"),
|
||||
gpuMemoryMaximumMib: numberValue(load.gpu_memory_maximum_mib, "M4.8S.load.gpu_memory_maximum_mib"),
|
||||
queueMaximumDepth: integerValue(load.queue_maximum_depth, "M4.8S.load.queue_maximum_depth"),
|
||||
queueCapacity: integerValue(load.queue_capacity, "M4.8S.load.queue_capacity"),
|
||||
failures: integerValue(load.failures, "M4.8S.load.failures"),
|
||||
},
|
||||
integratedWorldState: integratedGate
|
||||
? integratedWorldStateValue(metrics.integrated_world_state)
|
||||
: null,
|
||||
},
|
||||
decision: {
|
||||
selectedCandidate: "rf-detr",
|
||||
readyForReferenceGraphShadow: true,
|
||||
integratedWorldStateGateEvaluated: integratedGate,
|
||||
integratedWorldStateGatePassed: integratedGate,
|
||||
detectorReplacementAuthorized: false,
|
||||
productionAccepted: false,
|
||||
},
|
||||
limitations: arrayValue(payload.limitations, "M4.8S.limitations").map((item, index) => textValue(item, `M4.8S.limitations[${index}]`)),
|
||||
authority: authorityValue(payload.authority, "M4.8S.authority"),
|
||||
frames,
|
||||
};
|
||||
}
|
||||
|
||||
function detectionValue(value: unknown, label: string): M48SDetection {
|
||||
const detection = objectValue(value, label);
|
||||
const bbox = arrayValue(detection.bbox_xyxy, `${label}.bbox_xyxy`).map((item, index) => numberValue(item, `${label}.bbox_xyxy[${index}]`));
|
||||
if (
|
||||
bbox.length !== 4
|
||||
|| bbox[0]! < 0
|
||||
|| bbox[1]! < 0
|
||||
|| bbox[2]! > 800
|
||||
|| bbox[3]! > 600
|
||||
|| bbox[0]! >= bbox[2]!
|
||||
|| bbox[1]! >= bbox[3]!
|
||||
) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}.bbox_xyxy: рамка недопустима.`);
|
||||
}
|
||||
const score = numberValue(detection.score, `${label}.score`);
|
||||
if (score < 0.5 || score > 1) {
|
||||
throw new M48SFixedClassDetectorContractError(`${label}.score: нарушен порог.`);
|
||||
}
|
||||
return {
|
||||
label: textValue(detection.label, `${label}.label`),
|
||||
score,
|
||||
bboxXyxy: bbox as unknown as readonly [number, number, number, number],
|
||||
};
|
||||
}
|
||||
|
||||
function parseFrame(value: unknown, resultId: string, frameId: string): M48SDetectorFrame {
|
||||
const payload = objectValue(value, "M4.8S frame");
|
||||
exact(payload.schema_version, "missioncore.m48s-fixed-class-detector-frame/v1", "M4.8S frame.schema_version");
|
||||
exact(payload.result_id, resultId, "M4.8S frame.result_id");
|
||||
exact(payload.frame_id, frameId, "M4.8S frame.frame_id");
|
||||
exact(payload.comparison_threshold, 0.5, "M4.8S frame.comparison_threshold");
|
||||
exact(payload.ground_truth_available, false, "M4.8S frame.ground_truth_available");
|
||||
exact(payload.access, "read-only", "M4.8S frame.access");
|
||||
const camera = objectValue(payload.camera, "M4.8S frame.camera");
|
||||
exact(camera.media_type, "image/jpeg", "M4.8S frame.camera.media_type");
|
||||
exact(camera.width, 800, "M4.8S frame.camera.width");
|
||||
exact(camera.height, 600, "M4.8S frame.camera.height");
|
||||
exact(camera.exact_source_frame, true, "M4.8S frame.camera.exact_source_frame");
|
||||
const detections = objectValue(payload.detections, "M4.8S frame.detections");
|
||||
const parseModel = (model: M48SDetectorModel): readonly M48SDetection[] => arrayValue(
|
||||
detections[model],
|
||||
`M4.8S frame.detections.${model}`,
|
||||
).map((item, index) => detectionValue(item, `M4.8S frame.detections.${model}[${index}]`));
|
||||
return {
|
||||
resultId,
|
||||
frameId,
|
||||
sourceSequence: integerValue(payload.source_sequence, "M4.8S frame.source_sequence"),
|
||||
cameraUrl: `/api/v1/laboratory/m48s/fixed-class-detector/${encodeURIComponent(resultId)}/frames/${encodeURIComponent(frameId)}/camera`,
|
||||
imageWidth: 800,
|
||||
imageHeight: 600,
|
||||
comparisonThreshold: 0.5,
|
||||
detections: {
|
||||
yolox: parseModel("yolox"),
|
||||
dfine: parseModel("dfine"),
|
||||
"rf-detr": parseModel("rf-detr"),
|
||||
},
|
||||
groundTruthAvailable: false,
|
||||
authority: authorityValue(payload.authority, "M4.8S frame.authority"),
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchM48SFixedClassDetectorResult(
|
||||
resultId: string,
|
||||
{ fetcher = fetch, signal }: { fetcher?: LaboratoryFetch; signal?: AbortSignal } = {},
|
||||
): Promise<M48SFixedClassDetectorResult> {
|
||||
if (!RESULT_ID.test(resultId)) {
|
||||
throw new M48SFixedClassDetectorContractError("M4.8S result identity недопустима.");
|
||||
}
|
||||
const response = await fetcher(
|
||||
`/api/v1/laboratory/m48s/fixed-class-detector/${encodeURIComponent(resultId)}`,
|
||||
{ method: "GET", headers: { Accept: "application/json" }, signal },
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new M48SFixedClassDetectorContractError(`M4.8S недоступен: HTTP ${response.status}.`);
|
||||
}
|
||||
return parseResult(await response.json(), resultId);
|
||||
}
|
||||
|
||||
export async function fetchM48SFixedClassDetectorFrame(
|
||||
resultId: string,
|
||||
frameId: string,
|
||||
{ fetcher = fetch, signal }: { fetcher?: LaboratoryFetch; signal?: AbortSignal } = {},
|
||||
): Promise<M48SDetectorFrame> {
|
||||
if (!RESULT_ID.test(resultId) || !FRAME_ID.test(frameId)) {
|
||||
throw new M48SFixedClassDetectorContractError("M4.8S frame identity недопустима.");
|
||||
}
|
||||
const response = await fetcher(
|
||||
`/api/v1/laboratory/m48s/fixed-class-detector/${encodeURIComponent(resultId)}/frames/${encodeURIComponent(frameId)}`,
|
||||
{ method: "GET", headers: { Accept: "application/json" }, signal },
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new M48SFixedClassDetectorContractError(`M4.8S frame недоступен: HTTP ${response.status}.`);
|
||||
}
|
||||
return parseFrame(await response.json(), resultId, frameId);
|
||||
}
|
||||
@@ -133,6 +133,8 @@ export interface M4ThreatTimelineFrame {
|
||||
sessionSeconds: number;
|
||||
sourceAvailable: boolean;
|
||||
spatialAvailable: boolean;
|
||||
worldStateAvailable: boolean;
|
||||
terminalOutcome: "delivered" | "superseded";
|
||||
bodyFrame: {
|
||||
originMapXyzM: M4Point3;
|
||||
basisMapFromBody: M4Matrix3;
|
||||
@@ -141,6 +143,11 @@ export interface M4ThreatTimelineFrame {
|
||||
pointCloudSourceCount: number;
|
||||
pointCloudSampleCount: number;
|
||||
pointCloudLayer: "current-increment";
|
||||
cameraProjectedPointsXyd: readonly (readonly [number, number, number])[];
|
||||
cameraProjectedSourceCount: number;
|
||||
cameraProjectedPointCount: number;
|
||||
cameraProjectedSampleCount: number;
|
||||
cameraProjection: "factory-kb4-exact" | null;
|
||||
rollingMapComponentCount: number;
|
||||
metricObstacles: readonly M4ThreatMetricVisual[];
|
||||
cameraProposals: readonly M4ThreatCameraProposal[];
|
||||
@@ -163,6 +170,11 @@ export interface M4ThreatTimeline {
|
||||
pointSampleLimit: number;
|
||||
maximumSourcePointsPerFrame: number;
|
||||
pointDelivery: "exact-current-increment";
|
||||
cameraPointDelivery: "factory-kb4-projected-current-increment" | null;
|
||||
cameraPointSampleLimit: number;
|
||||
worldStateDelivery: "source-paced-latest-wins" | null;
|
||||
worldStateFrameCount: number;
|
||||
supersededFrameCount: number;
|
||||
sourceRepresentationId: "registered-map-increment-v1";
|
||||
localSurfaceVisualization: {
|
||||
derivation: "bounded-registered-increment-accumulation";
|
||||
@@ -186,6 +198,7 @@ export interface M4ThreatTimelineChunk {
|
||||
}
|
||||
|
||||
type LaboratoryFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
||||
export const M4_THREAT_TIMELINE_ENDPOINT_ROOT = "/api/v1/laboratory/m4-threat/results";
|
||||
class M4ThreatContractError extends Error {}
|
||||
const object = (value: unknown, label: string): Record<string, unknown> => {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
@@ -553,10 +566,18 @@ export async function fetchM4ThreatVisual(
|
||||
|
||||
export async function fetchM4ThreatTimeline(
|
||||
result: string,
|
||||
{ fetcher = fetch, signal }: { fetcher?: LaboratoryFetch; signal?: AbortSignal } = {},
|
||||
{
|
||||
fetcher = fetch,
|
||||
signal,
|
||||
endpointRoot = M4_THREAT_TIMELINE_ENDPOINT_ROOT,
|
||||
}: {
|
||||
fetcher?: LaboratoryFetch;
|
||||
signal?: AbortSignal;
|
||||
endpointRoot?: string;
|
||||
} = {},
|
||||
): Promise<M4ThreatTimeline> {
|
||||
const response = await fetcher(
|
||||
`/api/v1/laboratory/m4-threat/results/${result}/timeline`,
|
||||
`${endpointRoot}/${result}/timeline`,
|
||||
{ headers: { Accept: "application/json" }, signal },
|
||||
);
|
||||
if (!response.ok) throw new M4ThreatContractError(`M4.6 timeline: HTTP ${response.status}.`);
|
||||
@@ -626,6 +647,29 @@ export async function fetchM4ThreatTimeline(
|
||||
"exact-current-increment",
|
||||
"M4.6 point delivery",
|
||||
),
|
||||
cameraPointDelivery: payload.camera_point_delivery === undefined
|
||||
? null
|
||||
: exact(
|
||||
payload.camera_point_delivery,
|
||||
"factory-kb4-projected-current-increment",
|
||||
"M4.6 camera point delivery",
|
||||
),
|
||||
cameraPointSampleLimit: payload.camera_point_sample_limit === undefined
|
||||
? 0
|
||||
: integer(payload.camera_point_sample_limit, "M4.6 camera point limit"),
|
||||
worldStateDelivery: payload.world_state_delivery === undefined
|
||||
? null
|
||||
: exact(
|
||||
payload.world_state_delivery,
|
||||
"source-paced-latest-wins",
|
||||
"M4.6 world-state delivery",
|
||||
),
|
||||
worldStateFrameCount: payload.world_state_frame_count === undefined
|
||||
? frameCount
|
||||
: integer(payload.world_state_frame_count, "M4.6 world-state frames"),
|
||||
supersededFrameCount: payload.superseded_frame_count === undefined
|
||||
? 0
|
||||
: integer(payload.superseded_frame_count, "M4.6 superseded frames"),
|
||||
sourceRepresentationId: "registered-map-increment-v1",
|
||||
localSurfaceVisualization: {
|
||||
derivation: exact(
|
||||
@@ -668,14 +712,22 @@ export async function fetchM4ThreatTimelineChunk(
|
||||
result: string,
|
||||
startSequence: number,
|
||||
frameCount: number,
|
||||
{ fetcher = fetch, signal }: { fetcher?: LaboratoryFetch; signal?: AbortSignal } = {},
|
||||
{
|
||||
fetcher = fetch,
|
||||
signal,
|
||||
endpointRoot = M4_THREAT_TIMELINE_ENDPOINT_ROOT,
|
||||
}: {
|
||||
fetcher?: LaboratoryFetch;
|
||||
signal?: AbortSignal;
|
||||
endpointRoot?: string;
|
||||
} = {},
|
||||
): Promise<M4ThreatTimelineChunk> {
|
||||
const params = new URLSearchParams({
|
||||
start: String(startSequence),
|
||||
count: String(frameCount),
|
||||
});
|
||||
const response = await fetcher(
|
||||
`/api/v1/laboratory/m4-threat/results/${result}/timeline/chunk?${params}`,
|
||||
`${endpointRoot}/${result}/timeline/chunk?${params}`,
|
||||
{ headers: { Accept: "application/json" }, signal },
|
||||
);
|
||||
if (!response.ok) throw new M4ThreatContractError(`M4.6 timeline chunk: HTTP ${response.status}.`);
|
||||
@@ -692,7 +744,7 @@ export async function fetchM4ThreatTimelineChunk(
|
||||
throw new M4ThreatContractError("M4.6 timeline chunk start: нарушен контракт.");
|
||||
}
|
||||
const frames = array(payload.frames, "M4.6 timeline frames").map((raw, offset) =>
|
||||
parseTimelineFrame(raw, result, parsedStart + offset));
|
||||
parseTimelineFrame(raw, result, parsedStart + offset, endpointRoot));
|
||||
const parsedCount = integer(payload.frame_count, "M4.6 timeline chunk count");
|
||||
if (parsedCount !== frames.length || parsedCount > frameCount) {
|
||||
throw new M4ThreatContractError("M4.6 timeline chunk count: нарушен контракт.");
|
||||
@@ -712,6 +764,7 @@ function parseTimelineFrame(
|
||||
value: unknown,
|
||||
result: string,
|
||||
expectedSequence: number,
|
||||
endpointRoot: string,
|
||||
): M4ThreatTimelineFrame {
|
||||
const item = object(value, "M4.6 timeline frame");
|
||||
exact(
|
||||
@@ -742,7 +795,7 @@ function parseTimelineFrame(
|
||||
throw new M4ThreatContractError("M4.6 timeline body basis: нарушен размер.");
|
||||
}
|
||||
const cameraUrl = text(item.camera_url, "M4.6 timeline camera URL");
|
||||
if (!cameraUrl.includes(`/results/${result}/timeline/frames/${sequence}/camera`)) {
|
||||
if (!cameraUrl.includes(`${endpointRoot}/${result}/timeline/frames/${sequence}/camera`)) {
|
||||
throw new M4ThreatContractError("M4.6 timeline camera URL: нарушена идентичность.");
|
||||
}
|
||||
return {
|
||||
@@ -752,6 +805,16 @@ function parseTimelineFrame(
|
||||
sessionSeconds: number(item.session_seconds, "M4.6 timeline time"),
|
||||
sourceAvailable: typeof item.source_available === "boolean" && item.source_available,
|
||||
spatialAvailable,
|
||||
worldStateAvailable: item.world_state_available === undefined
|
||||
? true
|
||||
: typeof item.world_state_available === "boolean" && item.world_state_available,
|
||||
terminalOutcome: item.terminal_outcome === undefined
|
||||
? "delivered"
|
||||
: exact(
|
||||
item.terminal_outcome,
|
||||
item.world_state_available === false ? "superseded" : "delivered",
|
||||
"M4.6 terminal outcome",
|
||||
),
|
||||
bodyFrame: bodyFrame === null || basis === null
|
||||
? null
|
||||
: {
|
||||
@@ -771,6 +834,23 @@ function parseTimelineFrame(
|
||||
"current-increment",
|
||||
"M4.6 timeline point layer",
|
||||
),
|
||||
cameraProjectedPointsXyd: item.camera_projected_points_xyd === undefined
|
||||
? []
|
||||
: array(item.camera_projected_points_xyd, "M4.6 camera points").map(
|
||||
(point) => vector(point, 3, "M4.6 camera point") as [number, number, number],
|
||||
),
|
||||
cameraProjectedSourceCount: item.camera_projected_source_count === undefined
|
||||
? 0
|
||||
: integer(item.camera_projected_source_count, "M4.6 camera point source count"),
|
||||
cameraProjectedPointCount: item.camera_projected_point_count === undefined
|
||||
? 0
|
||||
: integer(item.camera_projected_point_count, "M4.6 projected point count"),
|
||||
cameraProjectedSampleCount: item.camera_projected_sample_count === undefined
|
||||
? 0
|
||||
: integer(item.camera_projected_sample_count, "M4.6 projected point sample count"),
|
||||
cameraProjection: item.camera_projection === undefined
|
||||
? null
|
||||
: exact(item.camera_projection, "factory-kb4-exact", "M4.6 camera projection"),
|
||||
rollingMapComponentCount: integer(
|
||||
item.rolling_map_component_count,
|
||||
"M4.6 rolling components",
|
||||
|
||||
@@ -44,6 +44,7 @@ import { M4ReplayThreatResultView } from "./M4ReplayThreatResult";
|
||||
import { M47ReferenceGraphResultView } from "./M47ReferenceGraphResult";
|
||||
import { M48ObjectCentricQualityResultView } from "./M48ObjectCentricQualityResult";
|
||||
import { M48SmallStaticPassageRegressionResultView } from "./M48SmallStaticPassageRegressionResult";
|
||||
import { M48SFixedClassDetectorResultView } from "./M48SFixedClassDetectorResult";
|
||||
|
||||
export { isAdvancedLaboratoryWorkId };
|
||||
export type { AdvancedLaboratoryWorkId };
|
||||
@@ -92,6 +93,9 @@ export function AdvancedLaboratoryResult({
|
||||
if (workId === "m48-small-static-passage-regression" && results.m48SmallStatic) {
|
||||
return <M48SmallStaticPassageRegressionResultView rigLabel={rigLabel} result={results.m48SmallStatic} />;
|
||||
}
|
||||
if (workId === "m48s-fixed-class-detector" && results.m48s) {
|
||||
return <M48SFixedClassDetectorResultView rigLabel={rigLabel} result={results.m48s} />;
|
||||
}
|
||||
if (workId === "m47-reference-graph-shadow" && results.m47Graph) {
|
||||
return <M47ReferenceGraphResultView rigLabel={rigLabel} result={results.m47Graph} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import {
|
||||
LaboratoryEvidence,
|
||||
LaboratoryResultSummary,
|
||||
LaboratorySummary,
|
||||
LaboratoryWorkTemplate,
|
||||
} from "../../components/laboratory/LaboratoryPresentation";
|
||||
import type { M48SFixedClassDetectorResult } from "../../core/laboratory/m48sFixedClassDetector";
|
||||
import { M4ReplayThreatVisual } from "./M4ReplayThreatVisual";
|
||||
|
||||
function decimal(value: number, digits = 1): string {
|
||||
return value.toLocaleString("ru-RU", { maximumFractionDigits: digits });
|
||||
}
|
||||
|
||||
export function M48SFixedClassDetectorResultView({
|
||||
rigLabel,
|
||||
result,
|
||||
}: {
|
||||
rigLabel: string;
|
||||
result: M48SFixedClassDetectorResult;
|
||||
}) {
|
||||
const selected = result.metrics.candidates.find((candidate) => candidate.selected);
|
||||
const load = result.metrics.detectorLoad;
|
||||
const integrated = result.metrics.integratedWorldState;
|
||||
const status = integrated
|
||||
? "Полный RF-DETR reference graph выдержал realtime shadow"
|
||||
: "RF-DETR-L выдержал detector-only realtime shadow";
|
||||
return (
|
||||
<LaboratoryWorkTemplate
|
||||
summary={(
|
||||
<LaboratorySummary
|
||||
title="M4.8S · fixed-class semantics риск-объектов"
|
||||
description="Сравнение трёх готовых COCO-детекторов на точных кадрах RAVNOVES00, 30-минутная квалификация RF-DETR-L и полный source-paced прогон RF-DETR → geometry → temporal → motion → rolling map → threat на Worker 006. Статические препятствия остаются в геометрическом контуре; классы используются только там, где меняется ожидаемое поведение."
|
||||
status={status}
|
||||
statusTone="success"
|
||||
facts={[
|
||||
{ label: "Источник", value: `${rigLabel} RIGHT · raw KB4 · ${result.source.evidenceFrameCount} diagnostic frames` },
|
||||
{ label: "Сравнение", value: "YOLOX-S · D-FINE-S · RF-DETR-L · единый threshold 0.50" },
|
||||
{ label: "Worker", value: "Worker 006 · RTX 4090 · TensorRT 11 + isolated Triton" },
|
||||
{ label: "Authority", value: "SHADOW ONLY · commands OFF · actuation OFF · production NO" },
|
||||
]}
|
||||
brief={{
|
||||
question: "Можно ли заменить слабую class-семантику YOLOX готовой моделью, не потеряв realtime на предельном Worker с RTX 4090?",
|
||||
approach: `YOLOX-S, D-FINE-S и RF-DETR-L сравнили на одинаковых ${result.source.evidenceFrameCount} raw-KB4 кадрах с порогом 0.50. RF-DETR-L отдельно квалифицировали ${decimal(load.durationSeconds / 60, 0)} минут, затем встроили в полный reference graph без дополнительного inference-прохода.`,
|
||||
principalResult: integrated
|
||||
? `Полный граф доставил ${integrated.deliveredWorldStates.toLocaleString("ru-RU")} world states при ${decimal(integrated.effectiveWorldStateFps, 3)} FPS и p95 ${decimal(integrated.worldStateCompletionAgeP95Ms, 3)} ms; ${integrated.supersededFrames} входных кадров штатно вытеснены latest-wins очередью.`
|
||||
: `RF-DETR-L выбран из трёх кандидатов и обработал ${load.sourceFramesConsumed.toLocaleString("ru-RU")} кадров detector-only без замен и ошибок.`,
|
||||
limitation: "Прогон доказывает runtime envelope, а не истинность классов, качество track identity, корректность risk policy или безопасность движения. Production authority и команды отключены.",
|
||||
}}
|
||||
method={{
|
||||
completeness: result.method.completeness,
|
||||
executionClass: result.method.executionClass,
|
||||
pipelineId: result.method.pipelineId,
|
||||
components: result.method.components.map((component) => ({
|
||||
...component,
|
||||
identitySha256: component.identitySha256,
|
||||
})),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
evidence={(
|
||||
<LaboratoryEvidence
|
||||
eyebrow="M4.8S VISUAL EVIDENCE · FULL REFERENCE GRAPH REPLAY"
|
||||
title="Полное видео: RF-DETR классы, LiDAR, 3D/PLAN и world-state на общем таймлайне"
|
||||
kind="diagnostic-model"
|
||||
resizable
|
||||
>
|
||||
<M4ReplayThreatVisual
|
||||
resultId={result.resultId}
|
||||
timelineEndpointRoot="/api/v1/laboratory/m48s/fixed-class-detector"
|
||||
evidenceLabel="M4.8S RF-DETR GRAPH"
|
||||
/>
|
||||
</LaboratoryEvidence>
|
||||
)}
|
||||
result={(
|
||||
<LaboratoryResultSummary
|
||||
title={integrated
|
||||
? "Что дал прогон: полный world-state graph проходит realtime envelope"
|
||||
: "Что дал прогон: RF-DETR-L проходит detector-only realtime envelope"}
|
||||
status={status}
|
||||
statusTone="success"
|
||||
metrics={integrated ? [
|
||||
{ label: "Complete graph", value: `${decimal(integrated.effectiveWorldStateFps, 3)} FPS`, hint: "target ≥ 9.5 FPS · source-paced" },
|
||||
{ label: "World-state age p95", value: `${decimal(integrated.worldStateCompletionAgeP95Ms, 3)} ms`, hint: `p99 ${decimal(integrated.worldStateCompletionAgeP99Ms, 3)} ms · target ≤ 175 ms` },
|
||||
{ label: "Delivered / superseded", value: `${integrated.deliveredWorldStates.toLocaleString("ru-RU")} / ${integrated.supersededFrames}`, hint: `${integrated.failures} failures · queues ${Math.max(...Object.values(integrated.queueHighWatermarks))}/${integrated.queueCapacity}` },
|
||||
{ label: "GPU / VRAM peak", value: `${decimal(integrated.gpuUtilizationMaximumPercent, 0)}% / ${decimal(integrated.gpuMemoryMaximumMib / 1024)} GiB`, hint: `GPU mean ${decimal(integrated.gpuUtilizationMeanPercent)}% · ${decimal(integrated.gpuPowerMaximumW)} W` },
|
||||
] : [
|
||||
{ label: "Detector capacity", value: `${decimal(selected?.capacityFps ?? 0)} FPS`, hint: "RF-DETR-L TensorRT/Triton" },
|
||||
{ label: "Completion age p95", value: `${decimal(load.completionAgeP95Ms)} ms`, hint: "detector-only · target ≤ 175 ms" },
|
||||
{ label: "Consumed / replaced", value: `${load.sourceFramesConsumed.toLocaleString("ru-RU")} / ${load.sourceFrameReplacements}`, hint: `${decimal(load.effectiveConsumedFps, 3)} source FPS · ${load.failures} failures` },
|
||||
{ label: "GPU / VRAM peak", value: `${decimal(load.gpuUtilizationMaximumPercent, 0)}% / ${decimal(load.gpuMemoryMaximumMib / 1024)} GiB`, hint: `GPU mean ${decimal(load.gpuUtilizationMeanPercent)}% · queue ${load.queueMaximumDepth}/${load.queueCapacity}` },
|
||||
]}
|
||||
conclusion={{
|
||||
proved: integrated
|
||||
? `На Worker 006 полный граф обработал ${integrated.sourceFramesAdmitted.toLocaleString("ru-RU")} входных кадров, доставил ${integrated.deliveredWorldStates.toLocaleString("ru-RU")} состояний без ошибок, удержал все очереди в пределах ${integrated.queueCapacity} и p95 ${decimal(integrated.worldStateCompletionAgeP95Ms, 3)} ms. Advisory сформировал публикации по семействам: geometry-only (${integrated.advisoryFamilyCounts["generic-obstacle"].toLocaleString("ru-RU")}), люди (${integrated.advisoryFamilyCounts.person.toLocaleString("ru-RU")}), животные (${integrated.advisoryFamilyCounts.animal.toLocaleString("ru-RU")}) и транспорт (${integrated.advisoryFamilyCounts.vehicle.toLocaleString("ru-RU")}); это не количество уникальных физических объектов и не потребовало второго inference.`
|
||||
: `RF-DETR-L ${decimal(load.durationSeconds / 60, 0)} минут устойчиво потреблял source-paced поток около 10 FPS: ${load.sourceFramesConsumed.toLocaleString("ru-RU")} кадров, 0 замен, 0 ошибок, completion-age p95 ${decimal(load.completionAgeP95Ms, 3)} ms.`,
|
||||
notProved: "Не доказаны unbiased precision/recall классов, независимое качество track identity и risk policy, поведение planner или collision safety. Кадровые рамки не заменяют геометрическую occupancy-карту.",
|
||||
decision: "Сохранить RF-DETR-L как risk-semantic shadow provider полного reference graph. Не классифицировать миллионы статических форм: неизвестное неподвижное препятствие остаётся geometry-owned и объезжается; классы сохраняются для людей, животных и транспорта. Production switch не разрешён.",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Icon, IconButton, StatusBadge } from "@nodedc/ui-react";
|
||||
|
||||
import { LaboratoryEvidenceViewer } from "../../components/laboratory/LaboratoryEvidenceViewer";
|
||||
import {
|
||||
RecordedEvidenceBoxOverlay,
|
||||
type RecordedEvidenceBox,
|
||||
type RecordedEvidenceBoxTone,
|
||||
} from "../../components/laboratory/RecordedEvidenceBoxOverlay";
|
||||
import {
|
||||
fetchM48SFixedClassDetectorFrame,
|
||||
type M48SDetectorFrame,
|
||||
type M48SDetectorMode,
|
||||
type M48SFixedClassDetectorResult,
|
||||
} from "../../core/laboratory/m48sFixedClassDetector";
|
||||
|
||||
const MODES = [
|
||||
{ value: "source", label: "SOURCE" },
|
||||
{ value: "yolox", label: "YOLOX" },
|
||||
{ value: "dfine", label: "D-FINE" },
|
||||
{ value: "rf-detr", label: "RF-DETR" },
|
||||
] as const;
|
||||
|
||||
const ANIMAL_LABELS = new Set([
|
||||
"bird",
|
||||
"cat",
|
||||
"dog",
|
||||
"horse",
|
||||
"sheep",
|
||||
"cow",
|
||||
"elephant",
|
||||
"bear",
|
||||
"zebra",
|
||||
"giraffe",
|
||||
]);
|
||||
const VULNERABLE_ROAD_USERS = new Set(["person", "bicycle", "motorcycle", "skateboard"]);
|
||||
|
||||
function message(error: unknown): string {
|
||||
return error instanceof Error && error.message.trim()
|
||||
? error.message
|
||||
: "M4.8S visual evidence недоступно.";
|
||||
}
|
||||
|
||||
function toneForLabel(label: string): RecordedEvidenceBoxTone {
|
||||
if (ANIMAL_LABELS.has(label)) return "danger";
|
||||
if (VULNERABLE_ROAD_USERS.has(label)) return "warning";
|
||||
return "accent";
|
||||
}
|
||||
|
||||
function DetectorScene({ frame, mode }: { frame: M48SDetectorFrame; mode: M48SDetectorMode }) {
|
||||
const boxes = useMemo<readonly RecordedEvidenceBox[]>(() => {
|
||||
if (mode === "source") return [];
|
||||
return frame.detections[mode].map((detection) => ({
|
||||
boxXyxy: detection.bboxXyxy,
|
||||
label: `${detection.label} · ${detection.score.toFixed(2)}`,
|
||||
tone: toneForLabel(detection.label),
|
||||
}));
|
||||
}, [frame, mode]);
|
||||
|
||||
return (
|
||||
<div className="m48-atlas-visual__scene">
|
||||
<img src={frame.cameraUrl} alt="" draggable={false} />
|
||||
<RecordedEvidenceBoxOverlay
|
||||
imageWidth={frame.imageWidth}
|
||||
imageHeight={frame.imageHeight}
|
||||
boxes={boxes}
|
||||
ariaLabel={`M4.8S ${mode} fixed-class detections`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function M48SFixedClassDetectorVisual({
|
||||
result,
|
||||
}: {
|
||||
result: M48SFixedClassDetectorResult;
|
||||
}) {
|
||||
const preferredIndex = Math.max(
|
||||
0,
|
||||
result.frames.findIndex((frame) => frame.frameId === "000253"),
|
||||
);
|
||||
const [index, setIndex] = useState(preferredIndex);
|
||||
const [frame, setFrame] = useState<M48SDetectorFrame | null>(null);
|
||||
const [mode, setMode] = useState<M48SDetectorMode>("rf-detr");
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const selected = result.frames[index] ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) {
|
||||
setFrame(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void fetchM48SFixedClassDetectorFrame(result.resultId, selected.frameId, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((next) => !controller.signal.aborted && setFrame(next))
|
||||
.catch((caught: unknown) => !controller.signal.aborted && setError(message(caught)))
|
||||
.finally(() => !controller.signal.aborted && setLoading(false));
|
||||
return () => controller.abort();
|
||||
}, [result.resultId, selected]);
|
||||
|
||||
const count = frame && mode !== "source" ? frame.detections[mode].length : 0;
|
||||
return (
|
||||
<LaboratoryEvidenceViewer
|
||||
label="M4.8S fixed-class detector comparison"
|
||||
className="m48-atlas-visual"
|
||||
mode={mode}
|
||||
modes={MODES}
|
||||
expanded={expanded}
|
||||
onModeChange={setMode}
|
||||
onExpandedChange={setExpanded}
|
||||
actions={(
|
||||
<>
|
||||
<IconButton
|
||||
label="Предыдущий кадр M4.8S"
|
||||
disabled={!result.frames.length}
|
||||
onClick={() => setIndex((current) => (
|
||||
current - 1 + result.frames.length
|
||||
) % result.frames.length)}
|
||||
>
|
||||
<Icon name="chevron-left" size={16} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Следующий кадр M4.8S"
|
||||
disabled={!result.frames.length}
|
||||
onClick={() => setIndex((current) => (current + 1) % result.frames.length)}
|
||||
>
|
||||
<Icon name="chevron-right" size={16} />
|
||||
</IconButton>
|
||||
</>
|
||||
)}
|
||||
overlay={selected ? (
|
||||
<div className="m48-atlas-visual__case">
|
||||
<StatusBadge tone="warning">SHADOW ONLY</StatusBadge>
|
||||
<strong>RAVNOVES00 · frame {selected.frameId} · {mode.toUpperCase()}</strong>
|
||||
<small>
|
||||
{count} risk detections · threshold 0.50 · independent ground truth отсутствует
|
||||
</small>
|
||||
</div>
|
||||
) : null}
|
||||
>
|
||||
{loading ? (
|
||||
<div className="m48-atlas-visual__state" role="status">
|
||||
<span className="busy-indicator" aria-hidden="true" />
|
||||
Загружаем точный camera-кадр
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="m48-atlas-visual__state" role="alert">
|
||||
<Icon name="alert" size={18} />
|
||||
{error}
|
||||
</div>
|
||||
) : frame ? (
|
||||
<DetectorScene frame={frame} mode={mode} />
|
||||
) : (
|
||||
<div className="m48-atlas-visual__state" role="alert">
|
||||
<Icon name="alert" size={18} />
|
||||
Каталог кадров M4.8S пуст.
|
||||
</div>
|
||||
)}
|
||||
</LaboratoryEvidenceViewer>
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
} from "../../components/laboratory/LaboratoryMetricEvidenceScene";
|
||||
import { LaboratoryEvidenceViewer } from "../../components/laboratory/LaboratoryEvidenceViewer";
|
||||
import { RecordedEvidenceImageScene } from "../../components/laboratory/RecordedEvidenceImageScene";
|
||||
import type { RecordedEvidencePointCloudOverlayData } from "../../components/laboratory/RecordedEvidencePointCloudOverlay";
|
||||
import type {
|
||||
RecordedEvidenceSemanticClass,
|
||||
RecordedEvidenceSemanticOverlay,
|
||||
@@ -58,10 +59,14 @@ function toneForProposal(proposal: M4ThreatCameraProposal): RecordedEvidenceBox[
|
||||
}
|
||||
|
||||
function proposalLabel(proposal: M4ThreatCameraProposal): string {
|
||||
const decision = proposal.threatDecision ?? "unknown";
|
||||
if (proposal.rangeM === null) return decision;
|
||||
const decision = proposal.threatDecision
|
||||
?? (proposal.occupiedSupport ? "geometry-supported" : "camera-only");
|
||||
const semantic = proposal.semanticHint ?? "object";
|
||||
if (proposal.rangeM === null) {
|
||||
return `${semantic} · ${proposal.objectness.toFixed(2)} · ${decision}`;
|
||||
}
|
||||
const range = `${proposal.rangeM.toLocaleString("ru-RU", { maximumFractionDigits: 2 })} м`;
|
||||
return `${range} · ${decision}`;
|
||||
return `${semantic} · ${proposal.objectness.toFixed(2)} · ${range} · ${decision}`;
|
||||
}
|
||||
|
||||
function boxes(proposals: readonly M4ThreatCameraProposal[]): readonly RecordedEvidenceBox[] {
|
||||
@@ -104,10 +109,14 @@ export function M4ReplayThreatVisual({
|
||||
resultId,
|
||||
semantic,
|
||||
reviewAnchors = EMPTY_REVIEW_ANCHORS,
|
||||
timelineEndpointRoot,
|
||||
evidenceLabel = "M4.6",
|
||||
}: {
|
||||
resultId: string;
|
||||
semantic?: M4ReplayThreatSemanticLayer;
|
||||
reviewAnchors?: readonly M4ReplayThreatReviewAnchor[];
|
||||
timelineEndpointRoot?: string;
|
||||
evidenceLabel?: string;
|
||||
}) {
|
||||
const [mediaMode, setMediaMode] = useState<M4ThreatMediaMode | null>("video");
|
||||
const [spatialMode, setSpatialMode] = useState<LaboratoryMetricSceneMode | null>(null);
|
||||
@@ -116,6 +125,7 @@ export function M4ReplayThreatVisual({
|
||||
const [showRollingMap, setShowRollingMap] = useState(true);
|
||||
const [showMediaSemantic, setShowMediaSemantic] = useState(true);
|
||||
const [showSpatialSemantic, setShowSpatialSemantic] = useState(true);
|
||||
const [showMediaPoints, setShowMediaPoints] = useState(false);
|
||||
const [splitPrimarySize, setSplitPrimarySize] = useState(50);
|
||||
const [splitOrientation, setSplitOrientation] = useState<SplitPaneOrientation>(() => (
|
||||
typeof window !== "undefined" && window.matchMedia("(max-width: 900px)").matches
|
||||
@@ -125,7 +135,7 @@ export function M4ReplayThreatVisual({
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [selectedReviewAnchorIndex, setSelectedReviewAnchorIndex] = useState(0);
|
||||
const metricSceneRef = useRef<LaboratoryMetricEvidenceSceneHandle | null>(null);
|
||||
const metadata = useM4ThreatTimelineMetadata(resultId);
|
||||
const metadata = useM4ThreatTimelineMetadata(resultId, timelineEndpointRoot);
|
||||
const playbackRange = useMemo(() => metadata.timeline ? ({
|
||||
startSeconds: metadata.timeline.timelineStartSeconds,
|
||||
endSeconds: metadata.timeline.timelineEndSeconds,
|
||||
@@ -139,6 +149,7 @@ export function M4ReplayThreatVisual({
|
||||
resultId,
|
||||
timeline: metadata.timeline,
|
||||
currentSeconds: playbackController.playback.currentSeconds,
|
||||
endpointRoot: timelineEndpointRoot,
|
||||
});
|
||||
const [videoSource, setVideoSource] = useState<ObservationSourceDescriptor | null>(null);
|
||||
const [videoLoading, setVideoLoading] = useState(false);
|
||||
@@ -362,6 +373,16 @@ export function M4ReplayThreatVisual({
|
||||
ariaLabel: `E47 semantic mask frame ${frame.sequence + 1}`,
|
||||
}
|
||||
: undefined;
|
||||
const pointCloudOverlay: RecordedEvidencePointCloudOverlayData | undefined =
|
||||
showMediaPoints && frame?.cameraProjection === "factory-kb4-exact"
|
||||
? {
|
||||
pointsXyd: frame.cameraProjectedPointsXyd,
|
||||
sourcePointCount: frame.cameraProjectedSourceCount,
|
||||
projectedPointCount: frame.cameraProjectedPointCount,
|
||||
projection: "factory-kb4-exact",
|
||||
ariaLabel: `${evidenceLabel} LiDAR projection: ${frame.cameraProjectedSampleCount} points`,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const handleMediaModeChange = (next: M4ThreatMediaSelection) => {
|
||||
if (next === "none") return;
|
||||
@@ -408,21 +429,35 @@ export function M4ReplayThreatVisual({
|
||||
</div>
|
||||
);
|
||||
|
||||
const mediaLayerControls = semantic ? (
|
||||
const mediaLayerControls = semantic || metadata.timeline?.cameraPointDelivery ? (
|
||||
<div
|
||||
className="m4-replay-threat-visual__pane-layer-controls"
|
||||
role="group"
|
||||
aria-label="Слои камеры и видео"
|
||||
>
|
||||
<Button
|
||||
size="compact"
|
||||
shape="pill"
|
||||
variant={showMediaSemantic ? "primary" : "secondary"}
|
||||
aria-pressed={showMediaSemantic}
|
||||
onClick={() => setShowMediaSemantic((visible) => !visible)}
|
||||
>
|
||||
SEMANTICS
|
||||
</Button>
|
||||
{semantic ? (
|
||||
<Button
|
||||
size="compact"
|
||||
shape="pill"
|
||||
variant={showMediaSemantic ? "primary" : "secondary"}
|
||||
aria-pressed={showMediaSemantic}
|
||||
onClick={() => setShowMediaSemantic((visible) => !visible)}
|
||||
>
|
||||
SEMANTICS
|
||||
</Button>
|
||||
) : null}
|
||||
{metadata.timeline?.cameraPointDelivery ? (
|
||||
<Button
|
||||
size="compact"
|
||||
shape="pill"
|
||||
variant={showMediaPoints ? "primary" : "secondary"}
|
||||
aria-pressed={showMediaPoints}
|
||||
title="Exact LiDAR increment · factory KB4 camera projection"
|
||||
onClick={() => setShowMediaPoints((visible) => !visible)}
|
||||
>
|
||||
POINTS
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
@@ -570,6 +605,12 @@ export function M4ReplayThreatVisual({
|
||||
{spatialFrame
|
||||
? `${spatialFrame.pointCloudSampleCount}/${spatialFrame.pointCloudSourceCount} exact · ${localSurface.pointsBodyXyzM.length} local SLAM / ${localSurface.sourceFrameCount} frames`
|
||||
: "квалифицированный spatial frame ещё не получен"}
|
||||
{frame.worldStateAvailable
|
||||
? " · world-state delivered"
|
||||
: ` · world-state gap (${frame.terminalOutcome})`}
|
||||
{pointCloudOverlay
|
||||
? ` · camera points ${frame.cameraProjectedSampleCount}/${frame.cameraProjectedPointCount}`
|
||||
: ""}
|
||||
{semantic && spatialSemanticFrame
|
||||
? ` · semantic L ${spatialSemanticFrame.counts.labeled} · A ${spatialSemanticFrame.counts.ambiguous} · U ${spatialSemanticFrame.counts.unprojected} · Ø ${spatialSemanticFrame.counts.absent}`
|
||||
: semantic ? " · semantic buffer" : ""}
|
||||
@@ -595,7 +636,7 @@ export function M4ReplayThreatVisual({
|
||||
content = (
|
||||
<div className="l3-visual-audit__state" role="status">
|
||||
<span className="busy-indicator" aria-hidden="true" />
|
||||
<span>Открываем recorded-realtime timeline M4.6</span>
|
||||
<span>Открываем recorded-realtime timeline {evidenceLabel}</span>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
@@ -628,7 +669,8 @@ export function M4ReplayThreatVisual({
|
||||
imageHeight={timeline.imageHeight}
|
||||
boxes={activeBoxes}
|
||||
semanticOverlay={mediaMode === "video" ? semanticOverlay : undefined}
|
||||
ariaLabel={`M4.6 recorded-realtime frame ${frame?.sequence ?? 0}: ${activeBoxes.length} proposals`}
|
||||
pointCloudOverlay={mediaMode === "video" ? pointCloudOverlay : undefined}
|
||||
ariaLabel={`${evidenceLabel} recorded-realtime frame ${frame?.sequence ?? 0}: ${activeBoxes.length} proposals`}
|
||||
interactive={false}
|
||||
segmentSequence={
|
||||
timelineFrame.activeSequence === null
|
||||
@@ -655,7 +697,8 @@ export function M4ReplayThreatVisual({
|
||||
imageHeight={timeline.imageHeight}
|
||||
boxes={activeBoxes}
|
||||
semanticOverlay={semanticOverlay}
|
||||
ariaLabel={`M4.6 exact camera frame ${frame.sequence}: ${activeBoxes.length} proposals`}
|
||||
pointCloudOverlay={pointCloudOverlay}
|
||||
ariaLabel={`${evidenceLabel} exact camera frame ${frame.sequence}: ${activeBoxes.length} proposals`}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
@@ -689,7 +732,7 @@ export function M4ReplayThreatVisual({
|
||||
corridor={timeline.corridor}
|
||||
occupiedVoxelSizeM={timeline.occupiedVoxelSizeM}
|
||||
mode={spatialMode}
|
||||
label="M4.6 exact current increment, bounded local SLAM surface and rolling occupancy"
|
||||
label={`${evidenceLabel} exact current increment, bounded local SLAM surface and rolling occupancy`}
|
||||
showCurrentIncrement={showCurrentIncrement}
|
||||
showLocalSurface={showLocalSurface}
|
||||
showRollingMap={showRollingMap}
|
||||
@@ -791,7 +834,7 @@ export function M4ReplayThreatVisual({
|
||||
<LaboratoryEvidenceViewer
|
||||
label={semantic
|
||||
? "E47 semantic + SLAM diagnostic replay"
|
||||
: "M4.6 dual-evidence recorded-realtime replay"}
|
||||
: `${evidenceLabel} recorded-realtime replay`}
|
||||
className="m4-replay-threat-evidence-viewer"
|
||||
mode={mediaMode ?? "none"}
|
||||
modes={[
|
||||
|
||||
@@ -77,6 +77,13 @@ const KNOWN_WORKS: Readonly<Record<Exclude<LaboratoryWorkId, `session:${string}`
|
||||
experimentName: "M4.8 · small static passage regression",
|
||||
variantName: "M4.8R1 · Worker 006 small-static assisted baseline",
|
||||
},
|
||||
"m48s-fixed-class-detector": {
|
||||
profileId: "rig-ravnoves-perception-gate-v1",
|
||||
profileName: (rigLabel) => `${rig(rigLabel)} RIGHT · RAVNOVES00 perception gate`,
|
||||
experimentId: "m48s-fixed-class-risk-detector",
|
||||
experimentName: "RAVNOVES00 fixed-class risk detector",
|
||||
variantName: "M4.8S · RF-DETR-L TensorRT/Triton shadow",
|
||||
},
|
||||
"m47-reference-graph-shadow": {
|
||||
profileId: "rig-dual-evidence-virtual-corridor-v1",
|
||||
profileName: (rigLabel) => `${rig(rigLabel)} RIGHT · Camera + LiDAR dual evidence`,
|
||||
|
||||
@@ -21,6 +21,7 @@ function mergeResults(
|
||||
m47Graph: next.m47Graph ?? current.m47Graph,
|
||||
m48: next.m48 ?? current.m48,
|
||||
m48SmallStatic: next.m48SmallStatic ?? current.m48SmallStatic,
|
||||
m48s: next.m48s ?? current.m48s,
|
||||
m4Threat: next.m4Threat ?? current.m4Threat,
|
||||
l3: next.l3 ?? current.l3,
|
||||
l31: next.l31 ?? current.l31,
|
||||
|
||||
@@ -41,7 +41,7 @@ export function cancelM4ThreatChunkRequestsOutsideWindow<T extends { abort(): vo
|
||||
}
|
||||
}
|
||||
|
||||
export function useM4ThreatTimelineMetadata(resultId: string) {
|
||||
export function useM4ThreatTimelineMetadata(resultId: string, endpointRoot?: string) {
|
||||
const [timeline, setTimeline] = useState<M4ThreatTimeline | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -49,7 +49,7 @@ export function useM4ThreatTimelineMetadata(resultId: string) {
|
||||
const controller = new AbortController();
|
||||
setTimeline(null);
|
||||
setError(null);
|
||||
void fetchM4ThreatTimeline(resultId, { signal: controller.signal })
|
||||
void fetchM4ThreatTimeline(resultId, { signal: controller.signal, endpointRoot })
|
||||
.then((next) => {
|
||||
if (!controller.signal.aborted) setTimeline(next);
|
||||
})
|
||||
@@ -59,7 +59,7 @@ export function useM4ThreatTimelineMetadata(resultId: string) {
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [resultId]);
|
||||
}, [endpointRoot, resultId]);
|
||||
|
||||
return { timeline, loading: !timeline && !error, error };
|
||||
}
|
||||
@@ -68,10 +68,12 @@ export function useM4ThreatTimelineFrame({
|
||||
resultId,
|
||||
timeline,
|
||||
currentSeconds,
|
||||
endpointRoot,
|
||||
}: {
|
||||
resultId: string;
|
||||
timeline: M4ThreatTimeline | null;
|
||||
currentSeconds: number;
|
||||
endpointRoot?: string;
|
||||
}) {
|
||||
const [chunks, setChunks] = useState<ReadonlyMap<number, M4ThreatTimelineChunk>>(
|
||||
() => new Map(),
|
||||
@@ -124,6 +126,7 @@ export function useM4ThreatTimelineFrame({
|
||||
inFlight.current.set(start, controller);
|
||||
void fetchM4ThreatTimelineChunk(resultId, start, chunkSize, {
|
||||
signal: controller.signal,
|
||||
endpointRoot,
|
||||
})
|
||||
.then((chunk) => {
|
||||
if (controller.signal.aborted) return;
|
||||
@@ -151,7 +154,7 @@ export function useM4ThreatTimelineFrame({
|
||||
if (inFlight.current.get(start) === controller) inFlight.current.delete(start);
|
||||
});
|
||||
}
|
||||
}, [activeChunkStart, chunkSize, resultId, timeline]);
|
||||
}, [activeChunkStart, chunkSize, endpointRoot, resultId, timeline]);
|
||||
|
||||
const activeFrame: M4ThreatTimelineFrame | null = useMemo(() => {
|
||||
if (activeSequence === null || activeChunkStart === null) return null;
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, test } from "node:test";
|
||||
import { createServer } from "vite";
|
||||
|
||||
let server;
|
||||
let fetchM48SFixedClassDetectorResult;
|
||||
let fetchM48SFixedClassDetectorFrame;
|
||||
|
||||
const resultId = `m48s-fixed-class-detector-lab-${"b".repeat(64)}`;
|
||||
const authority = {
|
||||
actuation_allowed: false,
|
||||
candidate_accepted: false,
|
||||
commands_enabled: false,
|
||||
ground_truth: false,
|
||||
navigation_or_safety_accepted: false,
|
||||
};
|
||||
|
||||
before(async () => {
|
||||
server = await createServer({
|
||||
appType: "custom",
|
||||
logLevel: "silent",
|
||||
server: { middlewareMode: true },
|
||||
});
|
||||
({
|
||||
fetchM48SFixedClassDetectorResult,
|
||||
fetchM48SFixedClassDetectorFrame,
|
||||
} = await server.ssrLoadModule("/src/core/laboratory/m48sFixedClassDetector.ts"));
|
||||
});
|
||||
|
||||
after(async () => server?.close());
|
||||
|
||||
function response(value) {
|
||||
return { ok: true, status: 200, json: async () => value };
|
||||
}
|
||||
|
||||
function resultPayload() {
|
||||
const candidate = (id, overrides = {}) => ({
|
||||
id,
|
||||
label: id,
|
||||
provider_id: `${id}/v1`,
|
||||
capacity_fps: 40,
|
||||
p95_ms: 35,
|
||||
frame_253_dog_detected: false,
|
||||
frame_253_dog_score: null,
|
||||
selected: false,
|
||||
...overrides,
|
||||
});
|
||||
return {
|
||||
schema_version: "missioncore.m48s-fixed-class-detector-result-view/v1",
|
||||
result_id: resultId,
|
||||
created_at_utc: "2026-08-25T11:06:28Z",
|
||||
status: "complete-reference-graph-shadow-passed-production-not-authorized",
|
||||
bounded_question_accepted: true,
|
||||
ground_truth: false,
|
||||
source: {
|
||||
source_session_id: "RAVNOVES00",
|
||||
camera_source_id: "sensor.camera.right",
|
||||
camera_raster: [800, 600],
|
||||
evidence_frame_count: 1,
|
||||
},
|
||||
configuration: {
|
||||
comparison_threshold: 0.5,
|
||||
display_modes: ["source", "yolox", "dfine", "rf-detr"],
|
||||
single_inference_per_frame: true,
|
||||
geometry_owns_static_occupancy: true,
|
||||
unknown_stationary_response: "route-around",
|
||||
unknown_moving_response: "conservative-risk",
|
||||
},
|
||||
method: {
|
||||
schema_version: "missioncore.laboratory-method/v1",
|
||||
completeness: "complete",
|
||||
execution_class: "ai-inference",
|
||||
pipeline_id: "raw-kb4-fixed-class-risk-detector-tournament/v1",
|
||||
components: [{
|
||||
kind: "model",
|
||||
name: "RF-DETR-L COCO",
|
||||
version: "trt11-fp16",
|
||||
role: "selected fixed-class risk detector",
|
||||
identity_sha256: "9".repeat(64),
|
||||
}],
|
||||
},
|
||||
metrics: {
|
||||
candidates: [
|
||||
candidate("yolox"),
|
||||
candidate("dfine"),
|
||||
candidate("rf-detr", {
|
||||
label: "RF-DETR-L",
|
||||
capacity_fps: 42.496232,
|
||||
frame_253_dog_detected: true,
|
||||
frame_253_dog_score: 0.741674,
|
||||
selected: true,
|
||||
}),
|
||||
],
|
||||
detector_load: {
|
||||
duration_seconds: 1800.019643,
|
||||
source_frames_consumed: 18008,
|
||||
source_frame_replacements: 0,
|
||||
effective_consumed_fps: 10.004444,
|
||||
end_to_end_p95_ms: 32.41534,
|
||||
completion_age_p95_ms: 40.620542,
|
||||
gpu_utilization_mean_percent: 51.407556,
|
||||
gpu_utilization_maximum_percent: 65,
|
||||
gpu_memory_maximum_mib: 9556,
|
||||
queue_maximum_depth: 1,
|
||||
queue_capacity: 2,
|
||||
failures: 0,
|
||||
},
|
||||
integrated_world_state: {
|
||||
duration_seconds: 458.900859,
|
||||
source_frames_admitted: 4489,
|
||||
delivered_world_states: 4481,
|
||||
superseded_frames: 8,
|
||||
effective_world_state_fps: 9.764636,
|
||||
world_state_completion_age_p95_ms: 74.733648,
|
||||
world_state_completion_age_p99_ms: 102.62048,
|
||||
world_state_completion_age_maximum_ms: 669.142137,
|
||||
local_obstacle_map_output_age_p95_ms: 70.635141,
|
||||
queue_high_watermarks: { detector: 2, geometry: 2, temporal: 2, rolling: 2, threat: 2 },
|
||||
queue_capacity: 2,
|
||||
gpu_utilization_mean_percent: 50.903371,
|
||||
gpu_utilization_maximum_percent: 60,
|
||||
gpu_memory_maximum_mib: 9576,
|
||||
gpu_power_maximum_w: 153.51,
|
||||
gpu_temperature_maximum_c: 39,
|
||||
unique_component_count: 44979,
|
||||
multi_frame_component_count: 15887,
|
||||
maximum_component_publications: 219,
|
||||
duplicate_component_ids_within_frame: 0,
|
||||
advisory_family_counts: {
|
||||
animal: 63,
|
||||
"generic-obstacle": 123919,
|
||||
"light-road-user": 329,
|
||||
person: 5600,
|
||||
vehicle: 55818,
|
||||
},
|
||||
semantic_hint_counts: { dog: 60, person: 5600, "geometry-only": 123919 },
|
||||
motion_counts: { moving: 12252, stationary: 1433, unknown: 172044 },
|
||||
additional_inference_passes: 0,
|
||||
failures: 0,
|
||||
},
|
||||
},
|
||||
decision: {
|
||||
selected_candidate: "rf-detr",
|
||||
ready_for_reference_graph_shadow: true,
|
||||
integrated_world_state_gate_evaluated: true,
|
||||
integrated_world_state_gate_passed: true,
|
||||
detector_replacement_authorized: false,
|
||||
production_accepted: false,
|
||||
},
|
||||
limitations: ["No independent semantic ground truth."],
|
||||
authority,
|
||||
frames: [{
|
||||
frame_id: "000253",
|
||||
source_sequence: 253,
|
||||
counts: { yolox: 4, dfine: 7, "rf-detr": 8 },
|
||||
}],
|
||||
access: "read-only",
|
||||
};
|
||||
}
|
||||
|
||||
test("M4.8S result exposes complete graph load without production authority", async () => {
|
||||
const result = await fetchM48SFixedClassDetectorResult(resultId, {
|
||||
fetcher: async (url) => {
|
||||
assert.equal(
|
||||
url,
|
||||
`/api/v1/laboratory/m48s/fixed-class-detector/${resultId}`,
|
||||
);
|
||||
return response(resultPayload());
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.metrics.detectorLoad.sourceFramesConsumed, 18008);
|
||||
assert.equal(result.metrics.detectorLoad.completionAgeP95Ms, 40.620542);
|
||||
assert.equal(result.metrics.candidates[2].frame253DogScore, 0.741674);
|
||||
assert.equal(result.metrics.integratedWorldState.deliveredWorldStates, 4481);
|
||||
assert.equal(result.metrics.integratedWorldState.worldStateCompletionAgeP95Ms, 74.733648);
|
||||
assert.equal(result.metrics.integratedWorldState.additionalInferencePasses, 0);
|
||||
assert.equal(result.decision.integratedWorldStateGatePassed, true);
|
||||
assert.equal(result.decision.productionAccepted, false);
|
||||
assert.equal(result.authority.navigationOrSafetyAccepted, false);
|
||||
});
|
||||
|
||||
test("M4.8S frame binds exact camera endpoint and risk-only boxes", async () => {
|
||||
const frame = await fetchM48SFixedClassDetectorFrame(resultId, "000253", {
|
||||
fetcher: async () => response({
|
||||
schema_version: "missioncore.m48s-fixed-class-detector-frame/v1",
|
||||
result_id: resultId,
|
||||
frame_id: "000253",
|
||||
source_sequence: 253,
|
||||
camera: {
|
||||
media_type: "image/jpeg",
|
||||
width: 800,
|
||||
height: 600,
|
||||
exact_source_frame: true,
|
||||
},
|
||||
comparison_threshold: 0.5,
|
||||
detections: {
|
||||
yolox: [],
|
||||
dfine: [{ label: "skateboard", score: 0.782227, bbox_xyxy: [236, 334, 274, 372] }],
|
||||
"rf-detr": [{ label: "dog", score: 0.741674, bbox_xyxy: [235, 336, 273, 376] }],
|
||||
},
|
||||
ground_truth_available: false,
|
||||
authority,
|
||||
access: "read-only",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(frame.detections["rf-detr"][0].label, "dog");
|
||||
assert.equal(
|
||||
frame.cameraUrl,
|
||||
`/api/v1/laboratory/m48s/fixed-class-detector/${resultId}/frames/000253/camera`,
|
||||
);
|
||||
assert.equal(frame.groundTruthAvailable, false);
|
||||
});
|
||||
|
||||
test("M4.8S adapter rejects any navigation authority escalation", async () => {
|
||||
await assert.rejects(
|
||||
fetchM48SFixedClassDetectorResult(resultId, {
|
||||
fetcher: async () => response({
|
||||
...resultPayload(),
|
||||
authority: { ...authority, navigation_or_safety_accepted: true },
|
||||
}),
|
||||
}),
|
||||
/navigation_or_safety_accepted/,
|
||||
);
|
||||
});
|
||||
@@ -326,6 +326,100 @@ test("M4.6 timeline keeps only a compact index and decodes bounded spatial chunk
|
||||
assert.equal(selectM4ThreatTimelineFrame(chunk.frames, 35.50).sequence, 1);
|
||||
});
|
||||
|
||||
test("M4.8S timeline binds factory-KB4 camera points through its exact endpoint", async () => {
|
||||
const replayResultId = `m48s-fixed-class-detector-lab-${"b".repeat(64)}`;
|
||||
const endpointRoot = "/api/v1/laboratory/m48s/fixed-class-detector";
|
||||
const frameTimesNs = Array.from(
|
||||
{ length: 4489 },
|
||||
(_, index) => 35_421_857_292 + index * 100_000_000,
|
||||
);
|
||||
let requested = "";
|
||||
const timeline = await fetchM4ThreatTimeline(replayResultId, {
|
||||
endpointRoot,
|
||||
fetcher: async (input) => {
|
||||
requested = String(input);
|
||||
return new Response(JSON.stringify({
|
||||
schema_version: "missioncore.recorded-spatial-evidence-timeline/v1",
|
||||
result_id: replayResultId,
|
||||
recorded_source: {
|
||||
session_id: "20260720T065719Z_viewer_live",
|
||||
source_id: "RAVNOVES00",
|
||||
representation_id: "registered-map-increment-v1",
|
||||
synchronization: "host-arrival-best-effort",
|
||||
},
|
||||
image_width: 800,
|
||||
image_height: 600,
|
||||
frame_count: 4489,
|
||||
frame_times_ns: frameTimesNs,
|
||||
timeline_start_seconds: 35.421857292,
|
||||
timeline_end_seconds: 484.221857292,
|
||||
nominal_frame_interval_seconds: 0.1,
|
||||
nominal_rate_hz: 10,
|
||||
max_chunk_frames: 24,
|
||||
point_sample_limit: 4096,
|
||||
maximum_source_points_per_frame: 3092,
|
||||
point_delivery: "exact-current-increment",
|
||||
camera_point_delivery: "factory-kb4-projected-current-increment",
|
||||
camera_point_sample_limit: 4096,
|
||||
world_state_delivery: "source-paced-latest-wins",
|
||||
world_state_frame_count: 4481,
|
||||
superseded_frame_count: 8,
|
||||
local_surface_visualization: {
|
||||
derivation: "bounded-registered-increment-accumulation",
|
||||
window_seconds: 2,
|
||||
voxel_size_m: 0.1,
|
||||
radius_m: 12,
|
||||
point_limit: 20000,
|
||||
authority: "visual-derived",
|
||||
},
|
||||
rig: { length_m: 1, width_m: 0.6, nominal_sensor_height_m: 1.25 },
|
||||
corridor: {
|
||||
forward_length_m: 8,
|
||||
rear_margin_m: 0.5,
|
||||
half_width_m: 0.5,
|
||||
occupied_voxel_size_m: 0.45,
|
||||
prediction_horizon_seconds: 5,
|
||||
},
|
||||
authority: "replay-simulated",
|
||||
}), { status: 200 });
|
||||
},
|
||||
});
|
||||
assert.equal(requested, `${endpointRoot}/${replayResultId}/timeline`);
|
||||
assert.equal(timeline.cameraPointDelivery, "factory-kb4-projected-current-increment");
|
||||
assert.equal(timeline.worldStateFrameCount, 4481);
|
||||
assert.equal(timeline.supersededFrameCount, 8);
|
||||
|
||||
const chunk = await fetchM4ThreatTimelineChunk(replayResultId, 1, 1, {
|
||||
endpointRoot,
|
||||
fetcher: async (input) => {
|
||||
requested = String(input);
|
||||
return new Response(JSON.stringify({
|
||||
schema_version: "missioncore.recorded-spatial-evidence-chunk/v1",
|
||||
result_id: replayResultId,
|
||||
start_sequence: 1,
|
||||
frame_count: 1,
|
||||
next_sequence: 2,
|
||||
frames: [timelineFrame(1, 35.521857292, {
|
||||
world_state_available: false,
|
||||
terminal_outcome: "superseded",
|
||||
camera_projected_points_xyd: [[100.5, 200.25, 3.75]],
|
||||
camera_projected_source_count: 847,
|
||||
camera_projected_point_count: 1,
|
||||
camera_projected_sample_count: 1,
|
||||
camera_projection: "factory-kb4-exact",
|
||||
camera_url: `${endpointRoot}/${replayResultId}/timeline/frames/1/camera`,
|
||||
})],
|
||||
authority: "replay-simulated",
|
||||
}), { status: 200 });
|
||||
},
|
||||
});
|
||||
assert.match(requested, new RegExp(`^${endpointRoot}/${replayResultId}/timeline/chunk`));
|
||||
assert.equal(chunk.frames[0].worldStateAvailable, false);
|
||||
assert.equal(chunk.frames[0].terminalOutcome, "superseded");
|
||||
assert.deepEqual(chunk.frames[0].cameraProjectedPointsXyd[0], [100.5, 200.25, 3.75]);
|
||||
assert.equal(chunk.frames[0].cameraProjection, "factory-kb4-exact");
|
||||
});
|
||||
|
||||
test("M4.6 local SLAM surface reprojects registered increments into the active body frame", () => {
|
||||
const frames = [
|
||||
timelineFrame(0, 10, {
|
||||
@@ -453,11 +547,12 @@ test("recorded VIDEO clock cannot reverse an explicit operator pause", () => {
|
||||
});
|
||||
|
||||
test("M4.6 viewer keeps media and spatial panes on one playback clock", async () => {
|
||||
const [visual, visualCss, imageScene, videoScene, metricScene] = await Promise.all([
|
||||
const [visual, visualCss, imageScene, videoScene, pointOverlay, metricScene] = await Promise.all([
|
||||
readFile(new URL("../src/workspaces/laboratory/M4ReplayThreatVisual.tsx", import.meta.url), "utf8"),
|
||||
readFile(new URL("../src/styles/m4-replay-threat.css", import.meta.url), "utf8"),
|
||||
readFile(new URL("../src/components/laboratory/RecordedEvidenceImageScene.tsx", import.meta.url), "utf8"),
|
||||
readFile(new URL("../src/components/laboratory/RecordedEvidenceVideoScene.tsx", import.meta.url), "utf8"),
|
||||
readFile(new URL("../src/components/laboratory/RecordedEvidencePointCloudOverlay.tsx", import.meta.url), "utf8"),
|
||||
readFile(new URL("../src/components/laboratory/LaboratoryMetricEvidenceScene.tsx", import.meta.url), "utf8"),
|
||||
]);
|
||||
assert.match(visual, /<RecordedEvidenceVideoScene/);
|
||||
@@ -474,6 +569,8 @@ test("M4.6 viewer keeps media and spatial panes on one playback clock", async ()
|
||||
assert.match(visual, /label: "CAMERA"/);
|
||||
assert.match(visual, /label: "3D"/);
|
||||
assert.match(visual, /label: "PLAN"/);
|
||||
assert.match(visual, />\s*POINTS\s*</);
|
||||
assert.match(visual, /pointCloudOverlay=/);
|
||||
assert.match(visual, /mediaMode/);
|
||||
assert.match(visual, /spatialMode/);
|
||||
assert.match(visual, /current === next \? null : next/);
|
||||
@@ -504,6 +601,9 @@ test("M4.6 viewer keeps media and spatial panes on one playback clock", async ()
|
||||
assert.match(visualCss, /bottom: auto/);
|
||||
assert.match(videoScene, /<RecordedFmp4Player/);
|
||||
assert.match(imageScene, /<RecordedEvidenceBoxOverlay/);
|
||||
assert.match(imageScene, /<RecordedEvidencePointCloudOverlay/);
|
||||
assert.match(videoScene, /<RecordedEvidencePointCloudOverlay/);
|
||||
assert.match(pointOverlay, /factory-kb4-exact/);
|
||||
assert.match(metricScene, /OrbitControls/);
|
||||
assert.match(visual, /LOCAL SLAM/);
|
||||
assert.match(visual, /showLocalSurface/);
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"schema_version": "missioncore.laboratory-evidence-definition/v1",
|
||||
"work_id": "m48s-fixed-class-detector",
|
||||
"evidence": {
|
||||
"runtime_relative_root": "m48s-semantic-shadow/fixed-class-detector-lab-results",
|
||||
"result_id_prefix": "m48s-fixed-class-detector-lab",
|
||||
"document_name": "manifest.json",
|
||||
"schema_version": "missioncore.m48s-fixed-class-detector-lab/v1"
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,20 @@
|
||||
"run": "missioncore.laboratory-run/v1",
|
||||
"evidence": "missioncore.e47-semantic-slam-result/v1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "m48s-fixed-class-detector",
|
||||
"lifecycle": "experimental",
|
||||
"isolation": "bounded-adapter",
|
||||
"adapter_id": "experimental.m48s-fixed-class-detector/v1",
|
||||
"input_roles": ["repository_root"],
|
||||
"contracts": {
|
||||
"source": "missioncore.m48s-sealed-detector-evidence/v1",
|
||||
"provider": "missioncore.rf-detr-risk-shadow-provider/v1",
|
||||
"graph": "missioncore.m48s-fixed-class-detector-lab-graph/v1",
|
||||
"run": "missioncore.laboratory-run/v1",
|
||||
"evidence": "missioncore.m48s-fixed-class-detector-lab/v1"
|
||||
}
|
||||
}
|
||||
],
|
||||
"legacy_work_ids": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schema_version": "missioncore.laboratory-value-review-registry/v1",
|
||||
"reviewed_at_utc": "2026-08-05T15:34:00Z",
|
||||
"reviewed_at_utc": "2026-08-25T11:06:28Z",
|
||||
"entries": [
|
||||
{
|
||||
"catalog_id": "e28-local-surface",
|
||||
@@ -246,6 +246,13 @@
|
||||
"signal": "retained",
|
||||
"lifecycle": "current",
|
||||
"visual_evidence": "available"
|
||||
},
|
||||
{
|
||||
"catalog_id": "m48s-fixed-class-detector",
|
||||
"evidence_id": "m48s-fixed-class-detector-lab-d1bac05a9e43d407b0f931105cc0e84183ef9ff37666911f03c41486beeb7ef9",
|
||||
"signal": "progress",
|
||||
"lifecycle": "current",
|
||||
"visual_evidence": "available"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"schema_version": "missioncore.fixed-class-detector-tournament-profile/v0",
|
||||
"profile_id": "m48s-fixed-class-detector-tournament/v0",
|
||||
"source": {
|
||||
"slice_id": "m48s-risk-11-valid-fov-fill/v1",
|
||||
"frame_count": 11,
|
||||
"valid_fov_result_id": "valid-fov-mask-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2",
|
||||
"baseline_result_id": "m48s-yolox-all-coco-shadow-7dbe6043b3fc12c7ddb162f609f883d86b34a4f2dd3785a632795f257e192d06"
|
||||
},
|
||||
"candidates": [
|
||||
{
|
||||
"profile_id": "dfine-s-coco-640-fp16/v0",
|
||||
"provider_id": "shadow-dfine-s-coco/v0",
|
||||
"role": "fast",
|
||||
"upstream": {
|
||||
"repository": "https://github.com/Peterande/D-FINE",
|
||||
"revision": "956d1709314c2c6a4df6f34de232054578a7449f",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"checkpoint": {
|
||||
"url": "https://github.com/Peterande/storage/releases/download/dfinev1.0/dfine_s_coco.pth",
|
||||
"training_basis": "COCO-only",
|
||||
"sha256": "48a6c8cc43eb57186843f752e2e8461ddd3326e0d3c575e71e6e960844683e89"
|
||||
},
|
||||
"model": {
|
||||
"dataset_vocabulary": "COCO-80",
|
||||
"input_width": 640,
|
||||
"input_height": 640,
|
||||
"published_coco_ap_50_95": 48.5,
|
||||
"published_t4_tensorrt_fp16_ms": 3.49,
|
||||
"published_parameter_count_millions": 10
|
||||
},
|
||||
"deployment_path": ["PyTorch qualification", "ONNX", "TensorRT FP16", "Triton"]
|
||||
},
|
||||
{
|
||||
"profile_id": "rf-detr-large-coco-704-fp16/v0",
|
||||
"provider_id": "shadow-rf-detr-large-coco/v0",
|
||||
"role": "strong",
|
||||
"upstream": {
|
||||
"repository": "https://github.com/roboflow/rf-detr",
|
||||
"version": "1.9.4",
|
||||
"revision": "9b009fa928d6218320439803d1da01869a85c072",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"checkpoint": {
|
||||
"url": "https://storage.googleapis.com/rfdetr/rf-detr-large-2026.pth",
|
||||
"training_basis": "Apache-designated COCO checkpoint",
|
||||
"expected_md5": "5cb72153541cbcb9aa6efa26222acc75",
|
||||
"sha256": "0f4e20e19a99c0f8a62b5685f57f6c8b5c371c59081feda6752a0561a79ccf38"
|
||||
},
|
||||
"model": {
|
||||
"dataset_vocabulary": "COCO-80",
|
||||
"input_width": 704,
|
||||
"input_height": 704,
|
||||
"published_coco_ap_50_95": 56.5,
|
||||
"published_t4_tensorrt_fp16_ms": 6.8,
|
||||
"published_parameter_count_millions": 33.9
|
||||
},
|
||||
"deployment_path": ["PyTorch qualification", "ONNX", "TensorRT FP16", "Triton"]
|
||||
}
|
||||
],
|
||||
"emission": {
|
||||
"class_vocabulary": "COCO-80",
|
||||
"qualification_score_thresholds": [0.25, 0.5],
|
||||
"geometry_owns_occupancy": true,
|
||||
"static_object_names_have_behavior_authority": false,
|
||||
"inference_passes_per_frame": 1
|
||||
},
|
||||
"risk_policy": {
|
||||
"classified_groups": ["person", "animal", "light-road-user", "vehicle"],
|
||||
"unknown_moving_response": "conservative-risk",
|
||||
"unknown_stationary_response": "route-around"
|
||||
},
|
||||
"promotion_gates": {
|
||||
"minimum_recorded_source_fps": 9.5,
|
||||
"maximum_world_state_p95_ms": 175,
|
||||
"maximum_worker_vram_gib": 20,
|
||||
"sustained_gpu_utilization_below_percent": 100,
|
||||
"queue_policy": "bounded-latest-wins",
|
||||
"full_load_duration_minutes": [30, 60]
|
||||
},
|
||||
"authority": {
|
||||
"ground_truth": false,
|
||||
"candidate_accepted": false,
|
||||
"commands_enabled": false,
|
||||
"actuation_allowed": false,
|
||||
"navigation_or_safety_accepted": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"schema_version": "missioncore.m48s-mask-grounding-dino-profile/v0",
|
||||
"profile_id": "m48s-mask-grounding-dino-research-shadow/v0",
|
||||
"model": {
|
||||
"catalog": "NVIDIA NGC",
|
||||
"catalog_url": "https://catalog.ngc.nvidia.com/orgs/nvidia/tao/models/pretrained_mask_grounding_dino_v2/mask_grounding_dino_swin_tiny_research_deployable_v2.0/version-history",
|
||||
"artifact": "mask_grounding_dino_epoch_021.onnx",
|
||||
"artifact_sha256": "4e8b066cf7782ae6b4269255b861c205f4b07b33ff752e5eaf297c42ecfb2f5e",
|
||||
"license_scope": "research-only",
|
||||
"commercial_checkpoint_acquired": false
|
||||
},
|
||||
"runtime": {
|
||||
"worker_node": "DESKTOP-OPJ8J04",
|
||||
"gpu": "NVIDIA GeForce RTX 4090",
|
||||
"container_reference": "nvcr.io/nvidia/tao/tao-toolkit:7.0.1-deploy",
|
||||
"container_image_id": "sha256:2a3095330dd83e4314aada21fc7d184fcdb442a9131d591e5593ca5497394e7a",
|
||||
"tensorrt_precision": "FP16",
|
||||
"engine_sha256": "1d127107d15f18dcddafd7345a0a766acfee204d63c5ab697eaabada2c7afcd2",
|
||||
"engine_size_bytes": 407588756
|
||||
},
|
||||
"binding": {
|
||||
"minimum_mask_iou": 0.9,
|
||||
"minimum_projected_points": 4,
|
||||
"minimum_support_fraction": 0.5,
|
||||
"maximum_secondary_support_fraction": 0.25,
|
||||
"minimum_label_confidence": 0.3,
|
||||
"minimum_label_margin": 0.1
|
||||
},
|
||||
"authority": {
|
||||
"ground_truth": false,
|
||||
"independent_truth": false,
|
||||
"candidate_accepted": false,
|
||||
"commands_enabled": false,
|
||||
"actuation_allowed": false,
|
||||
"navigation_or_safety_accepted": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
model_name: missioncore-m48s-mask-grounding-dino-shadow
|
||||
results_dir: /workspace/probe/results
|
||||
wandb:
|
||||
enable: false
|
||||
model:
|
||||
backbone: swin_tiny_224_1k
|
||||
num_queries: 900
|
||||
num_feature_levels: 4
|
||||
dec_layers: 6
|
||||
enc_layers: 6
|
||||
dim_feedforward: 2048
|
||||
dropout_ratio: 0.0
|
||||
log_scale: auto
|
||||
class_embed_bias: true
|
||||
num_region_queries: 100
|
||||
loss_types:
|
||||
- labels
|
||||
- boxes
|
||||
- masks
|
||||
- rela
|
||||
dataset:
|
||||
infer_data_sources:
|
||||
image_dir: /workspace/probe/input
|
||||
data_type: OD
|
||||
captions:
|
||||
- adult person
|
||||
- child
|
||||
- dog
|
||||
- bicycle
|
||||
- kick scooter
|
||||
- stroller
|
||||
- shopping cart
|
||||
- car
|
||||
- bus
|
||||
- truck
|
||||
- motorcycle
|
||||
- trash bin
|
||||
- bollard
|
||||
- post
|
||||
- concrete hemisphere
|
||||
- traffic cone
|
||||
- road sign
|
||||
- temporary barrier
|
||||
batch_size: 1
|
||||
workers: 1
|
||||
pin_memory: true
|
||||
max_labels: 80
|
||||
has_mask: true
|
||||
inference:
|
||||
trt_engine: /workspace/model/mask_grounding_dino_swin_tiny_research_fp16.engine
|
||||
results_dir: /workspace/probe/results
|
||||
batch_size: -1
|
||||
input_width: 960
|
||||
input_height: 544
|
||||
conf_threshold: 0.25
|
||||
ioi_threshold: 0.5
|
||||
nms_threshold: 0.2
|
||||
text_threshold: 0.3
|
||||
outline_width: 3
|
||||
gen_trt_engine:
|
||||
onnx_file: /workspace/model/mask_grounding_dino_epoch_021.onnx
|
||||
trt_engine: /workspace/model/mask_grounding_dino_swin_tiny_research_fp16.engine
|
||||
results_dir: /workspace/model/engine-build
|
||||
batch_size: -1
|
||||
verbose: false
|
||||
tensorrt:
|
||||
workspace_size: 8192
|
||||
min_batch_size: 1
|
||||
opt_batch_size: 1
|
||||
max_batch_size: 1
|
||||
data_type: FP16
|
||||
@@ -0,0 +1,95 @@
|
||||
{
|
||||
"schema_version": "missioncore.reference-perception-graph-config/v2",
|
||||
"graph_id": "reference-perception-graph/v2",
|
||||
"source_profile_id": "m4-ravnoves00-recorded-realtime/v1",
|
||||
"providers": [
|
||||
{
|
||||
"role": "source",
|
||||
"provider_id": "ravnoves00-recorded-source/v1",
|
||||
"version": "1.0.0",
|
||||
"revision": "m4-ravnoves00-recorded-realtime/v1",
|
||||
"sha256": "ea10359339e6cce31b5780a2710299771cab7cc0c1c2a2b56a1621f786b31fa8"
|
||||
},
|
||||
{
|
||||
"role": "detector",
|
||||
"provider_id": "triton-rf-detr-large-coco-risk-fp16-shadow/v0",
|
||||
"version": "0.1.0",
|
||||
"revision": "rf-detr-large-coco-704-trt11-fp16-risk-shadow/v0",
|
||||
"sha256": "0c307fd2d19cedd2c9267b6be2effdce82161a719a742f315fcd7a76f7061b08"
|
||||
},
|
||||
{
|
||||
"role": "geometry",
|
||||
"provider_id": "ravnoves00-geometry-association/v1",
|
||||
"version": "1.0.0",
|
||||
"revision": "m4-ravnoves00-e29-e32-geometry/v1",
|
||||
"sha256": "cc666c9389a5e221957faddec89584709b66918d14abaf646f1832e001421999"
|
||||
},
|
||||
{
|
||||
"role": "temporal",
|
||||
"provider_id": "bounded-spatial-temporal-layer/v1",
|
||||
"version": "1.0.0",
|
||||
"revision": "m4-bounded-temporal-motion/v1",
|
||||
"sha256": "7130eaee24a95c7d888bf7598010e03e129e1c3ac5b34bcd8401015ff4244b39"
|
||||
},
|
||||
{
|
||||
"role": "motion",
|
||||
"provider_id": "class-independent-motion-estimator/v1",
|
||||
"version": "1.0.0",
|
||||
"revision": "m4-bounded-temporal-motion/v1",
|
||||
"sha256": "7130eaee24a95c7d888bf7598010e03e129e1c3ac5b34bcd8401015ff4244b39"
|
||||
},
|
||||
{
|
||||
"role": "rolling",
|
||||
"provider_id": "rolling-local-obstacle-map/v1",
|
||||
"version": "1.0.0",
|
||||
"revision": "ravnoves00-rolling-local-obstacle-map/v1",
|
||||
"sha256": "f7e3315eaf6ffaf3aee1e04913933812092cf82bbcc9984c1a6fa2d9250e6784"
|
||||
},
|
||||
{
|
||||
"role": "threat",
|
||||
"provider_id": "dual-evidence-replay-threat/v3",
|
||||
"version": "3.0.0",
|
||||
"revision": "m4-ravnoves00-virtual-corridor/v3",
|
||||
"sha256": "8c3a5aa837da1f028f5998fb504a1381f9b2b68de6420a32160410b6dc0887c7"
|
||||
}
|
||||
],
|
||||
"queues": [
|
||||
{
|
||||
"stage_id": "detector",
|
||||
"capacity": 2,
|
||||
"deadline_ns": 1000000000,
|
||||
"terminal_timeout_ns": 90000000000
|
||||
},
|
||||
{
|
||||
"stage_id": "geometry",
|
||||
"capacity": 2,
|
||||
"deadline_ns": 1500000000,
|
||||
"terminal_timeout_ns": 90000000000
|
||||
},
|
||||
{
|
||||
"stage_id": "temporal",
|
||||
"capacity": 2,
|
||||
"deadline_ns": 1750000000,
|
||||
"terminal_timeout_ns": 90000000000
|
||||
},
|
||||
{
|
||||
"stage_id": "rolling",
|
||||
"capacity": 2,
|
||||
"deadline_ns": 2000000000,
|
||||
"terminal_timeout_ns": 90000000000
|
||||
},
|
||||
{
|
||||
"stage_id": "threat",
|
||||
"capacity": 2,
|
||||
"deadline_ns": 2250000000,
|
||||
"terminal_timeout_ns": 90000000000
|
||||
}
|
||||
],
|
||||
"authority": {
|
||||
"mode": "replay-simulated",
|
||||
"physical_live": false,
|
||||
"commands_enabled": false,
|
||||
"actuation_allowed": false,
|
||||
"navigation_or_safety_accepted": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"schema_version": "missioncore.semantic-object-quality-profile/v0",
|
||||
"profile_id": "m48s-urban-semantic-object-quality/v0",
|
||||
"vocabulary_id": "missioncore.urban-object-semantics/v0",
|
||||
"top_k": 5,
|
||||
"thresholds": {
|
||||
"minimum_prediction_coverage": 1.0,
|
||||
"minimum_exact_top1_accuracy": 0.8,
|
||||
"minimum_coarse_group_accuracy": 0.95,
|
||||
"minimum_exact_top_k_recall": 0.95,
|
||||
"maximum_unresolved_fraction": 0.1,
|
||||
"maximum_conflict_fraction": 0.05
|
||||
},
|
||||
"scope": {
|
||||
"object_presence_scored": false,
|
||||
"semantic_class_scored": true,
|
||||
"risk_policy_scored": false,
|
||||
"requires_separate_adjudicated_semantic_truth": true
|
||||
},
|
||||
"authority": {
|
||||
"physical_live": false,
|
||||
"commands_enabled": false,
|
||||
"actuation_allowed": false,
|
||||
"navigation_or_safety_accepted": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
{
|
||||
"schema_version": "missioncore.object-semantic-vocabulary/v0",
|
||||
"vocabulary_id": "missioncore.urban-object-semantics/v0",
|
||||
"status": "experimental",
|
||||
"scope": "urban-ground-robot",
|
||||
"classes": [
|
||||
{
|
||||
"class_id": "object.unknown",
|
||||
"parent_id": null,
|
||||
"aliases": ["unknown", "unknown_object"],
|
||||
"agency_prior": "unknown",
|
||||
"risk_traits": ["unknown-clearance", "unknown-motion-potential"]
|
||||
},
|
||||
{
|
||||
"class_id": "human.unknown",
|
||||
"parent_id": "object.unknown",
|
||||
"aliases": ["person", "human", "pedestrian"],
|
||||
"agency_prior": "animate",
|
||||
"risk_traits": ["vulnerable-road-user", "unpredictable-motion"]
|
||||
},
|
||||
{
|
||||
"class_id": "human.adult",
|
||||
"parent_id": "human.unknown",
|
||||
"aliases": ["adult", "adult_person"],
|
||||
"agency_prior": "animate",
|
||||
"risk_traits": ["vulnerable-road-user", "unpredictable-motion"]
|
||||
},
|
||||
{
|
||||
"class_id": "human.child",
|
||||
"parent_id": "human.unknown",
|
||||
"aliases": ["child", "kid", "toddler"],
|
||||
"agency_prior": "animate",
|
||||
"risk_traits": ["vulnerable-road-user", "high-unpredictability"]
|
||||
},
|
||||
{
|
||||
"class_id": "animal.unknown",
|
||||
"parent_id": "object.unknown",
|
||||
"aliases": ["animal", "unknown_animal"],
|
||||
"agency_prior": "animate",
|
||||
"risk_traits": ["unpredictable-motion"]
|
||||
},
|
||||
{
|
||||
"class_id": "animal.dog",
|
||||
"parent_id": "animal.unknown",
|
||||
"aliases": ["dog", "canine"],
|
||||
"agency_prior": "animate",
|
||||
"risk_traits": ["unpredictable-motion", "close-interaction-risk"]
|
||||
},
|
||||
{
|
||||
"class_id": "vehicle.unknown",
|
||||
"parent_id": "object.unknown",
|
||||
"aliases": ["vehicle", "unknown_vehicle"],
|
||||
"agency_prior": "self-propelled",
|
||||
"risk_traits": ["may-start-moving", "large-footprint"]
|
||||
},
|
||||
{
|
||||
"class_id": "vehicle.car",
|
||||
"parent_id": "vehicle.unknown",
|
||||
"aliases": ["car", "automobile"],
|
||||
"agency_prior": "self-propelled",
|
||||
"risk_traits": ["may-start-moving", "reversing-risk"]
|
||||
},
|
||||
{
|
||||
"class_id": "vehicle.heavy",
|
||||
"parent_id": "vehicle.unknown",
|
||||
"aliases": ["heavy_vehicle", "truck", "bus"],
|
||||
"agency_prior": "self-propelled",
|
||||
"risk_traits": ["may-start-moving", "large-footprint", "blind-zone"]
|
||||
},
|
||||
{
|
||||
"class_id": "vehicle.bicycle",
|
||||
"parent_id": "vehicle.unknown",
|
||||
"aliases": ["bicycle", "bike"],
|
||||
"agency_prior": "self-propelled",
|
||||
"risk_traits": ["may-start-moving", "vulnerable-road-user"]
|
||||
},
|
||||
{
|
||||
"class_id": "vehicle.motorcycle",
|
||||
"parent_id": "vehicle.unknown",
|
||||
"aliases": ["motorcycle", "motorbike"],
|
||||
"agency_prior": "self-propelled",
|
||||
"risk_traits": ["may-start-moving", "rapid-motion"]
|
||||
},
|
||||
{
|
||||
"class_id": "vehicle.kick-scooter",
|
||||
"parent_id": "vehicle.unknown",
|
||||
"aliases": ["kick_scooter", "scooter"],
|
||||
"agency_prior": "self-propelled",
|
||||
"risk_traits": ["may-start-moving", "vulnerable-road-user"]
|
||||
},
|
||||
{
|
||||
"class_id": "mobility.unknown",
|
||||
"parent_id": "object.unknown",
|
||||
"aliases": ["passive_mobility", "wheeled_object"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["may-be-pushed", "rolling-potential"]
|
||||
},
|
||||
{
|
||||
"class_id": "mobility.stroller",
|
||||
"parent_id": "mobility.unknown",
|
||||
"aliases": ["stroller", "pram"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["may-be-pushed", "vulnerable-occupant"]
|
||||
},
|
||||
{
|
||||
"class_id": "mobility.cart",
|
||||
"parent_id": "mobility.unknown",
|
||||
"aliases": ["cart", "shopping_cart", "trolley"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["may-be-pushed", "rolling-potential"]
|
||||
},
|
||||
{
|
||||
"class_id": "static.unknown",
|
||||
"parent_id": "object.unknown",
|
||||
"aliases": ["static_obstacle", "generic_obstacle", "obstacle"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["static-clearance"]
|
||||
},
|
||||
{
|
||||
"class_id": "static.trash-bin",
|
||||
"parent_id": "static.unknown",
|
||||
"aliases": ["trash_bin", "garbage_bin", "waste_bin"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["static-clearance", "movable-by-external-force"]
|
||||
},
|
||||
{
|
||||
"class_id": "static.bollard",
|
||||
"parent_id": "static.unknown",
|
||||
"aliases": ["bollard", "road_bollard"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["small-static", "rigid-clearance"]
|
||||
},
|
||||
{
|
||||
"class_id": "static.post",
|
||||
"parent_id": "static.unknown",
|
||||
"aliases": ["post", "pole", "pipe_post"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["small-static", "rigid-clearance"]
|
||||
},
|
||||
{
|
||||
"class_id": "static.concrete-hemisphere",
|
||||
"parent_id": "static.unknown",
|
||||
"aliases": ["concrete_hemisphere", "hemisphere", "dome_barrier"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["low-profile", "rigid-clearance"]
|
||||
},
|
||||
{
|
||||
"class_id": "static.traffic-cone",
|
||||
"parent_id": "static.unknown",
|
||||
"aliases": ["traffic_cone", "cone"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["small-static", "temporary-road-control"]
|
||||
},
|
||||
{
|
||||
"class_id": "static.road-sign",
|
||||
"parent_id": "static.unknown",
|
||||
"aliases": ["road_sign", "traffic_sign"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["static-clearance", "road-control-device"]
|
||||
},
|
||||
{
|
||||
"class_id": "static.temporary-barrier",
|
||||
"parent_id": "static.unknown",
|
||||
"aliases": ["temporary_barrier", "road_barrier", "barrier"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["static-clearance", "temporary-road-control"]
|
||||
},
|
||||
{
|
||||
"class_id": "terrain.unknown",
|
||||
"parent_id": "object.unknown",
|
||||
"aliases": ["terrain_hazard", "surface_hazard"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["surface-discontinuity"]
|
||||
},
|
||||
{
|
||||
"class_id": "terrain.curb",
|
||||
"parent_id": "terrain.unknown",
|
||||
"aliases": ["curb", "sidewalk_curb"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["surface-discontinuity", "vehicle-dependent-traversability"]
|
||||
},
|
||||
{
|
||||
"class_id": "terrain.step",
|
||||
"parent_id": "terrain.unknown",
|
||||
"aliases": ["step", "stair"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["surface-discontinuity", "vehicle-dependent-traversability"]
|
||||
},
|
||||
{
|
||||
"class_id": "terrain.pothole",
|
||||
"parent_id": "terrain.unknown",
|
||||
"aliases": ["pothole", "road_hole"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["negative-obstacle", "vehicle-dependent-traversability"]
|
||||
},
|
||||
{
|
||||
"class_id": "terrain.drainage-grate",
|
||||
"parent_id": "terrain.unknown",
|
||||
"aliases": ["drainage_grate", "drain", "road_grate"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["surface-discontinuity", "wheel-entrapment"]
|
||||
},
|
||||
{
|
||||
"class_id": "natural.unknown",
|
||||
"parent_id": "object.unknown",
|
||||
"aliases": ["natural_obstacle", "debris"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["irregular-clearance"]
|
||||
},
|
||||
{
|
||||
"class_id": "natural.rock",
|
||||
"parent_id": "natural.unknown",
|
||||
"aliases": ["rock", "stone"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["irregular-clearance", "rigid-clearance"]
|
||||
},
|
||||
{
|
||||
"class_id": "natural.branch",
|
||||
"parent_id": "natural.unknown",
|
||||
"aliases": ["branch", "fallen_branch"],
|
||||
"agency_prior": "inert",
|
||||
"risk_traits": ["irregular-clearance", "deformable-obstacle"]
|
||||
}
|
||||
],
|
||||
"policies": {
|
||||
"occupancy_independent_of_semantics": true,
|
||||
"unknown_preserves_obstacle": true,
|
||||
"class_prior_is_not_observed_state": true,
|
||||
"risk_is_advisory_only": true,
|
||||
"planner_command_authority": false,
|
||||
"max_hypotheses": 5
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"schema_version": "missioncore.open-vocabulary-semantic-shadow-profile/v0",
|
||||
"profile_id": "m48s-raw-kb4-urban-semantics-shadow/v0",
|
||||
"status": "experimental-shadow",
|
||||
"source": {
|
||||
"session_id": "20260720T065719Z_viewer_live",
|
||||
"source_id": "RAVNOVES00",
|
||||
"camera_source_id": "sensor.camera.right",
|
||||
"coordinate_space": "raw-kb4",
|
||||
"width": 800,
|
||||
"height": 600,
|
||||
"decoded_frame_basis": "zero-based-decoded-video-frame",
|
||||
"decoded_image_encoding": "jpeg-q2-yuvj420p",
|
||||
"valid_fov_result_id": "valid-fov-mask-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2",
|
||||
"valid_fov_mask_sha256": "a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63",
|
||||
"valid_fov_fill_value": 114
|
||||
},
|
||||
"provider": {
|
||||
"provider_id": "nvidia-tao-grounding-dino-trt/v1",
|
||||
"name": "NVIDIA TAO Grounding DINO Swin-Tiny Commercial",
|
||||
"version": "1.0",
|
||||
"model_id": "grounding-dino-swin-tiny-commercial/v1",
|
||||
"model_file": "grounding_dino_swin_tiny_commercial_deployable.onnx",
|
||||
"model_sha256": "6895acdc6b588e923f753e37b3bd18869e064256e5ecc1b2b9853e8c51125f94",
|
||||
"model_revision": "nvidia-tao-7.0.1-commercial-v1.0",
|
||||
"engine_file": "grounding_dino_swin_tiny_commercial_fp16.engine",
|
||||
"engine_sha256": "63213f60730ce8577047ff508dfe06113269347501e2dd832aeb56c89bc11489",
|
||||
"engine_precision": "FP16",
|
||||
"container_reference": "nvcr.io/nvidia/tao/tao-toolkit:7.0.1-deploy",
|
||||
"container_image_id": "sha256:2a3095330dd83e4314aada21fc7d184fcdb442a9131d591e5593ca5497394e7a",
|
||||
"preprocess_id": "raw-kb4-valid-fov-fill114-800x600-to-960x544/v1",
|
||||
"engine_input_width": 960,
|
||||
"engine_input_height": 544
|
||||
},
|
||||
"postprocessing": {
|
||||
"minimum_input_confidence": 0.25,
|
||||
"minimum_box_area_fraction": 0.00002,
|
||||
"maximum_box_area_fraction": 0.35,
|
||||
"minimum_valid_fov_fraction": 0.5,
|
||||
"require_center_inside_valid_fov": true,
|
||||
"fusion_iou_threshold": 0.7,
|
||||
"selected_minimum_confidence": 0.5,
|
||||
"selected_minimum_margin": 0.1,
|
||||
"max_hypotheses": 5
|
||||
},
|
||||
"prompt_groups": [
|
||||
{
|
||||
"prompt_set_id": "urban-static/v0",
|
||||
"captions": [
|
||||
"trash bin",
|
||||
"shopping cart",
|
||||
"bollard",
|
||||
"post",
|
||||
"concrete hemisphere",
|
||||
"traffic cone",
|
||||
"road sign",
|
||||
"temporary barrier"
|
||||
]
|
||||
},
|
||||
{
|
||||
"prompt_set_id": "urban-agents/v0",
|
||||
"captions": [
|
||||
"adult person",
|
||||
"child",
|
||||
"dog",
|
||||
"stroller",
|
||||
"kick scooter",
|
||||
"bicycle"
|
||||
]
|
||||
},
|
||||
{
|
||||
"prompt_set_id": "urban-vehicles/v0",
|
||||
"captions": ["car", "truck", "bus", "motorcycle"]
|
||||
}
|
||||
],
|
||||
"semantic_vocabulary_id": "missioncore.urban-object-semantics/v0",
|
||||
"risk_policy_id": "urban-object-risk-shadow/v0",
|
||||
"authority": {
|
||||
"ground_truth": false,
|
||||
"independent_truth": false,
|
||||
"candidate_accepted": false,
|
||||
"commands_enabled": false,
|
||||
"actuation_allowed": false,
|
||||
"navigation_or_safety_accepted": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
{
|
||||
"schema_version": "missioncore.rf-detr-risk-shadow-profile/v0",
|
||||
"profile_id": "rf-detr-large-coco-704-trt11-fp16-risk-shadow/v0",
|
||||
"provider_id": "triton-rf-detr-large-coco-risk-fp16-shadow/v0",
|
||||
"model": {
|
||||
"model_id": "rf_detr_large",
|
||||
"model_version": 1,
|
||||
"upstream_version": "1.9.4",
|
||||
"upstream_revision": "9b009fa928d6218320439803d1da01869a85c072",
|
||||
"checkpoint_sha256": "0f4e20e19a99c0f8a62b5685f57f6c8b5c371c59081feda6752a0561a79ccf38",
|
||||
"exported_onnx_sha256": "9c1948e56bbb6ff03349012b8bb334cacaf8ae480f22caa0704ee70de9a72300",
|
||||
"strongly_typed_fp16_onnx_sha256": "9015fcc1317f268ce866bed6b5a33132c24963e1502b02f145fa184e11de5ecb",
|
||||
"worker_006_rtx4090_tensorrt_11_engine_sha256": "986399ce706b7380472cf5e473232249fed6e628971d8007f6609e83128d46b8",
|
||||
"input": {
|
||||
"name": "input",
|
||||
"datatype": "FP32",
|
||||
"shape": [1, 3, 704, 704]
|
||||
},
|
||||
"outputs": [
|
||||
{"name": "dets", "datatype": "FP16", "shape": [1, 300, 4]},
|
||||
{"name": "labels", "datatype": "FP16", "shape": [1, 300, 91]}
|
||||
]
|
||||
},
|
||||
"preprocessing": {
|
||||
"source_raster": [800, 600],
|
||||
"source_color": "BGR",
|
||||
"model_color": "RGB",
|
||||
"valid_fov_fill_value": 114,
|
||||
"resize": "704x704-bilinear-antialias-false",
|
||||
"normalization_mean": [0.485, 0.456, 0.406],
|
||||
"normalization_std": [0.229, 0.224, 0.225]
|
||||
},
|
||||
"emission": {
|
||||
"single_inference_per_source_frame": true,
|
||||
"minimum_score": 0.25,
|
||||
"maximum_topk_query_class_pairs": 300,
|
||||
"behavior_relevant_classes": [
|
||||
"person",
|
||||
"bicycle",
|
||||
"car",
|
||||
"motorcycle",
|
||||
"bus",
|
||||
"truck",
|
||||
"bird",
|
||||
"cat",
|
||||
"dog",
|
||||
"horse",
|
||||
"sheep",
|
||||
"cow",
|
||||
"elephant",
|
||||
"bear",
|
||||
"zebra",
|
||||
"giraffe",
|
||||
"skateboard"
|
||||
],
|
||||
"geometry_owns_static_occupancy": true,
|
||||
"unlisted_semantic_classes_emitted": false,
|
||||
"minimum_box_area_pixels": 64,
|
||||
"maximum_box_area_fraction": 0.5,
|
||||
"minimum_valid_fov_fraction": 0.5,
|
||||
"require_center_inside_valid_fov": true
|
||||
},
|
||||
"queue": {
|
||||
"policy": "bounded-latest-wins",
|
||||
"capacity": 2
|
||||
},
|
||||
"status": {
|
||||
"tournament_finalist": true,
|
||||
"tensorrt_parity_passed": true,
|
||||
"detector_load_gate_passed": true,
|
||||
"integrated_world_state_gate_passed": false,
|
||||
"production_accepted": false
|
||||
},
|
||||
"authority": {
|
||||
"ground_truth": false,
|
||||
"candidate_accepted": false,
|
||||
"commands_enabled": false,
|
||||
"actuation_allowed": false,
|
||||
"navigation_or_safety_accepted": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"schema_version": "missioncore.yolox-detector-profile/v2",
|
||||
"profile_id": "yolox-s-raw-kb4-all-coco-shadow/v2",
|
||||
"provider_id": "triton-yolox-s-raw-kb4-all-coco/v2",
|
||||
"model": {
|
||||
"model_id": "yolox_s:1",
|
||||
"model_sha256": "c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063",
|
||||
"dataset_vocabulary": "COCO-80",
|
||||
"additional_inference_passes": 0
|
||||
},
|
||||
"preprocess": {
|
||||
"source_width": 800,
|
||||
"source_height": 600,
|
||||
"input_width": 640,
|
||||
"input_height": 640,
|
||||
"fill_value": 114,
|
||||
"valid_fov_mask_sha256": "a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"
|
||||
},
|
||||
"postprocess": {
|
||||
"minimum_score": 0.5,
|
||||
"nms_iou_threshold": 0.45,
|
||||
"target_class_ids": [
|
||||
0, 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
|
||||
],
|
||||
"minimum_box_area_pixels": 64.0,
|
||||
"maximum_box_area_fraction": 0.5,
|
||||
"minimum_valid_fov_fraction": 0.5,
|
||||
"require_center_inside_valid_fov": true
|
||||
},
|
||||
"class_policy": {
|
||||
"emission": "all-qualified-coco-classes",
|
||||
"behavior_authority": "separate-risk-policy-only",
|
||||
"risk_groups": {
|
||||
"person": ["person"],
|
||||
"animal": [
|
||||
"bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear",
|
||||
"zebra", "giraffe"
|
||||
],
|
||||
"light-road-user": ["bicycle", "motorcycle", "skateboard"],
|
||||
"vehicle": ["car", "bus", "truck"]
|
||||
},
|
||||
"unmapped_label_response": "advisory-only",
|
||||
"unknown_moving_response": "conservative-risk",
|
||||
"unknown_stationary_response": "route-around"
|
||||
},
|
||||
"authority": {
|
||||
"ground_truth": false,
|
||||
"candidate_accepted": false,
|
||||
"commands_enabled": false,
|
||||
"actuation_allowed": false,
|
||||
"navigation_or_safety_accepted": false
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,48 @@ device protocol, transport, identity, or command state.
|
||||
12. A plugin UI contribution is not ownership of Mission Core navigation,
|
||||
scene layout, persistence, or global application state.
|
||||
|
||||
## Object understanding projection
|
||||
|
||||
Mission Core also has one bounded, executable perception vocabulary profile:
|
||||
`missioncore.urban-object-semantics/v0`. It is referenced by the separate
|
||||
`missioncore.object-understanding/v1` document and remains experimental. This
|
||||
is a versioned projection over an existing `ObstacleObservation`; it is not a
|
||||
second occupancy model, a long-term identity store, or a runtime ontology
|
||||
service.
|
||||
|
||||
| Term | Meaning |
|
||||
|---|---|
|
||||
| `ObjectUnderstanding` | A source/frame-bound composition of immutable geometry, ranked semantic hypotheses, explicit semantic resolution, object state, advisory risk and evidence provenance. |
|
||||
| `SemanticHypothesis` | One provider label mapped to a canonical class candidate with confidence, rank and evidence IDs. It is not class truth. |
|
||||
| `SemanticDecision` | An explicit `unresolved`, `selected`, `ambiguous` or `conflict` result over the ranked hypotheses. |
|
||||
| `ObjectStateEstimate` | Observed motion plus a separately qualified agency claim. A class prior is carried as a prior and never rewritten as observed motion. |
|
||||
| `AdvisoryRiskAssessment` | Evidence-qualified risk level and suggested response for a future policy consumer. It never grants planner, navigation, safety or actuation authority. |
|
||||
| `EvidenceProvenance` | The exact provider/model/revision/preprocess/prompt-set identity and source-frame binding supporting a claim. |
|
||||
|
||||
The v0 class profile is intentionally shallow. It covers the current named
|
||||
consumers: human/adult/child, animal/dog, vehicle subtypes, passive wheeled
|
||||
objects, common small static street obstacles, terrain discontinuities and
|
||||
natural debris. Unknown and group-level classes remain valid outcomes; the
|
||||
profile does not require a fragile leaf-class decision.
|
||||
|
||||
Mandatory object-perception non-conflation rules:
|
||||
|
||||
1. Occupancy identity is owned by `ObstacleObservation`, not by a semantic
|
||||
class, detector label or provider tracklet.
|
||||
2. A missing or unresolved semantic class never means free space and never
|
||||
removes an occupied obstacle.
|
||||
3. A raw provider label is not a canonical class; a ranked class hypothesis is
|
||||
not a selected class; a selected class is not independent truth.
|
||||
4. Observed motion is not a class motion prior. In particular, a currently
|
||||
stationary vehicle may retain a self-propelled agency prior.
|
||||
5. Semantic risk is advisory. `reduce-speed`, `yield`, `stop` and
|
||||
`route-around` values describe policy hints, not issued commands.
|
||||
6. Vehicle-dependent traversability is not encoded as an intrinsic property
|
||||
of a curb, step, hemisphere or other obstacle class.
|
||||
7. The class-free M4.8 obstacle-quality truth remains class-free. Semantic
|
||||
evaluation requires a separate sealed label generation and cannot rewrite
|
||||
an existing M4.8 result.
|
||||
|
||||
## Deferred compatibility work
|
||||
|
||||
The following meanings are intentionally unresolved in v0alpha2. They must be
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# M48S fixed-class detector tournament и Worker deployment gate
|
||||
|
||||
Дата: 2026-08-25
|
||||
Режим: experimental shadow
|
||||
Worker: `worker-006`, NVIDIA GeForce RTX 4090
|
||||
Production acceptance: **нет**
|
||||
|
||||
## Решение
|
||||
|
||||
RF-DETR-L выиграл bounded-турнир, был экспортирован в ONNX, преобразован в
|
||||
strongly typed FP16 graph, собран TensorRT 11 и проверен через изолированный
|
||||
Triton. Detector-only нагрузочный gate длиной 30 минут принят. Кандидат готов к
|
||||
следующему shadow-gate внутри полного reference graph, но не получил
|
||||
navigation, safety, command или actuation authority.
|
||||
|
||||
Production critical path не включает Mask Grounding DINO, SAM 2 или OpenCLIP.
|
||||
Статические неизвестные объекты остаются ответственностью geometry/occupancy и
|
||||
объезжаются без расхода detector inference на их название. Один fixed-class
|
||||
проход камеры используется только для поведенчески значимых классов.
|
||||
|
||||
## Поведенческая граница
|
||||
|
||||
RF-DETR shadow provider выпускает только:
|
||||
|
||||
- `person`;
|
||||
- `bicycle`, `motorcycle`, `skateboard`;
|
||||
- `car`, `bus`, `truck`;
|
||||
- COCO animal classes, включая `dog`.
|
||||
|
||||
Урны, столбы, полусферы, бордюры и прочие статические препятствия не обязаны
|
||||
получать семантическое имя: их наличие и геометрия принадлежат class-free
|
||||
occupancy. Неизвестный движущийся объект остаётся conservative. Отдельного
|
||||
COCO-класса `scooter` нет, поэтому самокат пока нельзя считать надёжно
|
||||
классифицированным: до отдельного admission gate он остаётся geometry/motion
|
||||
hazard, а не безопасным отрицанием.
|
||||
|
||||
## Турнир на immutable 11-frame slice
|
||||
|
||||
Все профили выполняли один inference pass на кадр; ручная проверка не объявлена
|
||||
ground truth.
|
||||
|
||||
| Профиль | Core capacity | p95 | Собака на frame 253 | Решение |
|
||||
|---|---:|---:|---|---|
|
||||
| YOLOX-S all-COCO/v2 | 39,136 FPS | 38,267 мс | нет | regression baseline |
|
||||
| D-FINE-S COCO FP16 | 31,100 FPS | 42,945 мс | нет при 0,25 и 0,5 | отклонён |
|
||||
| RF-DETR-L COCO FP16 | 44,786 FPS | 32,588 мс | да, score 0,740723 | finalist |
|
||||
|
||||
D-FINE также давал заметные semantic confusions: собака как `skateboard`, корпус
|
||||
сканера как `surfboard`, дублирующиеся risk-labels на одном объекте. RF-DETR на
|
||||
этом slice дал более чистые person/vehicle labels и корректную собаку.
|
||||
|
||||
Immutable tournament result:
|
||||
`m48s-fixed-detector-tournament-0e61d75e6dc575d53e4bb98772a41d240fe627ad642de5178beb1154636e1299`.
|
||||
|
||||
## TensorRT/Triton квалификация
|
||||
|
||||
Закреплены следующие identities:
|
||||
|
||||
- upstream RF-DETR revision: `9b009fa928d6218320439803d1da01869a85c072`;
|
||||
- checkpoint SHA-256: `0f4e20e19a99c0f8a62b5685f57f6c8b5c371c59081feda6752a0561a79ccf38`;
|
||||
- exported ONNX SHA-256: `9c1948e56bbb6ff03349012b8bb334cacaf8ae480f22caa0704ee70de9a72300`;
|
||||
- strongly typed FP16 ONNX SHA-256: `9015fcc1317f268ce866bed6b5a33132c24963e1502b02f145fa184e11de5ecb`;
|
||||
- Worker 006 TensorRT engine SHA-256: `986399ce706b7380472cf5e473232249fed6e628971d8007f6609e83128d46b8`.
|
||||
|
||||
TensorRT parity на frame 253:
|
||||
|
||||
- PyTorch dog score: 0,740723;
|
||||
- TensorRT dog score: 0,741674;
|
||||
- абсолютная разница score: 0,000951;
|
||||
- box IoU: 0,990117;
|
||||
- class counts при threshold 0,5 совпадают точно: 57 `car`, 8 `truck`,
|
||||
6 `person`, 1 `dog`, 1 `fire hydrant`.
|
||||
|
||||
100-iteration Triton benchmark: 42,496 FPS end-to-end; mean 23,531 мс; p95
|
||||
34,156 мс. Production Triton во время проверки не изменялся: использовался
|
||||
отдельный безпортовый Triton-контейнер в namespace эксперимента.
|
||||
|
||||
## 30-минутный source-paced gate
|
||||
|
||||
Источник: RAVNOVES00, SHA-256
|
||||
`cadd1696ff000904eb78633a0a8418104b8024f178b91f3421789021ccb160e8`,
|
||||
10,0039 FPS. Durable background services на Worker оставались включёнными.
|
||||
|
||||
| Метрика | Результат | Gate |
|
||||
|---|---:|---:|
|
||||
| Время | 1800,020 с | ≥ 1800 с |
|
||||
| Кадры | 18 008 produced / 18 008 consumed | без потерь |
|
||||
| Effective FPS | 10,004 | ≥ 9,5 |
|
||||
| Detector end-to-end p95 | 32,415 мс | наблюдение |
|
||||
| Detector completion age p95 | 40,621 мс | ≤ 175 мс |
|
||||
| Queue | max depth 1/2, replacements 0 | bounded latest-wins |
|
||||
| GPU utilization | mean 51,408%, p95 55%, max 65% | без sustained 100% |
|
||||
| Worker VRAM | mean 9542,7 MiB, max 9556 MiB | ≤ 20 GiB |
|
||||
| Ошибки | 0 | 0 |
|
||||
|
||||
Все восемь автоматических load checks приняты. Это detector-only gate, поэтому
|
||||
он не доказывает p95 полного world state, качество tracker association или
|
||||
корректность risk-policy.
|
||||
|
||||
Immutable deployment result:
|
||||
`m48s-rf-detr-deployment-gate-2feb9e1b12a5588951ad35d63bf23cf6bdd579d54b5329d46d7696f88c444547`.
|
||||
|
||||
## Реализация
|
||||
|
||||
- `src/k1link/perception/rf_detr_object_detector.py` — pinned preprocessing,
|
||||
Triton V2 binary HTTP backend, FP16 output validation, fixed risk-class
|
||||
qualification и fail-closed FOV/area gates.
|
||||
- `src/k1link/perception/detector.py` — `RfDetrShadowDetectorProvider`, один
|
||||
inference pass и semantic hints без authority.
|
||||
- `config/perception/rf-detr-large-risk-shadow-v0.json` — неизменяемый профиль,
|
||||
threshold 0,25, bounded latest-wins queue capacity 2, geometry-owned static
|
||||
occupancy.
|
||||
- `experiments/perception/worker/` — воспроизводимые export/build/Triton
|
||||
declarations.
|
||||
- `experiments/perception/run_m48s_rf_detr_load_worker.py` — source-paced
|
||||
concurrent-load gate с GPU, queue и Triton accounting.
|
||||
- `experiments/perception/seal_m48s_rf_detr_deployment.py` — content-addressed
|
||||
immutable seal с false authority.
|
||||
|
||||
## Следующий gate
|
||||
|
||||
Подключить этот provider в полный reference graph вместе с существующими
|
||||
geometry observations, tracker и advisory risk-policy. На том же записанном
|
||||
источнике и при сохранённых Worker services требуется:
|
||||
|
||||
1. world-state p95 не более 175 мс;
|
||||
2. не менее 9,5 source FPS, bounded latest-wins без неучтённых потерь;
|
||||
3. стабильные track identities и conservative unknown-moving handling;
|
||||
4. раздельные реакции на person/animal/light-road-user/vehicle;
|
||||
5. отсутствие navigation/safety/command authority до отдельного acceptance.
|
||||
|
||||
Только после этого можно решать вопрос о замене текущего production detector.
|
||||
Текущий результат разрешает reference-graph shadow, а не production switch.
|
||||
@@ -0,0 +1,84 @@
|
||||
# M48S Mask Grounding DINO shadow report
|
||||
|
||||
Date: 2026-08-25
|
||||
Status: completed shadow; rejected for semantic and navigation authority
|
||||
|
||||
## Question
|
||||
|
||||
Can a ready open-vocabulary instance-segmentation model name the urban obstacles
|
||||
already discovered by Mission Core geometry, without a manual annotation program?
|
||||
|
||||
## Frozen setup
|
||||
|
||||
- Source: the same 11 raw 800 × 600 KB4 frames and 73 occupied-geometry
|
||||
observations admitted by the M4.8 semantic slice.
|
||||
- Model: NVIDIA TAO Mask Grounding DINO Swin-Tiny research deployable v2.0,
|
||||
ONNX SHA-256
|
||||
`4e8b066cf7782ae6b4269255b861c205f4b07b33ff752e5eaf297c42ecfb2f5e`.
|
||||
- Runtime: TAO 7.0.1 deploy container on the Worker RTX 4090; generated FP16
|
||||
TensorRT engine SHA-256
|
||||
`1d127107d15f18dcddafd7345a0a766acfee204d63c5ab697eaabada2c7afcd2`.
|
||||
- Prompts: separate static, agent, and vehicle groups. Adult, child, and dog were
|
||||
also rerun as three independent single-class probes on frames 253 and 1228.
|
||||
- Binding: masks were clustered at IoU ≥ 0.90 and bound only through exact
|
||||
projected LiDAR point identities. A mask had to cover ≥ 50% of one obstacle's
|
||||
projected points and ≤ 25% of every secondary obstacle.
|
||||
- Authority: false for ground truth, acceptance, commands, actuation, navigation,
|
||||
and safety throughout.
|
||||
|
||||
The model choice and TensorRT path follow NVIDIA's official
|
||||
[Mask Grounding DINO documentation](https://docs.nvidia.com/tao/tao-toolkit/latest/text/cv_finetuning/pytorch/instance_segmentation/mask_grounding_dino.html)
|
||||
and
|
||||
[TAO Deploy documentation](https://docs.nvidia.com/tao/tao-toolkit/latest/text/tao_deploy/mask_grounding_dino.html).
|
||||
The checkpoint is the official
|
||||
[NGC research deployable v2.0](https://catalog.ngc.nvidia.com/orgs/nvidia/tao/models/pretrained_mask_grounding_dino_v2/mask_grounding_dino_swin_tiny_research_deployable_v2.0/version-history).
|
||||
No commercial-model license was accepted on the user's behalf.
|
||||
|
||||
## Result
|
||||
|
||||
| Measure | Result |
|
||||
|---|---:|
|
||||
| Frames completed | 11 / 11 |
|
||||
| Geometry obstacles retained | 73 |
|
||||
| Raw mask detections | 25 |
|
||||
| Pixel-instance clusters after caption deduplication | 7 |
|
||||
| Instances exclusively bound to one LiDAR obstacle | 4 |
|
||||
| Instances covering multiple LiDAR obstacles | 2 |
|
||||
| Instances without occupied-geometry support | 1 |
|
||||
| Final named instances | 0 |
|
||||
| Adult single-class detections | 0 |
|
||||
| Child single-class detections | 0 |
|
||||
| Dog single-class detections | 0 |
|
||||
|
||||
The mask head was useful: four instances had strong exclusive LiDAR support.
|
||||
The language classification was not. The same near-identical mask was repeatedly
|
||||
named `trash bin`, `shopping cart`, `road sign`, and `truck`. After the required
|
||||
confidence margin, six of seven instances were ambiguous and one unresolved.
|
||||
|
||||
The full evidence result is
|
||||
`m48s-mask-grounding-dino-shadow-b0a37f265223b4138754f76d5d7b8d17e7c4f5395481990f169fccc1645baba8`.
|
||||
|
||||
## Decision
|
||||
|
||||
This research checkpoint is rejected as an object-name provider and is not a
|
||||
candidate for navigation or safety authority. The zero-result single-class probes
|
||||
show that prompt competition was not the reason adult, child, and dog were missed.
|
||||
|
||||
The next candidate separates the two jobs:
|
||||
|
||||
1. LiDAR geometry supplies point/box prompts to a promptable mask segmenter.
|
||||
2. An independent zero-shot image encoder ranks canonical Mission Core classes on
|
||||
the geometry-owned crop and masked crop.
|
||||
3. The name stays unresolved unless the two views agree and the class margin passes.
|
||||
4. Unknown objects remain occupied and route-around; no physical traversability
|
||||
model is introduced.
|
||||
|
||||
SAM 2 officially supports point and box prompts through its
|
||||
[image predictor](https://github.com/facebookresearch/sam2/blob/main/sam2/sam2_image_predictor.py).
|
||||
OpenCLIP is the current open implementation candidate for independent zero-shot
|
||||
crop classification; its official repository is
|
||||
[mlfoundations/open_clip](https://github.com/mlfoundations/open_clip).
|
||||
|
||||
No manual annotation program is authorized by this result. A small two-reviewer
|
||||
truth slice remains necessary only to score candidates; it is evidence QA, not a
|
||||
training-dataset commitment.
|
||||
@@ -0,0 +1,62 @@
|
||||
# M48S YOLOX-S all-COCO shadow report
|
||||
|
||||
Date: 2026-08-25
|
||||
Status: executable shadow completed; full-load promotion gate open
|
||||
|
||||
## Why six classes were previously emitted
|
||||
|
||||
The accepted `triton-yolox-s-raw-kb4/v1` provider was deliberately frozen on
|
||||
COCO ids `0, 1, 2, 3, 5, 7`: person, bicycle, car, motorcycle, bus and truck.
|
||||
That was a bounded detector qualification and reproducibility boundary, not an
|
||||
inference optimization. YOLOX-S already returns an `[1, 8400, 85]` tensor with
|
||||
all 80 COCO class scores. The six-class filter ran after the single inference.
|
||||
|
||||
The old provider, hashes and M4 replay results remain unchanged. The new
|
||||
`triton-yolox-s-raw-kb4-all-coco/v2` provider uses the same model, tensor,
|
||||
preprocess, thresholds and valid-FOV gates, but emits every qualified COCO class.
|
||||
|
||||
## Worker comparison
|
||||
|
||||
Both profiles were applied to the exact same tensor response for each of the 11
|
||||
M48S frames. The client shared the Worker's `mission-core-compute_default`
|
||||
network with Triton, avoiding host-NAT tensor transport.
|
||||
|
||||
| Measure | Frozen six classes | All COCO-80 |
|
||||
|---|---:|---:|
|
||||
| Inference passes per frame | 1 | 1, shared |
|
||||
| Detections | 44 | 45 |
|
||||
| Postprocess mean, 220 balanced iterations | 6.430 ms | 6.725 ms |
|
||||
| Postprocess p50 | 5.671 ms | 5.679 ms |
|
||||
| Postprocess p95 | 11.013 ms | 11.592 ms |
|
||||
|
||||
The measured mean postprocess difference was `0.295 ms`; the p50 difference was
|
||||
`0.008 ms`. The combined preprocess + inference + all-COCO postprocess capacity
|
||||
was `39.136 FPS` on this bounded slice. This is a capacity diagnostic, not a
|
||||
full-route load acceptance.
|
||||
|
||||
The only newly emitted detection was `handbag` on frame 253, correctly covering
|
||||
the bag carried by the visible person. The class counts were 36 car, five truck,
|
||||
three person and one handbag. The visible dog on frame 253 was not detected.
|
||||
Removing the filter therefore exposes all model answers at negligible compute
|
||||
cost, but does not repair classes the model fails to recognize.
|
||||
|
||||
Immutable result:
|
||||
`m48s-yolox-all-coco-shadow-7dbe6043b3fc12c7ddb162f609f883d86b34a4f2dd3785a632795f257e192d06`.
|
||||
|
||||
## Policy boundary
|
||||
|
||||
All qualified COCO labels are now available to downstream consumers. Emission
|
||||
does not grant every class behavioral authority:
|
||||
|
||||
- person, animal, light road user and vehicle labels may enter a separately
|
||||
versioned risk policy after qualification;
|
||||
- other labels remain advisory diagnostics;
|
||||
- geometry owns occupancy for every object;
|
||||
- unknown moving objects retain conservative risk;
|
||||
- unknown stationary objects remain route-around;
|
||||
- commands, actuation, navigation and safety authority remain false.
|
||||
|
||||
The next gate is the full recorded source under representative concurrent Worker
|
||||
load. It must compare source delivery, detector FPS, p95 latency, queue depth,
|
||||
drops, GPU utilization and VRAM against the frozen six-class baseline before v2
|
||||
can replace v1 in the production assembly.
|
||||
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Convert the pinned RF-DETR ONNX graph to a strongly typed FP16 graph."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
import onnx # type: ignore[import-not-found]
|
||||
from onnx import TensorProto
|
||||
from onnxconverter_common import float16 # type: ignore[import-not-found]
|
||||
|
||||
SCHEMA_VERSION: Final = "missioncore.m48s-rf-detr-onnx-fp16-conversion/v3"
|
||||
FALSE_AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--input", type=Path, required=True)
|
||||
parser.add_argument("--expected-input-sha256", required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
arguments = parser.parse_args()
|
||||
|
||||
source = arguments.input.resolve(strict=True)
|
||||
source_sha256 = sha256_path(source)
|
||||
if source_sha256 != arguments.expected_input_sha256:
|
||||
raise RuntimeError("source ONNX SHA-256 does not match the export manifest")
|
||||
output = arguments.output.absolute()
|
||||
manifest = arguments.manifest.absolute()
|
||||
if output.exists() or manifest.exists():
|
||||
raise RuntimeError("FP16 ONNX output or manifest already exists")
|
||||
|
||||
started_utc_ns = time.time_ns()
|
||||
graph = onnx.load(str(source))
|
||||
converted = float16.convert_float_to_float16(
|
||||
graph,
|
||||
keep_io_types=False,
|
||||
disable_shape_infer=False,
|
||||
)
|
||||
retargeted_casts = _retarget_float_casts_to_fp16(converted)
|
||||
_insert_fp32_input_cast(converted)
|
||||
onnx.checker.check_model(converted)
|
||||
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
onnx.save(converted, str(output))
|
||||
verified = onnx.load(str(output), load_external_data=False)
|
||||
onnx.checker.check_model(verified)
|
||||
input_types = {value.name: value.type.tensor_type.elem_type for value in verified.graph.input}
|
||||
output_types = {
|
||||
value.name: value.type.tensor_type.elem_type for value in verified.graph.output
|
||||
}
|
||||
if input_types != {"input": TensorProto.FLOAT}:
|
||||
raise RuntimeError(f"FP16 ONNX input boundary is not FLOAT: {input_types}")
|
||||
if output_types != {"dets": TensorProto.FLOAT16, "labels": TensorProto.FLOAT16}:
|
||||
raise RuntimeError(f"FP16 ONNX outputs are not FLOAT16: {output_types}")
|
||||
initializer_counts = _initializer_type_counts(verified)
|
||||
if initializer_counts.get("FLOAT16", 0) == 0:
|
||||
raise RuntimeError("FP16 ONNX has no FLOAT16 initializers")
|
||||
document = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"profile_id": "rf-detr-large-coco-704-trt11-fp16/v0",
|
||||
"source_onnx_sha256": source_sha256,
|
||||
"output_onnx_sha256": sha256_path(output),
|
||||
"output_size_bytes": output.stat().st_size,
|
||||
"boundary_types": {"inputs": input_types, "outputs": output_types},
|
||||
"initializer_type_counts": initializer_counts,
|
||||
"float_casts_retargeted_to_fp16": retargeted_casts,
|
||||
"started_utc_ns": started_utc_ns,
|
||||
"completed_utc_ns": time.time_ns(),
|
||||
"completed": True,
|
||||
"authority": FALSE_AUTHORITY,
|
||||
}
|
||||
manifest.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
manifest.write_bytes(canonical_json(document) + b"\n")
|
||||
print(output)
|
||||
print(json.dumps(document, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _initializer_type_counts(graph: Any) -> dict[str, int]:
|
||||
counts: dict[str, int] = {}
|
||||
for initializer in graph.graph.initializer:
|
||||
name = TensorProto.DataType.Name(initializer.data_type)
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
return dict(sorted(counts.items()))
|
||||
|
||||
|
||||
def _insert_fp32_input_cast(graph: Any) -> None:
|
||||
"""Keep a conventional FP32 client boundary before the strongly typed FP16 graph."""
|
||||
|
||||
input_value = next((item for item in graph.graph.input if item.name == "input"), None)
|
||||
if input_value is None:
|
||||
raise RuntimeError("RF-DETR graph has no input tensor named 'input'")
|
||||
if input_value.type.tensor_type.elem_type != TensorProto.FLOAT16:
|
||||
raise RuntimeError("RF-DETR converted input is not FLOAT16 before boundary adaptation")
|
||||
cast_output = "missioncore_input_fp16"
|
||||
for node in graph.graph.node:
|
||||
for index, name in enumerate(node.input):
|
||||
if name == "input":
|
||||
node.input[index] = cast_output
|
||||
cast = onnx.helper.make_node(
|
||||
"Cast",
|
||||
inputs=["input"],
|
||||
outputs=[cast_output],
|
||||
name="missioncore_input_fp32_to_fp16",
|
||||
to=TensorProto.FLOAT16,
|
||||
)
|
||||
graph.graph.node.insert(0, cast)
|
||||
input_value.type.tensor_type.elem_type = TensorProto.FLOAT
|
||||
|
||||
|
||||
def _retarget_float_casts_to_fp16(graph: Any) -> int:
|
||||
"""Retarget explicit PyTorch FLOAT casts that would re-expand an FP16 data path."""
|
||||
|
||||
count = 0
|
||||
for node in graph.graph.node:
|
||||
if node.op_type != "Cast":
|
||||
continue
|
||||
for attribute in node.attribute:
|
||||
if attribute.name == "to" and attribute.i == TensorProto.FLOAT:
|
||||
attribute.i = TensorProto.FLOAT16
|
||||
count += 1
|
||||
if count == 0:
|
||||
raise RuntimeError("RF-DETR graph has no FLOAT casts to retarget")
|
||||
return count
|
||||
|
||||
|
||||
def sha256_path(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export the pinned M48S RF-DETR finalist to a static ONNX artifact."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
import onnx # type: ignore[import-not-found]
|
||||
|
||||
SCHEMA_VERSION: Final = "missioncore.m48s-rf-detr-onnx-export/v0"
|
||||
FALSE_AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--checkpoint", type=Path, required=True)
|
||||
parser.add_argument("--expected-checkpoint-sha256", required=True)
|
||||
parser.add_argument("--output-root", type=Path, required=True)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
parser.add_argument("--upstream-revision", required=True)
|
||||
arguments = parser.parse_args()
|
||||
|
||||
checkpoint = arguments.checkpoint.resolve(strict=True)
|
||||
checkpoint_sha256 = sha256_path(checkpoint)
|
||||
if checkpoint_sha256 != arguments.expected_checkpoint_sha256:
|
||||
raise RuntimeError("checkpoint SHA-256 does not match the pinned finalist")
|
||||
output_root = arguments.output_root.absolute()
|
||||
manifest_path = arguments.manifest.absolute()
|
||||
if output_root.exists():
|
||||
raise RuntimeError("ONNX output root already exists")
|
||||
if manifest_path.exists():
|
||||
raise RuntimeError("ONNX export manifest already exists")
|
||||
|
||||
from rfdetr import RFDETRLarge # type: ignore[import-not-found]
|
||||
|
||||
started_utc_ns = time.time_ns()
|
||||
model = RFDETRLarge(pretrain_weights=str(checkpoint))
|
||||
exported_path = Path(
|
||||
model.export(
|
||||
output_dir=str(output_root),
|
||||
format="onnx",
|
||||
shape=(704, 704),
|
||||
batch_size=1,
|
||||
dynamic_batch=False,
|
||||
opset_version=17,
|
||||
verbose=False,
|
||||
notes={
|
||||
"missioncore_profile_id": "rf-detr-large-coco-704-fp16/v0",
|
||||
"upstream_revision": arguments.upstream_revision,
|
||||
"checkpoint_sha256": checkpoint_sha256,
|
||||
"authority": FALSE_AUTHORITY,
|
||||
},
|
||||
)
|
||||
).resolve(strict=True)
|
||||
graph = onnx.load(str(exported_path), load_external_data=False)
|
||||
onnx.checker.check_model(graph)
|
||||
inputs = [_tensor_description(value) for value in graph.graph.input]
|
||||
outputs = [_tensor_description(value) for value in graph.graph.output]
|
||||
expected_input = [{"name": "input", "element_type": 1, "shape": [1, 3, 704, 704]}]
|
||||
if inputs != expected_input:
|
||||
raise RuntimeError(f"unexpected RF-DETR ONNX input contract: {inputs}")
|
||||
if [item["name"] for item in outputs] != ["dets", "labels"]:
|
||||
raise RuntimeError(f"unexpected RF-DETR ONNX outputs: {outputs}")
|
||||
|
||||
document = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"profile_id": "rf-detr-large-coco-704-fp16/v0",
|
||||
"provider_id": "shadow-rf-detr-large-coco-onnx/v0",
|
||||
"upstream_revision": arguments.upstream_revision,
|
||||
"checkpoint_sha256": checkpoint_sha256,
|
||||
"onnx": {
|
||||
"path": str(exported_path),
|
||||
"sha256": sha256_path(exported_path),
|
||||
"size_bytes": exported_path.stat().st_size,
|
||||
"opset_imports": [
|
||||
{"domain": item.domain, "version": item.version}
|
||||
for item in graph.opset_import
|
||||
],
|
||||
"inputs": inputs,
|
||||
"outputs": outputs,
|
||||
},
|
||||
"started_utc_ns": started_utc_ns,
|
||||
"completed_utc_ns": time.time_ns(),
|
||||
"completed": True,
|
||||
"authority": FALSE_AUTHORITY,
|
||||
}
|
||||
manifest_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
manifest_path.write_bytes(canonical_json(document) + b"\n")
|
||||
print(exported_path)
|
||||
print(json.dumps(document["onnx"], indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _tensor_description(value: Any) -> dict[str, object]:
|
||||
tensor = value.type.tensor_type
|
||||
return {
|
||||
"name": value.name,
|
||||
"element_type": tensor.elem_type,
|
||||
"shape": [_dimension_value(item) for item in tensor.shape.dim],
|
||||
}
|
||||
|
||||
|
||||
def _dimension_value(value: Any) -> int | str | None:
|
||||
if value.HasField("dim_value"):
|
||||
return int(value.dim_value)
|
||||
if value.HasField("dim_param"):
|
||||
return str(value.dim_param)
|
||||
return None
|
||||
|
||||
|
||||
def sha256_path(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
def _names(values: Iterable[dict[str, object]]) -> tuple[object, ...]:
|
||||
"""Keep static analyzers honest when ONNX collections are inspected in tests."""
|
||||
|
||||
return tuple(value.get("name") for value in values)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Materialize geometry-owned raw-KB4 crops for the M48S Worker shadow."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.perception.baseline import BASELINE_RECORDED_JOB_ID
|
||||
from k1link.perception.contracts import SourceEnvelope
|
||||
from k1link.perception.detector_replay_result import (
|
||||
read_detector_replay_result,
|
||||
require_m4_detector_replay_acceptance,
|
||||
)
|
||||
from k1link.perception.geometry import (
|
||||
DEFAULT_GEOMETRY_PROFILE_PATH,
|
||||
Ravnoves00GeometryAssociationProvider,
|
||||
RecordedGeometryStore,
|
||||
load_geometry_profile,
|
||||
)
|
||||
from k1link.perception.geometry_semantic_roi import (
|
||||
GeometrySemanticRoiProfile,
|
||||
build_geometry_semantic_rois,
|
||||
materialize_geometry_semantic_crop,
|
||||
)
|
||||
from k1link.perception.graph_validation import validate_observations
|
||||
from k1link.perception.providers import SourcePacket
|
||||
from k1link.perception.recorded_source import RECORDED_SOURCE_PACK_ID, RecordedFrameReference
|
||||
|
||||
FRAME_INDICES = (121, 131, 253, 275, 443, 463, 1094, 1228, 1454, 1856, 2386)
|
||||
DETECTOR_RESULT_ID = (
|
||||
"m4-detector-replay-11f83f2e0b81758ac2a5a5fc54e9d293b501678df5f6ef97b5c6069ba08605c5"
|
||||
)
|
||||
SCHEMA_VERSION = "missioncore.m48s-geometry-semantic-roi-package/v0"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
runtime = repository / ".runtime/compute-experiments/m48s-semantic-shadow"
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--repository-root", type=Path, default=repository)
|
||||
parser.add_argument(
|
||||
"--input-root",
|
||||
type=Path,
|
||||
default=runtime / "raw-11-valid-fov-fill-v1",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-root",
|
||||
type=Path,
|
||||
default=runtime / "geometry-rois-v1",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
root = arguments.repository_root.resolve(strict=True)
|
||||
inputs = arguments.input_root.resolve(strict=True)
|
||||
output = arguments.output_root.expanduser().absolute()
|
||||
if output.exists():
|
||||
raise RuntimeError("geometry semantic ROI package already exists")
|
||||
|
||||
detector = read_detector_replay_result(root / ".runtime/worker-results" / DETECTOR_RESULT_ID)
|
||||
require_m4_detector_replay_acceptance(detector)
|
||||
by_sequence = {item.sequence: item for item in detector.frames}
|
||||
if any(index not in by_sequence for index in FRAME_INDICES):
|
||||
raise RuntimeError("geometry semantic frame escaped the accepted detector timeline")
|
||||
geometry_profile_path = root / DEFAULT_GEOMETRY_PROFILE_PATH
|
||||
geometry_profile = load_geometry_profile(geometry_profile_path)
|
||||
store = RecordedGeometryStore.from_repository(root, profile=geometry_profile)
|
||||
provider = Ravnoves00GeometryAssociationProvider(store=store)
|
||||
roi_profile = GeometrySemanticRoiProfile()
|
||||
|
||||
staging = output.parent / f".{output.name}.{uuid.uuid4().hex}.tmp"
|
||||
staging.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
try:
|
||||
input_destination = staging / "input"
|
||||
input_destination.mkdir(mode=0o700)
|
||||
frame_documents: list[dict[str, object]] = []
|
||||
artifacts: list[dict[str, object]] = []
|
||||
total_observations = 0
|
||||
total_rois = 0
|
||||
for frame_index in FRAME_INDICES:
|
||||
detector_frame = by_sequence[frame_index]
|
||||
if detector_frame.outcome != "completed":
|
||||
raise RuntimeError("accepted detector frame is incomplete")
|
||||
packet = _packet(detector_frame.envelope)
|
||||
observations = provider.associate(packet, ())
|
||||
validate_observations(packet, (), observations)
|
||||
frame = store.frame(packet)
|
||||
if frame is None:
|
||||
raise RuntimeError("selected geometry frame is unavailable")
|
||||
roi_frame = build_geometry_semantic_rois(
|
||||
frame=frame,
|
||||
observations=observations,
|
||||
profile=roi_profile,
|
||||
)
|
||||
source = inputs / f"frame-{frame_index:06d}.png"
|
||||
frame_rois: list[dict[str, object]] = []
|
||||
for roi in roi_frame.rois:
|
||||
destination = input_destination / roi.crop_name
|
||||
materialize_geometry_semantic_crop(
|
||||
image_path=source,
|
||||
roi=roi,
|
||||
destination=destination,
|
||||
)
|
||||
document = roi.to_dict()
|
||||
document["crop_sha256"] = _sha256(destination)
|
||||
document["crop_width"] = int(roi.crop_region.x_max - roi.crop_region.x_min)
|
||||
document["crop_height"] = int(roi.crop_region.y_max - roi.crop_region.y_min)
|
||||
frame_rois.append(document)
|
||||
artifacts.append(
|
||||
{
|
||||
"path": f"input/{roi.crop_name}",
|
||||
"sha256": document["crop_sha256"],
|
||||
}
|
||||
)
|
||||
frame_documents.append(
|
||||
{
|
||||
"frame_index": frame_index,
|
||||
"frame_id": detector_frame.envelope.frame_id,
|
||||
"source_image": source.name,
|
||||
"source_image_sha256": _sha256(source),
|
||||
"geometry_observation_count": len(observations),
|
||||
"roi_count": len(roi_frame.rois),
|
||||
"not_projected_observations": [
|
||||
item.to_dict() for item in roi_frame.not_projected_observations
|
||||
],
|
||||
"rois": frame_rois,
|
||||
}
|
||||
)
|
||||
total_observations += len(observations)
|
||||
total_rois += len(roi_frame.rois)
|
||||
identity = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"detector_result_id": detector.result_id,
|
||||
"geometry_profile_id": geometry_profile.profile_id,
|
||||
"geometry_profile_sha256": _sha256(geometry_profile_path),
|
||||
"roi_producer_sha256": _sha256(
|
||||
root / "src/k1link/perception/geometry_semantic_roi.py"
|
||||
),
|
||||
"frame_indices": list(FRAME_INDICES),
|
||||
"roi_profile": {
|
||||
"minimum_projected_points": roi_profile.minimum_projected_points,
|
||||
"minimum_crop_width": roi_profile.minimum_crop_width,
|
||||
"minimum_crop_height": roi_profile.minimum_crop_height,
|
||||
"padding_fraction": roi_profile.padding_fraction,
|
||||
"minimum_padding_pixels": roi_profile.minimum_padding_pixels,
|
||||
},
|
||||
"geometry_observation_count": total_observations,
|
||||
"roi_count": total_rois,
|
||||
"not_projected_observation_count": total_observations - total_rois,
|
||||
"frames": frame_documents,
|
||||
"artifacts": artifacts,
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
digest = hashlib.sha256(_canonical_json(identity)).hexdigest()
|
||||
manifest = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"package_id": f"m48s-geometry-semantic-rois-{digest}",
|
||||
"identity_sha256": digest,
|
||||
"identity": identity,
|
||||
}
|
||||
(staging / "manifest.json").write_bytes(_canonical_json(manifest) + b"\n")
|
||||
staging.rename(output)
|
||||
except Exception:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
raise
|
||||
print(json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _packet(envelope: SourceEnvelope) -> SourcePacket:
|
||||
image = RecordedFrameReference(BASELINE_RECORDED_JOB_ID, envelope.sequence)
|
||||
geometry = RecordedFrameReference(RECORDED_SOURCE_PACK_ID, envelope.sequence)
|
||||
return SourcePacket(
|
||||
envelope=envelope,
|
||||
image_payload=image,
|
||||
registered_point_increment_payload=geometry,
|
||||
pose_payload=geometry,
|
||||
)
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.resolve(strict=True).open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _false_authority() -> dict[str, bool]:
|
||||
return {
|
||||
"ground_truth": False,
|
||||
"independent_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate bounded prompt-group specs for Mask Grounding DINO Worker replay."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
PROMPT_SUFFIXES = {
|
||||
"urban-static/v0": "static",
|
||||
"urban-agents/v0": "agents",
|
||||
"urban-vehicles/v0": "vehicles",
|
||||
}
|
||||
AGENT_PROBES = {
|
||||
"adult": "adult person",
|
||||
"child": "child",
|
||||
"dog": "dog",
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--repository-root", type=Path, default=repository)
|
||||
parser.add_argument(
|
||||
"--output-root",
|
||||
type=Path,
|
||||
default=(
|
||||
repository
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow"
|
||||
/ "mask-grounding-dino-worker-specs-v0"
|
||||
),
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
root = arguments.repository_root.resolve(strict=True)
|
||||
output = arguments.output_root.expanduser().absolute()
|
||||
if output.exists():
|
||||
raise RuntimeError("Mask Grounding DINO Worker specs already exist")
|
||||
base = yaml.safe_load(
|
||||
(root / "config/perception/m48s-mask-grounding-dino-shadow-v0.yaml").read_text(
|
||||
"utf-8"
|
||||
)
|
||||
)
|
||||
profile = json.loads(
|
||||
(root / "config/perception/open-vocabulary-semantic-shadow-v0.json").read_text(
|
||||
"utf-8"
|
||||
)
|
||||
)
|
||||
if not isinstance(base, dict) or not isinstance(profile, dict):
|
||||
raise RuntimeError("M48S mask semantic source configs are incompatible")
|
||||
groups = profile.get("prompt_groups")
|
||||
if not isinstance(groups, list):
|
||||
raise RuntimeError("M48S semantic prompt groups are unavailable")
|
||||
output.mkdir(mode=0o700, parents=True)
|
||||
for raw_group in groups:
|
||||
if not isinstance(raw_group, dict):
|
||||
raise RuntimeError("M48S semantic prompt group is incompatible")
|
||||
prompt_id = raw_group.get("prompt_set_id")
|
||||
captions = raw_group.get("captions")
|
||||
if prompt_id not in PROMPT_SUFFIXES or not isinstance(captions, list):
|
||||
raise RuntimeError("M48S semantic prompt group escaped the bounded profile")
|
||||
suffix = PROMPT_SUFFIXES[prompt_id]
|
||||
spec = copy.deepcopy(base)
|
||||
spec["model_name"] = f"missioncore-m48s-mask-grounding-dino-{suffix}"
|
||||
spec["results_dir"] = f"/workspace/probe/results-{suffix}"
|
||||
spec["dataset"]["infer_data_sources"]["captions"] = captions
|
||||
spec["inference"]["results_dir"] = f"/workspace/probe/results-{suffix}"
|
||||
(output / f"mask-{suffix}.yaml").write_text(
|
||||
yaml.safe_dump(spec, sort_keys=False),
|
||||
"utf-8",
|
||||
)
|
||||
for suffix, caption in AGENT_PROBES.items():
|
||||
spec = copy.deepcopy(base)
|
||||
spec["model_name"] = f"missioncore-m48s-mask-grounding-dino-probe-{suffix}"
|
||||
spec["results_dir"] = f"/workspace/probe/results-{suffix}"
|
||||
spec["dataset"]["infer_data_sources"]["captions"] = [caption]
|
||||
spec["inference"]["results_dir"] = f"/workspace/probe/results-{suffix}"
|
||||
(output / f"mask-{suffix}.yaml").write_text(
|
||||
yaml.safe_dump(spec, sort_keys=False),
|
||||
"utf-8",
|
||||
)
|
||||
print(output)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,288 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare frozen road classes with all COCO classes on one YOLOX tensor pass."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from k1link.perception.yolox_object_detector import (
|
||||
ALL_COCO_YOLOX_CONFIG,
|
||||
COCO_CLASSES,
|
||||
FROZEN_YOLOX_CONFIG,
|
||||
YOLOX_MODEL_SHA256,
|
||||
TritonHttpInferenceBackend,
|
||||
YoloxPostprocessConfig,
|
||||
load_valid_fov_mask,
|
||||
postprocess_yolox,
|
||||
preprocess_raw_kb4,
|
||||
)
|
||||
|
||||
SCHEMA: Final = "missioncore.m48s-yolox-all-coco-shadow/v0"
|
||||
POSTPROCESS_BENCHMARK_ITERATIONS: Final = 20
|
||||
AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--input-root", type=Path, required=True)
|
||||
parser.add_argument("--valid-fov-mask", type=Path, required=True)
|
||||
parser.add_argument("--output-root", type=Path, required=True)
|
||||
parser.add_argument(
|
||||
"--triton-endpoint",
|
||||
default="http://host.docker.internal:8000",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
input_root = arguments.input_root.resolve(strict=True)
|
||||
images = tuple(sorted(input_root.glob("frame-*.jpg")))
|
||||
if len(images) != 11:
|
||||
raise RuntimeError("M48S all-COCO shadow requires the exact 11-frame slice")
|
||||
output_parent = arguments.output_root.expanduser().absolute()
|
||||
output_parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
mask = load_valid_fov_mask(arguments.valid_fov_mask)
|
||||
backend = TritonHttpInferenceBackend(arguments.triton_endpoint)
|
||||
rows = []
|
||||
totals: Counter[str] = Counter()
|
||||
timings: dict[str, list[float]] = {
|
||||
"decode_ms": [],
|
||||
"preprocess_ms": [],
|
||||
"inference_ms": [],
|
||||
"frozen_postprocess_ms": [],
|
||||
"all_coco_postprocess_ms": [],
|
||||
"all_coco_core_ms": [],
|
||||
}
|
||||
postprocess_benchmark: dict[str, list[float]] = {
|
||||
"frozen_ms": [],
|
||||
"all_coco_ms": [],
|
||||
}
|
||||
try:
|
||||
for image_path in images:
|
||||
started = time.perf_counter_ns()
|
||||
with Image.open(image_path) as opened:
|
||||
rgb = np.asarray(opened.convert("RGB"), dtype=np.uint8)
|
||||
bgr = np.ascontiguousarray(rgb[:, :, ::-1])
|
||||
decoded = time.perf_counter_ns()
|
||||
tensor = preprocess_raw_kb4(bgr, mask, config=ALL_COCO_YOLOX_CONFIG)
|
||||
preprocessed = time.perf_counter_ns()
|
||||
output = backend.infer(tensor)
|
||||
inferred = time.perf_counter_ns()
|
||||
frozen = postprocess_yolox(output, mask, config=FROZEN_YOLOX_CONFIG)
|
||||
frozen_postprocessed = time.perf_counter_ns()
|
||||
all_coco = postprocess_yolox(output, mask, config=ALL_COCO_YOLOX_CONFIG)
|
||||
all_postprocessed = time.perf_counter_ns()
|
||||
_benchmark_postprocess(
|
||||
output,
|
||||
mask,
|
||||
destination=postprocess_benchmark,
|
||||
)
|
||||
frozen_ids = {
|
||||
_detection_identity(item.class_id, item.score, item.bbox_xyxy)
|
||||
for item in frozen.detections
|
||||
}
|
||||
added = tuple(
|
||||
item
|
||||
for item in all_coco.detections
|
||||
if _detection_identity(item.class_id, item.score, item.bbox_xyxy)
|
||||
not in frozen_ids
|
||||
)
|
||||
totals["frame_count"] += 1
|
||||
totals["frozen_detection_count"] += len(frozen.detections)
|
||||
totals["all_coco_detection_count"] += len(all_coco.detections)
|
||||
totals["added_detection_count"] += len(added)
|
||||
for item in all_coco.detections:
|
||||
totals[f"class:{item.label}"] += 1
|
||||
timings["decode_ms"].append(_milliseconds(started, decoded))
|
||||
timings["preprocess_ms"].append(_milliseconds(decoded, preprocessed))
|
||||
timings["inference_ms"].append(_milliseconds(preprocessed, inferred))
|
||||
timings["frozen_postprocess_ms"].append(
|
||||
_milliseconds(inferred, frozen_postprocessed)
|
||||
)
|
||||
timings["all_coco_postprocess_ms"].append(
|
||||
_milliseconds(frozen_postprocessed, all_postprocessed)
|
||||
)
|
||||
timings["all_coco_core_ms"].append(
|
||||
_milliseconds(decoded, preprocessed)
|
||||
+ _milliseconds(preprocessed, inferred)
|
||||
+ _milliseconds(frozen_postprocessed, all_postprocessed)
|
||||
)
|
||||
rows.append(
|
||||
{
|
||||
"frame_name": image_path.name,
|
||||
"source_sha256": _sha256(image_path),
|
||||
"frozen_detections": [
|
||||
_detection_document(item) for item in frozen.detections
|
||||
],
|
||||
"all_coco_detections": [
|
||||
_detection_document(item) for item in all_coco.detections
|
||||
],
|
||||
"added_detections": [_detection_document(item) for item in added],
|
||||
"timing_ms": {name: values[-1] for name, values in timings.items()},
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
)
|
||||
finally:
|
||||
backend.close()
|
||||
frame_bytes = b"".join(_canonical_json(item) + b"\n" for item in rows)
|
||||
timing_metrics = {name: _timing_summary(values) for name, values in timings.items()}
|
||||
mean_core_ms = timing_metrics["all_coco_core_ms"]["mean"]
|
||||
metrics = {
|
||||
"frames": {"requested": 11, "completed": totals["frame_count"]},
|
||||
"inference_passes_per_frame": 1,
|
||||
"frozen_detection_count": totals["frozen_detection_count"],
|
||||
"all_coco_detection_count": totals["all_coco_detection_count"],
|
||||
"added_detection_count": totals["added_detection_count"],
|
||||
"all_coco_class_counts": {
|
||||
key.removeprefix("class:"): value
|
||||
for key, value in sorted(totals.items())
|
||||
if key.startswith("class:")
|
||||
},
|
||||
"timing_ms": timing_metrics,
|
||||
"postprocess_benchmark": {
|
||||
"iterations_per_profile_per_frame": POSTPROCESS_BENCHMARK_ITERATIONS,
|
||||
"timing_ms": {
|
||||
name: _timing_summary(values)
|
||||
for name, values in postprocess_benchmark.items()
|
||||
},
|
||||
},
|
||||
"all_coco_core_capacity_fps": round(1000.0 / mean_core_ms, 6),
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
identity = {
|
||||
"schema_version": SCHEMA,
|
||||
"model_sha256": YOLOX_MODEL_SHA256,
|
||||
"class_count": len(COCO_CLASSES),
|
||||
"frozen_target_class_ids": list(FROZEN_YOLOX_CONFIG.target_class_ids),
|
||||
"all_coco_target_class_ids": list(ALL_COCO_YOLOX_CONFIG.target_class_ids),
|
||||
"valid_fov_mask_sha256": _sha256(arguments.valid_fov_mask),
|
||||
"producer_sha256": _sha256(Path(__file__)),
|
||||
"frames_sha256": hashlib.sha256(frame_bytes).hexdigest(),
|
||||
"metrics": metrics,
|
||||
"completed": totals["frame_count"] == 11,
|
||||
"accepted": False,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
result_id = "m48s-yolox-all-coco-shadow-" + hashlib.sha256(
|
||||
_canonical_json(identity)
|
||||
).hexdigest()
|
||||
destination = output_parent / result_id
|
||||
if destination.exists():
|
||||
raise RuntimeError("immutable M48S all-COCO result already exists")
|
||||
destination.mkdir(mode=0o700)
|
||||
(destination / "frames.jsonl").write_bytes(frame_bytes)
|
||||
(destination / "manifest.json").write_bytes(
|
||||
_canonical_json({"result_id": result_id, **identity}) + b"\n"
|
||||
)
|
||||
(destination / "report.json").write_bytes(
|
||||
_canonical_json(
|
||||
{
|
||||
"schema_version": SCHEMA,
|
||||
"result_id": result_id,
|
||||
"completed": identity["completed"],
|
||||
"accepted": False,
|
||||
"metrics": metrics,
|
||||
"decision": {
|
||||
"all_coco_emission_completed": True,
|
||||
"additional_inference_passes": 0,
|
||||
"navigation_or_safety_accepted": False,
|
||||
"next_gate": "full-load all-COCO detector replay",
|
||||
},
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
)
|
||||
+ b"\n"
|
||||
)
|
||||
print(result_id)
|
||||
print(json.dumps(metrics, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _detection_identity(
|
||||
class_id: int,
|
||||
score: float,
|
||||
box: tuple[float, float, float, float],
|
||||
) -> tuple[int, float, tuple[float, float, float, float]]:
|
||||
return class_id, score, box
|
||||
|
||||
|
||||
def _benchmark_postprocess(
|
||||
output: np.ndarray[Any, Any],
|
||||
mask: np.ndarray[Any, Any],
|
||||
*,
|
||||
destination: dict[str, list[float]],
|
||||
) -> None:
|
||||
for iteration in range(POSTPROCESS_BENCHMARK_ITERATIONS):
|
||||
profiles: tuple[tuple[str, YoloxPostprocessConfig], ...]
|
||||
if iteration % 2:
|
||||
profiles = (
|
||||
("frozen_ms", FROZEN_YOLOX_CONFIG),
|
||||
("all_coco_ms", ALL_COCO_YOLOX_CONFIG),
|
||||
)
|
||||
else:
|
||||
profiles = (
|
||||
("all_coco_ms", ALL_COCO_YOLOX_CONFIG),
|
||||
("frozen_ms", FROZEN_YOLOX_CONFIG),
|
||||
)
|
||||
for name, profile in profiles:
|
||||
started = time.perf_counter_ns()
|
||||
postprocess_yolox(output, mask, config=profile)
|
||||
completed = time.perf_counter_ns()
|
||||
destination[name].append(_milliseconds(started, completed))
|
||||
|
||||
|
||||
def _detection_document(item: Any) -> dict[str, object]:
|
||||
return {
|
||||
"class_id": item.class_id,
|
||||
"label": item.label,
|
||||
"score": item.score,
|
||||
"bbox_xyxy": list(item.bbox_xyxy),
|
||||
"valid_fov_fraction": item.valid_fov_fraction,
|
||||
}
|
||||
|
||||
|
||||
def _milliseconds(started: int, completed: int) -> float:
|
||||
return round(max(0, completed - started) / 1_000_000.0, 6)
|
||||
|
||||
|
||||
def _timing_summary(values: list[float]) -> dict[str, float]:
|
||||
array = np.asarray(values, dtype=np.float64)
|
||||
return {
|
||||
"mean": round(float(array.mean()), 6),
|
||||
"p50": round(float(np.percentile(array, 50)), 6),
|
||||
"p95": round(float(np.percentile(array, 95)), 6),
|
||||
"max": round(float(array.max()), 6),
|
||||
}
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,546 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run one fixed-class detector candidate on the exact M48S risk slice."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any, Final, Protocol, cast
|
||||
|
||||
import numpy as np
|
||||
import torch # type: ignore[import-not-found]
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
WORKER_RUN_SCHEMA: Final = "missioncore.m48s-fixed-detector-candidate-worker/v0"
|
||||
EXACT_FRAME_NAMES: Final = (
|
||||
"frame-000121.png",
|
||||
"frame-000131.png",
|
||||
"frame-000253.png",
|
||||
"frame-000275.png",
|
||||
"frame-000443.png",
|
||||
"frame-000463.png",
|
||||
"frame-001094.png",
|
||||
"frame-001228.png",
|
||||
"frame-001454.png",
|
||||
"frame-001856.png",
|
||||
"frame-002386.png",
|
||||
)
|
||||
COCO_CLASSES: Final = (
|
||||
"person",
|
||||
"bicycle",
|
||||
"car",
|
||||
"motorcycle",
|
||||
"airplane",
|
||||
"bus",
|
||||
"train",
|
||||
"truck",
|
||||
"boat",
|
||||
"traffic light",
|
||||
"fire hydrant",
|
||||
"stop sign",
|
||||
"parking meter",
|
||||
"bench",
|
||||
"bird",
|
||||
"cat",
|
||||
"dog",
|
||||
"horse",
|
||||
"sheep",
|
||||
"cow",
|
||||
"elephant",
|
||||
"bear",
|
||||
"zebra",
|
||||
"giraffe",
|
||||
"backpack",
|
||||
"umbrella",
|
||||
"handbag",
|
||||
"tie",
|
||||
"suitcase",
|
||||
"frisbee",
|
||||
"skis",
|
||||
"snowboard",
|
||||
"sports ball",
|
||||
"kite",
|
||||
"baseball bat",
|
||||
"baseball glove",
|
||||
"skateboard",
|
||||
"surfboard",
|
||||
"tennis racket",
|
||||
"bottle",
|
||||
"wine glass",
|
||||
"cup",
|
||||
"fork",
|
||||
"knife",
|
||||
"spoon",
|
||||
"bowl",
|
||||
"banana",
|
||||
"apple",
|
||||
"sandwich",
|
||||
"orange",
|
||||
"broccoli",
|
||||
"carrot",
|
||||
"hot dog",
|
||||
"pizza",
|
||||
"donut",
|
||||
"cake",
|
||||
"chair",
|
||||
"couch",
|
||||
"potted plant",
|
||||
"bed",
|
||||
"dining table",
|
||||
"toilet",
|
||||
"tv",
|
||||
"laptop",
|
||||
"mouse",
|
||||
"remote",
|
||||
"keyboard",
|
||||
"cell phone",
|
||||
"microwave",
|
||||
"oven",
|
||||
"toaster",
|
||||
"sink",
|
||||
"refrigerator",
|
||||
"book",
|
||||
"clock",
|
||||
"vase",
|
||||
"scissors",
|
||||
"teddy bear",
|
||||
"hair drier",
|
||||
"toothbrush",
|
||||
)
|
||||
AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
MINIMUM_BOX_AREA_PIXELS: Final = 64.0
|
||||
MAXIMUM_BOX_AREA_FRACTION: Final = 0.5
|
||||
MINIMUM_VALID_FOV_FRACTION: Final = 0.5
|
||||
OVERLAY_THRESHOLD: Final = 0.25
|
||||
|
||||
|
||||
class Detector(Protocol):
|
||||
def infer(self, image: Image.Image) -> tuple[RawDetection, ...]: ...
|
||||
|
||||
|
||||
class RawDetection(tuple[int, str, float, tuple[float, float, float, float]]):
|
||||
"""Normalized detector output: class id, label, score and source-pixel box."""
|
||||
|
||||
__slots__ = ()
|
||||
|
||||
def __new__(
|
||||
cls,
|
||||
class_id: int,
|
||||
label: str,
|
||||
score: float,
|
||||
box: tuple[float, float, float, float],
|
||||
) -> RawDetection:
|
||||
return tuple.__new__(cls, (class_id, label, score, box))
|
||||
|
||||
@property
|
||||
def class_id(self) -> int:
|
||||
return self[0]
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return self[1]
|
||||
|
||||
@property
|
||||
def score(self) -> float:
|
||||
return self[2]
|
||||
|
||||
@property
|
||||
def box(self) -> tuple[float, float, float, float]:
|
||||
return self[3]
|
||||
|
||||
|
||||
class DfineDetector:
|
||||
"""Pinned D-FINE-S COCO PyTorch qualification adapter."""
|
||||
|
||||
def __init__(self, source_root: Path, config_path: Path, checkpoint: Path) -> None:
|
||||
sys.path.insert(0, str(source_root))
|
||||
from src.core import YAMLConfig # type: ignore[import-not-found]
|
||||
|
||||
config = YAMLConfig(str(config_path), resume=str(checkpoint))
|
||||
if "HGNetv2" in config.yaml_cfg:
|
||||
config.yaml_cfg["HGNetv2"]["pretrained"] = False
|
||||
state = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
||||
weights = state["ema"]["module"] if "ema" in state else state["model"]
|
||||
config.model.load_state_dict(weights)
|
||||
self._model = config.model.deploy().to("cuda").eval()
|
||||
self._postprocessor = config.postprocessor.deploy()
|
||||
|
||||
def infer(self, image: Image.Image) -> tuple[RawDetection, ...]:
|
||||
tensor, ratio, padding = _dfine_preprocess(image)
|
||||
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.float16):
|
||||
output = self._model(tensor)
|
||||
size = torch.tensor([[640, 640]], device="cuda")
|
||||
labels, boxes, scores = self._postprocessor(output, size)
|
||||
labels_array = labels[0].detach().to("cpu").numpy()
|
||||
boxes_array = boxes[0].detach().to("cpu").numpy()
|
||||
scores_array = scores[0].detach().to("cpu").numpy()
|
||||
pad_x, pad_y = padding
|
||||
detections = []
|
||||
for raw_label, raw_score, raw_box in zip(
|
||||
labels_array,
|
||||
scores_array,
|
||||
boxes_array,
|
||||
strict=True,
|
||||
):
|
||||
class_id = int(raw_label)
|
||||
if not 0 <= class_id < len(COCO_CLASSES):
|
||||
continue
|
||||
box = (
|
||||
(float(raw_box[0]) - pad_x) / ratio,
|
||||
(float(raw_box[1]) - pad_y) / ratio,
|
||||
(float(raw_box[2]) - pad_x) / ratio,
|
||||
(float(raw_box[3]) - pad_y) / ratio,
|
||||
)
|
||||
detections.append(
|
||||
RawDetection(class_id, COCO_CLASSES[class_id], float(raw_score), box)
|
||||
)
|
||||
return tuple(detections)
|
||||
|
||||
|
||||
class RfDetrDetector:
|
||||
"""Pinned RF-DETR-L COCO PyTorch qualification adapter."""
|
||||
|
||||
def __init__(self, checkpoint: Path) -> None:
|
||||
from rfdetr import RFDETRLarge # type: ignore[import-not-found]
|
||||
|
||||
self._model = RFDETRLarge(pretrain_weights=str(checkpoint))
|
||||
self._model.inference(compile=False, dtype=torch.float16, inplace=True)
|
||||
|
||||
def infer(self, image: Image.Image) -> tuple[RawDetection, ...]:
|
||||
prediction = self._model.predict(
|
||||
image,
|
||||
threshold=0.1,
|
||||
include_source_image=False,
|
||||
)
|
||||
boxes = np.asarray(prediction.xyxy)
|
||||
scores = np.asarray(prediction.confidence)
|
||||
names = np.asarray(prediction.data["class_name"])
|
||||
detections = []
|
||||
for raw_name, raw_score, raw_box in zip(names, scores, boxes, strict=True):
|
||||
label = str(raw_name)
|
||||
try:
|
||||
class_id = COCO_CLASSES.index(label)
|
||||
except ValueError:
|
||||
continue
|
||||
detections.append(
|
||||
RawDetection(
|
||||
class_id,
|
||||
label,
|
||||
float(raw_score),
|
||||
cast(
|
||||
tuple[float, float, float, float],
|
||||
tuple(float(value) for value in raw_box),
|
||||
),
|
||||
)
|
||||
)
|
||||
return tuple(detections)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--candidate",
|
||||
choices=("dfine-s-coco", "rf-detr-large-coco"),
|
||||
required=True,
|
||||
)
|
||||
parser.add_argument("--profile-id", required=True)
|
||||
parser.add_argument("--provider-id", required=True)
|
||||
parser.add_argument("--upstream-revision", required=True)
|
||||
parser.add_argument("--input-root", type=Path, required=True)
|
||||
parser.add_argument("--valid-fov-mask", type=Path, required=True)
|
||||
parser.add_argument("--checkpoint", type=Path, required=True)
|
||||
parser.add_argument("--expected-checkpoint-sha256", required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--dfine-root", type=Path, default=Path("/opt/dfine"))
|
||||
parser.add_argument(
|
||||
"--dfine-config",
|
||||
type=Path,
|
||||
default=Path("/opt/dfine/configs/dfine/dfine_hgnetv2_s_coco.yml"),
|
||||
)
|
||||
parser.add_argument("--warmup-iterations", type=int, default=5)
|
||||
parser.add_argument("--benchmark-iterations", type=int, default=30)
|
||||
arguments = parser.parse_args()
|
||||
if arguments.warmup_iterations < 1 or arguments.benchmark_iterations < 1:
|
||||
raise RuntimeError("warmup and benchmark iterations must be positive")
|
||||
input_root = arguments.input_root.resolve(strict=True)
|
||||
images = tuple(sorted(input_root.glob("frame-*.png")))
|
||||
if tuple(path.name for path in images) != EXACT_FRAME_NAMES:
|
||||
raise RuntimeError("candidate Worker requires the exact M48S risk slice")
|
||||
mask = _load_mask(arguments.valid_fov_mask.resolve(strict=True))
|
||||
checkpoint = arguments.checkpoint.resolve(strict=True)
|
||||
checkpoint_sha256 = _sha256(checkpoint)
|
||||
if checkpoint_sha256 != arguments.expected_checkpoint_sha256:
|
||||
raise RuntimeError("checkpoint SHA-256 does not match the pinned profile")
|
||||
output = arguments.output.absolute()
|
||||
if output.exists():
|
||||
raise RuntimeError("candidate Worker output already exists")
|
||||
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
overlay_root = output.parent / f"{output.stem}-overlays"
|
||||
overlay_root.mkdir(mode=0o700)
|
||||
gpu_before = _gpu_sample()
|
||||
started_utc_ns = time.time_ns()
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
detector: Detector
|
||||
if arguments.candidate == "dfine-s-coco":
|
||||
detector = DfineDetector(
|
||||
arguments.dfine_root.resolve(strict=True),
|
||||
arguments.dfine_config.resolve(strict=True),
|
||||
checkpoint,
|
||||
)
|
||||
else:
|
||||
detector = RfDetrDetector(checkpoint)
|
||||
with Image.open(images[0]) as opened:
|
||||
warmup_image = opened.convert("RGB")
|
||||
for _ in range(arguments.warmup_iterations):
|
||||
detector.infer(warmup_image)
|
||||
_synchronize()
|
||||
frames = []
|
||||
totals: Counter[str] = Counter()
|
||||
evidence_timings = []
|
||||
for image_path in images:
|
||||
with Image.open(image_path) as opened:
|
||||
image = opened.convert("RGB")
|
||||
_synchronize()
|
||||
started = time.perf_counter_ns()
|
||||
raw = detector.infer(image)
|
||||
_synchronize()
|
||||
completed = time.perf_counter_ns()
|
||||
elapsed_ms = _milliseconds(started, completed)
|
||||
evidence_timings.append(elapsed_ms)
|
||||
detections = _qualify(raw, mask, image.size)
|
||||
totals["frame_count"] += 1
|
||||
totals["detection_count"] += len(detections)
|
||||
for detection in detections:
|
||||
totals[f"class:{detection['label']}"] += 1
|
||||
frames.append(
|
||||
{
|
||||
"frame_name": image_path.name,
|
||||
"source_sha256": _sha256(image_path),
|
||||
"detections": detections,
|
||||
"timing_ms": {"end_to_end": elapsed_ms},
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
)
|
||||
_write_overlay(image, detections, overlay_root / image_path.name)
|
||||
with Image.open(input_root / "frame-000253.png") as opened:
|
||||
benchmark_image = opened.convert("RGB")
|
||||
benchmark_timings = []
|
||||
for _ in range(arguments.benchmark_iterations):
|
||||
_synchronize()
|
||||
started = time.perf_counter_ns()
|
||||
detector.infer(benchmark_image)
|
||||
_synchronize()
|
||||
benchmark_timings.append(_milliseconds(started, time.perf_counter_ns()))
|
||||
gpu_after = _gpu_sample()
|
||||
timing = _timing_summary(evidence_timings)
|
||||
benchmark_timing = _timing_summary(benchmark_timings)
|
||||
metrics = {
|
||||
"frames": {"requested": 11, "completed": totals["frame_count"]},
|
||||
"detection_count_at_minimum_score_0_1": totals["detection_count"],
|
||||
"class_counts_at_minimum_score_0_1": {
|
||||
key.removeprefix("class:"): value
|
||||
for key, value in sorted(totals.items())
|
||||
if key.startswith("class:")
|
||||
},
|
||||
"evidence_timing_ms": timing,
|
||||
"benchmark": {
|
||||
"frame_name": "frame-000253.png",
|
||||
"iterations": arguments.benchmark_iterations,
|
||||
"timing_ms": benchmark_timing,
|
||||
"core_capacity_fps": round(1000.0 / benchmark_timing["mean"], 6),
|
||||
},
|
||||
"torch_peak_memory": {
|
||||
"allocated_bytes": torch.cuda.max_memory_allocated(),
|
||||
"reserved_bytes": torch.cuda.max_memory_reserved(),
|
||||
},
|
||||
"gpu_before": gpu_before,
|
||||
"gpu_after": gpu_after,
|
||||
}
|
||||
document = {
|
||||
"schema_version": WORKER_RUN_SCHEMA,
|
||||
"profile_id": arguments.profile_id,
|
||||
"provider_id": arguments.provider_id,
|
||||
"candidate": arguments.candidate,
|
||||
"upstream_revision": arguments.upstream_revision,
|
||||
"checkpoint_sha256": checkpoint_sha256,
|
||||
"started_utc_ns": started_utc_ns,
|
||||
"completed_utc_ns": time.time_ns(),
|
||||
"completed": totals["frame_count"] == 11,
|
||||
"execution": {
|
||||
"worker_id": "worker-006",
|
||||
"device": torch.cuda.get_device_name(0),
|
||||
"precision": "fp16",
|
||||
"inference_passes_per_evidence_frame": 1,
|
||||
"warmup_iterations": arguments.warmup_iterations,
|
||||
"benchmark_iterations": arguments.benchmark_iterations,
|
||||
"concurrent_services_retained": True,
|
||||
},
|
||||
"frames": frames,
|
||||
"metrics": metrics,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
output.write_bytes(_canonical_json(document) + b"\n")
|
||||
print(output)
|
||||
print(json.dumps(metrics, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _dfine_preprocess(
|
||||
image: Image.Image,
|
||||
) -> tuple[torch.Tensor, float, tuple[int, int]]:
|
||||
width, height = image.size
|
||||
ratio = min(640.0 / width, 640.0 / height)
|
||||
resized_width = int(width * ratio)
|
||||
resized_height = int(height * ratio)
|
||||
resized = image.resize((resized_width, resized_height), Image.Resampling.BILINEAR)
|
||||
padded = Image.new("RGB", (640, 640))
|
||||
pad_x = (640 - resized_width) // 2
|
||||
pad_y = (640 - resized_height) // 2
|
||||
padded.paste(resized, (pad_x, pad_y))
|
||||
array = np.asarray(padded, dtype=np.float32) / 255.0
|
||||
tensor = torch.from_numpy(np.ascontiguousarray(array.transpose(2, 0, 1)))
|
||||
return tensor.unsqueeze(0).to("cuda", non_blocking=True), ratio, (pad_x, pad_y)
|
||||
|
||||
|
||||
def _qualify(
|
||||
detections: tuple[RawDetection, ...],
|
||||
mask: np.ndarray[Any, Any],
|
||||
image_size: tuple[int, int],
|
||||
) -> list[dict[str, object]]:
|
||||
width, height = image_size
|
||||
image_area = float(width * height)
|
||||
qualified = []
|
||||
for detection in detections:
|
||||
if detection.score < 0.1:
|
||||
continue
|
||||
x1, y1, x2, y2 = detection.box
|
||||
x1 = max(0.0, min(float(width), x1))
|
||||
y1 = max(0.0, min(float(height), y1))
|
||||
x2 = max(0.0, min(float(width), x2))
|
||||
y2 = max(0.0, min(float(height), y2))
|
||||
area = max(0.0, x2 - x1) * max(0.0, y2 - y1)
|
||||
if area < MINIMUM_BOX_AREA_PIXELS or area > MAXIMUM_BOX_AREA_FRACTION * image_area:
|
||||
continue
|
||||
center_x = min(width - 1, max(0, int((x1 + x2) / 2.0)))
|
||||
center_y = min(height - 1, max(0, int((y1 + y2) / 2.0)))
|
||||
if not bool(mask[center_y, center_x]):
|
||||
continue
|
||||
ix1 = min(width - 1, max(0, int(np.floor(x1))))
|
||||
iy1 = min(height - 1, max(0, int(np.floor(y1))))
|
||||
ix2 = min(width, max(ix1 + 1, int(np.ceil(x2))))
|
||||
iy2 = min(height, max(iy1 + 1, int(np.ceil(y2))))
|
||||
valid_fraction = float(mask[iy1:iy2, ix1:ix2].mean())
|
||||
if valid_fraction < MINIMUM_VALID_FOV_FRACTION:
|
||||
continue
|
||||
qualified.append(
|
||||
{
|
||||
"class_id": detection.class_id,
|
||||
"label": detection.label,
|
||||
"score": round(detection.score, 6),
|
||||
"bbox_xyxy": [round(value, 3) for value in (x1, y1, x2, y2)],
|
||||
"valid_fov_fraction": round(valid_fraction, 6),
|
||||
}
|
||||
)
|
||||
qualified.sort(key=lambda item: (-cast(float, item["score"]), cast(int, item["class_id"])))
|
||||
return qualified
|
||||
|
||||
|
||||
def _write_overlay(
|
||||
image: Image.Image,
|
||||
detections: list[dict[str, object]],
|
||||
destination: Path,
|
||||
) -> None:
|
||||
annotated = image.copy()
|
||||
draw = ImageDraw.Draw(annotated)
|
||||
for detection in detections:
|
||||
score = cast(float, detection["score"])
|
||||
if score < OVERLAY_THRESHOLD:
|
||||
continue
|
||||
box = cast(list[float], detection["bbox_xyxy"])
|
||||
label = cast(str, detection["label"])
|
||||
draw.rectangle(box, outline=(255, 84, 0), width=3)
|
||||
draw.text((box[0] + 3, box[1] + 3), f"{label} {score:.2f}", fill=(255, 255, 255))
|
||||
annotated.save(destination)
|
||||
|
||||
|
||||
def _load_mask(path: Path) -> np.ndarray[Any, Any]:
|
||||
with Image.open(path) as image:
|
||||
array = np.asarray(image.convert("L"), dtype=np.uint8)
|
||||
if array.shape != (600, 800):
|
||||
raise RuntimeError("valid-FOV mask must be 800x600")
|
||||
return array > 0
|
||||
|
||||
|
||||
def _gpu_sample() -> dict[str, object]:
|
||||
completed = subprocess.run(
|
||||
[
|
||||
"nvidia-smi",
|
||||
"--query-gpu=name,memory.total,memory.used,utilization.gpu,temperature.gpu,power.draw",
|
||||
"--format=csv,noheader,nounits",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
values = [value.strip() for value in completed.stdout.strip().split(",")]
|
||||
if len(values) != 6:
|
||||
raise RuntimeError("unexpected nvidia-smi response")
|
||||
return {
|
||||
"name": values[0],
|
||||
"memory_total_mib": float(values[1]),
|
||||
"memory_used_mib": float(values[2]),
|
||||
"utilization_gpu_percent": float(values[3]),
|
||||
"temperature_c": float(values[4]),
|
||||
"power_w": float(values[5]),
|
||||
}
|
||||
|
||||
|
||||
def _synchronize() -> None:
|
||||
torch.cuda.synchronize()
|
||||
|
||||
|
||||
def _timing_summary(values: list[float]) -> dict[str, float]:
|
||||
array = np.asarray(values, dtype=np.float64)
|
||||
return {
|
||||
"mean": round(float(array.mean()), 6),
|
||||
"p50": round(float(np.percentile(array, 50)), 6),
|
||||
"p95": round(float(np.percentile(array, 95)), 6),
|
||||
"max": round(float(array.max()), 6),
|
||||
}
|
||||
|
||||
|
||||
def _milliseconds(started: int, completed: int) -> float:
|
||||
return round(max(0, completed - started) / 1_000_000.0, 6)
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the bounded geometry-first M48S semantic shadow result."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.perception.geometry_semantic_shadow_replay import (
|
||||
build_geometry_semantic_shadow_replay,
|
||||
)
|
||||
|
||||
FRAME_INDICES = (121, 131, 253, 275, 443, 463, 1094, 1228, 1454, 1856, 2386)
|
||||
DETECTOR_RESULT_ID = (
|
||||
"m4-detector-replay-11f83f2e0b81758ac2a5a5fc54e9d293b501678df5f6ef97b5c6069ba08605c5"
|
||||
)
|
||||
VALID_FOV_RESULT_ID = (
|
||||
"valid-fov-mask-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
runtime = root / ".runtime/compute-experiments/m48s-semantic-shadow"
|
||||
worker = runtime / "worker-results/geometry-roi58-20260825T0804Z"
|
||||
result = build_geometry_semantic_shadow_replay(
|
||||
repository_root=root,
|
||||
profile_path=root / "config/perception/open-vocabulary-semantic-shadow-v0.json",
|
||||
vocabulary_path=root / "config/perception/object-semantic-vocabulary-v0.json",
|
||||
detector_result_root=root / ".runtime/worker-results" / DETECTOR_RESULT_ID,
|
||||
roi_package_root=runtime / "geometry-rois-v1",
|
||||
valid_fov_mask_path=(
|
||||
root / ".runtime/compute-experiments/e1/valid-fov" / VALID_FOV_RESULT_ID / "mask.png"
|
||||
),
|
||||
worker_result_roots={
|
||||
"urban-static/v0": worker / "results-static/trt_inference",
|
||||
"urban-agents/v0": worker / "results-agents/trt_inference",
|
||||
"urban-vehicles/v0": worker / "results-vehicles/trt_inference",
|
||||
},
|
||||
frame_indices=FRAME_INDICES,
|
||||
worker_execution={
|
||||
"worker_node": "DESKTOP-OPJ8J04",
|
||||
"gpu_name": "NVIDIA GeForce RTX 4090",
|
||||
"container_reference": "nvcr.io/nvidia/tao/tao-toolkit:7.0.1-deploy",
|
||||
"container_image_id": (
|
||||
"sha256:2a3095330dd83e4314aada21fc7d184fcdb442a9131d591e5593ca5497394e7a"
|
||||
),
|
||||
"remote_root": (
|
||||
"D:/NDC_MISSIONCORE/runtime/experiments/"
|
||||
"m48s-geometry-roi58-20260825T0804Z"
|
||||
),
|
||||
"network_observation": (
|
||||
"TAO performed Hugging Face metadata requests despite a populated cache"
|
||||
),
|
||||
"authority": {
|
||||
"ground_truth": False,
|
||||
"independent_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
},
|
||||
},
|
||||
output_root=runtime / "geometry-first-results",
|
||||
)
|
||||
print(result.result_id)
|
||||
print(json.dumps(result.metrics, ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,323 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build immutable Mask Grounding DINO × LiDAR shadow evidence for M48S."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections import Counter
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from k1link.perception.detector_replay_result import (
|
||||
read_detector_replay_result,
|
||||
require_m4_detector_replay_acceptance,
|
||||
)
|
||||
from k1link.perception.geometry import Ravnoves00GeometryAssociationProvider, RecordedGeometryStore
|
||||
from k1link.perception.geometry_math import project_map_points_kb4
|
||||
from k1link.perception.mask_grounding_semantics import (
|
||||
MaskBindingResolution,
|
||||
MaskGeometryBindingProfile,
|
||||
MaskGroundingDetection,
|
||||
MaskLabelResolution,
|
||||
bind_mask_instances_to_geometry,
|
||||
cluster_mask_instances,
|
||||
load_mask_grounding_evidence,
|
||||
resolve_mask_instance_label,
|
||||
)
|
||||
from k1link.perception.semantic_shadow_replay import semantic_replay_packet
|
||||
|
||||
SCHEMA: Final = "missioncore.m48s-mask-grounding-dino-shadow-analysis/v0"
|
||||
FRAME_INDICES: Final = (121, 131, 253, 275, 443, 463, 1094, 1228, 1454, 1856, 2386)
|
||||
DETECTOR_RESULT_ID: Final = (
|
||||
"m4-detector-replay-11f83f2e0b81758ac2a5a5fc54e9d293b501678df5f6ef97b5c6069ba08605c5"
|
||||
)
|
||||
GROUPS: Final = {
|
||||
"static": "urban-static/v0",
|
||||
"agents": "urban-agents/v0",
|
||||
"vehicles": "urban-vehicles/v0",
|
||||
}
|
||||
AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"independent_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
runtime = root / ".runtime/compute-experiments/m48s-semantic-shadow"
|
||||
split_root = (
|
||||
runtime
|
||||
/ "worker-results/mask-grounding-dino-split11-20260825T0833Z"
|
||||
).resolve(strict=True)
|
||||
agent_root = (
|
||||
runtime
|
||||
/ "worker-results/mask-grounding-dino-agent2-20260825T0836Z"
|
||||
).resolve(strict=True)
|
||||
profile_path = root / "config/perception/m48s-mask-grounding-dino-evidence-v0.json"
|
||||
profile_document = json.loads(profile_path.read_text("utf-8"))
|
||||
binding_profile = MaskGeometryBindingProfile(**profile_document["binding"])
|
||||
detector = read_detector_replay_result(
|
||||
root / ".runtime/worker-results" / DETECTOR_RESULT_ID
|
||||
)
|
||||
require_m4_detector_replay_acceptance(detector)
|
||||
detector_by_sequence = {item.sequence: item for item in detector.frames}
|
||||
store = RecordedGeometryStore.from_repository(root)
|
||||
geometry = Ravnoves00GeometryAssociationProvider(store=store)
|
||||
totals: Counter[str] = Counter()
|
||||
geometry_resolutions: Counter[str] = Counter()
|
||||
label_resolutions: Counter[str] = Counter()
|
||||
combined_resolutions: Counter[str] = Counter()
|
||||
frame_documents = []
|
||||
input_artifacts: dict[str, str] = {}
|
||||
evidence_writer_sha256 = _matching_evidence_writer_sha256(split_root, agent_root)
|
||||
for frame_index in FRAME_INDICES:
|
||||
detector_frame = detector_by_sequence[frame_index]
|
||||
packet = semantic_replay_packet(detector_frame.envelope)
|
||||
observations = geometry.associate(packet, ())
|
||||
geometry_frame = store.frame(packet)
|
||||
if geometry_frame is None:
|
||||
raise RuntimeError("selected M48S geometry frame is unavailable")
|
||||
projected = project_map_points_kb4(
|
||||
geometry_frame.points_map,
|
||||
position_map_xyz=geometry_frame.sensor_position_map,
|
||||
orientation_map_from_lidar_xyzw=geometry_frame.sensor_orientation_xyzw,
|
||||
profile=geometry_frame.projection,
|
||||
)
|
||||
detections: list[MaskGroundingDetection] = []
|
||||
source_file_sha256: str | None = None
|
||||
group_counts = {}
|
||||
for suffix, prompt_set_id in GROUPS.items():
|
||||
evidence_path = (
|
||||
split_root / f"results-{suffix}/masks/frame-{frame_index:06d}.npz"
|
||||
)
|
||||
evidence = load_mask_grounding_evidence(
|
||||
evidence_path,
|
||||
prompt_set_id=prompt_set_id,
|
||||
)
|
||||
if source_file_sha256 not in (None, evidence.source_file_sha256):
|
||||
raise RuntimeError("Mask Grounding DINO groups used different source rasters")
|
||||
source_file_sha256 = evidence.source_file_sha256
|
||||
detections.extend(evidence.detections)
|
||||
group_counts[prompt_set_id] = len(evidence.detections)
|
||||
input_artifacts[str(evidence_path.relative_to(root))] = _sha256(evidence_path)
|
||||
for name in ("experiment.yaml", "status.json"):
|
||||
artifact = split_root / f"results-{suffix}" / name
|
||||
input_artifacts[str(artifact.relative_to(root))] = _sha256(artifact)
|
||||
instances = cluster_mask_instances(tuple(detections), profile=binding_profile)
|
||||
bindings = bind_mask_instances_to_geometry(
|
||||
instances,
|
||||
observations=observations,
|
||||
projected=projected,
|
||||
profile=binding_profile,
|
||||
)
|
||||
decisions = tuple(
|
||||
resolve_mask_instance_label(item, profile=binding_profile) for item in instances
|
||||
)
|
||||
instance_documents = []
|
||||
for instance, binding, decision in zip(
|
||||
instances, bindings, decisions, strict=True
|
||||
):
|
||||
geometry_resolutions[binding.resolution.value] += 1
|
||||
label_resolutions[decision.resolution.value] += 1
|
||||
combined = _combined_resolution(binding.resolution, decision.resolution)
|
||||
combined_resolutions[combined] += 1
|
||||
instance_documents.append(
|
||||
{
|
||||
"instance_id": instance.instance_id,
|
||||
"member_detection_ids": [
|
||||
item.detection_id for item in instance.detections
|
||||
],
|
||||
"member_mask_sha256": sorted(
|
||||
{item.mask_sha256 for item in instance.detections}
|
||||
),
|
||||
"ranked_labels": [
|
||||
{"label": label, "confidence": confidence}
|
||||
for label, confidence in decision.ranked_labels
|
||||
],
|
||||
"geometry_binding": {
|
||||
"resolution": binding.resolution.value,
|
||||
"selected_observation_id": binding.selected_observation_id,
|
||||
"reason_code": binding.reason_code,
|
||||
"supports": [
|
||||
{
|
||||
"observation_id": item.observation_id,
|
||||
"projected_point_count": item.projected_point_count,
|
||||
"support_fraction": item.support_fraction,
|
||||
}
|
||||
for item in binding.supports
|
||||
],
|
||||
},
|
||||
"label_decision": {
|
||||
"resolution": decision.resolution.value,
|
||||
"selected_label": decision.selected_label,
|
||||
"reason_code": decision.reason_code,
|
||||
},
|
||||
"combined_resolution": combined,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
)
|
||||
totals["frame_count"] += 1
|
||||
totals["geometry_observation_count"] += len(observations)
|
||||
totals["raw_detection_count"] += len(detections)
|
||||
totals["mask_instance_count"] += len(instances)
|
||||
frame_documents.append(
|
||||
{
|
||||
"frame_index": frame_index,
|
||||
"frame_id": detector_frame.envelope.frame_id,
|
||||
"source_file_sha256": source_file_sha256,
|
||||
"geometry_observation_count": len(observations),
|
||||
"group_detection_counts": group_counts,
|
||||
"instances": instance_documents,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
)
|
||||
agent_probe = _agent_probe(agent_root, root=root, input_artifacts=input_artifacts)
|
||||
metrics = {
|
||||
"frames": {
|
||||
"requested": len(FRAME_INDICES),
|
||||
"completed": totals["frame_count"],
|
||||
},
|
||||
"geometry_observation_count": totals["geometry_observation_count"],
|
||||
"raw_detection_count": totals["raw_detection_count"],
|
||||
"mask_instance_count": totals["mask_instance_count"],
|
||||
"geometry_binding_resolution_counts": dict(sorted(geometry_resolutions.items())),
|
||||
"label_resolution_counts": dict(sorted(label_resolutions.items())),
|
||||
"combined_resolution_counts": dict(sorted(combined_resolutions.items())),
|
||||
"single_class_agent_probe": agent_probe,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
frames_bytes = b"".join(
|
||||
_canonical_json(item) + b"\n" for item in frame_documents
|
||||
)
|
||||
identity = {
|
||||
"schema_version": SCHEMA,
|
||||
"profile_sha256": _sha256(profile_path),
|
||||
"detector_result_id": detector.result_id,
|
||||
"frame_indices": list(FRAME_INDICES),
|
||||
"worker_input_artifacts": dict(sorted(input_artifacts.items())),
|
||||
"evidence_writer_sha256": evidence_writer_sha256,
|
||||
"producer_sha256": {
|
||||
"mask_grounding_semantics.py": _sha256(
|
||||
root / "src/k1link/perception/mask_grounding_semantics.py"
|
||||
),
|
||||
"run_m48s_mask_grounding_dino_analysis.py": _sha256(Path(__file__))
|
||||
},
|
||||
"frames_sha256": hashlib.sha256(frames_bytes).hexdigest(),
|
||||
"metrics": metrics,
|
||||
"completed": totals["frame_count"] == len(FRAME_INDICES),
|
||||
"accepted": False,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
result_id = "m48s-mask-grounding-dino-shadow-" + hashlib.sha256(
|
||||
_canonical_json(identity)
|
||||
).hexdigest()
|
||||
output = runtime / "mask-grounding-dino-results" / result_id
|
||||
if output.exists():
|
||||
raise RuntimeError("immutable Mask Grounding DINO result already exists")
|
||||
output.mkdir(mode=0o700, parents=True)
|
||||
(output / "frames.jsonl").write_bytes(frames_bytes)
|
||||
manifest = {"result_id": result_id, **identity}
|
||||
(output / "manifest.json").write_bytes(_canonical_json(manifest) + b"\n")
|
||||
report = {
|
||||
"schema_version": SCHEMA,
|
||||
"result_id": result_id,
|
||||
"created_at_utc": datetime.now(UTC).isoformat(timespec="milliseconds").replace(
|
||||
"+00:00", "Z"
|
||||
),
|
||||
"completed": identity["completed"],
|
||||
"accepted": False,
|
||||
"metrics": metrics,
|
||||
"decision": {
|
||||
"mask_instance_geometry_binding_completed": True,
|
||||
"semantic_quality_accepted": False,
|
||||
"agent_semantics_accepted": False,
|
||||
"reason_codes": [
|
||||
"single-class-adult-child-dog-probes-returned-zero-masks",
|
||||
"geometry-supported-instances-retained-conflicting-class-labels",
|
||||
"two-reviewer-independent-truth-unavailable",
|
||||
"research-checkpoint-not-for-commercial-deployment",
|
||||
],
|
||||
"next_candidate": (
|
||||
"geometry-prompted-mask-segmentation-plus-independent-zero-shot-"
|
||||
"crop-classifier"
|
||||
),
|
||||
},
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
(output / "report.json").write_bytes(_canonical_json(report) + b"\n")
|
||||
print(result_id)
|
||||
print(json.dumps(metrics, ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _combined_resolution(
|
||||
geometry: MaskBindingResolution,
|
||||
label: MaskLabelResolution,
|
||||
) -> str:
|
||||
if geometry is MaskBindingResolution.UNRESOLVED:
|
||||
return "unresolved"
|
||||
if geometry is MaskBindingResolution.AMBIGUOUS:
|
||||
return "ambiguous"
|
||||
return label.value
|
||||
|
||||
|
||||
def _agent_probe(
|
||||
agent_root: Path,
|
||||
*,
|
||||
root: Path,
|
||||
input_artifacts: dict[str, str],
|
||||
) -> dict[str, object]:
|
||||
counts: Counter[str] = Counter()
|
||||
for label in ("adult", "child", "dog"):
|
||||
for frame_index in (253, 1228):
|
||||
path = agent_root / f"results-{label}/masks/frame-{frame_index:06d}.npz"
|
||||
evidence = load_mask_grounding_evidence(
|
||||
path,
|
||||
prompt_set_id=f"agent-probe-{label}/v0",
|
||||
)
|
||||
counts[label] += len(evidence.detections)
|
||||
input_artifacts[str(path.relative_to(root))] = _sha256(path)
|
||||
for name in ("experiment.yaml", "status.json"):
|
||||
artifact = agent_root / f"results-{label}" / name
|
||||
input_artifacts[str(artifact.relative_to(root))] = _sha256(artifact)
|
||||
return {
|
||||
"frame_indices": [253, 1228],
|
||||
"detection_counts": dict(sorted(counts.items())),
|
||||
"passed": False,
|
||||
}
|
||||
|
||||
|
||||
def _matching_evidence_writer_sha256(split_root: Path, agent_root: Path) -> str:
|
||||
split = _sha256(split_root / "sitecustomize.py")
|
||||
agent = _sha256(agent_root / "sitecustomize.py")
|
||||
if split != agent:
|
||||
raise RuntimeError("Mask Grounding DINO evidence writers changed between runs")
|
||||
return split
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Persist raw Mask Grounding DINO tensors before TAO visualization.
|
||||
|
||||
This Worker-only wrapper leaves NVIDIA's inference and postprocessing intact. It
|
||||
intercepts the documented OD drawing seam solely to persist the already-filtered
|
||||
class, score, box and binary-mask evidence in a lossless NPZ ledger.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from nvidia_tao_deploy.cv.mask_grounding_dino.entrypoint.mask_grounding_dino import main
|
||||
from nvidia_tao_deploy.cv.mask_grounding_dino.inferencer import MaskGDINOInferencer
|
||||
from PIL import Image
|
||||
|
||||
INPUT_ROOT = Path(os.environ.get("M48S_INPUT_ROOT", "/workspace/probe/input"))
|
||||
MASK_ROOT = Path(os.environ.get("M48S_MASK_ROOT", "/workspace/probe/results/masks"))
|
||||
|
||||
|
||||
def _pixel_sha256(image: Image.Image) -> str:
|
||||
digest = hashlib.sha256()
|
||||
normalized = image.convert("RGB")
|
||||
digest.update(normalized.width.to_bytes(4, "big"))
|
||||
digest.update(normalized.height.to_bytes(4, "big"))
|
||||
digest.update(normalized.tobytes())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _source_index() -> dict[str, tuple[str, str]]:
|
||||
result: dict[str, tuple[str, str]] = {}
|
||||
for path in sorted(INPUT_ROOT.glob("*.png")):
|
||||
with Image.open(path) as image:
|
||||
pixel_sha256 = _pixel_sha256(image)
|
||||
file_sha256 = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
if pixel_sha256 in result:
|
||||
raise RuntimeError("M48S mask input rasters are duplicated")
|
||||
result[pixel_sha256] = (path.stem, file_sha256)
|
||||
if not result:
|
||||
raise RuntimeError("M48S mask input root is empty")
|
||||
return result
|
||||
|
||||
|
||||
SOURCE_INDEX = _source_index()
|
||||
ORIGINAL_DRAW_BBOX = MaskGDINOInferencer.draw_bbox
|
||||
|
||||
|
||||
def _evidence_draw_bbox(
|
||||
self: MaskGDINOInferencer,
|
||||
image: Image.Image,
|
||||
prediction: np.ndarray[Any, Any],
|
||||
masks: np.ndarray[Any, Any],
|
||||
class_mapping: dict[int, str],
|
||||
threshold: float = 0.3,
|
||||
color_map: dict[str, object] | None = None,
|
||||
) -> tuple[Image.Image, list[str]]:
|
||||
source = SOURCE_INDEX.get(_pixel_sha256(image))
|
||||
if source is None:
|
||||
raise RuntimeError("M48S mask inference image escaped the admitted input set")
|
||||
stem, source_file_sha256 = source
|
||||
if masks.ndim != 3 or masks.shape[-1] != prediction.shape[0]:
|
||||
raise RuntimeError("M48S mask output shape is incompatible")
|
||||
selected = tuple(
|
||||
index
|
||||
for index, item in enumerate(prediction)
|
||||
if int(item[0]) in class_mapping and float(item[1]) >= threshold
|
||||
)
|
||||
class_ids = np.asarray([int(prediction[index, 0]) for index in selected], dtype=np.int16)
|
||||
class_names = np.asarray([class_mapping[int(item)] for item in class_ids], dtype="U128")
|
||||
scores = np.asarray([prediction[index, 1] for index in selected], dtype=np.float32)
|
||||
boxes = np.asarray(
|
||||
[prediction[index, 2:6] for index in selected], dtype=np.float32
|
||||
).reshape((-1, 4))
|
||||
if selected:
|
||||
binary_masks = np.transpose(masks[..., selected] > 0.5, (2, 0, 1)).astype(np.uint8)
|
||||
else:
|
||||
binary_masks = np.empty((0, masks.shape[0], masks.shape[1]), dtype=np.uint8)
|
||||
MASK_ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
destination = MASK_ROOT / f"{stem}.npz"
|
||||
if destination.exists():
|
||||
raise RuntimeError("M48S mask evidence destination already exists")
|
||||
np.savez_compressed(
|
||||
destination,
|
||||
schema_version=np.asarray("missioncore.m48s-mask-grounding-dino-evidence/v0"),
|
||||
source_file_sha256=np.asarray(source_file_sha256),
|
||||
source_pixel_sha256=np.asarray(_pixel_sha256(image)),
|
||||
class_ids=class_ids,
|
||||
class_names=class_names,
|
||||
scores=scores,
|
||||
boxes_xyxy=boxes,
|
||||
masks=binary_masks,
|
||||
)
|
||||
return ORIGINAL_DRAW_BBOX(
|
||||
self,
|
||||
image,
|
||||
prediction,
|
||||
masks,
|
||||
class_mapping,
|
||||
threshold,
|
||||
color_map,
|
||||
)
|
||||
|
||||
|
||||
MaskGDINOInferencer.draw_bbox = _evidence_draw_bbox
|
||||
print("M48S raw-mask evidence hook installed", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,581 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run RF-DETR through the complete source-paced reference graph on Worker 006."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import resource
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter, defaultdict
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import asdict, fields
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Any, Final, TextIO, cast
|
||||
|
||||
import numpy as np
|
||||
|
||||
from k1link.perception.contracts import MotionState
|
||||
from k1link.perception.contracts import ObjectProposal2D
|
||||
from k1link.perception.detector import (
|
||||
DetectorProviderSnapshot,
|
||||
RfDetrShadowDetectorProvider,
|
||||
)
|
||||
from k1link.perception.geometry import Ravnoves00GeometryAssociationProvider
|
||||
from k1link.perception.graph_contracts import (
|
||||
DeliveredFrame,
|
||||
GraphRunMode,
|
||||
GraphRunResultV2,
|
||||
GraphState,
|
||||
TerminalOutcomeType,
|
||||
)
|
||||
from k1link.perception.m48s_advisory import (
|
||||
AdvisoryFamily,
|
||||
M48sSemanticAdvisory,
|
||||
advisory_policy_matrix,
|
||||
project_m48s_advisories,
|
||||
)
|
||||
from k1link.perception.m48s_reference_graph_runtime import (
|
||||
build_m48s_reference_graph_runtime,
|
||||
)
|
||||
from k1link.perception.motion import ClassIndependentMotionEstimator
|
||||
from k1link.perception.object_understanding import AdvisoryResponse
|
||||
from k1link.perception.reference_graph_runtime import ReferenceGraphRuntimePaths
|
||||
from k1link.perception.providers import SourcePacket
|
||||
from k1link.perception.rolling_map import RollingLocalObstacleMapProvider
|
||||
from k1link.perception.temporal import BoundedSpatialTemporalProvider
|
||||
|
||||
SCHEMA_VERSION: Final = "missioncore.m48s-reference-graph-shadow-load/v0"
|
||||
FRAME_EVIDENCE_SCHEMA: Final = "missioncore.m48s-reference-graph-frame-evidence/v0"
|
||||
AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
class GpuTelemetry:
|
||||
def __init__(self, interval_seconds: float) -> None:
|
||||
self.interval_seconds = interval_seconds
|
||||
self.samples: list[dict[str, float]] = []
|
||||
self._stop = threading.Event()
|
||||
self._thread = threading.Thread(target=self._run, daemon=True)
|
||||
|
||||
def __enter__(self) -> GpuTelemetry:
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args: object) -> None:
|
||||
self._stop.set()
|
||||
self._thread.join(timeout=10.0)
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[
|
||||
"nvidia-smi",
|
||||
"--query-gpu=utilization.gpu,memory.used,power.draw,temperature.gpu",
|
||||
"--format=csv,noheader,nounits",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10.0,
|
||||
)
|
||||
values = [float(value.strip()) for value in completed.stdout.split(",")]
|
||||
if len(values) == 4:
|
||||
self.samples.append(
|
||||
{
|
||||
"gpu_utilization_percent": values[0],
|
||||
"gpu_memory_used_mib": values[1],
|
||||
"gpu_power_w": values[2],
|
||||
"gpu_temperature_c": values[3],
|
||||
}
|
||||
)
|
||||
except (OSError, ValueError, subprocess.SubprocessError):
|
||||
pass
|
||||
self._stop.wait(self.interval_seconds)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in (
|
||||
"graph-config",
|
||||
"baseline-profile",
|
||||
"detector-profile",
|
||||
"geometry-profile",
|
||||
"temporal-motion-profile",
|
||||
"rolling-map-profile",
|
||||
"threat-profile",
|
||||
"camera-index",
|
||||
"source-pack",
|
||||
"local-surface",
|
||||
"video",
|
||||
"valid-fov-mask",
|
||||
):
|
||||
parser.add_argument(f"--{name}", type=Path, required=True)
|
||||
parser.add_argument("--triton-origin", default="http://127.0.0.1:8000")
|
||||
parser.add_argument("--loops", type=int, default=1)
|
||||
parser.add_argument("--maximum-frames", type=int)
|
||||
parser.add_argument("--telemetry-interval-seconds", type=float, default=1.0)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--progress", type=Path, required=True)
|
||||
parser.add_argument("--frame-ledger", type=Path, required=True)
|
||||
arguments = parser.parse_args()
|
||||
if arguments.loops < 1:
|
||||
raise RuntimeError("loop count must be positive")
|
||||
if arguments.maximum_frames is not None and arguments.maximum_frames < 1:
|
||||
raise RuntimeError("maximum frame count must be positive")
|
||||
if arguments.telemetry_interval_seconds <= 0:
|
||||
raise RuntimeError("telemetry interval must be positive")
|
||||
output = arguments.output.absolute()
|
||||
progress = arguments.progress.absolute()
|
||||
frame_ledger = arguments.frame_ledger.absolute()
|
||||
if output.exists() or progress.exists() or frame_ledger.exists():
|
||||
raise RuntimeError("result, progress, or frame ledger artifact already exists")
|
||||
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
paths = ReferenceGraphRuntimePaths(
|
||||
graph_config=arguments.graph_config,
|
||||
baseline_profile=arguments.baseline_profile,
|
||||
geometry_profile=arguments.geometry_profile,
|
||||
temporal_motion_profile=arguments.temporal_motion_profile,
|
||||
rolling_map_profile=arguments.rolling_map_profile,
|
||||
threat_profile=arguments.threat_profile,
|
||||
camera_index=arguments.camera_index,
|
||||
source_pack=arguments.source_pack,
|
||||
local_surface=arguments.local_surface,
|
||||
video=arguments.video,
|
||||
valid_fov_mask=arguments.valid_fov_mask,
|
||||
)
|
||||
started_ns = time.monotonic_ns()
|
||||
started_utc_ns = time.time_ns()
|
||||
rss_before_kib = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||||
loop_documents: list[dict[str, object]] = []
|
||||
completion_ages_ms: list[float] = []
|
||||
map_output_ages_ms: list[float] = []
|
||||
all_deliveries: list[DeliveredFrame] = []
|
||||
with (
|
||||
progress.open("x", encoding="utf-8") as progress_stream,
|
||||
frame_ledger.open("x", encoding="utf-8") as frame_ledger_stream,
|
||||
GpuTelemetry(arguments.telemetry_interval_seconds) as gpu,
|
||||
):
|
||||
for loop_index in range(arguments.loops):
|
||||
loop_completion_ages_ns: list[int] = []
|
||||
setup_started_ns = time.monotonic_ns()
|
||||
|
||||
with build_m48s_reference_graph_runtime(
|
||||
paths=paths,
|
||||
detector_profile=arguments.detector_profile,
|
||||
triton_origin=arguments.triton_origin,
|
||||
run_mode=GraphRunMode.SOURCE_PACED_LATEST_WINS,
|
||||
delivery_observer=partial(
|
||||
_record_completion_age,
|
||||
loop_completion_ages_ns,
|
||||
),
|
||||
delivery_evidence_observer=partial(
|
||||
_record_delivery_evidence,
|
||||
frame_ledger_stream,
|
||||
loop_index,
|
||||
),
|
||||
maximum_frames=arguments.maximum_frames,
|
||||
) as runtime:
|
||||
loop_started_ns = time.monotonic_ns()
|
||||
result = runtime.graph.run()
|
||||
loop_completed_ns = time.monotonic_ns()
|
||||
detector_snapshot = cast(
|
||||
RfDetrShadowDetectorProvider,
|
||||
runtime.graph.detector,
|
||||
).snapshot()
|
||||
provider_snapshots = {
|
||||
"geometry": asdict(
|
||||
cast(
|
||||
Ravnoves00GeometryAssociationProvider,
|
||||
runtime.graph.geometry,
|
||||
).snapshot()
|
||||
),
|
||||
"temporal": asdict(
|
||||
cast(
|
||||
BoundedSpatialTemporalProvider,
|
||||
runtime.graph.temporal,
|
||||
).snapshot()
|
||||
),
|
||||
"motion": asdict(
|
||||
cast(
|
||||
ClassIndependentMotionEstimator,
|
||||
runtime.graph.motion,
|
||||
).snapshot()
|
||||
),
|
||||
"rolling": asdict(
|
||||
cast(
|
||||
RollingLocalObstacleMapProvider,
|
||||
runtime.graph.rolling,
|
||||
).snapshot()
|
||||
),
|
||||
}
|
||||
if not isinstance(result, GraphRunResultV2):
|
||||
raise RuntimeError("RF-DETR shadow did not return a V2 graph result")
|
||||
loop_wall_seconds = (loop_completed_ns - loop_started_ns) / 1_000_000_000.0
|
||||
setup_seconds = (loop_started_ns - setup_started_ns) / 1_000_000_000.0
|
||||
if len(loop_completion_ages_ns) != len(result.deliveries):
|
||||
raise RuntimeError("final delivery timing accounting did not close")
|
||||
loop_document = _loop_document(
|
||||
loop_index=loop_index,
|
||||
result=result,
|
||||
detector_snapshot=detector_snapshot,
|
||||
provider_snapshots=provider_snapshots,
|
||||
completion_ages_ns=loop_completion_ages_ns,
|
||||
wall_seconds=loop_wall_seconds,
|
||||
setup_seconds=setup_seconds,
|
||||
)
|
||||
loop_documents.append(loop_document)
|
||||
completion_ages_ms.extend(value / 1_000_000.0 for value in loop_completion_ages_ns)
|
||||
map_output_ages_ms.extend(
|
||||
delivery.obstacle_map.output_age_ns / 1_000_000.0
|
||||
for delivery in result.deliveries
|
||||
)
|
||||
all_deliveries.extend(result.deliveries)
|
||||
frame_ledger_stream.flush()
|
||||
progress_row = {
|
||||
"loop": loop_index + 1,
|
||||
"loops": arguments.loops,
|
||||
"elapsed_seconds": round(
|
||||
(time.monotonic_ns() - started_ns) / 1_000_000_000.0,
|
||||
3,
|
||||
),
|
||||
"admitted": result.admitted_count,
|
||||
"delivered": len(result.deliveries),
|
||||
"world_state_completion_p95_ms": _distribution(
|
||||
[value / 1_000_000.0 for value in loop_completion_ages_ns]
|
||||
)["p95"],
|
||||
}
|
||||
progress_stream.write(json.dumps(progress_row, separators=(",", ":")) + "\n")
|
||||
progress_stream.flush()
|
||||
print(json.dumps(progress_row, sort_keys=True), flush=True)
|
||||
|
||||
completed_ns = time.monotonic_ns()
|
||||
wall_seconds = (completed_ns - started_ns) / 1_000_000_000.0
|
||||
rss_after_kib = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||||
accounting: Counter[str] = Counter()
|
||||
for loop in loop_documents:
|
||||
accounting.update(cast(Mapping[str, int], loop["terminal_outcomes"]))
|
||||
admitted = sum(cast(int, loop["admitted_count"]) for loop in loop_documents)
|
||||
delivered = len(all_deliveries)
|
||||
processing_wall_seconds = sum(
|
||||
cast(float, loop["wall_seconds"]) for loop in loop_documents
|
||||
)
|
||||
queue_high_watermarks = {
|
||||
stage: max(
|
||||
cast(dict[str, int], loop["queue_high_watermarks"])[stage]
|
||||
for loop in loop_documents
|
||||
)
|
||||
for stage in ("detector", "geometry", "temporal", "rolling", "threat")
|
||||
}
|
||||
advisories = tuple(
|
||||
advisory
|
||||
for delivery in all_deliveries
|
||||
for advisory in project_m48s_advisories(delivery)
|
||||
)
|
||||
identity = _identity_metrics(all_deliveries)
|
||||
semantic = _semantic_metrics(all_deliveries, advisories)
|
||||
world_state_fps = delivered / processing_wall_seconds
|
||||
checks = {
|
||||
"loop_count_completed": len(loop_documents) == arguments.loops,
|
||||
"graph_stopped_cleanly": all(
|
||||
loop["state"] == GraphState.STOPPED.value for loop in loop_documents
|
||||
),
|
||||
"closed_terminal_accounting": admitted == sum(accounting.values()),
|
||||
"zero_failed_stale_rejected_or_unavailable": all(
|
||||
accounting[outcome.value] == 0
|
||||
for outcome in (
|
||||
TerminalOutcomeType.FAILED,
|
||||
TerminalOutcomeType.STALE,
|
||||
TerminalOutcomeType.REJECTED,
|
||||
TerminalOutcomeType.UNAVAILABLE,
|
||||
)
|
||||
),
|
||||
"minimum_world_state_fps": world_state_fps >= 9.5,
|
||||
"maximum_world_state_completion_p95_ms": (
|
||||
_distribution(completion_ages_ms)["p95"] <= 175.0
|
||||
),
|
||||
"bounded_latest_wins_queues": all(value <= 2 for value in queue_high_watermarks.values()),
|
||||
"temporal_identity_reuse_observed": cast(
|
||||
int,
|
||||
identity["multi_frame_component_count"],
|
||||
)
|
||||
> 0,
|
||||
"conservative_unknown_motion_advisory": _unknown_motion_is_conservative(advisories),
|
||||
"distinct_class_family_policy": len(set(advisory_policy_matrix().values()))
|
||||
== len(AdvisoryFamily),
|
||||
"authority_remains_false": all(value is False for value in AUTHORITY.values()),
|
||||
}
|
||||
integrated_runtime_gate_passed = all(checks.values())
|
||||
document = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"source": {
|
||||
"source_id": "RAVNOVES00",
|
||||
"loops": arguments.loops,
|
||||
"maximum_frames_per_loop": arguments.maximum_frames,
|
||||
},
|
||||
"identity": {
|
||||
"worker_id": "worker-006",
|
||||
"graph_id": "reference-perception-graph/v2",
|
||||
"detector_provider_id": "triton-rf-detr-large-coco-risk-fp16-shadow/v0",
|
||||
"inputs": _input_digests(paths, arguments.detector_profile),
|
||||
},
|
||||
"execution": {
|
||||
"run_mode": GraphRunMode.SOURCE_PACED_LATEST_WINS.value,
|
||||
"wall_seconds": round(wall_seconds, 6),
|
||||
"source_processing_wall_seconds": round(processing_wall_seconds, 6),
|
||||
"admitted_frames": admitted,
|
||||
"delivered_world_states": delivered,
|
||||
"effective_world_state_fps": round(world_state_fps, 6),
|
||||
"terminal_outcomes": dict(sorted(accounting.items())),
|
||||
"queue_high_watermarks": queue_high_watermarks,
|
||||
"loops": loop_documents,
|
||||
"frame_evidence": {
|
||||
"schema_version": FRAME_EVIDENCE_SCHEMA,
|
||||
"path": frame_ledger.name,
|
||||
"row_count": delivered,
|
||||
"sha256": _sha256(frame_ledger),
|
||||
},
|
||||
},
|
||||
"metrics": {
|
||||
"world_state_completion_age_ms": _distribution(completion_ages_ms),
|
||||
"local_obstacle_map_output_age_ms": _distribution(map_output_ages_ms),
|
||||
"identity_continuity": identity,
|
||||
"semantic_advisory": semantic,
|
||||
"gpu": _telemetry_summary(gpu.samples),
|
||||
"process_peak_rss_before_mib": round(rss_before_kib / 1024.0, 6),
|
||||
"process_peak_rss_after_mib": round(rss_after_kib / 1024.0, 6),
|
||||
},
|
||||
"checks": checks,
|
||||
"integrated_runtime_gate_passed": integrated_runtime_gate_passed,
|
||||
"independent_track_identity_quality_evaluated": False,
|
||||
"independent_risk_policy_quality_evaluated": False,
|
||||
"production_accepted": False,
|
||||
"started_utc_ns": started_utc_ns,
|
||||
"completed_utc_ns": time.time_ns(),
|
||||
"completed": True,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
output.write_bytes(_canonical_json(document) + b"\n")
|
||||
print(output)
|
||||
print(json.dumps(checks, indent=2, sort_keys=True))
|
||||
return 0 if integrated_runtime_gate_passed else 2
|
||||
|
||||
|
||||
def _record_completion_age(
|
||||
samples: list[int],
|
||||
_delivery: DeliveredFrame,
|
||||
completion_age_ns: int,
|
||||
) -> None:
|
||||
samples.append(completion_age_ns)
|
||||
|
||||
|
||||
def _record_delivery_evidence(
|
||||
stream: TextIO,
|
||||
loop_index: int,
|
||||
delivery: DeliveredFrame,
|
||||
packet: SourcePacket,
|
||||
proposals: tuple[ObjectProposal2D, ...],
|
||||
associated_proposal_ids: frozenset[str],
|
||||
completion_age_ns: int,
|
||||
) -> None:
|
||||
if delivery.sequence != packet.envelope.sequence:
|
||||
raise RuntimeError("delivery evidence sequence binding changed")
|
||||
row = {
|
||||
"schema_version": FRAME_EVIDENCE_SCHEMA,
|
||||
"loop_index": loop_index,
|
||||
"source_envelope": packet.envelope.to_dict(),
|
||||
"completion_age_ns": completion_age_ns,
|
||||
"local_obstacle_map_output_age_ns": delivery.obstacle_map.output_age_ns,
|
||||
"delivery": delivery.canonical_dict(),
|
||||
"detector_proposals": [proposal.to_dict() for proposal in proposals],
|
||||
"associated_proposal_ids": sorted(associated_proposal_ids),
|
||||
"semantic_advisories": [
|
||||
advisory.to_dict() for advisory in project_m48s_advisories(delivery)
|
||||
],
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
stream.write(_canonical_json(row).decode("utf-8") + "\n")
|
||||
|
||||
|
||||
def _loop_document(
|
||||
*,
|
||||
loop_index: int,
|
||||
result: GraphRunResultV2,
|
||||
detector_snapshot: DetectorProviderSnapshot,
|
||||
provider_snapshots: dict[str, dict[str, object]],
|
||||
completion_ages_ns: list[int],
|
||||
wall_seconds: float,
|
||||
setup_seconds: float,
|
||||
) -> dict[str, object]:
|
||||
outcomes = Counter(item.outcome.value for item in result.terminal_outcomes)
|
||||
outcome_stages = Counter(
|
||||
f"{item.outcome.value}:{item.stage_id}:{item.reason}"
|
||||
for item in result.terminal_outcomes
|
||||
)
|
||||
return {
|
||||
"loop_index": loop_index,
|
||||
"state": result.state.value,
|
||||
"wall_seconds": round(wall_seconds, 6),
|
||||
"setup_seconds": round(setup_seconds, 6),
|
||||
"admitted_count": result.admitted_count,
|
||||
"delivered_count": len(result.deliveries),
|
||||
"effective_world_state_fps": round(len(result.deliveries) / wall_seconds, 6),
|
||||
"terminal_outcomes": dict(sorted(outcomes.items())),
|
||||
"terminal_outcome_stages": dict(sorted(outcome_stages.items())),
|
||||
"terminal_outcome_details": [item.to_dict() for item in result.terminal_outcomes],
|
||||
"queue_high_watermarks": dict(result.queue_high_watermarks),
|
||||
"canonical_payload_sha256": result.canonical_payload_sha256,
|
||||
"world_state_completion_age_ms": _distribution(
|
||||
[value / 1_000_000.0 for value in completion_ages_ns]
|
||||
),
|
||||
"detector": asdict(detector_snapshot),
|
||||
"providers": provider_snapshots,
|
||||
}
|
||||
|
||||
|
||||
def _identity_metrics(deliveries: list[DeliveredFrame]) -> dict[str, object]:
|
||||
appearances: dict[str, list[int]] = defaultdict(list)
|
||||
duplicate_components = 0
|
||||
for delivery in deliveries:
|
||||
components = (
|
||||
*delivery.obstacle_map.occupied,
|
||||
*delivery.obstacle_map.unknown,
|
||||
)
|
||||
ids = [item.component_id for item in components]
|
||||
duplicate_components += len(ids) - len(set(ids))
|
||||
for component_id in ids:
|
||||
appearances[component_id].append(delivery.sequence)
|
||||
lengths = [len(values) for values in appearances.values()]
|
||||
return {
|
||||
"unique_component_count": len(appearances),
|
||||
"multi_frame_component_count": sum(value > 1 for value in lengths),
|
||||
"maximum_component_publications": max(lengths, default=0),
|
||||
"mean_component_publications": round(float(np.mean(lengths)), 6) if lengths else 0.0,
|
||||
"duplicate_component_ids_within_frame": duplicate_components,
|
||||
"identity_scope": "ephemeral",
|
||||
"independent_truth_available": False,
|
||||
}
|
||||
|
||||
|
||||
def _semantic_metrics(
|
||||
deliveries: list[DeliveredFrame],
|
||||
advisories: tuple[M48sSemanticAdvisory, ...],
|
||||
) -> dict[str, object]:
|
||||
hints: Counter[str] = Counter()
|
||||
motions: Counter[str] = Counter()
|
||||
for delivery in deliveries:
|
||||
obstacles = (
|
||||
*delivery.obstacle_map.occupied,
|
||||
*delivery.obstacle_map.unknown,
|
||||
)
|
||||
for obstacle in obstacles:
|
||||
hints[obstacle.semantic_hint or "geometry-only"] += 1
|
||||
motions[obstacle.motion.value] += 1
|
||||
for proposal in delivery.obstacle_map.camera_uncertainty:
|
||||
hints[proposal.semantic_hint or "unclassified-camera"] += 1
|
||||
motions[MotionState.UNKNOWN.value] += 1
|
||||
families = Counter(item.family.value for item in advisories)
|
||||
responses = Counter(
|
||||
response.value
|
||||
for item in advisories
|
||||
for response in item.responses
|
||||
)
|
||||
return {
|
||||
"semantic_hint_counts": dict(sorted(hints.items())),
|
||||
"motion_counts": dict(sorted(motions.items())),
|
||||
"advisory_family_counts": dict(sorted(families.items())),
|
||||
"advisory_response_counts": dict(sorted(responses.items())),
|
||||
"policy_matrix": {
|
||||
family.value: [response.value for response in policy]
|
||||
for family, policy in advisory_policy_matrix().items()
|
||||
},
|
||||
"additional_inference_passes": 0,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
|
||||
|
||||
def _unknown_motion_is_conservative(
|
||||
advisories: tuple[M48sSemanticAdvisory, ...],
|
||||
) -> bool:
|
||||
for item in advisories:
|
||||
if item.motion is not MotionState.UNKNOWN:
|
||||
continue
|
||||
responses = set(item.responses)
|
||||
if not responses.intersection(
|
||||
{
|
||||
AdvisoryResponse.REDUCE_SPEED,
|
||||
AdvisoryResponse.YIELD,
|
||||
AdvisoryResponse.STOP,
|
||||
AdvisoryResponse.ROUTE_AROUND,
|
||||
}
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _distribution(values: list[float]) -> dict[str, float]:
|
||||
if not values:
|
||||
return {"mean": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0, "maximum": 0.0}
|
||||
array = np.asarray(values, dtype=np.float64)
|
||||
return {
|
||||
"mean": round(float(array.mean()), 6),
|
||||
"p50": round(float(np.percentile(array, 50)), 6),
|
||||
"p95": round(float(np.percentile(array, 95)), 6),
|
||||
"p99": round(float(np.percentile(array, 99)), 6),
|
||||
"maximum": round(float(array.max()), 6),
|
||||
}
|
||||
|
||||
|
||||
def _telemetry_summary(samples: list[dict[str, float]]) -> dict[str, Any]:
|
||||
result: dict[str, Any] = {"sample_count": len(samples)}
|
||||
for key in (
|
||||
"gpu_utilization_percent",
|
||||
"gpu_memory_used_mib",
|
||||
"gpu_power_w",
|
||||
"gpu_temperature_c",
|
||||
):
|
||||
result[key] = _distribution([sample[key] for sample in samples])
|
||||
return result
|
||||
|
||||
|
||||
def _input_digests(
|
||||
paths: ReferenceGraphRuntimePaths,
|
||||
detector_profile: Path,
|
||||
) -> dict[str, str]:
|
||||
values = {
|
||||
field.name: _sha256(getattr(paths, field.name))
|
||||
for field in fields(ReferenceGraphRuntimePaths)
|
||||
}
|
||||
values["detector_profile"] = _sha256(detector_profile)
|
||||
return dict(sorted(values.items()))
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.resolve(strict=True).open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,417 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run a source-paced bounded-queue RF-DETR/Triton stability qualification."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import resource
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter, deque
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
import av # type: ignore[import-not-found]
|
||||
import numpy as np
|
||||
import run_rf_detr_triton as qualifier # type: ignore[import-not-found]
|
||||
import tritonclient.http as httpclient # type: ignore[import-not-found]
|
||||
from PIL import Image
|
||||
|
||||
SCHEMA_VERSION: Final = "missioncore.m48s-rf-detr-source-paced-load/v0"
|
||||
SOURCE_SHA256: Final = "cadd1696ff000904eb78633a0a8418104b8024f178b91f3421789021ccb160e8"
|
||||
SOURCE_FPS: Final = 10.003944527024467
|
||||
AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SourceFrame:
|
||||
sequence: int
|
||||
scheduled_ns: int
|
||||
image: Image.Image
|
||||
|
||||
|
||||
class LatestWinsQueue:
|
||||
"""Bounded source queue that reports every replacement explicitly."""
|
||||
|
||||
def __init__(self, capacity: int) -> None:
|
||||
if capacity < 1:
|
||||
raise ValueError("queue capacity must be positive")
|
||||
self.capacity = capacity
|
||||
self._items: deque[SourceFrame] = deque()
|
||||
self._condition = threading.Condition()
|
||||
self._closed = False
|
||||
self.replacements = 0
|
||||
self.maximum_depth = 0
|
||||
|
||||
def put(self, item: SourceFrame) -> None:
|
||||
with self._condition:
|
||||
if self._closed:
|
||||
return
|
||||
if len(self._items) == self.capacity:
|
||||
self._items.popleft()
|
||||
self.replacements += 1
|
||||
self._items.append(item)
|
||||
self.maximum_depth = max(self.maximum_depth, len(self._items))
|
||||
self._condition.notify()
|
||||
|
||||
def get(self) -> SourceFrame | None:
|
||||
with self._condition:
|
||||
while not self._items and not self._closed:
|
||||
self._condition.wait(timeout=1.0)
|
||||
if self._items:
|
||||
return self._items.popleft()
|
||||
return None
|
||||
|
||||
def close(self) -> None:
|
||||
with self._condition:
|
||||
self._closed = True
|
||||
self._condition.notify_all()
|
||||
|
||||
|
||||
class GpuTelemetry:
|
||||
def __init__(self, interval_seconds: float) -> None:
|
||||
self.interval_seconds = interval_seconds
|
||||
self.samples: list[dict[str, float]] = []
|
||||
self._stop = threading.Event()
|
||||
self._thread = threading.Thread(target=self._run, daemon=True)
|
||||
|
||||
def __enter__(self) -> GpuTelemetry:
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args: object) -> None:
|
||||
self._stop.set()
|
||||
self._thread.join(timeout=10.0)
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[
|
||||
"nvidia-smi",
|
||||
"--query-gpu=utilization.gpu,memory.used,power.draw,temperature.gpu",
|
||||
"--format=csv,noheader,nounits",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10.0,
|
||||
)
|
||||
values = [float(value.strip()) for value in completed.stdout.split(",")]
|
||||
if len(values) == 4:
|
||||
self.samples.append(
|
||||
{
|
||||
"gpu_utilization_percent": values[0],
|
||||
"gpu_memory_used_mib": values[1],
|
||||
"gpu_power_w": values[2],
|
||||
"gpu_temperature_c": values[3],
|
||||
}
|
||||
)
|
||||
except (OSError, ValueError, subprocess.SubprocessError):
|
||||
pass
|
||||
self._stop.wait(self.interval_seconds)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--source-video", type=Path, required=True)
|
||||
parser.add_argument("--valid-fov-mask", type=Path, required=True)
|
||||
parser.add_argument("--endpoint", default="localhost:8100")
|
||||
parser.add_argument("--model-name", default="rf_detr_large")
|
||||
parser.add_argument("--duration-seconds", type=float, default=1800.0)
|
||||
parser.add_argument("--queue-capacity", type=int, default=2)
|
||||
parser.add_argument("--telemetry-interval-seconds", type=float, default=1.0)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--progress", type=Path, required=True)
|
||||
arguments = parser.parse_args()
|
||||
if arguments.duration_seconds <= 0:
|
||||
raise RuntimeError("duration must be positive")
|
||||
if arguments.telemetry_interval_seconds <= 0:
|
||||
raise RuntimeError("telemetry interval must be positive")
|
||||
source = arguments.source_video.resolve(strict=True)
|
||||
if _sha256(source) != SOURCE_SHA256:
|
||||
raise RuntimeError("RAVNOVES00 camera stream identity changed")
|
||||
mask = qualifier._load_mask(arguments.valid_fov_mask.resolve(strict=True))
|
||||
output = arguments.output.absolute()
|
||||
progress = arguments.progress.absolute()
|
||||
if output.exists() or progress.exists():
|
||||
raise RuntimeError("load result or progress artifact already exists")
|
||||
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
|
||||
client = httpclient.InferenceServerClient(arguments.endpoint, concurrency=1)
|
||||
if not client.is_server_ready() or not client.is_model_ready(arguments.model_name):
|
||||
raise RuntimeError("isolated Triton or RF-DETR model is not ready")
|
||||
metadata = client.get_model_metadata(arguments.model_name)
|
||||
qualifier._validate_metadata(metadata)
|
||||
triton_before = client.get_inference_statistics(arguments.model_name)
|
||||
gpu_before = qualifier._gpu_sample()
|
||||
rss_before_kib = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||||
queue = LatestWinsQueue(arguments.queue_capacity)
|
||||
producer_stop = threading.Event()
|
||||
producer_errors: list[str] = []
|
||||
produced_count = [0]
|
||||
source_loops = [0]
|
||||
started_ns = time.monotonic_ns()
|
||||
started_utc_ns = time.time_ns()
|
||||
producer = threading.Thread(
|
||||
target=_produce,
|
||||
args=(
|
||||
source,
|
||||
queue,
|
||||
producer_stop,
|
||||
producer_errors,
|
||||
produced_count,
|
||||
source_loops,
|
||||
started_ns,
|
||||
arguments.duration_seconds,
|
||||
),
|
||||
daemon=True,
|
||||
)
|
||||
consumed = 0
|
||||
failures = 0
|
||||
class_counts: Counter[str] = Counter()
|
||||
end_to_end_ms: list[float] = []
|
||||
triton_round_trip_ms: list[float] = []
|
||||
completion_age_ms: list[float] = []
|
||||
last_progress_ns = started_ns
|
||||
producer.start()
|
||||
with progress.open("x", encoding="utf-8") as progress_stream, GpuTelemetry(
|
||||
arguments.telemetry_interval_seconds
|
||||
) as telemetry:
|
||||
try:
|
||||
while True:
|
||||
item = queue.get()
|
||||
if item is None:
|
||||
break
|
||||
raw, timing = qualifier._infer(client, arguments.model_name, item.image)
|
||||
detections = qualifier._qualify(raw, mask, item.image.size)
|
||||
for detection in detections:
|
||||
if float(detection["score"]) >= 0.5:
|
||||
class_counts[str(detection["label"])] += 1
|
||||
consumed += 1
|
||||
end_to_end_ms.append(timing["end_to_end"])
|
||||
triton_round_trip_ms.append(timing["triton_round_trip"])
|
||||
completion_age_ms.append((time.monotonic_ns() - item.scheduled_ns) / 1_000_000.0)
|
||||
now_ns = time.monotonic_ns()
|
||||
if now_ns - last_progress_ns >= 60_000_000_000:
|
||||
row = {
|
||||
"elapsed_seconds": round((now_ns - started_ns) / 1_000_000_000.0, 3),
|
||||
"produced": produced_count[0],
|
||||
"consumed": consumed,
|
||||
"replacements": queue.replacements,
|
||||
"completion_age_p95_ms": _distribution(completion_age_ms)["p95"],
|
||||
}
|
||||
progress_stream.write(json.dumps(row, separators=(",", ":")) + "\n")
|
||||
progress_stream.flush()
|
||||
print(json.dumps(row, sort_keys=True), flush=True)
|
||||
last_progress_ns = now_ns
|
||||
except BaseException:
|
||||
failures += 1
|
||||
raise
|
||||
finally:
|
||||
producer_stop.set()
|
||||
queue.close()
|
||||
producer.join(timeout=15.0)
|
||||
|
||||
completed_ns = time.monotonic_ns()
|
||||
wall_seconds = (completed_ns - started_ns) / 1_000_000_000.0
|
||||
if producer.is_alive():
|
||||
raise RuntimeError("source producer did not stop")
|
||||
if producer_errors:
|
||||
raise RuntimeError(f"source producer failed: {producer_errors}")
|
||||
triton_after = client.get_inference_statistics(arguments.model_name)
|
||||
gpu_after = qualifier._gpu_sample()
|
||||
rss_after_kib = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||||
core = _distribution(end_to_end_ms)
|
||||
completion_age = _distribution(completion_age_ms)
|
||||
telemetry_summary = _telemetry_summary(telemetry.samples)
|
||||
checks = {
|
||||
"minimum_duration": wall_seconds >= arguments.duration_seconds,
|
||||
"zero_failures": failures == 0,
|
||||
"minimum_source_fps": consumed / arguments.duration_seconds >= 9.5,
|
||||
"maximum_detector_completion_age_p95_ms": completion_age["p95"] <= 175.0,
|
||||
"maximum_worker_vram_gib": (
|
||||
float(telemetry_summary["gpu_memory_used_mib"]["maximum"]) <= 20 * 1024
|
||||
),
|
||||
"no_sustained_100_percent_gpu": _longest_full_gpu_run(telemetry.samples)
|
||||
< max(5, round(30.0 / arguments.telemetry_interval_seconds)),
|
||||
"bounded_latest_wins_queue": queue.maximum_depth <= arguments.queue_capacity,
|
||||
"triton_request_accounting": _triton_inference_count(triton_after)
|
||||
- _triton_inference_count(triton_before)
|
||||
== consumed,
|
||||
}
|
||||
detector_load_gate_passed = all(checks.values())
|
||||
document = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"profile_id": "rf-detr-large-coco-704-trt11-fp16-source-paced/v0",
|
||||
"source": {
|
||||
"source_id": "RAVNOVES00",
|
||||
"sha256": SOURCE_SHA256,
|
||||
"frame_rate": SOURCE_FPS,
|
||||
"duration_seconds": arguments.duration_seconds,
|
||||
"source_loops": source_loops[0],
|
||||
},
|
||||
"model_metadata": metadata,
|
||||
"execution": {
|
||||
"worker_id": "worker-006",
|
||||
"queue_policy": "bounded-latest-wins",
|
||||
"queue_capacity": arguments.queue_capacity,
|
||||
"queue_maximum_depth": queue.maximum_depth,
|
||||
"source_frames_produced": produced_count[0],
|
||||
"source_frames_consumed": consumed,
|
||||
"source_frame_replacements": queue.replacements,
|
||||
"failures": failures,
|
||||
"wall_seconds": round(wall_seconds, 6),
|
||||
"effective_consumed_fps": round(consumed / arguments.duration_seconds, 6),
|
||||
"background_services_retained": True,
|
||||
},
|
||||
"metrics": {
|
||||
"end_to_end_ms": core,
|
||||
"triton_round_trip_ms": _distribution(triton_round_trip_ms),
|
||||
"detector_completion_age_ms": completion_age,
|
||||
"class_counts_at_score_0_5": dict(sorted(class_counts.items())),
|
||||
"gpu": telemetry_summary,
|
||||
"gpu_before": gpu_before,
|
||||
"gpu_after": gpu_after,
|
||||
"process_peak_rss_before_mib": round(rss_before_kib / 1024.0, 6),
|
||||
"process_peak_rss_after_mib": round(rss_after_kib / 1024.0, 6),
|
||||
"triton_statistics_before": triton_before,
|
||||
"triton_statistics_after": triton_after,
|
||||
},
|
||||
"checks": checks,
|
||||
"detector_load_gate_passed": detector_load_gate_passed,
|
||||
"integrated_world_state_gate_evaluated": False,
|
||||
"candidate_accepted": False,
|
||||
"started_utc_ns": started_utc_ns,
|
||||
"completed_utc_ns": time.time_ns(),
|
||||
"completed": True,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
output.write_bytes(_canonical_json(document) + b"\n")
|
||||
print(output)
|
||||
print(json.dumps(document["execution"], indent=2, sort_keys=True))
|
||||
print(json.dumps(checks, indent=2, sort_keys=True))
|
||||
return 0 if detector_load_gate_passed else 2
|
||||
|
||||
|
||||
def _produce(
|
||||
source: Path,
|
||||
queue: LatestWinsQueue,
|
||||
stop: threading.Event,
|
||||
errors: list[str],
|
||||
produced_count: list[int],
|
||||
source_loops: list[int],
|
||||
started_ns: int,
|
||||
duration_seconds: float,
|
||||
) -> None:
|
||||
try:
|
||||
period_ns = round(1_000_000_000.0 / SOURCE_FPS)
|
||||
while not stop.is_set():
|
||||
container = av.open(str(source))
|
||||
try:
|
||||
streams = container.streams.video
|
||||
if len(streams) != 1:
|
||||
raise RuntimeError("RAVNOVES00 video stream count changed")
|
||||
for decoded in container.decode(streams[0]):
|
||||
sequence = produced_count[0]
|
||||
scheduled_ns = started_ns + sequence * period_ns
|
||||
if scheduled_ns - started_ns >= round(duration_seconds * 1_000_000_000):
|
||||
queue.close()
|
||||
return
|
||||
remaining_seconds = (scheduled_ns - time.monotonic_ns()) / 1_000_000_000.0
|
||||
if remaining_seconds > 0 and stop.wait(remaining_seconds):
|
||||
queue.close()
|
||||
return
|
||||
bgr = decoded.to_ndarray(format="bgr24")
|
||||
if bgr.shape != (600, 800, 3):
|
||||
raise RuntimeError("RAVNOVES00 source raster changed")
|
||||
rgb = np.ascontiguousarray(bgr[:, :, ::-1])
|
||||
queue.put(SourceFrame(sequence, scheduled_ns, Image.fromarray(rgb, "RGB")))
|
||||
produced_count[0] += 1
|
||||
if stop.is_set():
|
||||
queue.close()
|
||||
return
|
||||
source_loops[0] += 1
|
||||
finally:
|
||||
container.close()
|
||||
except BaseException as error:
|
||||
errors.append(f"{type(error).__name__}: {error}")
|
||||
queue.close()
|
||||
|
||||
|
||||
def _distribution(values: list[float]) -> dict[str, float]:
|
||||
if not values:
|
||||
return {"mean": 0.0, "p50": 0.0, "p95": 0.0, "maximum": 0.0}
|
||||
array = np.asarray(values, dtype=np.float64)
|
||||
return {
|
||||
"mean": round(float(array.mean()), 6),
|
||||
"p50": round(float(np.percentile(array, 50)), 6),
|
||||
"p95": round(float(np.percentile(array, 95)), 6),
|
||||
"maximum": round(float(array.max()), 6),
|
||||
}
|
||||
|
||||
|
||||
def _telemetry_summary(samples: list[dict[str, float]]) -> dict[str, Any]:
|
||||
summary: dict[str, Any] = {"sample_count": len(samples)}
|
||||
for key in (
|
||||
"gpu_utilization_percent",
|
||||
"gpu_memory_used_mib",
|
||||
"gpu_power_w",
|
||||
"gpu_temperature_c",
|
||||
):
|
||||
summary[key] = _distribution([sample[key] for sample in samples])
|
||||
summary["longest_100_percent_gpu_sample_run"] = _longest_full_gpu_run(samples)
|
||||
return summary
|
||||
|
||||
|
||||
def _longest_full_gpu_run(samples: list[dict[str, float]]) -> int:
|
||||
longest = 0
|
||||
current = 0
|
||||
for sample in samples:
|
||||
if sample["gpu_utilization_percent"] >= 100.0:
|
||||
current += 1
|
||||
longest = max(longest, current)
|
||||
else:
|
||||
current = 0
|
||||
return longest
|
||||
|
||||
|
||||
def _triton_inference_count(statistics: dict[str, Any]) -> int:
|
||||
model_stats = statistics.get("model_stats")
|
||||
if not isinstance(model_stats, list) or len(model_stats) != 1:
|
||||
raise RuntimeError("unexpected Triton model statistics")
|
||||
count = model_stats[0].get("inference_count")
|
||||
if not isinstance(count, int):
|
||||
raise RuntimeError("Triton inference count is unavailable")
|
||||
return count
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,508 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Qualify the pinned RF-DETR TensorRT finalist through isolated Triton."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any, Final, cast
|
||||
|
||||
import numpy as np
|
||||
import tritonclient.http as httpclient # type: ignore[import-not-found]
|
||||
from PIL import Image, ImageDraw
|
||||
from torchvision.transforms import functional as vision_functional # type: ignore[import-not-found]
|
||||
|
||||
WORKER_RUN_SCHEMA: Final = "missioncore.m48s-fixed-detector-candidate-worker/v0"
|
||||
EXACT_FRAME_NAMES: Final = (
|
||||
"frame-000121.png",
|
||||
"frame-000131.png",
|
||||
"frame-000253.png",
|
||||
"frame-000275.png",
|
||||
"frame-000443.png",
|
||||
"frame-000463.png",
|
||||
"frame-001094.png",
|
||||
"frame-001228.png",
|
||||
"frame-001454.png",
|
||||
"frame-001856.png",
|
||||
"frame-002386.png",
|
||||
)
|
||||
COCO_CLASSES: Final = (
|
||||
"person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck",
|
||||
"boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench",
|
||||
"bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra",
|
||||
"giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
|
||||
"skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove",
|
||||
"skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork",
|
||||
"knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli",
|
||||
"carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant",
|
||||
"bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard",
|
||||
"cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book",
|
||||
"clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush",
|
||||
)
|
||||
COCO_SPARSE_IDS: Final = (
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21,
|
||||
22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
|
||||
43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
|
||||
61, 62, 63, 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
|
||||
82, 84, 85, 86, 87, 88, 89, 90,
|
||||
)
|
||||
COCO_SPARSE_NAMES: Final = dict(zip(COCO_SPARSE_IDS, COCO_CLASSES, strict=True))
|
||||
AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
MEANS: Final = (0.485, 0.456, 0.406)
|
||||
STDS: Final = (0.229, 0.224, 0.225)
|
||||
MINIMUM_BOX_AREA_PIXELS: Final = 64.0
|
||||
MAXIMUM_BOX_AREA_FRACTION: Final = 0.5
|
||||
MINIMUM_VALID_FOV_FRACTION: Final = 0.5
|
||||
OVERLAY_THRESHOLD: Final = 0.25
|
||||
|
||||
|
||||
class RawDetection(tuple[int, str, float, tuple[float, float, float, float]]):
|
||||
__slots__ = ()
|
||||
|
||||
def __new__(
|
||||
cls,
|
||||
class_id: int,
|
||||
label: str,
|
||||
score: float,
|
||||
box: tuple[float, float, float, float],
|
||||
) -> RawDetection:
|
||||
return tuple.__new__(cls, (class_id, label, score, box))
|
||||
|
||||
@property
|
||||
def class_id(self) -> int:
|
||||
return self[0]
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return self[1]
|
||||
|
||||
@property
|
||||
def score(self) -> float:
|
||||
return self[2]
|
||||
|
||||
@property
|
||||
def box(self) -> tuple[float, float, float, float]:
|
||||
return self[3]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--endpoint", default="localhost:8100")
|
||||
parser.add_argument("--model-name", default="rf_detr_large")
|
||||
parser.add_argument("--profile-id", required=True)
|
||||
parser.add_argument("--provider-id", required=True)
|
||||
parser.add_argument("--upstream-revision", required=True)
|
||||
parser.add_argument("--input-root", type=Path, required=True)
|
||||
parser.add_argument("--valid-fov-mask", type=Path, required=True)
|
||||
parser.add_argument("--engine", type=Path, required=True)
|
||||
parser.add_argument("--expected-engine-sha256", required=True)
|
||||
parser.add_argument("--checkpoint-sha256", required=True)
|
||||
parser.add_argument("--pytorch-reference", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--warmup-iterations", type=int, default=10)
|
||||
parser.add_argument("--benchmark-iterations", type=int, default=100)
|
||||
arguments = parser.parse_args()
|
||||
if arguments.warmup_iterations < 1 or arguments.benchmark_iterations < 1:
|
||||
raise RuntimeError("warmup and benchmark iterations must be positive")
|
||||
input_root = arguments.input_root.resolve(strict=True)
|
||||
images = tuple(sorted(input_root.glob("frame-*.png")))
|
||||
if tuple(path.name for path in images) != EXACT_FRAME_NAMES:
|
||||
raise RuntimeError("Triton qualifier requires the exact M48S risk slice")
|
||||
mask = _load_mask(arguments.valid_fov_mask.resolve(strict=True))
|
||||
engine = arguments.engine.resolve(strict=True)
|
||||
engine_sha256 = _sha256(engine)
|
||||
if engine_sha256 != arguments.expected_engine_sha256:
|
||||
raise RuntimeError("TensorRT engine SHA-256 does not match the pinned finalist")
|
||||
reference_path = arguments.pytorch_reference.resolve(strict=True)
|
||||
output = arguments.output.absolute()
|
||||
if output.exists():
|
||||
raise RuntimeError("Triton Worker output already exists")
|
||||
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
overlay_root = output.parent / f"{output.stem}-overlays"
|
||||
overlay_root.mkdir(mode=0o700)
|
||||
|
||||
client = httpclient.InferenceServerClient(arguments.endpoint, concurrency=1)
|
||||
if not client.is_server_ready() or not client.is_model_ready(arguments.model_name):
|
||||
raise RuntimeError("isolated Triton or RF-DETR model is not ready")
|
||||
metadata = client.get_model_metadata(arguments.model_name)
|
||||
_validate_metadata(metadata)
|
||||
statistics_before = client.get_inference_statistics(arguments.model_name)
|
||||
gpu_before = _gpu_sample()
|
||||
started_utc_ns = time.time_ns()
|
||||
with Image.open(images[0]) as opened:
|
||||
warmup_image = opened.convert("RGB")
|
||||
for _ in range(arguments.warmup_iterations):
|
||||
_infer(client, arguments.model_name, warmup_image)
|
||||
|
||||
frames = []
|
||||
totals: Counter[str] = Counter()
|
||||
evidence_timings = []
|
||||
network_timings = []
|
||||
for image_path in images:
|
||||
with Image.open(image_path) as opened:
|
||||
image = opened.convert("RGB")
|
||||
raw, timing = _infer(client, arguments.model_name, image)
|
||||
evidence_timings.append(timing["end_to_end"])
|
||||
network_timings.append(timing["triton_round_trip"])
|
||||
detections = _qualify(raw, mask, image.size)
|
||||
totals["frame_count"] += 1
|
||||
totals["detection_count"] += len(detections)
|
||||
for detection in detections:
|
||||
totals[f"class:{detection['label']}"] += 1
|
||||
frames.append(
|
||||
{
|
||||
"frame_name": image_path.name,
|
||||
"source_sha256": _sha256(image_path),
|
||||
"detections": detections,
|
||||
"timing_ms": timing,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
)
|
||||
_write_overlay(image, detections, overlay_root / image_path.name)
|
||||
|
||||
with Image.open(input_root / "frame-000253.png") as opened:
|
||||
benchmark_image = opened.convert("RGB")
|
||||
benchmark_timings = []
|
||||
benchmark_network_timings = []
|
||||
for _ in range(arguments.benchmark_iterations):
|
||||
_, timing = _infer(client, arguments.model_name, benchmark_image)
|
||||
benchmark_timings.append(timing["end_to_end"])
|
||||
benchmark_network_timings.append(timing["triton_round_trip"])
|
||||
gpu_after = _gpu_sample()
|
||||
statistics_after = client.get_inference_statistics(arguments.model_name)
|
||||
benchmark = _timing_summary(benchmark_timings)
|
||||
parity = _reference_parity(frames, reference_path)
|
||||
metrics = {
|
||||
"frames": {"requested": 11, "completed": totals["frame_count"]},
|
||||
"detection_count_at_minimum_score_0_1": totals["detection_count"],
|
||||
"class_counts_at_minimum_score_0_1": {
|
||||
key.removeprefix("class:"): value
|
||||
for key, value in sorted(totals.items())
|
||||
if key.startswith("class:")
|
||||
},
|
||||
"evidence_timing_ms": _timing_summary(evidence_timings),
|
||||
"evidence_triton_round_trip_ms": _timing_summary(network_timings),
|
||||
"benchmark": {
|
||||
"frame_name": "frame-000253.png",
|
||||
"iterations": arguments.benchmark_iterations,
|
||||
"timing_ms": benchmark,
|
||||
"triton_round_trip_ms": _timing_summary(benchmark_network_timings),
|
||||
"end_to_end_capacity_fps": round(1000.0 / benchmark["mean"], 6),
|
||||
},
|
||||
"pytorch_reference_parity": parity,
|
||||
"triton_statistics_before": statistics_before,
|
||||
"triton_statistics_after": statistics_after,
|
||||
"gpu_before": gpu_before,
|
||||
"gpu_after": gpu_after,
|
||||
}
|
||||
document = {
|
||||
"schema_version": WORKER_RUN_SCHEMA,
|
||||
"profile_id": arguments.profile_id,
|
||||
"provider_id": arguments.provider_id,
|
||||
"candidate": "rf-detr-large-coco-tensorrt",
|
||||
"upstream_revision": arguments.upstream_revision,
|
||||
"checkpoint_sha256": arguments.checkpoint_sha256,
|
||||
"engine_sha256": engine_sha256,
|
||||
"started_utc_ns": started_utc_ns,
|
||||
"completed_utc_ns": time.time_ns(),
|
||||
"completed": totals["frame_count"] == 11,
|
||||
"execution": {
|
||||
"worker_id": "worker-006",
|
||||
"device": gpu_after["name"],
|
||||
"precision": "strongly-typed-fp16",
|
||||
"inference_passes_per_evidence_frame": 1,
|
||||
"warmup_iterations": arguments.warmup_iterations,
|
||||
"benchmark_iterations": arguments.benchmark_iterations,
|
||||
"isolated_triton": True,
|
||||
"concurrent_services_retained": True,
|
||||
},
|
||||
"model_metadata": metadata,
|
||||
"frames": frames,
|
||||
"metrics": metrics,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
output.write_bytes(_canonical_json(document) + b"\n")
|
||||
print(output)
|
||||
print(json.dumps(metrics, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _infer(
|
||||
client: httpclient.InferenceServerClient,
|
||||
model_name: str,
|
||||
image: Image.Image,
|
||||
) -> tuple[tuple[RawDetection, ...], dict[str, float]]:
|
||||
started = time.perf_counter_ns()
|
||||
tensor = vision_functional.to_tensor(image)
|
||||
tensor = vision_functional.resize(tensor, [704, 704], antialias=False)
|
||||
tensor = vision_functional.normalize(tensor, MEANS, STDS)
|
||||
batch = np.ascontiguousarray(tensor.unsqueeze(0).numpy(), dtype=np.float32)
|
||||
preprocessed = time.perf_counter_ns()
|
||||
infer_input = httpclient.InferInput("input", batch.shape, "FP32")
|
||||
infer_input.set_data_from_numpy(batch, binary_data=True)
|
||||
response = client.infer(
|
||||
model_name,
|
||||
[infer_input],
|
||||
outputs=[
|
||||
httpclient.InferRequestedOutput("dets", binary_data=True),
|
||||
httpclient.InferRequestedOutput("labels", binary_data=True),
|
||||
],
|
||||
)
|
||||
inferred = time.perf_counter_ns()
|
||||
boxes = response.as_numpy("dets")
|
||||
logits = response.as_numpy("labels")
|
||||
if boxes is None or logits is None:
|
||||
raise RuntimeError("Triton RF-DETR response is missing outputs")
|
||||
detections = decode_outputs(boxes, logits, image.size)
|
||||
completed = time.perf_counter_ns()
|
||||
return detections, {
|
||||
"preprocess": _milliseconds(started, preprocessed),
|
||||
"triton_round_trip": _milliseconds(preprocessed, inferred),
|
||||
"postprocess": _milliseconds(inferred, completed),
|
||||
"end_to_end": _milliseconds(started, completed),
|
||||
}
|
||||
|
||||
|
||||
def decode_outputs(
|
||||
boxes: np.ndarray[Any, Any],
|
||||
logits: np.ndarray[Any, Any],
|
||||
image_size: tuple[int, int],
|
||||
) -> tuple[RawDetection, ...]:
|
||||
if boxes.shape != (1, 300, 4) or logits.shape != (1, 300, 91):
|
||||
raise RuntimeError(f"unexpected RF-DETR output shapes: {boxes.shape}, {logits.shape}")
|
||||
probabilities = 1.0 / (1.0 + np.exp(-np.clip(logits[0].astype(np.float32), -80.0, 80.0)))
|
||||
flattened = probabilities.reshape(-1)
|
||||
topk = np.argsort(-flattened, kind="stable")[:300]
|
||||
width, height = image_size
|
||||
decoded = []
|
||||
for flat_index in topk:
|
||||
score = float(flattened[flat_index])
|
||||
if score <= 0.1:
|
||||
continue
|
||||
query_index = int(flat_index // logits.shape[2])
|
||||
sparse_class_id = int(flat_index % logits.shape[2])
|
||||
label = COCO_SPARSE_NAMES.get(sparse_class_id)
|
||||
if label is None:
|
||||
continue
|
||||
center_x, center_y, box_width, box_height = (
|
||||
float(value) for value in boxes[0, query_index].astype(np.float32)
|
||||
)
|
||||
box = (
|
||||
(center_x - box_width / 2.0) * width,
|
||||
(center_y - box_height / 2.0) * height,
|
||||
(center_x + box_width / 2.0) * width,
|
||||
(center_y + box_height / 2.0) * height,
|
||||
)
|
||||
decoded.append(RawDetection(COCO_CLASSES.index(label), label, score, box))
|
||||
return tuple(decoded)
|
||||
|
||||
|
||||
def _qualify(
|
||||
detections: tuple[RawDetection, ...],
|
||||
mask: np.ndarray[Any, Any],
|
||||
image_size: tuple[int, int],
|
||||
) -> list[dict[str, object]]:
|
||||
width, height = image_size
|
||||
image_area = float(width * height)
|
||||
qualified = []
|
||||
for detection in detections:
|
||||
x1, y1, x2, y2 = detection.box
|
||||
x1 = max(0.0, min(float(width), x1))
|
||||
y1 = max(0.0, min(float(height), y1))
|
||||
x2 = max(0.0, min(float(width), x2))
|
||||
y2 = max(0.0, min(float(height), y2))
|
||||
area = max(0.0, x2 - x1) * max(0.0, y2 - y1)
|
||||
if area < MINIMUM_BOX_AREA_PIXELS or area > MAXIMUM_BOX_AREA_FRACTION * image_area:
|
||||
continue
|
||||
center_x = min(width - 1, max(0, int((x1 + x2) / 2.0)))
|
||||
center_y = min(height - 1, max(0, int((y1 + y2) / 2.0)))
|
||||
if not bool(mask[center_y, center_x]):
|
||||
continue
|
||||
ix1 = min(width - 1, max(0, int(np.floor(x1))))
|
||||
iy1 = min(height - 1, max(0, int(np.floor(y1))))
|
||||
ix2 = min(width, max(ix1 + 1, int(np.ceil(x2))))
|
||||
iy2 = min(height, max(iy1 + 1, int(np.ceil(y2))))
|
||||
valid_fraction = float(mask[iy1:iy2, ix1:ix2].mean())
|
||||
if valid_fraction < MINIMUM_VALID_FOV_FRACTION:
|
||||
continue
|
||||
qualified.append(
|
||||
{
|
||||
"class_id": detection.class_id,
|
||||
"label": detection.label,
|
||||
"score": round(detection.score, 6),
|
||||
"bbox_xyxy": [round(value, 3) for value in (x1, y1, x2, y2)],
|
||||
"valid_fov_fraction": round(valid_fraction, 6),
|
||||
}
|
||||
)
|
||||
qualified.sort(key=lambda item: (-cast(float, item["score"]), cast(int, item["class_id"])))
|
||||
return qualified
|
||||
|
||||
|
||||
def _reference_parity(frames: list[dict[str, object]], reference_path: Path) -> dict[str, object]:
|
||||
reference = json.loads(reference_path.read_text(encoding="utf-8"))
|
||||
if not isinstance(reference, dict):
|
||||
raise RuntimeError("PyTorch reference must be a JSON object")
|
||||
reference_frames = reference.get("frames")
|
||||
if not isinstance(reference_frames, list):
|
||||
raise RuntimeError("PyTorch reference lacks frames")
|
||||
actual = _best_detection(frames, "frame-000253.png", "dog")
|
||||
expected = _best_detection(reference_frames, "frame-000253.png", "dog")
|
||||
if actual is None or expected is None:
|
||||
return {
|
||||
"frame_000253_dog_present_in_pytorch": expected is not None,
|
||||
"frame_000253_dog_present_in_tensorrt": actual is not None,
|
||||
"score_absolute_delta": None,
|
||||
"box_iou": None,
|
||||
"passed": False,
|
||||
}
|
||||
score_delta = abs(
|
||||
float(cast(float, actual["score"])) - float(cast(float, expected["score"]))
|
||||
)
|
||||
iou = _box_iou(
|
||||
cast(list[float], actual["bbox_xyxy"]),
|
||||
cast(list[float], expected["bbox_xyxy"]),
|
||||
)
|
||||
return {
|
||||
"frame_000253_dog_present_in_pytorch": True,
|
||||
"frame_000253_dog_present_in_tensorrt": True,
|
||||
"pytorch_score": expected["score"],
|
||||
"tensorrt_score": actual["score"],
|
||||
"score_absolute_delta": round(score_delta, 6),
|
||||
"box_iou": round(iou, 6),
|
||||
"passed": score_delta <= 0.05 and iou >= 0.9,
|
||||
}
|
||||
|
||||
|
||||
def _best_detection(
|
||||
frames: list[Any], frame_name: str, label: str
|
||||
) -> dict[str, object] | None:
|
||||
for frame in frames:
|
||||
if not isinstance(frame, dict) or frame.get("frame_name") != frame_name:
|
||||
continue
|
||||
detections = frame.get("detections")
|
||||
if not isinstance(detections, list):
|
||||
raise RuntimeError("reference frame detections must be a list")
|
||||
selected = [
|
||||
item
|
||||
for item in detections
|
||||
if isinstance(item, dict) and item.get("label") == label
|
||||
]
|
||||
return max(selected, key=lambda item: float(item["score"])) if selected else None
|
||||
raise RuntimeError(f"reference frame not found: {frame_name}")
|
||||
|
||||
|
||||
def _box_iou(left: list[float], right: list[float]) -> float:
|
||||
intersection_width = max(0.0, min(left[2], right[2]) - max(left[0], right[0]))
|
||||
intersection_height = max(0.0, min(left[3], right[3]) - max(left[1], right[1]))
|
||||
intersection = intersection_width * intersection_height
|
||||
left_area = max(0.0, left[2] - left[0]) * max(0.0, left[3] - left[1])
|
||||
right_area = max(0.0, right[2] - right[0]) * max(0.0, right[3] - right[1])
|
||||
union = left_area + right_area - intersection
|
||||
return intersection / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def _validate_metadata(metadata: dict[str, Any]) -> None:
|
||||
expected_inputs = [{"name": "input", "datatype": "FP32", "shape": [1, 3, 704, 704]}]
|
||||
expected_outputs = [
|
||||
{"name": "dets", "datatype": "FP16", "shape": [1, 300, 4]},
|
||||
{"name": "labels", "datatype": "FP16", "shape": [1, 300, 91]},
|
||||
]
|
||||
if metadata.get("inputs") != expected_inputs or metadata.get("outputs") != expected_outputs:
|
||||
raise RuntimeError(f"unexpected isolated Triton model metadata: {metadata}")
|
||||
|
||||
|
||||
def _write_overlay(
|
||||
image: Image.Image, detections: list[dict[str, object]], destination: Path
|
||||
) -> None:
|
||||
annotated = image.copy()
|
||||
draw = ImageDraw.Draw(annotated)
|
||||
for detection in detections:
|
||||
score = cast(float, detection["score"])
|
||||
if score < OVERLAY_THRESHOLD:
|
||||
continue
|
||||
box = cast(list[float], detection["bbox_xyxy"])
|
||||
draw.rectangle(box, outline=(0, 220, 112), width=3)
|
||||
draw.text(
|
||||
(box[0] + 3, box[1] + 3),
|
||||
f"{detection['label']} {score:.2f}",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
annotated.save(destination)
|
||||
|
||||
|
||||
def _load_mask(path: Path) -> np.ndarray[Any, Any]:
|
||||
with Image.open(path) as image:
|
||||
array = np.asarray(image.convert("L"), dtype=np.uint8)
|
||||
if array.shape != (600, 800):
|
||||
raise RuntimeError("valid-FOV mask must be 800x600")
|
||||
return array > 0
|
||||
|
||||
|
||||
def _gpu_sample() -> dict[str, object]:
|
||||
completed = subprocess.run(
|
||||
[
|
||||
"nvidia-smi",
|
||||
"--query-gpu=name,memory.total,memory.used,utilization.gpu,temperature.gpu,power.draw",
|
||||
"--format=csv,noheader,nounits",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
values = [value.strip() for value in completed.stdout.strip().split(",")]
|
||||
if len(values) != 6:
|
||||
raise RuntimeError("unexpected nvidia-smi response")
|
||||
return {
|
||||
"name": values[0],
|
||||
"memory_total_mib": float(values[1]),
|
||||
"memory_used_mib": float(values[2]),
|
||||
"utilization_gpu_percent": float(values[3]),
|
||||
"temperature_c": float(values[4]),
|
||||
"power_w": float(values[5]),
|
||||
}
|
||||
|
||||
|
||||
def _timing_summary(values: list[float]) -> dict[str, float]:
|
||||
array = np.asarray(values, dtype=np.float64)
|
||||
return {
|
||||
"mean": round(float(array.mean()), 6),
|
||||
"p50": round(float(np.percentile(array, 50)), 6),
|
||||
"p95": round(float(np.percentile(array, 95)), 6),
|
||||
"max": round(float(array.max()), 6),
|
||||
}
|
||||
|
||||
|
||||
def _milliseconds(started: int, completed: int) -> float:
|
||||
return round(max(0, completed - started) / 1_000_000.0, 6)
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the bounded raw-KB4 M48S semantic shadow result."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.perception.semantic_shadow_replay import build_semantic_shadow_replay
|
||||
|
||||
FRAME_INDICES = (121, 131, 253, 275, 443, 463, 1094, 1228, 1454, 1856, 2386)
|
||||
DETECTOR_RESULT_ID = (
|
||||
"m4-detector-replay-11f83f2e0b81758ac2a5a5fc54e9d293b501678df5f6ef97b5c6069ba08605c5"
|
||||
)
|
||||
VALID_FOV_RESULT_ID = (
|
||||
"valid-fov-mask-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
default_runtime = (
|
||||
repository
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/worker-results"
|
||||
/ "fovfill11-20260825T0755Z"
|
||||
)
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--repository-root", type=Path, default=repository)
|
||||
parser.add_argument("--worker-results", type=Path, default=default_runtime)
|
||||
parser.add_argument(
|
||||
"--source-frames",
|
||||
type=Path,
|
||||
default=(repository / ".runtime/compute-experiments/m48s-semantic-shadow/raw-11-frames-v1"),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--inference-frames",
|
||||
type=Path,
|
||||
default=(
|
||||
repository
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow"
|
||||
/ "raw-11-valid-fov-fill-v1"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-root",
|
||||
type=Path,
|
||||
default=(repository / ".runtime/compute-experiments/m48s-semantic-shadow/results"),
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
root = arguments.repository_root.resolve(strict=True)
|
||||
worker = arguments.worker_results.resolve(strict=True)
|
||||
result = build_semantic_shadow_replay(
|
||||
repository_root=root,
|
||||
profile_path=root / "config/perception/open-vocabulary-semantic-shadow-v0.json",
|
||||
vocabulary_path=root / "config/perception/object-semantic-vocabulary-v0.json",
|
||||
detector_result_root=root / ".runtime/worker-results" / DETECTOR_RESULT_ID,
|
||||
source_frames_root=arguments.source_frames,
|
||||
inference_frames_root=arguments.inference_frames,
|
||||
valid_fov_mask_path=(
|
||||
root / ".runtime/compute-experiments/e1/valid-fov" / VALID_FOV_RESULT_ID / "mask.png"
|
||||
),
|
||||
worker_result_roots={
|
||||
"urban-static/v0": worker / "results-static/trt_inference",
|
||||
"urban-agents/v0": worker / "results-agents/trt_inference",
|
||||
"urban-vehicles/v0": worker / "results-vehicles/trt_inference",
|
||||
},
|
||||
worker_identity_path=worker / "worker-identity.json",
|
||||
frame_indices=FRAME_INDICES,
|
||||
output_root=arguments.output_root,
|
||||
)
|
||||
print(result.result_id)
|
||||
print(json.dumps(result.metrics, ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish the sealed M4.8S detector evidence as an immutable LAB result."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.laboratory.m48s_fixed_class_detector_lab import (
|
||||
build_m48s_fixed_class_detector_lab,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
result = build_m48s_fixed_class_detector_lab(
|
||||
repository_root=repository,
|
||||
output_root=(
|
||||
repository
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/"
|
||||
"fixed-class-detector-lab-results"
|
||||
),
|
||||
)
|
||||
print(result.result_id)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Seal the bounded M48S fixed-class detector tournament."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from collections import Counter
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
from k1link.perception.fixed_class_detector_tournament import (
|
||||
TOURNAMENT_SCHEMA,
|
||||
CandidateWorkerRun,
|
||||
canonical_json,
|
||||
false_authority,
|
||||
sha256_path,
|
||||
)
|
||||
|
||||
RESULT_PREFIX: Final = "m48s-fixed-detector-tournament-"
|
||||
THRESHOLDS: Final = (0.25, 0.5)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
runtime = repository / ".runtime/compute-experiments/m48s-semantic-shadow"
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--profile",
|
||||
type=Path,
|
||||
default=repository / "config/perception/fixed-class-detector-tournament-v0.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dfine-result",
|
||||
type=Path,
|
||||
default=runtime / "fixed-detector-tournament-worker/dfine-s-worker.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--rf-detr-result",
|
||||
type=Path,
|
||||
default=runtime / "fixed-detector-tournament-worker/rf-detr-large-worker.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--yolox-result",
|
||||
type=Path,
|
||||
default=(
|
||||
runtime
|
||||
/ "yolox-all-coco-results"
|
||||
/ (
|
||||
"m48s-yolox-all-coco-shadow-"
|
||||
"7dbe6043b3fc12c7ddb162f609f883d86b34a4f2dd3785a632795f257e192d06"
|
||||
)
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-root",
|
||||
type=Path,
|
||||
default=runtime / "fixed-detector-tournament-results",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
profile_path = arguments.profile.resolve(strict=True)
|
||||
profile = _load_object(profile_path)
|
||||
if profile.get("schema_version") != "missioncore.fixed-class-detector-tournament-profile/v0":
|
||||
raise RuntimeError("unexpected fixed-class tournament profile schema")
|
||||
dfine_path = arguments.dfine_result.resolve(strict=True)
|
||||
rf_detr_path = arguments.rf_detr_result.resolve(strict=True)
|
||||
dfine = CandidateWorkerRun.from_path(dfine_path)
|
||||
rf_detr = CandidateWorkerRun.from_path(rf_detr_path)
|
||||
yolox_root = arguments.yolox_result.resolve(strict=True)
|
||||
yolox_manifest_path = yolox_root / "manifest.json"
|
||||
yolox_frames_path = yolox_root / "frames.jsonl"
|
||||
yolox_manifest = _load_object(yolox_manifest_path)
|
||||
yolox_frames = _load_jsonl(yolox_frames_path)
|
||||
if yolox_manifest.get("result_id") != profile["source"]["baseline_result_id"]:
|
||||
raise RuntimeError("YOLOX baseline result does not match the tournament profile")
|
||||
worker_paths = {
|
||||
dfine.profile_id: dfine_path,
|
||||
rf_detr.profile_id: rf_detr_path,
|
||||
}
|
||||
candidate_summaries = {
|
||||
dfine.profile_id: _candidate_summary(dfine),
|
||||
rf_detr.profile_id: _candidate_summary(rf_detr),
|
||||
}
|
||||
baseline_summary = {
|
||||
"profile_id": "yolox-s-raw-kb4-all-coco-shadow/v2",
|
||||
"provider_id": "triton-yolox-s-raw-kb4-all-coco/v2",
|
||||
"quality": {
|
||||
str(threshold): _yolox_quality(yolox_frames, threshold)
|
||||
for threshold in THRESHOLDS
|
||||
},
|
||||
"worker_metrics": yolox_manifest["metrics"],
|
||||
}
|
||||
evidence = {
|
||||
"profile_sha256": sha256_path(profile_path),
|
||||
"worker_result_sha256": {
|
||||
profile_id: sha256_path(path) for profile_id, path in sorted(worker_paths.items())
|
||||
},
|
||||
"yolox_manifest_sha256": sha256_path(yolox_manifest_path),
|
||||
"yolox_frames_sha256": sha256_path(yolox_frames_path),
|
||||
"manual_visual_review": {
|
||||
"reviewed_frames": [253, 275, 443, 1228],
|
||||
"rf_detr_frame_253_dog_box_correct": True,
|
||||
"dfine_frame_253_dog_box_present_at_0_25": False,
|
||||
"dfine_observed_confusions": [
|
||||
"dog-as-skateboard",
|
||||
"scanner-body-as-surfboard",
|
||||
"duplicate-risk-labels-on-one-object",
|
||||
],
|
||||
"rf_detr_observed_advantage": "correct dog and cleaner person/vehicle labeling",
|
||||
"ground_truth": False,
|
||||
},
|
||||
}
|
||||
decision = {
|
||||
"finalist_profile_id": rf_detr.profile_id,
|
||||
"finalist_provider_id": rf_detr.provider_id,
|
||||
"eliminated_profile_ids": [
|
||||
"yolox-s-raw-kb4-all-coco-shadow/v2",
|
||||
dfine.profile_id,
|
||||
],
|
||||
"reasons": {
|
||||
"yolox-s-raw-kb4-all-coco-shadow/v2": (
|
||||
"visible frame-253 dog missed; retained only as regression baseline"
|
||||
),
|
||||
dfine.profile_id: (
|
||||
"frame-253 dog missed at 0.25 and 0.5; more risk-class confusions; slower qualifier"
|
||||
),
|
||||
rf_detr.profile_id: (
|
||||
"correct frame-253 dog at 0.741; cleaner risk labels; 44.786 FPS PyTorch qualifier"
|
||||
),
|
||||
},
|
||||
"candidate_accepted": False,
|
||||
"next_gate": (
|
||||
"RF-DETR-L TensorRT FP16 through isolated Triton, then full recorded "
|
||||
"concurrent-load replay"
|
||||
),
|
||||
}
|
||||
identity = {
|
||||
"schema_version": TOURNAMENT_SCHEMA,
|
||||
"profile_id": profile["profile_id"],
|
||||
"evidence": evidence,
|
||||
"baseline": baseline_summary,
|
||||
"candidates": candidate_summaries,
|
||||
"decision": decision,
|
||||
"completed": True,
|
||||
"accepted": False,
|
||||
"authority": false_authority(),
|
||||
}
|
||||
result_id = RESULT_PREFIX + hashlib.sha256(canonical_json(identity)).hexdigest()
|
||||
output_root = arguments.output_root.absolute()
|
||||
output_root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
destination = output_root / result_id
|
||||
if destination.exists():
|
||||
raise RuntimeError("immutable fixed-class tournament result already exists")
|
||||
destination.mkdir(mode=0o700)
|
||||
for source, name in (
|
||||
(dfine_path, "dfine-s-worker.json"),
|
||||
(rf_detr_path, "rf-detr-large-worker.json"),
|
||||
):
|
||||
(destination / name).write_bytes(source.read_bytes())
|
||||
manifest = {"result_id": result_id, **identity}
|
||||
(destination / "manifest.json").write_bytes(canonical_json(manifest) + b"\n")
|
||||
(destination / "report.json").write_bytes(
|
||||
canonical_json(
|
||||
{
|
||||
"schema_version": TOURNAMENT_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"completed": True,
|
||||
"accepted": False,
|
||||
"baseline": baseline_summary,
|
||||
"candidates": candidate_summaries,
|
||||
"decision": decision,
|
||||
"authority": false_authority(),
|
||||
}
|
||||
)
|
||||
+ b"\n"
|
||||
)
|
||||
print(result_id)
|
||||
print(json.dumps(decision, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _candidate_summary(run: CandidateWorkerRun) -> dict[str, object]:
|
||||
return {
|
||||
"profile_id": run.profile_id,
|
||||
"provider_id": run.provider_id,
|
||||
"upstream_revision": run.upstream_revision,
|
||||
"checkpoint_sha256": run.checkpoint_sha256,
|
||||
"quality": {
|
||||
str(threshold): run.quality_summary(threshold=threshold)
|
||||
for threshold in THRESHOLDS
|
||||
},
|
||||
"worker_metrics": run.metrics,
|
||||
}
|
||||
|
||||
|
||||
def _yolox_quality(frames: list[Mapping[str, Any]], threshold: float) -> dict[str, object]:
|
||||
selected = []
|
||||
dog_selected = []
|
||||
for frame in frames:
|
||||
detections = frame.get("all_coco_detections")
|
||||
if not isinstance(detections, list):
|
||||
raise RuntimeError("YOLOX frame lacks all-COCO detections")
|
||||
for detection in detections:
|
||||
if not isinstance(detection, dict):
|
||||
raise RuntimeError("YOLOX detection must be an object")
|
||||
score = detection.get("score")
|
||||
label = detection.get("label")
|
||||
if isinstance(score, int | float) and score >= threshold and isinstance(label, str):
|
||||
selected.append(label)
|
||||
if frame.get("frame_name") == "frame-000253.jpg" and label == "dog":
|
||||
dog_selected.append(float(score))
|
||||
counts = Counter(selected)
|
||||
return {
|
||||
"threshold": threshold,
|
||||
"detection_count": len(selected),
|
||||
"class_counts": dict(sorted(counts.items())),
|
||||
"frame_000253_dog_detected": bool(dog_selected),
|
||||
"frame_000253_dog_max_score": max(dog_selected) if dog_selected else None,
|
||||
}
|
||||
|
||||
|
||||
def _load_object(path: Path) -> Mapping[str, Any]:
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(document, dict):
|
||||
raise RuntimeError(f"JSON document must be an object: {path}")
|
||||
return document
|
||||
|
||||
|
||||
def _load_jsonl(path: Path) -> list[Mapping[str, Any]]:
|
||||
rows: list[Mapping[str, Any]] = []
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
document = json.loads(line)
|
||||
if not isinstance(document, dict):
|
||||
raise RuntimeError(f"JSONL row must be an object: {path}")
|
||||
rows.append(document)
|
||||
return rows
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Seal exact per-frame evidence from the full M4.8S reference-graph replay."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
from k1link.perception.fixed_class_detector_tournament import canonical_json, sha256_path
|
||||
|
||||
SCHEMA_VERSION: Final = "missioncore.m48s-reference-graph-replay/v0"
|
||||
RAW_SCHEMA_VERSION: Final = "missioncore.m48s-reference-graph-shadow-load/v0"
|
||||
FRAME_SCHEMA_VERSION: Final = "missioncore.m48s-reference-graph-frame-evidence/v0"
|
||||
RESULT_PREFIX: Final = "m48s-reference-graph-replay-"
|
||||
AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--raw-result", type=Path, required=True)
|
||||
parser.add_argument("--progress", type=Path, required=True)
|
||||
parser.add_argument("--frames", type=Path, required=True)
|
||||
parser.add_argument("--wheel-sha256", required=True)
|
||||
parser.add_argument("--worker-release-id", required=True)
|
||||
parser.add_argument(
|
||||
"--output-root",
|
||||
type=Path,
|
||||
default=(
|
||||
repository
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/"
|
||||
"reference-graph-replay-results"
|
||||
),
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
paths = {
|
||||
"raw_result": arguments.raw_result.resolve(strict=True),
|
||||
"progress": arguments.progress.resolve(strict=True),
|
||||
"frames": arguments.frames.resolve(strict=True),
|
||||
}
|
||||
raw = _load_object(paths["raw_result"])
|
||||
frame_summary = _validate(raw, paths["frames"])
|
||||
if (
|
||||
len(arguments.wheel_sha256) != 64
|
||||
or any(value not in "0123456789abcdef" for value in arguments.wheel_sha256)
|
||||
):
|
||||
raise RuntimeError("worker wheel digest is invalid")
|
||||
if not arguments.worker_release_id.startswith("mission-core-m48s-reference-graph-replay-"):
|
||||
raise RuntimeError("worker replay release identity is invalid")
|
||||
|
||||
evidence = {
|
||||
"files": {
|
||||
name: {"sha256": sha256_path(path), "size_bytes": path.stat().st_size}
|
||||
for name, path in sorted(paths.items())
|
||||
},
|
||||
"worker": {
|
||||
"worker_id": "worker-006",
|
||||
"release_id": arguments.worker_release_id,
|
||||
"wheel_sha256": arguments.wheel_sha256,
|
||||
"historical_triton_action": "none",
|
||||
"durable_worker_action": "none",
|
||||
},
|
||||
"execution": raw["execution"],
|
||||
"metrics": raw["metrics"],
|
||||
"frame_summary": frame_summary,
|
||||
"checks": raw["checks"],
|
||||
}
|
||||
identity = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"source_session_id": "20260720T065719Z_viewer_live",
|
||||
"source_id": "RAVNOVES00",
|
||||
"graph_id": "reference-perception-graph/v2",
|
||||
"detector_provider_id": "triton-rf-detr-large-coco-risk-fp16-shadow/v0",
|
||||
"evidence": evidence,
|
||||
"completed": True,
|
||||
"accepted": True,
|
||||
"production_accepted": False,
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
result_id = RESULT_PREFIX + hashlib.sha256(canonical_json(identity)).hexdigest()
|
||||
output_root = arguments.output_root.expanduser().absolute()
|
||||
output_root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
destination = output_root / result_id
|
||||
if destination.exists():
|
||||
existing = _load_object(destination / "manifest.json")
|
||||
if existing.get("result_id") != result_id or existing.get("identity") != identity:
|
||||
raise RuntimeError("immutable replay result exists with different identity")
|
||||
print(result_id)
|
||||
return 0
|
||||
|
||||
temporary = Path(tempfile.mkdtemp(prefix=".m48s-reference-replay-", dir=output_root))
|
||||
try:
|
||||
shutil.copyfile(paths["raw_result"], temporary / "worker-result.json")
|
||||
shutil.copyfile(paths["progress"], temporary / "worker-progress.jsonl")
|
||||
shutil.copyfile(paths["frames"], temporary / "frames.jsonl")
|
||||
report = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"result_id": result_id,
|
||||
"completed": True,
|
||||
"accepted": True,
|
||||
"production_accepted": False,
|
||||
"frame_summary": frame_summary,
|
||||
"limitations": [
|
||||
"This is source-paced replay evidence, not physical-live authority.",
|
||||
"Latest-wins superseded source frames retain exact camera/LiDAR source evidence but have no invented world state.",
|
||||
"LiDAR camera points are generated later from the pinned factory KB4 calibration and are not semantic labels.",
|
||||
],
|
||||
"authority": AUTHORITY,
|
||||
}
|
||||
(temporary / "report.json").write_bytes(canonical_json(report) + b"\n")
|
||||
artifacts = {
|
||||
path.name: {"sha256": sha256_path(path), "size_bytes": path.stat().st_size}
|
||||
for path in sorted(temporary.iterdir())
|
||||
if path.is_file()
|
||||
}
|
||||
manifest = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"result_id": result_id,
|
||||
"identity": identity,
|
||||
"artifacts": artifacts,
|
||||
}
|
||||
(temporary / "manifest.json").write_bytes(canonical_json(manifest) + b"\n")
|
||||
temporary.rename(destination)
|
||||
except Exception:
|
||||
shutil.rmtree(temporary, ignore_errors=True)
|
||||
raise
|
||||
print(result_id)
|
||||
print(json.dumps(frame_summary, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _validate(raw: dict[str, Any], frames_path: Path) -> dict[str, object]:
|
||||
if (
|
||||
raw.get("schema_version") != RAW_SCHEMA_VERSION
|
||||
or raw.get("completed") is not True
|
||||
or raw.get("integrated_runtime_gate_passed") is not True
|
||||
or raw.get("production_accepted") is not False
|
||||
or raw.get("authority") != AUTHORITY
|
||||
):
|
||||
raise RuntimeError("raw graph replay is not accepted shadow evidence")
|
||||
checks = raw.get("checks")
|
||||
execution = raw.get("execution")
|
||||
if (
|
||||
not isinstance(checks, dict)
|
||||
or not checks
|
||||
or not all(value is True for value in checks.values())
|
||||
or not isinstance(execution, dict)
|
||||
or execution.get("admitted_frames") != 4489
|
||||
or execution.get("run_mode") != "source-paced-latest-wins"
|
||||
or not isinstance(execution.get("loops"), list)
|
||||
or len(execution["loops"]) != 1
|
||||
):
|
||||
raise RuntimeError("raw graph replay execution contract failed")
|
||||
ledger = execution.get("frame_evidence")
|
||||
if (
|
||||
not isinstance(ledger, dict)
|
||||
or ledger.get("schema_version") != FRAME_SCHEMA_VERSION
|
||||
or ledger.get("sha256") != sha256_path(frames_path)
|
||||
or ledger.get("path") != frames_path.name
|
||||
):
|
||||
raise RuntimeError("frame ledger binding failed")
|
||||
loop = execution["loops"][0]
|
||||
if not isinstance(loop, dict) or not isinstance(loop.get("terminal_outcome_details"), list):
|
||||
raise RuntimeError("terminal outcome details are unavailable")
|
||||
outcomes = loop["terminal_outcome_details"]
|
||||
if len(outcomes) != 4489:
|
||||
raise RuntimeError("terminal outcome details do not close source accounting")
|
||||
outcome_by_sequence: dict[int, str] = {}
|
||||
superseded_sequences: list[int] = []
|
||||
delivered_sequences: list[int] = []
|
||||
for item in outcomes:
|
||||
if not isinstance(item, dict) or item.get("schema_version") != "missioncore.perception-terminal-outcome/v1":
|
||||
raise RuntimeError("terminal outcome row is invalid")
|
||||
sequence = item.get("sequence")
|
||||
outcome = item.get("outcome")
|
||||
if not isinstance(sequence, int) or isinstance(sequence, bool) or sequence in outcome_by_sequence:
|
||||
raise RuntimeError("terminal sequence identity is invalid")
|
||||
if outcome not in {"delivered", "superseded"}:
|
||||
raise RuntimeError("unexpected terminal outcome in accepted replay")
|
||||
outcome_by_sequence[sequence] = outcome
|
||||
(delivered_sequences if outcome == "delivered" else superseded_sequences).append(sequence)
|
||||
if sorted(outcome_by_sequence) != list(range(4489)):
|
||||
raise RuntimeError("terminal sequence set is incomplete")
|
||||
|
||||
ledger_sequences: list[int] = []
|
||||
source_times_ns: list[int] = []
|
||||
with frames_path.open("r", encoding="utf-8") as stream:
|
||||
for line_number, line in enumerate(stream, 1):
|
||||
try:
|
||||
row = json.loads(line)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(f"invalid frame ledger JSON at line {line_number}") from exc
|
||||
if (
|
||||
not isinstance(row, dict)
|
||||
or row.get("schema_version") != FRAME_SCHEMA_VERSION
|
||||
or row.get("loop_index") != 0
|
||||
or row.get("authority") != AUTHORITY
|
||||
):
|
||||
raise RuntimeError(f"invalid frame ledger contract at line {line_number}")
|
||||
envelope = row.get("source_envelope")
|
||||
delivery = row.get("delivery")
|
||||
if not isinstance(envelope, dict) or not isinstance(delivery, dict):
|
||||
raise RuntimeError("frame ledger source or delivery is missing")
|
||||
sequence = envelope.get("sequence")
|
||||
timestamps = envelope.get("timestamps")
|
||||
if (
|
||||
not isinstance(sequence, int)
|
||||
or isinstance(sequence, bool)
|
||||
or delivery.get("sequence") != sequence
|
||||
or outcome_by_sequence.get(sequence) != "delivered"
|
||||
or not isinstance(timestamps, dict)
|
||||
or not isinstance(timestamps.get("source_ns"), int)
|
||||
):
|
||||
raise RuntimeError(f"frame ledger binding failed at line {line_number}")
|
||||
ledger_sequences.append(sequence)
|
||||
source_times_ns.append(timestamps["source_ns"])
|
||||
if ledger_sequences != sorted(delivered_sequences) or len(ledger_sequences) != ledger.get("row_count"):
|
||||
raise RuntimeError("frame ledger delivered sequence set does not close")
|
||||
if any(right <= left for left, right in zip(source_times_ns, source_times_ns[1:])):
|
||||
raise RuntimeError("frame ledger source clock is not monotonic")
|
||||
return {
|
||||
"source_frame_count": 4489,
|
||||
"world_state_frame_count": len(ledger_sequences),
|
||||
"superseded_frame_count": len(superseded_sequences),
|
||||
"superseded_sequences": sorted(superseded_sequences),
|
||||
"first_source_time_ns": source_times_ns[0],
|
||||
"last_source_time_ns": source_times_ns[-1],
|
||||
"frame_schema_version": FRAME_SCHEMA_VERSION,
|
||||
}
|
||||
|
||||
|
||||
def _load_object(path: Path) -> dict[str, Any]:
|
||||
document = json.loads(path.read_text("utf-8"))
|
||||
if not isinstance(document, dict):
|
||||
raise RuntimeError(f"JSON document must be an object: {path}")
|
||||
return document
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Seal the complete RF-DETR reference-graph runtime gate."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
from k1link.perception.fixed_class_detector_tournament import (
|
||||
canonical_json,
|
||||
false_authority,
|
||||
sha256_path,
|
||||
)
|
||||
|
||||
SCHEMA_VERSION: Final = "missioncore.m48s-reference-graph-shadow-gate/v0"
|
||||
RAW_SCHEMA_VERSION: Final = "missioncore.m48s-reference-graph-shadow-load/v0"
|
||||
RESULT_PREFIX: Final = "m48s-reference-graph-shadow-gate-"
|
||||
EXPECTED_GRAPH_CONFIG_SHA256: Final = (
|
||||
"e607916c0d2db5a1078bc194fa0e5e1bac1ca336de8daad29359ed0d2791b6cd"
|
||||
)
|
||||
EXPECTED_DETECTOR_PROFILE_SHA256: Final = (
|
||||
"0c307fd2d19cedd2c9267b6be2effdce82161a719a742f315fcd7a76f7061b08"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--raw-result",
|
||||
type=Path,
|
||||
default=(
|
||||
repository
|
||||
/ ".runtime/m48s-reference-graph-shadow/full-1x-a6ee52c9/result.json"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--progress",
|
||||
type=Path,
|
||||
default=(
|
||||
repository
|
||||
/ ".runtime/m48s-reference-graph-shadow/full-1x-a6ee52c9/progress.jsonl"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--graph-config",
|
||||
type=Path,
|
||||
default=(
|
||||
repository
|
||||
/ "config/perception/m48s-rf-detr-reference-graph-shadow-v0.json"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--detector-profile",
|
||||
type=Path,
|
||||
default=repository / "config/perception/rf-detr-large-risk-shadow-v0.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--wheel-sha256",
|
||||
default="a6ee52c9113bd298f899352b323f9e2b8175d15ca33f342cb8a9b896c41d64ca",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--worker-release-id",
|
||||
default="mission-core-m48s-reference-graph-shadow-a6ee52c9",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-root",
|
||||
type=Path,
|
||||
default=(
|
||||
repository
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/"
|
||||
"reference-graph-shadow-results"
|
||||
),
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
paths = {
|
||||
"raw_result": arguments.raw_result.resolve(strict=True),
|
||||
"progress": arguments.progress.resolve(strict=True),
|
||||
"graph_config": arguments.graph_config.resolve(strict=True),
|
||||
"detector_profile": arguments.detector_profile.resolve(strict=True),
|
||||
}
|
||||
raw = _load_object(paths["raw_result"])
|
||||
_validate(
|
||||
raw,
|
||||
graph_config_sha256=sha256_path(paths["graph_config"]),
|
||||
detector_profile_sha256=sha256_path(paths["detector_profile"]),
|
||||
wheel_sha256=arguments.wheel_sha256,
|
||||
worker_release_id=arguments.worker_release_id,
|
||||
)
|
||||
execution = raw["execution"]
|
||||
metrics = raw["metrics"]
|
||||
evidence = {
|
||||
"files": {
|
||||
name: {"sha256": sha256_path(path), "size_bytes": path.stat().st_size}
|
||||
for name, path in sorted(paths.items())
|
||||
},
|
||||
"worker": {
|
||||
"worker_id": "worker-006",
|
||||
"release_id": arguments.worker_release_id,
|
||||
"wheel_sha256": arguments.wheel_sha256,
|
||||
"historical_triton_action": "none",
|
||||
"durable_worker_action": "none",
|
||||
},
|
||||
"execution": execution,
|
||||
"world_state_completion_age_ms": metrics["world_state_completion_age_ms"],
|
||||
"local_obstacle_map_output_age_ms": metrics[
|
||||
"local_obstacle_map_output_age_ms"
|
||||
],
|
||||
"identity_continuity": metrics["identity_continuity"],
|
||||
"semantic_advisory": metrics["semantic_advisory"],
|
||||
"gpu": metrics["gpu"],
|
||||
"checks": raw["checks"],
|
||||
}
|
||||
decision = {
|
||||
"complete_reference_graph_shadow_passed": True,
|
||||
"source_paced_runtime_gate_accepted": True,
|
||||
"ready_for_visual_lab": True,
|
||||
"independent_track_identity_quality_evaluated": False,
|
||||
"independent_risk_policy_quality_evaluated": False,
|
||||
"detector_replacement_authorized": False,
|
||||
"production_accepted": False,
|
||||
"next_gate": (
|
||||
"publish the complete world-state replay in Mission Core LAB and retain "
|
||||
"independent object-centric review as a separate acceptance"
|
||||
),
|
||||
}
|
||||
identity = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"graph_id": "reference-perception-graph/v2",
|
||||
"detector_provider_id": "triton-rf-detr-large-coco-risk-fp16-shadow/v0",
|
||||
"evidence": evidence,
|
||||
"decision": decision,
|
||||
"completed": True,
|
||||
"accepted": True,
|
||||
"production_accepted": False,
|
||||
"authority": false_authority(),
|
||||
}
|
||||
result_id = RESULT_PREFIX + hashlib.sha256(canonical_json(identity)).hexdigest()
|
||||
destination = arguments.output_root.absolute() / result_id
|
||||
if destination.exists():
|
||||
existing = _load_object(destination / "manifest.json")
|
||||
if existing.get("result_id") != result_id or existing.get("identity") != identity:
|
||||
raise RuntimeError("immutable M48S graph result already exists with different bytes")
|
||||
print(result_id)
|
||||
return 0
|
||||
destination.mkdir(mode=0o700, parents=True)
|
||||
shutil.copyfile(paths["raw_result"], destination / "worker-result.json")
|
||||
shutil.copyfile(paths["progress"], destination / "worker-progress.jsonl")
|
||||
report = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"result_id": result_id,
|
||||
"completed": True,
|
||||
"accepted": True,
|
||||
"production_accepted": False,
|
||||
"evidence": evidence,
|
||||
"decision": decision,
|
||||
"authority": false_authority(),
|
||||
}
|
||||
(destination / "report.json").write_bytes(canonical_json(report) + b"\n")
|
||||
manifest = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"result_id": result_id,
|
||||
"identity": identity,
|
||||
"artifacts": {
|
||||
"worker-result.json": sha256_path(destination / "worker-result.json"),
|
||||
"worker-progress.jsonl": sha256_path(destination / "worker-progress.jsonl"),
|
||||
"report.json": sha256_path(destination / "report.json"),
|
||||
},
|
||||
}
|
||||
(destination / "manifest.json").write_bytes(canonical_json(manifest) + b"\n")
|
||||
print(result_id)
|
||||
print(json.dumps(decision, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _validate(
|
||||
raw: dict[str, Any],
|
||||
*,
|
||||
graph_config_sha256: str,
|
||||
detector_profile_sha256: str,
|
||||
wheel_sha256: str,
|
||||
worker_release_id: str,
|
||||
) -> None:
|
||||
if (
|
||||
raw.get("schema_version") != RAW_SCHEMA_VERSION
|
||||
or raw.get("completed") is not True
|
||||
or raw.get("integrated_runtime_gate_passed") is not True
|
||||
or raw.get("production_accepted") is not False
|
||||
or raw.get("authority") != false_authority()
|
||||
):
|
||||
raise RuntimeError("M48S complete graph result is not accepted shadow evidence")
|
||||
if graph_config_sha256 != EXPECTED_GRAPH_CONFIG_SHA256:
|
||||
raise RuntimeError("M48S complete graph config identity changed")
|
||||
if detector_profile_sha256 != EXPECTED_DETECTOR_PROFILE_SHA256:
|
||||
raise RuntimeError("M48S detector profile identity changed")
|
||||
if len(wheel_sha256) != 64 or any(value not in "0123456789abcdef" for value in wheel_sha256):
|
||||
raise RuntimeError("M48S worker wheel digest is invalid")
|
||||
if worker_release_id != "mission-core-m48s-reference-graph-shadow-a6ee52c9":
|
||||
raise RuntimeError("M48S worker release identity changed")
|
||||
checks = raw.get("checks")
|
||||
execution = raw.get("execution")
|
||||
metrics = raw.get("metrics")
|
||||
if (
|
||||
not isinstance(checks, dict)
|
||||
or not checks
|
||||
or not all(value is True for value in checks.values())
|
||||
or not isinstance(execution, dict)
|
||||
or not isinstance(metrics, dict)
|
||||
):
|
||||
raise RuntimeError("M48S complete graph checks are incomplete")
|
||||
outcomes = execution.get("terminal_outcomes")
|
||||
queues = execution.get("queue_high_watermarks")
|
||||
completion = metrics.get("world_state_completion_age_ms")
|
||||
identity = metrics.get("identity_continuity")
|
||||
semantic = metrics.get("semantic_advisory")
|
||||
if (
|
||||
execution.get("admitted_frames") != 4489
|
||||
or not isinstance(outcomes, dict)
|
||||
or sum(outcomes.values()) != 4489
|
||||
or outcomes.get("delivered") != execution.get("delivered_world_states")
|
||||
or any(outcomes.get(key, 0) != 0 for key in ("failed", "stale", "rejected", "unavailable"))
|
||||
or float(execution.get("effective_world_state_fps", 0.0)) < 9.5
|
||||
or not isinstance(queues, dict)
|
||||
or set(queues) != {"detector", "geometry", "temporal", "rolling", "threat"}
|
||||
or any(not isinstance(value, int) or value > 2 for value in queues.values())
|
||||
or not isinstance(completion, dict)
|
||||
or float(completion.get("p95", 1_000.0)) > 175.0
|
||||
or not isinstance(identity, dict)
|
||||
or identity.get("duplicate_component_ids_within_frame") != 0
|
||||
or int(identity.get("multi_frame_component_count", 0)) < 1
|
||||
or identity.get("independent_truth_available") is not False
|
||||
or not isinstance(semantic, dict)
|
||||
or semantic.get("additional_inference_passes") != 0
|
||||
or semantic.get("authority") != false_authority()
|
||||
):
|
||||
raise RuntimeError("M48S complete graph runtime contract failed")
|
||||
|
||||
|
||||
def _load_object(path: Path) -> dict[str, Any]:
|
||||
document = json.loads(path.read_text("utf-8"))
|
||||
if not isinstance(document, dict):
|
||||
raise RuntimeError(f"JSON document must be an object: {path}")
|
||||
return document
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Seal the RF-DETR TensorRT/Triton detector deployment gate."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
from k1link.perception.fixed_class_detector_tournament import (
|
||||
CandidateWorkerRun,
|
||||
canonical_json,
|
||||
false_authority,
|
||||
sha256_path,
|
||||
)
|
||||
|
||||
SCHEMA_VERSION: Final = "missioncore.m48s-rf-detr-deployment-gate/v0"
|
||||
RESULT_PREFIX: Final = "m48s-rf-detr-deployment-gate-"
|
||||
ENGINE_SHA256: Final = "986399ce706b7380472cf5e473232249fed6e628971d8007f6609e83128d46b8"
|
||||
EXPORTED_ONNX_SHA256: Final = (
|
||||
"9c1948e56bbb6ff03349012b8bb334cacaf8ae480f22caa0704ee70de9a72300"
|
||||
)
|
||||
FP16_ONNX_SHA256: Final = "9015fcc1317f268ce866bed6b5a33132c24963e1502b02f145fa184e11de5ecb"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
runtime = repository / ".runtime/compute-experiments/m48s-semantic-shadow"
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--profile",
|
||||
type=Path,
|
||||
default=repository / "config/perception/rf-detr-large-risk-shadow-v0.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--tournament",
|
||||
type=Path,
|
||||
default=(
|
||||
runtime
|
||||
/ "fixed-detector-tournament-results"
|
||||
/ (
|
||||
"m48s-fixed-detector-tournament-"
|
||||
"0e61d75e6dc575d53e4bb98772a41d240fe627ad642de5178beb1154636e1299"
|
||||
)
|
||||
/ "manifest.json"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--pytorch-result",
|
||||
type=Path,
|
||||
default=runtime / "fixed-detector-tournament-worker/rf-detr-large-worker.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--triton-result",
|
||||
type=Path,
|
||||
default=runtime / "fixed-detector-tournament-worker/rf-detr-large-triton-worker.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--onnx-export",
|
||||
type=Path,
|
||||
default=runtime / "rf-detr-deployment-worker/rf-detr-large-onnx-export.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--fp16-conversion",
|
||||
type=Path,
|
||||
default=(
|
||||
runtime
|
||||
/ "rf-detr-deployment-worker/rf-detr-large-onnx-fp16-conversion-v4.json"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--trtexec-log",
|
||||
type=Path,
|
||||
default=runtime / "rf-detr-deployment-worker/rf-detr-large-trtexec-build-v6.log",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--load-result",
|
||||
type=Path,
|
||||
default=runtime / "rf-detr-deployment-worker/rf-detr-load-30m.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-root",
|
||||
type=Path,
|
||||
default=runtime / "rf-detr-deployment-results",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
|
||||
paths = {
|
||||
"profile": arguments.profile.resolve(strict=True),
|
||||
"tournament": arguments.tournament.resolve(strict=True),
|
||||
"pytorch_result": arguments.pytorch_result.resolve(strict=True),
|
||||
"triton_result": arguments.triton_result.resolve(strict=True),
|
||||
"onnx_export": arguments.onnx_export.resolve(strict=True),
|
||||
"fp16_conversion": arguments.fp16_conversion.resolve(strict=True),
|
||||
"trtexec_log": arguments.trtexec_log.resolve(strict=True),
|
||||
"load_result": arguments.load_result.resolve(strict=True),
|
||||
}
|
||||
profile = _load_object(paths["profile"])
|
||||
tournament = _load_object(paths["tournament"])
|
||||
pytorch = CandidateWorkerRun.from_path(paths["pytorch_result"])
|
||||
triton = CandidateWorkerRun.from_path(paths["triton_result"])
|
||||
triton_document = _load_object(paths["triton_result"])
|
||||
onnx_export = _load_object(paths["onnx_export"])
|
||||
fp16_conversion = _load_object(paths["fp16_conversion"])
|
||||
load_result = _load_object(paths["load_result"])
|
||||
build_log = paths["trtexec_log"].read_text("utf-8")
|
||||
|
||||
_validate(
|
||||
profile=profile,
|
||||
tournament=tournament,
|
||||
pytorch=pytorch,
|
||||
triton=triton,
|
||||
triton_document=triton_document,
|
||||
onnx_export=onnx_export,
|
||||
fp16_conversion=fp16_conversion,
|
||||
load_result=load_result,
|
||||
build_log=build_log,
|
||||
)
|
||||
pytorch_quality = pytorch.quality_summary(threshold=0.5)
|
||||
triton_quality = triton.quality_summary(threshold=0.5)
|
||||
evidence = {
|
||||
"files": {
|
||||
name: {"sha256": sha256_path(path), "size_bytes": path.stat().st_size}
|
||||
for name, path in sorted(paths.items())
|
||||
},
|
||||
"engine_sha256": ENGINE_SHA256,
|
||||
"exported_onnx_sha256": EXPORTED_ONNX_SHA256,
|
||||
"strongly_typed_fp16_onnx_sha256": FP16_ONNX_SHA256,
|
||||
"pytorch_quality_at_0_5": pytorch_quality,
|
||||
"triton_quality_at_0_5": triton_quality,
|
||||
"tensorrt_parity": triton_document["metrics"]["pytorch_reference_parity"],
|
||||
"triton_benchmark": triton_document["metrics"]["benchmark"],
|
||||
"source_paced_load": {
|
||||
"execution": load_result["execution"],
|
||||
"checks": load_result["checks"],
|
||||
"end_to_end_ms": load_result["metrics"]["end_to_end_ms"],
|
||||
"detector_completion_age_ms": load_result["metrics"][
|
||||
"detector_completion_age_ms"
|
||||
],
|
||||
"gpu": load_result["metrics"]["gpu"],
|
||||
},
|
||||
}
|
||||
decision = {
|
||||
"tournament_finalist": True,
|
||||
"tensorrt_numeric_parity_passed": True,
|
||||
"detector_source_paced_load_gate_passed": True,
|
||||
"ready_for_reference_graph_shadow": True,
|
||||
"integrated_world_state_gate_evaluated": False,
|
||||
"production_accepted": False,
|
||||
"next_gate": (
|
||||
"run the RF-DETR shadow provider inside the complete reference graph and require "
|
||||
"world-state p95 <= 175 ms without changing false authority"
|
||||
),
|
||||
}
|
||||
identity = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"profile_id": profile["profile_id"],
|
||||
"evidence": evidence,
|
||||
"decision": decision,
|
||||
"completed": True,
|
||||
"accepted": False,
|
||||
"authority": false_authority(),
|
||||
}
|
||||
result_id = RESULT_PREFIX + hashlib.sha256(canonical_json(identity)).hexdigest()
|
||||
destination = arguments.output_root.absolute() / result_id
|
||||
if destination.exists():
|
||||
raise RuntimeError("immutable RF-DETR deployment result already exists")
|
||||
destination.mkdir(mode=0o700, parents=True)
|
||||
for name, path in paths.items():
|
||||
suffix = path.suffix or ".evidence"
|
||||
(destination / f"{name}{suffix}").write_bytes(path.read_bytes())
|
||||
manifest = {"result_id": result_id, **identity}
|
||||
(destination / "manifest.json").write_bytes(canonical_json(manifest) + b"\n")
|
||||
(destination / "report.json").write_bytes(
|
||||
canonical_json(
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"result_id": result_id,
|
||||
"completed": True,
|
||||
"accepted": False,
|
||||
"evidence": evidence,
|
||||
"decision": decision,
|
||||
"authority": false_authority(),
|
||||
}
|
||||
)
|
||||
+ b"\n"
|
||||
)
|
||||
print(result_id)
|
||||
print(json.dumps(decision, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def _validate(
|
||||
*,
|
||||
profile: dict[str, Any],
|
||||
tournament: dict[str, Any],
|
||||
pytorch: CandidateWorkerRun,
|
||||
triton: CandidateWorkerRun,
|
||||
triton_document: dict[str, Any],
|
||||
onnx_export: dict[str, Any],
|
||||
fp16_conversion: dict[str, Any],
|
||||
load_result: dict[str, Any],
|
||||
build_log: str,
|
||||
) -> None:
|
||||
if profile.get("schema_version") != "missioncore.rf-detr-risk-shadow-profile/v0":
|
||||
raise RuntimeError("unexpected RF-DETR shadow profile schema")
|
||||
decision = tournament.get("decision")
|
||||
if not isinstance(decision, dict) or decision.get("finalist_profile_id") != pytorch.profile_id:
|
||||
raise RuntimeError("tournament does not select the RF-DETR PyTorch reference")
|
||||
if triton.profile_id != "rf-detr-large-coco-704-trt11-fp16/v0":
|
||||
raise RuntimeError("unexpected RF-DETR Triton profile")
|
||||
if triton_document.get("engine_sha256") != ENGINE_SHA256:
|
||||
raise RuntimeError("RF-DETR Triton engine identity changed")
|
||||
parity = triton_document.get("metrics", {}).get("pytorch_reference_parity", {})
|
||||
if not isinstance(parity, dict) or parity.get("passed") is not True:
|
||||
raise RuntimeError("RF-DETR TensorRT numeric parity failed")
|
||||
if pytorch.quality_summary(threshold=0.5)["class_counts"] != triton.quality_summary(
|
||||
threshold=0.5
|
||||
)["class_counts"]:
|
||||
raise RuntimeError("RF-DETR TensorRT 0.5 class counts diverged from PyTorch")
|
||||
if onnx_export.get("onnx", {}).get("sha256") != EXPORTED_ONNX_SHA256:
|
||||
raise RuntimeError("RF-DETR exported ONNX identity changed")
|
||||
if fp16_conversion.get("output_onnx_sha256") != FP16_ONNX_SHA256:
|
||||
raise RuntimeError("RF-DETR strongly typed FP16 ONNX identity changed")
|
||||
required_build_markers = (
|
||||
"Precision: Strongly Typed",
|
||||
"Input binding for input with dimensions 1x3x704x704 and type fp32",
|
||||
"Output binding for dets with dimensions 1x300x4 and type fp16",
|
||||
"Output binding for labels with dimensions 1x300x91 and type fp16",
|
||||
"&&&& PASSED TensorRT.trtexec",
|
||||
)
|
||||
if any(marker not in build_log for marker in required_build_markers):
|
||||
raise RuntimeError("TensorRT build log is incomplete")
|
||||
if (
|
||||
load_result.get("schema_version")
|
||||
!= "missioncore.m48s-rf-detr-source-paced-load/v0"
|
||||
or load_result.get("completed") is not True
|
||||
or load_result.get("detector_load_gate_passed") is not True
|
||||
or load_result.get("candidate_accepted") is not False
|
||||
or load_result.get("integrated_world_state_gate_evaluated") is not False
|
||||
):
|
||||
raise RuntimeError("RF-DETR source-paced load result is incompatible")
|
||||
checks = load_result.get("checks")
|
||||
if (
|
||||
not isinstance(checks, dict)
|
||||
or not checks
|
||||
or not all(value is True for value in checks.values())
|
||||
):
|
||||
raise RuntimeError("RF-DETR source-paced load checks did not all pass")
|
||||
if load_result.get("authority") != false_authority():
|
||||
raise RuntimeError("RF-DETR source-paced load gained authority")
|
||||
|
||||
|
||||
def _load_object(path: Path) -> dict[str, Any]:
|
||||
document = json.loads(path.read_text("utf-8"))
|
||||
if not isinstance(document, dict):
|
||||
raise RuntimeError(f"JSON document must be an object: {path}")
|
||||
return document
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,30 @@
|
||||
FROM nvcr.io/nvidia/tritonserver:26.06-py3
|
||||
|
||||
ARG DFINE_REVISION=956d1709314c2c6a4df6f34de232054578a7449f
|
||||
|
||||
RUN python3 -m pip install --no-cache-dir \
|
||||
--index-url https://download.pytorch.org/whl/cu130 \
|
||||
"torch==2.9.1+cu130" \
|
||||
"torchvision==0.24.1+cu130"
|
||||
|
||||
RUN git clone https://github.com/Peterande/D-FINE.git /opt/dfine \
|
||||
&& git -C /opt/dfine checkout --detach "${DFINE_REVISION}" \
|
||||
&& test "$(git -C /opt/dfine rev-parse HEAD)" = "${DFINE_REVISION}"
|
||||
|
||||
RUN python3 -m pip install --no-cache-dir \
|
||||
"rfdetr[onnx]==1.9.4" \
|
||||
"numpy==1.26.4" \
|
||||
"ml_dtypes==0.5.4" \
|
||||
"onnxconverter-common==1.16.0" \
|
||||
"tritonclient[http]==2.71.0" \
|
||||
"faster-coco-eval>=1.6.6" \
|
||||
"PyYAML>=6.0" \
|
||||
"scipy>=1.10" \
|
||||
"calflops>=0.3" \
|
||||
"loguru>=0.7" \
|
||||
"tensorboard>=2.17"
|
||||
|
||||
LABEL com.nodedc.product="mission-core" \
|
||||
com.nodedc.stack="ndc-mission-core-compute" \
|
||||
com.nodedc.role="bounded-detector-qualification" \
|
||||
com.nodedc.managed-by="codex-bounded-experiment"
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
readonly DFINE_REVISION="956d1709314c2c6a4df6f34de232054578a7449f"
|
||||
|
||||
python3 -m pip install --no-cache-dir \
|
||||
--index-url https://download.pytorch.org/whl/cu130 \
|
||||
"torch==2.9.1+cu130" \
|
||||
"torchvision==0.24.1+cu130"
|
||||
|
||||
git clone https://github.com/Peterande/D-FINE.git /opt/dfine
|
||||
git -C /opt/dfine checkout --detach "${DFINE_REVISION}"
|
||||
test "$(git -C /opt/dfine rev-parse HEAD)" = "${DFINE_REVISION}"
|
||||
|
||||
python3 -m pip install --no-cache-dir \
|
||||
"rfdetr[onnx]==1.9.4" \
|
||||
"numpy==1.26.4" \
|
||||
"ml_dtypes==0.5.4" \
|
||||
"onnxconverter-common==1.16.0" \
|
||||
"tritonclient[http]==2.71.0" \
|
||||
"faster-coco-eval>=1.6.6" \
|
||||
"PyYAML>=6.0" \
|
||||
"scipy>=1.10" \
|
||||
"calflops>=0.3" \
|
||||
"loguru>=0.7" \
|
||||
"tensorboard>=2.17"
|
||||
|
||||
python3 -c "import importlib.metadata, rfdetr, torch, torchvision; print(torch.__version__, torchvision.__version__, importlib.metadata.version('rfdetr'))"
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "$#" -ne 3 ]]; then
|
||||
echo "usage: $0 ONNX_PATH ENGINE_PATH LOG_PATH" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
readonly onnx_path="$1"
|
||||
readonly engine_path="$2"
|
||||
readonly log_path="$3"
|
||||
readonly timing_cache="${engine_path}.timing-cache"
|
||||
|
||||
test -f "${onnx_path}"
|
||||
test ! -e "${engine_path}"
|
||||
test ! -e "${log_path}"
|
||||
mkdir -p "$(dirname "${engine_path}")" "$(dirname "${log_path}")"
|
||||
|
||||
/usr/bin/trtexec \
|
||||
--onnx="${onnx_path}" \
|
||||
--saveEngine="${engine_path}" \
|
||||
--timingCacheFile="${timing_cache}" \
|
||||
--memPoolSize=workspace:4096 \
|
||||
--warmUp=1000 \
|
||||
--duration=5 \
|
||||
--avgRuns=100 \
|
||||
2>&1 | tee "${log_path}"
|
||||
|
||||
test -s "${engine_path}"
|
||||
sha256sum "${onnx_path}" "${engine_path}" "${log_path}"
|
||||
@@ -0,0 +1,47 @@
|
||||
name: "rf_detr_large"
|
||||
platform: "tensorrt_plan"
|
||||
max_batch_size: 0
|
||||
|
||||
input [
|
||||
{
|
||||
name: "input"
|
||||
data_type: TYPE_FP32
|
||||
dims: [ 1, 3, 704, 704 ]
|
||||
}
|
||||
]
|
||||
|
||||
output [
|
||||
{
|
||||
name: "dets"
|
||||
data_type: TYPE_FP16
|
||||
dims: [ 1, 300, 4 ]
|
||||
},
|
||||
{
|
||||
name: "labels"
|
||||
data_type: TYPE_FP16
|
||||
dims: [ 1, 300, 91 ]
|
||||
}
|
||||
]
|
||||
|
||||
instance_group [
|
||||
{
|
||||
count: 1
|
||||
kind: KIND_GPU
|
||||
gpus: [ 0 ]
|
||||
}
|
||||
]
|
||||
|
||||
model_warmup [
|
||||
{
|
||||
name: "rf_detr_large_zero"
|
||||
batch_size: 0
|
||||
inputs: {
|
||||
key: "input"
|
||||
value: {
|
||||
data_type: TYPE_FP32
|
||||
dims: [ 1, 3, 704, 704 ]
|
||||
zero_data: true
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,287 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$ReleaseRoot,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidatePattern("^[a-f0-9]{64}$")]
|
||||
[string]$ExpectedWheelSha256,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidatePattern("^[A-Za-z0-9._-]{1,96}$")]
|
||||
[string]$RunId,
|
||||
[ValidateRange(1, 10)]
|
||||
[int]$Loops = 1,
|
||||
[ValidateRange(1, 4489)]
|
||||
[int]$MaximumFrames = 120,
|
||||
[string]$OutputRoot = "D:\NDC_MISSIONCORE\runtime\results\m48s-reference-graph-shadow"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$ProgressPreference = "SilentlyContinue"
|
||||
|
||||
function Assert-LastExitCode([string]$Operation) {
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "$Operation failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
function Get-Sha256([string]$Path) {
|
||||
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
}
|
||||
|
||||
function Assert-File([string]$Path, [string]$ExpectedSha256, [string]$Label) {
|
||||
$item = Get-Item -LiteralPath (Resolve-Path -LiteralPath $Path).Path -Force
|
||||
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw "$Label must be a regular file"
|
||||
}
|
||||
if ((Get-Sha256 $item.FullName) -cne $ExpectedSha256) {
|
||||
throw "$Label SHA-256 changed"
|
||||
}
|
||||
return $item.FullName
|
||||
}
|
||||
|
||||
function Resolve-DDirectory([string]$Path, [string]$Label, [bool]$Create) {
|
||||
if ($Create -and -not (Test-Path -LiteralPath $Path)) {
|
||||
$null = New-Item -ItemType Directory -Path $Path
|
||||
}
|
||||
$item = Get-Item -LiteralPath (Resolve-Path -LiteralPath $Path).Path -Force
|
||||
if (
|
||||
-not $item.PSIsContainer -or
|
||||
($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or
|
||||
[IO.Path]::GetPathRoot($item.FullName).TrimEnd("\") -ine "D:"
|
||||
) {
|
||||
throw "$Label must be a real D: directory"
|
||||
}
|
||||
return $item.FullName
|
||||
}
|
||||
|
||||
function Convert-ToDockerPath([string]$Path) {
|
||||
return $Path.Replace("\", "/")
|
||||
}
|
||||
|
||||
function Get-Container([string]$Name) {
|
||||
$rows = @((& docker inspect $Name) | ConvertFrom-Json)
|
||||
Assert-LastExitCode "Docker inspection for $Name"
|
||||
if ($rows.Count -ne 1) {
|
||||
throw "Container identity for $Name is not unique"
|
||||
}
|
||||
return $rows[0]
|
||||
}
|
||||
|
||||
if ($env:COMPUTERNAME -cne "DESKTOP-OPJ8J04") {
|
||||
throw "M48S graph shadow is pinned to DESKTOP-OPJ8J04"
|
||||
}
|
||||
|
||||
$release = Resolve-DDirectory $ReleaseRoot "M48S release root" $false
|
||||
$output = Resolve-DDirectory $OutputRoot "M48S output root" $true
|
||||
$runOutput = Join-Path $output $RunId
|
||||
if (Test-Path -LiteralPath $runOutput) {
|
||||
throw "M48S run output already exists"
|
||||
}
|
||||
$null = New-Item -ItemType Directory -Path $runOutput
|
||||
$runOutput = Resolve-DDirectory $runOutput "M48S run output" $false
|
||||
$wheel = Assert-File (
|
||||
Join-Path $release "nodedc_mission_core-0.1.0-py3-none-any.whl"
|
||||
) $ExpectedWheelSha256 "M48S wheel"
|
||||
|
||||
$expectedConfigs = [ordered]@{
|
||||
"m48s-rf-detr-reference-graph-shadow-v0.json" = "e607916c0d2db5a1078bc194fa0e5e1bac1ca336de8daad29359ed0d2791b6cd"
|
||||
"m4-recorded-realtime-baseline-v1.json" = "ea10359339e6cce31b5780a2710299771cab7cc0c1c2a2b56a1621f786b31fa8"
|
||||
"rf-detr-large-risk-shadow-v0.json" = "0c307fd2d19cedd2c9267b6be2effdce82161a719a742f315fcd7a76f7061b08"
|
||||
"m4-geometry-association-v1.json" = "cc666c9389a5e221957faddec89584709b66918d14abaf646f1832e001421999"
|
||||
"m4-temporal-motion-v1.json" = "7130eaee24a95c7d888bf7598010e03e129e1c3ac5b34bcd8401015ff4244b39"
|
||||
"m4-rolling-local-map-v1.json" = "f7e3315eaf6ffaf3aee1e04913933812092cf82bbcc9984c1a6fa2d9250e6784"
|
||||
"m4-replay-threat-v3.json" = "8c3a5aa837da1f028f5998fb504a1381f9b2b68de6420a32160410b6dc0887c7"
|
||||
}
|
||||
foreach ($entry in $expectedConfigs.GetEnumerator()) {
|
||||
$null = Assert-File (Join-Path $release $entry.Key) $entry.Value (
|
||||
"M48S config {0}" -f $entry.Key
|
||||
)
|
||||
}
|
||||
$runner = Get-Item -LiteralPath (
|
||||
Join-Path $release "run_m48s_reference_graph_shadow_worker.py"
|
||||
)
|
||||
if ($runner.PSIsContainer -or ($runner.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw "M48S graph runner must be a regular file"
|
||||
}
|
||||
|
||||
$experimentRoot = Resolve-DDirectory (
|
||||
"D:\NDC_MISSIONCORE\runtime\experiments\m48t-fixed-detector-20260825T095425Z"
|
||||
) "M48S RF-DETR experiment root" $false
|
||||
$modelRoot = Resolve-DDirectory (
|
||||
(Join-Path $experimentRoot "triton-models")
|
||||
) "M48S RF-DETR Triton model root" $false
|
||||
$null = Assert-File (
|
||||
(Join-Path $modelRoot "rf_detr_large\1\model.plan")
|
||||
) "986399ce706b7380472cf5e473232249fed6e628971d8007f6609e83128d46b8" (
|
||||
"RF-DETR TensorRT engine"
|
||||
)
|
||||
$null = Assert-File (
|
||||
(Join-Path $modelRoot "rf_detr_large\config.pbtxt")
|
||||
) "80947cad235e5b000f11aa869a33af0e8c727f07e04046691468df1e171479b6" (
|
||||
"RF-DETR Triton config"
|
||||
)
|
||||
|
||||
$image = "nvcr.io/nvidia/tritonserver:26.06-py3@sha256:58df7489c3f2276f9591d500a012dee03e23d35543ce3c390b4c001e6bf90794"
|
||||
& docker image inspect $image *> $null
|
||||
Assert-LastExitCode "Pinned M48S image inspection"
|
||||
$historicalTriton = Get-Container "ndc-mission-core-triton"
|
||||
if (-not $historicalTriton.State.Running -or $historicalTriton.State.Health.Status -cne "healthy") {
|
||||
throw "Historical Triton must remain healthy during M48S shadow"
|
||||
}
|
||||
$historicalTritonId = [string]$historicalTriton.Id
|
||||
$tritonName = "ndc-mission-core-m48s-rf-detr-triton-shadow"
|
||||
$graphName = "ndc-mission-core-m48s-reference-graph-shadow"
|
||||
foreach ($name in @($tritonName, $graphName)) {
|
||||
if (& docker ps -a --format "{{.Names}}" --filter "name=^/$name$") {
|
||||
throw "M48S candidate container $name already exists"
|
||||
}
|
||||
}
|
||||
|
||||
$source = [ordered]@{
|
||||
CameraIndex = "D:\NDC_MISSIONCORE\runtime\jobs\recorded-camera-602ac89026ed12978619801d\input\camera\sensor.camera.right\epoch-1\index.jsonl"
|
||||
SourcePack = "D:\NDC_MISSIONCORE\runtime\derived\e10-lidar-pack-576c994a6c814e2592dd6240ace3902a5db94843312c759a73ba0c9166157d2b\lidar-pack.npz"
|
||||
LocalSurface = "D:\NDC_MISSIONCORE\runtime\derived\k1-local-surface-23762244c8bdb97de26fb721ac957d7a00bc9a63571ac4cfa4be19c4effc7d55\local-surface.npz"
|
||||
Video = "D:\NDC_MISSIONCORE\runtime\experiments\e46e\inputs\right-cadd1696ff000904eb78633a0a8418104b8024f178b91f3421789021ccb160e8.mp4"
|
||||
Mask = "D:\NDC_MISSIONCORE\runtime\inputs\e2\valid-fov-mask-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2\mask.png"
|
||||
}
|
||||
foreach ($entry in $source.GetEnumerator()) {
|
||||
if (-not (Test-Path -LiteralPath $entry.Value -PathType Leaf)) {
|
||||
throw "M48S source $($entry.Key) is missing"
|
||||
}
|
||||
}
|
||||
|
||||
$media = Resolve-DDirectory (
|
||||
"D:\NDC_MISSIONCORE\runtime\derived\perception-e15-media-pyav180-lz445-v1"
|
||||
) "PyAV dependency" $false
|
||||
$opencv = Resolve-DDirectory (
|
||||
"D:\NDC_MISSIONCORE\runtime\derived\perception-e3-opencv413092-v1\packages"
|
||||
) "OpenCV dependency" $false
|
||||
$pillow = Resolve-DDirectory (
|
||||
"D:\NDC_MISSIONCORE\runtime\derived\perception-p0-env-v1"
|
||||
) "Pillow dependency" $false
|
||||
|
||||
try {
|
||||
& docker create `
|
||||
--name $tritonName `
|
||||
--read-only `
|
||||
--security-opt "no-new-privileges:true" `
|
||||
--cap-drop ALL `
|
||||
--pids-limit 512 `
|
||||
--shm-size 1g `
|
||||
--gpus all `
|
||||
--tmpfs "/tmp:rw,noexec,nosuid,size=2g" `
|
||||
--health-cmd "curl --fail --silent http://127.0.0.1:8000/v2/health/ready" `
|
||||
--health-interval 5s `
|
||||
--health-timeout 3s `
|
||||
--health-start-period 20s `
|
||||
--health-retries 24 `
|
||||
-v ("{0}:/models:ro" -f (Convert-ToDockerPath $modelRoot)) `
|
||||
$image `
|
||||
tritonserver `
|
||||
--model-repository=/models `
|
||||
--model-control-mode=explicit `
|
||||
--load-model=rf_detr_large `
|
||||
--disable-auto-complete-config `
|
||||
--strict-readiness=true `
|
||||
--exit-on-error=true `
|
||||
--allow-http=true `
|
||||
--allow-grpc=false `
|
||||
--allow-metrics=false *> $null
|
||||
Assert-LastExitCode "M48S Triton creation"
|
||||
& docker start $tritonName *> $null
|
||||
Assert-LastExitCode "M48S Triton start"
|
||||
$ready = $false
|
||||
foreach ($attempt in 1..60) {
|
||||
Start-Sleep -Seconds 2
|
||||
$candidate = Get-Container $tritonName
|
||||
if (-not $candidate.State.Running) {
|
||||
throw "M48S Triton stopped during startup"
|
||||
}
|
||||
if ($candidate.State.Health.Status -ceq "healthy") {
|
||||
$ready = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (-not $ready) {
|
||||
throw "M48S Triton did not become healthy"
|
||||
}
|
||||
if (@((Get-Container $tritonName).HostConfig.PortBindings.PSObject.Properties).Count -ne 0) {
|
||||
throw "M48S Triton published a host port"
|
||||
}
|
||||
|
||||
$dockerRelease = Convert-ToDockerPath $release
|
||||
$dockerOutput = Convert-ToDockerPath $runOutput
|
||||
$maximumArguments = @()
|
||||
if ($MaximumFrames -gt 0) {
|
||||
$maximumArguments = @("--maximum-frames", ([string]$MaximumFrames))
|
||||
}
|
||||
$arguments = @(
|
||||
"run", "--name", $graphName,
|
||||
"--network", ("container:{0}" -f $tritonName),
|
||||
"--read-only",
|
||||
"--security-opt", "no-new-privileges:true",
|
||||
"--cap-drop", "ALL",
|
||||
"--pids-limit", "256",
|
||||
"--gpus", "all",
|
||||
"--tmpfs", "/tmp:rw,noexec,nosuid,size=2g",
|
||||
"-e", "PYTHONDONTWRITEBYTECODE=1",
|
||||
"-e", "PYTHONPATH=/release/nodedc_mission_core-0.1.0-py3-none-any.whl:/opt/media:/opt/opencv:/opt/pillow",
|
||||
"-v", ("{0}:/release:ro" -f $dockerRelease),
|
||||
"-v", ("{0}:/output:rw" -f $dockerOutput),
|
||||
"-v", ("{0}:/opt/media:ro" -f (Convert-ToDockerPath $media)),
|
||||
"-v", ("{0}:/opt/opencv:ro" -f (Convert-ToDockerPath $opencv)),
|
||||
"-v", ("{0}:/opt/pillow:ro" -f (Convert-ToDockerPath $pillow)),
|
||||
"-v", ("{0}:/source/camera-index.jsonl:ro" -f (Convert-ToDockerPath $source.CameraIndex)),
|
||||
"-v", ("{0}:/source/source-pack.npz:ro" -f (Convert-ToDockerPath $source.SourcePack)),
|
||||
"-v", ("{0}:/source/local-surface.npz:ro" -f (Convert-ToDockerPath $source.LocalSurface)),
|
||||
"-v", ("{0}:/source/right.mp4:ro" -f (Convert-ToDockerPath $source.Video)),
|
||||
"-v", ("{0}:/source/mask.png:ro" -f (Convert-ToDockerPath $source.Mask)),
|
||||
"--entrypoint", "python3",
|
||||
$image,
|
||||
"/release/run_m48s_reference_graph_shadow_worker.py",
|
||||
"--graph-config", "/release/m48s-rf-detr-reference-graph-shadow-v0.json",
|
||||
"--baseline-profile", "/release/m4-recorded-realtime-baseline-v1.json",
|
||||
"--detector-profile", "/release/rf-detr-large-risk-shadow-v0.json",
|
||||
"--geometry-profile", "/release/m4-geometry-association-v1.json",
|
||||
"--temporal-motion-profile", "/release/m4-temporal-motion-v1.json",
|
||||
"--rolling-map-profile", "/release/m4-rolling-local-map-v1.json",
|
||||
"--threat-profile", "/release/m4-replay-threat-v3.json",
|
||||
"--camera-index", "/source/camera-index.jsonl",
|
||||
"--source-pack", "/source/source-pack.npz",
|
||||
"--local-surface", "/source/local-surface.npz",
|
||||
"--video", "/source/right.mp4",
|
||||
"--valid-fov-mask", "/source/mask.png",
|
||||
"--triton-origin", "http://127.0.0.1:8000",
|
||||
"--loops", ([string]$Loops),
|
||||
"--output", "/output/result.json",
|
||||
"--progress", "/output/progress.jsonl",
|
||||
"--frame-ledger", "/output/frames.jsonl"
|
||||
) + $maximumArguments
|
||||
& docker @arguments
|
||||
Assert-LastExitCode "M48S complete reference graph shadow"
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $runOutput "result.json") -PathType Leaf)) {
|
||||
throw "M48S graph result was not written"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $runOutput "frames.jsonl") -PathType Leaf)) {
|
||||
throw "M48S frame evidence ledger was not written"
|
||||
}
|
||||
} finally {
|
||||
foreach ($name in @($graphName, $tritonName)) {
|
||||
if (& docker ps -a --format "{{.Names}}" --filter "name=^/$name$") {
|
||||
& docker rm -f $name *> $null
|
||||
}
|
||||
}
|
||||
$historicalAfter = Get-Container "ndc-mission-core-triton"
|
||||
if (
|
||||
$historicalAfter.Id -cne $historicalTritonId -or
|
||||
-not $historicalAfter.State.Running -or
|
||||
$historicalAfter.State.Health.Status -cne "healthy"
|
||||
) {
|
||||
throw "Historical Triton changed during M48S shadow"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Output ("M48S_RESULT={0}" -f (Join-Path $runOutput "result.json"))
|
||||
Write-Output "HISTORICAL_TRITON_ACTION=none"
|
||||
Write-Output "DURABLE_WORKER_ACTION=none"
|
||||
Write-Output "PRODUCTION_ACCEPTED=false"
|
||||
@@ -321,9 +321,27 @@ def canonical_laboratory_adapters() -> dict[str, LaboratoryAdapter]:
|
||||
"canonical.e35-degradation-recovery/v1": _run_e35,
|
||||
"canonical.e46j-raw-fisheye-realtime/v1": _run_e46j,
|
||||
"experimental.e47-semantic-slam-shadow/v1": _run_e47,
|
||||
"experimental.m48s-fixed-class-detector/v1": _run_m48s_fixed_class_detector,
|
||||
}
|
||||
|
||||
|
||||
def _run_m48s_fixed_class_detector(
|
||||
request: LaboratoryRunRequest,
|
||||
) -> LaboratoryAdapterResult:
|
||||
from k1link.laboratory.m48s_fixed_class_detector_lab import (
|
||||
build_m48s_fixed_class_detector_lab,
|
||||
)
|
||||
|
||||
result = build_m48s_fixed_class_detector_lab(
|
||||
repository_root=request.inputs["repository_root"],
|
||||
output_root=request.output_root,
|
||||
)
|
||||
return LaboratoryAdapterResult(
|
||||
result_root=result.result_root,
|
||||
result_id=result.result_id,
|
||||
)
|
||||
|
||||
|
||||
def _run_m48_small_static_passage_regression(
|
||||
request: LaboratoryRunRequest,
|
||||
) -> LaboratoryAdapterResult:
|
||||
|
||||
@@ -0,0 +1,892 @@
|
||||
"""Build the immutable M4.8S fixed-class detector laboratory projection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Final, cast
|
||||
|
||||
from k1link.perception.fixed_class_detector_tournament import (
|
||||
canonical_json,
|
||||
false_authority,
|
||||
sha256_path,
|
||||
)
|
||||
|
||||
LAB_SCHEMA: Final = "missioncore.m48s-fixed-class-detector-lab/v1"
|
||||
CATALOG_SCHEMA: Final = "missioncore.m48s-fixed-class-detector-frame-catalog/v1"
|
||||
FRAME_SCHEMA: Final = "missioncore.m48s-fixed-class-detector-frame/v1"
|
||||
REPORT_SCHEMA: Final = "missioncore.m48s-fixed-class-detector-report/v1"
|
||||
METHOD_SCHEMA: Final = "missioncore.laboratory-method/v1"
|
||||
RESULT_PREFIX: Final = "m48s-fixed-class-detector-lab-"
|
||||
TOURNAMENT_ID: Final = (
|
||||
"m48s-fixed-detector-tournament-"
|
||||
"0e61d75e6dc575d53e4bb98772a41d240fe627ad642de5178beb1154636e1299"
|
||||
)
|
||||
DEPLOYMENT_ID: Final = (
|
||||
"m48s-rf-detr-deployment-gate-2feb9e1b12a5588951ad35d63bf23cf6bdd579d54b5329d46d7696f88c444547"
|
||||
)
|
||||
REFERENCE_GRAPH_ID: Final = (
|
||||
"m48s-reference-graph-shadow-gate-"
|
||||
"e8da7a521768daba0ead1a6e4803871ce3a85f91a7d8ee36c5719ac10433e791"
|
||||
)
|
||||
REFERENCE_GRAPH_REPLAY_ID: Final = (
|
||||
"m48s-reference-graph-replay-"
|
||||
"16d69d610c22e6f42071b8378cd75dfa6b95db4ceb800f9c7508fa3673504478"
|
||||
)
|
||||
INTEGRATED_STATUS: Final = "complete-reference-graph-shadow-passed-production-not-authorized"
|
||||
YOLOX_ID: Final = (
|
||||
"m48s-yolox-all-coco-shadow-7dbe6043b3fc12c7ddb162f609f883d86b34a4f2dd3785a632795f257e192d06"
|
||||
)
|
||||
SOURCE_SHA256: Final = "cadd1696ff000904eb78633a0a8418104b8024f178b91f3421789021ccb160e8"
|
||||
ENGINE_SHA256: Final = "986399ce706b7380472cf5e473232249fed6e628971d8007f6609e83128d46b8"
|
||||
RISK_LABELS: Final = frozenset(
|
||||
{
|
||||
"person",
|
||||
"bicycle",
|
||||
"car",
|
||||
"motorcycle",
|
||||
"bus",
|
||||
"truck",
|
||||
"bird",
|
||||
"cat",
|
||||
"dog",
|
||||
"horse",
|
||||
"sheep",
|
||||
"cow",
|
||||
"elephant",
|
||||
"bear",
|
||||
"zebra",
|
||||
"giraffe",
|
||||
"skateboard",
|
||||
}
|
||||
)
|
||||
FRAME_IDS: Final = (
|
||||
"000121",
|
||||
"000131",
|
||||
"000253",
|
||||
"000275",
|
||||
"000443",
|
||||
"000463",
|
||||
"001094",
|
||||
"001228",
|
||||
"001454",
|
||||
"001856",
|
||||
"002386",
|
||||
)
|
||||
|
||||
|
||||
class M48SFixedClassDetectorLabError(RuntimeError):
|
||||
"""The sealed detector evidence cannot produce an honest LAB result."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class M48SFixedClassDetectorLabResult:
|
||||
result_root: Path
|
||||
result_id: str
|
||||
manifest: dict[str, Any]
|
||||
|
||||
|
||||
def build_m48s_fixed_class_detector_lab(
|
||||
*,
|
||||
repository_root: Path,
|
||||
output_root: Path,
|
||||
) -> M48SFixedClassDetectorLabResult:
|
||||
repository = repository_root.expanduser().resolve(strict=True)
|
||||
if not repository.is_dir():
|
||||
raise M48SFixedClassDetectorLabError("repository root is invalid")
|
||||
runtime = repository / ".runtime/compute-experiments/m48s-semantic-shadow"
|
||||
tournament_path = (
|
||||
runtime / "fixed-detector-tournament-results" / TOURNAMENT_ID / "manifest.json"
|
||||
)
|
||||
deployment_root = runtime / "rf-detr-deployment-results" / DEPLOYMENT_ID
|
||||
deployment_path = deployment_root / "manifest.json"
|
||||
load_path = deployment_root / "load_result.json"
|
||||
reference_graph_root = runtime / "reference-graph-shadow-results" / REFERENCE_GRAPH_ID
|
||||
reference_graph_path = reference_graph_root / "manifest.json"
|
||||
reference_graph_worker_path = reference_graph_root / "worker-result.json"
|
||||
reference_graph_replay_root = (
|
||||
runtime / "reference-graph-replay-results" / REFERENCE_GRAPH_REPLAY_ID
|
||||
)
|
||||
reference_graph_replay_path = reference_graph_replay_root / "manifest.json"
|
||||
reference_graph_replay_worker_path = reference_graph_replay_root / "worker-result.json"
|
||||
reference_graph_replay_frames_path = reference_graph_replay_root / "frames.jsonl"
|
||||
yolox_root = runtime / "yolox-all-coco-results" / YOLOX_ID
|
||||
yolox_manifest_path = yolox_root / "manifest.json"
|
||||
yolox_frames_path = yolox_root / "frames.jsonl"
|
||||
candidate_root = runtime / "fixed-detector-tournament-worker"
|
||||
dfine_path = candidate_root / "dfine-s-worker.json"
|
||||
rf_detr_path = candidate_root / "rf-detr-large-triton-worker.json"
|
||||
source_root = runtime / "raw-11-frames-v1"
|
||||
profile_path = repository / "config/perception/rf-detr-large-risk-shadow-v0.json"
|
||||
for path in (
|
||||
tournament_path,
|
||||
deployment_path,
|
||||
load_path,
|
||||
reference_graph_path,
|
||||
reference_graph_worker_path,
|
||||
reference_graph_replay_path,
|
||||
reference_graph_replay_worker_path,
|
||||
reference_graph_replay_frames_path,
|
||||
yolox_manifest_path,
|
||||
yolox_frames_path,
|
||||
dfine_path,
|
||||
rf_detr_path,
|
||||
profile_path,
|
||||
):
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise M48SFixedClassDetectorLabError(
|
||||
f"required sealed evidence is missing: {path.name}"
|
||||
)
|
||||
|
||||
tournament = _read_object(tournament_path)
|
||||
deployment = _read_object(deployment_path)
|
||||
load = _read_object(load_path)
|
||||
reference_graph = _read_object(reference_graph_path)
|
||||
reference_graph_worker = _read_object(reference_graph_worker_path)
|
||||
reference_graph_replay = _read_object(reference_graph_replay_path)
|
||||
reference_graph_replay_worker = _read_object(reference_graph_replay_worker_path)
|
||||
yolox_manifest = _read_object(yolox_manifest_path)
|
||||
dfine = _read_object(dfine_path)
|
||||
rf_detr = _read_object(rf_detr_path)
|
||||
profile = _read_object(profile_path)
|
||||
yolox_frames = _read_jsonl(yolox_frames_path)
|
||||
_validate_inputs(
|
||||
tournament=tournament,
|
||||
deployment=deployment,
|
||||
load=load,
|
||||
reference_graph=reference_graph,
|
||||
reference_graph_worker=reference_graph_worker,
|
||||
reference_graph_replay=reference_graph_replay,
|
||||
reference_graph_replay_worker=reference_graph_replay_worker,
|
||||
reference_graph_replay_frames_path=reference_graph_replay_frames_path,
|
||||
yolox_manifest=yolox_manifest,
|
||||
dfine=dfine,
|
||||
rf_detr=rf_detr,
|
||||
profile=profile,
|
||||
yolox_frames=yolox_frames,
|
||||
)
|
||||
|
||||
source_paths = {frame_id: source_root / f"frame-{frame_id}.jpg" for frame_id in FRAME_IDS}
|
||||
if any(path.is_symlink() or not path.is_file() for path in source_paths.values()):
|
||||
raise M48SFixedClassDetectorLabError("the exact 11-frame visual slice is incomplete")
|
||||
source_descriptors = [
|
||||
{
|
||||
"frame_id": frame_id,
|
||||
"source_sequence": int(frame_id),
|
||||
"sha256": sha256_path(source_paths[frame_id]),
|
||||
"byte_length": source_paths[frame_id].stat().st_size,
|
||||
}
|
||||
for frame_id in FRAME_IDS
|
||||
]
|
||||
method = _method(
|
||||
profile=profile,
|
||||
tournament=tournament,
|
||||
deployment=deployment,
|
||||
reference_graph=reference_graph,
|
||||
)
|
||||
identity = {
|
||||
"schema_version": LAB_SCHEMA,
|
||||
"source": {
|
||||
"source_session_id": "RAVNOVES00",
|
||||
"recording_sha256": SOURCE_SHA256,
|
||||
"camera_source_id": "sensor.camera.right",
|
||||
"camera_raster": [800, 600],
|
||||
"evidence_frame_count": len(FRAME_IDS),
|
||||
"replay_frame_count": 4489,
|
||||
"frames": source_descriptors,
|
||||
},
|
||||
"configuration": {
|
||||
"comparison_threshold": 0.5,
|
||||
"display_modes": ["source", "yolox", "dfine", "rf-detr"],
|
||||
"replay_display_modes": ["video", "camera", "3d", "plan"],
|
||||
"camera_point_overlay": "factory-kb4-exact",
|
||||
"world_state_delivery": "source-paced-latest-wins",
|
||||
"single_inference_per_frame": True,
|
||||
"risk_labels": sorted(RISK_LABELS),
|
||||
"geometry_owns_static_occupancy": True,
|
||||
"unknown_stationary_response": "route-around",
|
||||
"unknown_moving_response": "conservative-risk",
|
||||
},
|
||||
"inputs": {
|
||||
"tournament_result_id": TOURNAMENT_ID,
|
||||
"tournament_document_sha256": sha256_path(tournament_path),
|
||||
"deployment_result_id": DEPLOYMENT_ID,
|
||||
"deployment_document_sha256": sha256_path(deployment_path),
|
||||
"reference_graph_result_id": REFERENCE_GRAPH_ID,
|
||||
"reference_graph_document_sha256": sha256_path(reference_graph_path),
|
||||
"reference_graph_worker_sha256": sha256_path(reference_graph_worker_path),
|
||||
"reference_graph_replay_result_id": REFERENCE_GRAPH_REPLAY_ID,
|
||||
"reference_graph_replay_document_sha256": sha256_path(
|
||||
reference_graph_replay_path
|
||||
),
|
||||
"reference_graph_replay_worker_sha256": sha256_path(
|
||||
reference_graph_replay_worker_path
|
||||
),
|
||||
"reference_graph_replay_frames_sha256": sha256_path(
|
||||
reference_graph_replay_frames_path
|
||||
),
|
||||
"yolox_result_id": YOLOX_ID,
|
||||
"yolox_document_sha256": sha256_path(yolox_manifest_path),
|
||||
},
|
||||
"method": method,
|
||||
"authority": false_authority(),
|
||||
}
|
||||
identity_sha256 = hashlib.sha256(canonical_json(identity)).hexdigest()
|
||||
result_id = RESULT_PREFIX + identity_sha256
|
||||
completed_utc_ns = reference_graph_replay_worker.get("completed_utc_ns")
|
||||
if not isinstance(completed_utc_ns, int) or isinstance(completed_utc_ns, bool):
|
||||
raise M48SFixedClassDetectorLabError(
|
||||
"complete reference-graph completion time is unavailable"
|
||||
)
|
||||
created_at_utc = (
|
||||
datetime.fromtimestamp(completed_utc_ns / 1_000_000_000, UTC)
|
||||
.isoformat(timespec="microseconds")
|
||||
.replace("+00:00", "Z")
|
||||
)
|
||||
candidates = _candidate_summaries(
|
||||
tournament=tournament,
|
||||
yolox_manifest=yolox_manifest,
|
||||
dfine=dfine,
|
||||
rf_detr=rf_detr,
|
||||
deployment=deployment,
|
||||
)
|
||||
metrics = _metrics(
|
||||
deployment=deployment,
|
||||
load=load,
|
||||
reference_graph=reference_graph,
|
||||
candidates=candidates,
|
||||
)
|
||||
decision = {
|
||||
"bounded_question_accepted": True,
|
||||
"selected_candidate": "rf-detr",
|
||||
"ready_for_reference_graph_shadow": True,
|
||||
"integrated_world_state_gate_evaluated": True,
|
||||
"integrated_world_state_gate_passed": True,
|
||||
"full_replay_visual_published": True,
|
||||
"detector_replacement_authorized": False,
|
||||
"production_accepted": False,
|
||||
}
|
||||
limitations = [
|
||||
"The 11-frame slice is diagnostic and has no independent semantic ground truth.",
|
||||
(
|
||||
"The complete reference-graph replay qualifies runtime behavior, but has no "
|
||||
"independent track-identity or risk-policy truth."
|
||||
),
|
||||
"COCO has no dedicated scooter class; unknown moving objects remain conservative hazards.",
|
||||
(
|
||||
"Camera boxes do not replace geometry-owned occupancy or grant navigation/safety "
|
||||
"authority."
|
||||
),
|
||||
(
|
||||
"Eight source frames were superseded by the qualified latest-wins graph; their "
|
||||
"camera/LiDAR source evidence remains visible without invented world state."
|
||||
),
|
||||
]
|
||||
|
||||
root = output_root.expanduser().absolute()
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
destination = root / result_id
|
||||
if destination.exists():
|
||||
raise M48SFixedClassDetectorLabError("immutable M4.8S LAB result already exists")
|
||||
temporary = Path(tempfile.mkdtemp(prefix=".m48s-fixed-class-lab-", dir=root))
|
||||
try:
|
||||
(temporary / "frames").mkdir(mode=0o700)
|
||||
yolox_by_frame = _yolox_by_frame(yolox_frames)
|
||||
dfine_by_frame = _worker_by_frame(dfine)
|
||||
rf_detr_by_frame = _worker_by_frame(rf_detr)
|
||||
frame_descriptors: list[dict[str, object]] = []
|
||||
for frame_id in FRAME_IDS:
|
||||
camera_name = f"frames/frame-{frame_id}.jpg"
|
||||
detail_name = f"frame-{frame_id}.json"
|
||||
camera_path = temporary / camera_name
|
||||
shutil.copyfile(source_paths[frame_id], camera_path)
|
||||
detections_by_model: dict[str, list[dict[str, object]]] = {
|
||||
"yolox": _qualified(yolox_by_frame[frame_id]),
|
||||
"dfine": _qualified(dfine_by_frame[frame_id]),
|
||||
"rf-detr": _qualified(rf_detr_by_frame[frame_id]),
|
||||
}
|
||||
frame_document = {
|
||||
"schema_version": FRAME_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"frame_id": frame_id,
|
||||
"source_sequence": int(frame_id),
|
||||
"camera": {
|
||||
"path": camera_name,
|
||||
"media_type": "image/jpeg",
|
||||
"width": 800,
|
||||
"height": 600,
|
||||
"sha256": sha256_path(camera_path),
|
||||
"exact_source_frame": True,
|
||||
},
|
||||
"comparison_threshold": 0.5,
|
||||
"detections": detections_by_model,
|
||||
"ground_truth_available": False,
|
||||
"authority": false_authority(),
|
||||
}
|
||||
detail_path = temporary / detail_name
|
||||
detail_path.write_bytes(canonical_json(frame_document) + b"\n")
|
||||
frame_descriptors.append(
|
||||
{
|
||||
"frame_id": frame_id,
|
||||
"source_sequence": int(frame_id),
|
||||
"camera_path": camera_name,
|
||||
"camera_sha256": sha256_path(camera_path),
|
||||
"camera_byte_length": camera_path.stat().st_size,
|
||||
"detail_path": detail_name,
|
||||
"detail_sha256": sha256_path(detail_path),
|
||||
"detail_byte_length": detail_path.stat().st_size,
|
||||
"counts": {key: len(value) for key, value in detections_by_model.items()},
|
||||
}
|
||||
)
|
||||
catalog = {
|
||||
"schema_version": CATALOG_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"frame_count": len(frame_descriptors),
|
||||
"frames": frame_descriptors,
|
||||
}
|
||||
catalog_path = temporary / "catalog.json"
|
||||
catalog_path.write_bytes(canonical_json(catalog) + b"\n")
|
||||
shutil.copyfile(tournament_path, temporary / "tournament.json")
|
||||
shutil.copyfile(deployment_path, temporary / "deployment.json")
|
||||
shutil.copyfile(reference_graph_path, temporary / "reference-graph.json")
|
||||
shutil.copyfile(
|
||||
reference_graph_worker_path,
|
||||
temporary / "reference-graph-worker-result.json",
|
||||
)
|
||||
shutil.copyfile(
|
||||
reference_graph_replay_path,
|
||||
temporary / "reference-graph-replay.json",
|
||||
)
|
||||
shutil.copyfile(
|
||||
reference_graph_replay_worker_path,
|
||||
temporary / "reference-graph-replay-worker-result.json",
|
||||
)
|
||||
shutil.copyfile(
|
||||
reference_graph_replay_frames_path,
|
||||
temporary / "reference-graph-replay-frames.jsonl",
|
||||
)
|
||||
report = {
|
||||
"schema_version": REPORT_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"source": identity["source"],
|
||||
"configuration": identity["configuration"],
|
||||
"method": method,
|
||||
"execution": {
|
||||
"detector_load": load["execution"],
|
||||
"complete_reference_graph": reference_graph["identity"]["evidence"]["execution"],
|
||||
},
|
||||
"metrics": metrics,
|
||||
"acceptance": {
|
||||
"detector_load": load["checks"],
|
||||
"complete_reference_graph": reference_graph["identity"]["evidence"]["checks"],
|
||||
},
|
||||
"decision": decision,
|
||||
"limitations": limitations,
|
||||
"authority": false_authority(),
|
||||
"visual_evidence": {
|
||||
"kind": "full-reference-graph-recorded-replay",
|
||||
"frame_count": 4489,
|
||||
"world_state_frame_count": 4481,
|
||||
"superseded_frame_count": 8,
|
||||
"modes": ["video", "camera", "3d", "plan"],
|
||||
"camera_layers": ["rf-detr", "points"],
|
||||
"ground_truth": False,
|
||||
},
|
||||
}
|
||||
report_path = temporary / "report.json"
|
||||
report_path.write_bytes(canonical_json(report) + b"\n")
|
||||
artifacts = _artifact_manifest(temporary)
|
||||
manifest = {
|
||||
"schema_version": LAB_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"identity_sha256": identity_sha256,
|
||||
"identity": identity,
|
||||
"created_at_utc": created_at_utc,
|
||||
"status": INTEGRATED_STATUS,
|
||||
"completed": True,
|
||||
"bounded_question_accepted": True,
|
||||
"ground_truth": False,
|
||||
"catalog": {
|
||||
"path": "catalog.json",
|
||||
"sha256": sha256_path(catalog_path),
|
||||
"byte_length": catalog_path.stat().st_size,
|
||||
},
|
||||
"method": method,
|
||||
"metrics": metrics,
|
||||
"decision": decision,
|
||||
"limitations": limitations,
|
||||
"authority": false_authority(),
|
||||
"artifacts": artifacts,
|
||||
}
|
||||
(temporary / "manifest.json").write_bytes(canonical_json(manifest) + b"\n")
|
||||
temporary.replace(destination)
|
||||
except BaseException:
|
||||
shutil.rmtree(temporary, ignore_errors=True)
|
||||
raise
|
||||
return M48SFixedClassDetectorLabResult(
|
||||
result_root=destination,
|
||||
result_id=result_id,
|
||||
manifest=manifest,
|
||||
)
|
||||
|
||||
|
||||
def _validate_inputs(
|
||||
*,
|
||||
tournament: dict[str, Any],
|
||||
deployment: dict[str, Any],
|
||||
load: dict[str, Any],
|
||||
reference_graph: dict[str, Any],
|
||||
reference_graph_worker: dict[str, Any],
|
||||
reference_graph_replay: dict[str, Any],
|
||||
reference_graph_replay_worker: dict[str, Any],
|
||||
reference_graph_replay_frames_path: Path,
|
||||
yolox_manifest: dict[str, Any],
|
||||
dfine: dict[str, Any],
|
||||
rf_detr: dict[str, Any],
|
||||
profile: dict[str, Any],
|
||||
yolox_frames: list[dict[str, Any]],
|
||||
) -> None:
|
||||
decision = deployment.get("decision")
|
||||
graph_identity = reference_graph.get("identity")
|
||||
graph_artifacts = reference_graph.get("artifacts")
|
||||
graph_decision = graph_identity.get("decision") if isinstance(graph_identity, dict) else None
|
||||
graph_checks = reference_graph_worker.get("checks")
|
||||
replay_identity = reference_graph_replay.get("identity")
|
||||
replay_artifacts = reference_graph_replay.get("artifacts")
|
||||
replay_frame_summary = (
|
||||
replay_identity.get("evidence", {}).get("frame_summary")
|
||||
if isinstance(replay_identity, dict)
|
||||
and isinstance(replay_identity.get("evidence"), dict)
|
||||
else None
|
||||
)
|
||||
if (
|
||||
tournament.get("result_id") != TOURNAMENT_ID
|
||||
or tournament.get("accepted") is not False
|
||||
or deployment.get("result_id") != DEPLOYMENT_ID
|
||||
or deployment.get("accepted") is not False
|
||||
or not isinstance(decision, dict)
|
||||
or decision.get("ready_for_reference_graph_shadow") is not True
|
||||
or decision.get("production_accepted") is not False
|
||||
or load.get("detector_load_gate_passed") is not True
|
||||
or load.get("candidate_accepted") is not False
|
||||
or reference_graph.get("result_id") != REFERENCE_GRAPH_ID
|
||||
or reference_graph.get("schema_version")
|
||||
!= "missioncore.m48s-reference-graph-shadow-gate/v0"
|
||||
or not isinstance(graph_identity, dict)
|
||||
or graph_identity.get("graph_id") != "reference-perception-graph/v2"
|
||||
or graph_identity.get("accepted") is not True
|
||||
or graph_identity.get("production_accepted") is not False
|
||||
or graph_identity.get("authority") != false_authority()
|
||||
or not isinstance(graph_decision, dict)
|
||||
or graph_decision.get("complete_reference_graph_shadow_passed") is not True
|
||||
or graph_decision.get("source_paced_runtime_gate_accepted") is not True
|
||||
or graph_decision.get("detector_replacement_authorized") is not False
|
||||
or graph_decision.get("production_accepted") is not False
|
||||
or not isinstance(graph_artifacts, dict)
|
||||
or graph_artifacts.get("worker-result.json")
|
||||
!= hashlib.sha256(canonical_json(reference_graph_worker) + b"\n").hexdigest()
|
||||
or reference_graph_worker.get("completed") is not True
|
||||
or reference_graph_worker.get("integrated_runtime_gate_passed") is not True
|
||||
or reference_graph_worker.get("production_accepted") is not False
|
||||
or reference_graph_worker.get("authority") != false_authority()
|
||||
or not isinstance(graph_checks, dict)
|
||||
or not graph_checks
|
||||
or not all(value is True for value in graph_checks.values())
|
||||
or reference_graph_replay.get("result_id") != REFERENCE_GRAPH_REPLAY_ID
|
||||
or reference_graph_replay.get("schema_version")
|
||||
!= "missioncore.m48s-reference-graph-replay/v0"
|
||||
or not isinstance(replay_identity, dict)
|
||||
or replay_identity.get("accepted") is not True
|
||||
or replay_identity.get("production_accepted") is not False
|
||||
or replay_identity.get("authority") != false_authority()
|
||||
or not isinstance(replay_frame_summary, dict)
|
||||
or replay_frame_summary.get("source_frame_count") != 4489
|
||||
or replay_frame_summary.get("world_state_frame_count") != 4481
|
||||
or replay_frame_summary.get("superseded_frame_count") != 8
|
||||
or not isinstance(replay_artifacts, dict)
|
||||
or not isinstance(replay_artifacts.get("frames.jsonl"), dict)
|
||||
or replay_artifacts["frames.jsonl"].get("sha256")
|
||||
!= sha256_path(reference_graph_replay_frames_path)
|
||||
or not isinstance(replay_artifacts.get("worker-result.json"), dict)
|
||||
or replay_artifacts["worker-result.json"].get("sha256")
|
||||
!= hashlib.sha256(canonical_json(reference_graph_replay_worker) + b"\n").hexdigest()
|
||||
or reference_graph_replay_worker.get("integrated_runtime_gate_passed") is not True
|
||||
or reference_graph_replay_worker.get("production_accepted") is not False
|
||||
or reference_graph_replay_worker.get("authority") != false_authority()
|
||||
or yolox_manifest.get("result_id") != YOLOX_ID
|
||||
or dfine.get("profile_id") != "dfine-s-coco-640-fp16/v0"
|
||||
or rf_detr.get("profile_id") != "rf-detr-large-coco-704-trt11-fp16/v0"
|
||||
or rf_detr.get("engine_sha256") != ENGINE_SHA256
|
||||
or profile.get("profile_id") != "rf-detr-large-coco-704-trt11-fp16-risk-shadow/v0"
|
||||
or len(yolox_frames) != len(FRAME_IDS)
|
||||
):
|
||||
raise M48SFixedClassDetectorLabError("sealed M4.8S evidence identity changed")
|
||||
for document in (
|
||||
tournament,
|
||||
deployment,
|
||||
load,
|
||||
reference_graph_worker,
|
||||
reference_graph_replay_worker,
|
||||
dfine,
|
||||
rf_detr,
|
||||
profile,
|
||||
):
|
||||
authority = document.get("authority")
|
||||
if authority is not None and authority != false_authority():
|
||||
raise M48SFixedClassDetectorLabError("sealed M4.8S evidence gained authority")
|
||||
|
||||
|
||||
def _method(
|
||||
*,
|
||||
profile: dict[str, Any],
|
||||
tournament: dict[str, Any],
|
||||
deployment: dict[str, Any],
|
||||
reference_graph: dict[str, Any],
|
||||
) -> dict[str, object]:
|
||||
candidates = tournament["candidates"]
|
||||
if not isinstance(candidates, dict):
|
||||
raise M48SFixedClassDetectorLabError("tournament candidates are unavailable")
|
||||
dfine = candidates["dfine-s-coco-640-fp16/v0"]
|
||||
rf_detr = candidates["rf-detr-large-coco-704-fp16/v0"]
|
||||
if not isinstance(dfine, dict) or not isinstance(rf_detr, dict):
|
||||
raise M48SFixedClassDetectorLabError("tournament candidates are invalid")
|
||||
return {
|
||||
"schema_version": METHOD_SCHEMA,
|
||||
"completeness": "complete",
|
||||
"execution_class": "ai-inference",
|
||||
"pipeline_id": "raw-kb4-rf-detr-reference-graph-shadow/v1",
|
||||
"components": [
|
||||
{
|
||||
"kind": "source",
|
||||
"name": "RAVNOVES00 RIGHT",
|
||||
"version": "immutable recorded source",
|
||||
"role": "11-frame visual slice and 30-minute source-paced replay",
|
||||
"identity_sha256": SOURCE_SHA256,
|
||||
},
|
||||
{
|
||||
"kind": "model",
|
||||
"name": "YOLOX-S COCO-80",
|
||||
"version": "triton-yolox-s-raw-kb4-all-coco/v2",
|
||||
"role": "regression baseline",
|
||||
"identity_sha256": (
|
||||
"c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063"
|
||||
),
|
||||
},
|
||||
{
|
||||
"kind": "model",
|
||||
"name": "D-FINE-S COCO",
|
||||
"version": str(dfine["upstream_revision"]),
|
||||
"role": "fixed-class tournament candidate",
|
||||
"identity_sha256": str(dfine["checkpoint_sha256"]),
|
||||
},
|
||||
{
|
||||
"kind": "model",
|
||||
"name": "RF-DETR-L COCO",
|
||||
"version": str(rf_detr["upstream_revision"]),
|
||||
"role": "selected fixed-class risk detector",
|
||||
"identity_sha256": str(rf_detr["checkpoint_sha256"]),
|
||||
},
|
||||
{
|
||||
"kind": "runtime",
|
||||
"name": "TensorRT 11 + isolated Triton",
|
||||
"version": "worker-006 RTX 4090 strongly-typed-fp16",
|
||||
"role": "numeric parity and source-paced load qualification",
|
||||
"identity_sha256": str(deployment["evidence"]["engine_sha256"]),
|
||||
},
|
||||
{
|
||||
"kind": "algorithm",
|
||||
"name": "risk-only fixed-class qualification",
|
||||
"version": str(profile["profile_id"]),
|
||||
"role": "emit behavior-relevant semantics while geometry owns static occupancy",
|
||||
"identity_sha256": hashlib.sha256(canonical_json(profile)).hexdigest(),
|
||||
},
|
||||
{
|
||||
"kind": "algorithm",
|
||||
"name": "reference perception graph",
|
||||
"version": str(reference_graph["identity"]["graph_id"]),
|
||||
"role": (
|
||||
"geometry, temporal identity, motion, rolling occupancy, threat, "
|
||||
"and class advisory"
|
||||
),
|
||||
"identity_sha256": str(
|
||||
reference_graph["identity"]["evidence"]["files"]["graph_config"]["sha256"]
|
||||
),
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _candidate_summaries(
|
||||
*,
|
||||
tournament: dict[str, Any],
|
||||
yolox_manifest: dict[str, Any],
|
||||
dfine: dict[str, Any],
|
||||
rf_detr: dict[str, Any],
|
||||
deployment: dict[str, Any],
|
||||
) -> list[dict[str, object]]:
|
||||
baseline = tournament["baseline"]
|
||||
candidates = tournament["candidates"]
|
||||
triton_benchmark = deployment["evidence"]["triton_benchmark"]
|
||||
if not isinstance(baseline, dict) or not isinstance(candidates, dict):
|
||||
raise M48SFixedClassDetectorLabError("tournament summaries are invalid")
|
||||
return [
|
||||
{
|
||||
"id": "yolox",
|
||||
"label": "YOLOX-S",
|
||||
"provider_id": baseline["provider_id"],
|
||||
"capacity_fps": yolox_manifest["metrics"]["all_coco_core_capacity_fps"],
|
||||
"p95_ms": yolox_manifest["metrics"]["timing_ms"]["all_coco_core_ms"]["p95"],
|
||||
"frame_253_dog_detected": False,
|
||||
"frame_253_dog_score": None,
|
||||
"selected": False,
|
||||
},
|
||||
{
|
||||
"id": "dfine",
|
||||
"label": "D-FINE-S",
|
||||
"provider_id": dfine["provider_id"],
|
||||
"capacity_fps": dfine["metrics"]["benchmark"]["core_capacity_fps"],
|
||||
"p95_ms": dfine["metrics"]["benchmark"]["timing_ms"]["p95"],
|
||||
"frame_253_dog_detected": False,
|
||||
"frame_253_dog_score": None,
|
||||
"selected": False,
|
||||
},
|
||||
{
|
||||
"id": "rf-detr",
|
||||
"label": "RF-DETR-L",
|
||||
"provider_id": rf_detr["provider_id"],
|
||||
"capacity_fps": triton_benchmark["end_to_end_capacity_fps"],
|
||||
"p95_ms": triton_benchmark["timing_ms"]["p95"],
|
||||
"frame_253_dog_detected": True,
|
||||
"frame_253_dog_score": deployment["evidence"]["tensorrt_parity"]["tensorrt_score"],
|
||||
"selected": True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _metrics(
|
||||
*,
|
||||
deployment: dict[str, Any],
|
||||
load: dict[str, Any],
|
||||
reference_graph: dict[str, Any],
|
||||
candidates: list[dict[str, object]],
|
||||
) -> dict[str, object]:
|
||||
graph_evidence = reference_graph["identity"]["evidence"]
|
||||
graph_execution = graph_evidence["execution"]
|
||||
graph_completion = graph_evidence["world_state_completion_age_ms"]
|
||||
map_age = graph_evidence["local_obstacle_map_output_age_ms"]
|
||||
gpu = graph_evidence["gpu"]
|
||||
identity = graph_evidence["identity_continuity"]
|
||||
advisory = graph_evidence["semantic_advisory"]
|
||||
terminal_outcomes = graph_execution["terminal_outcomes"]
|
||||
return {
|
||||
"candidate_count": len(candidates),
|
||||
"evidence_frame_count": len(FRAME_IDS),
|
||||
"selected_candidate": "rf-detr",
|
||||
"candidates": candidates,
|
||||
"tensorrt_parity": deployment["evidence"]["tensorrt_parity"],
|
||||
"detector_load": {
|
||||
"duration_seconds": load["execution"]["wall_seconds"],
|
||||
"source_frames_consumed": load["execution"]["source_frames_consumed"],
|
||||
"source_frame_replacements": load["execution"]["source_frame_replacements"],
|
||||
"effective_consumed_fps": load["execution"]["effective_consumed_fps"],
|
||||
"end_to_end_p95_ms": load["metrics"]["end_to_end_ms"]["p95"],
|
||||
"completion_age_p95_ms": load["metrics"]["detector_completion_age_ms"]["p95"],
|
||||
"gpu_utilization_mean_percent": load["metrics"]["gpu"]["gpu_utilization_percent"][
|
||||
"mean"
|
||||
],
|
||||
"gpu_utilization_maximum_percent": load["metrics"]["gpu"]["gpu_utilization_percent"][
|
||||
"maximum"
|
||||
],
|
||||
"gpu_memory_maximum_mib": load["metrics"]["gpu"]["gpu_memory_used_mib"]["maximum"],
|
||||
"queue_maximum_depth": load["execution"]["queue_maximum_depth"],
|
||||
"queue_capacity": load["execution"]["queue_capacity"],
|
||||
"failures": load["execution"]["failures"],
|
||||
},
|
||||
"integrated_world_state": {
|
||||
"duration_seconds": graph_execution["source_processing_wall_seconds"],
|
||||
"source_frames_admitted": graph_execution["admitted_frames"],
|
||||
"delivered_world_states": graph_execution["delivered_world_states"],
|
||||
"superseded_frames": terminal_outcomes["superseded"],
|
||||
"effective_world_state_fps": graph_execution["effective_world_state_fps"],
|
||||
"world_state_completion_age_p95_ms": graph_completion["p95"],
|
||||
"world_state_completion_age_p99_ms": graph_completion["p99"],
|
||||
"world_state_completion_age_maximum_ms": graph_completion["maximum"],
|
||||
"local_obstacle_map_output_age_p95_ms": map_age["p95"],
|
||||
"queue_high_watermarks": graph_execution["queue_high_watermarks"],
|
||||
"queue_capacity": 2,
|
||||
"gpu_utilization_mean_percent": gpu["gpu_utilization_percent"]["mean"],
|
||||
"gpu_utilization_maximum_percent": gpu["gpu_utilization_percent"]["maximum"],
|
||||
"gpu_memory_maximum_mib": gpu["gpu_memory_used_mib"]["maximum"],
|
||||
"gpu_power_maximum_w": gpu["gpu_power_w"]["maximum"],
|
||||
"gpu_temperature_maximum_c": gpu["gpu_temperature_c"]["maximum"],
|
||||
"unique_component_count": identity["unique_component_count"],
|
||||
"multi_frame_component_count": identity["multi_frame_component_count"],
|
||||
"maximum_component_publications": identity["maximum_component_publications"],
|
||||
"duplicate_component_ids_within_frame": identity[
|
||||
"duplicate_component_ids_within_frame"
|
||||
],
|
||||
"advisory_family_counts": advisory["advisory_family_counts"],
|
||||
"semantic_hint_counts": advisory["semantic_hint_counts"],
|
||||
"motion_counts": advisory["motion_counts"],
|
||||
"additional_inference_passes": advisory["additional_inference_passes"],
|
||||
"failures": sum(
|
||||
terminal_outcomes.get(key, 0)
|
||||
for key in ("failed", "stale", "rejected", "unavailable")
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _qualified(detections: list[dict[str, Any]]) -> list[dict[str, object]]:
|
||||
result: list[dict[str, object]] = []
|
||||
for detection in detections:
|
||||
label = detection.get("label")
|
||||
score = detection.get("score")
|
||||
bbox = detection.get("bbox_xyxy")
|
||||
if (
|
||||
label not in RISK_LABELS
|
||||
or not isinstance(score, (int, float))
|
||||
or isinstance(score, bool)
|
||||
or float(score) < 0.5
|
||||
or not isinstance(bbox, list)
|
||||
or len(bbox) != 4
|
||||
or not all(isinstance(value, (int, float)) for value in bbox)
|
||||
):
|
||||
continue
|
||||
result.append(
|
||||
{
|
||||
"label": label,
|
||||
"score": round(float(score), 6),
|
||||
"bbox_xyxy": [round(float(value), 3) for value in bbox],
|
||||
}
|
||||
)
|
||||
result.sort(key=lambda item: (-cast(float, item["score"]), str(item["label"])))
|
||||
return result
|
||||
|
||||
|
||||
def _yolox_by_frame(rows: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
|
||||
result: dict[str, list[dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
frame_id = _frame_id(row.get("frame_name"))
|
||||
detections = row.get("all_coco_detections")
|
||||
if frame_id is None or not isinstance(detections, list):
|
||||
raise M48SFixedClassDetectorLabError("YOLOX frame evidence is invalid")
|
||||
result[frame_id] = _objects(detections, "YOLOX detections")
|
||||
if tuple(sorted(result)) != tuple(sorted(FRAME_IDS)):
|
||||
raise M48SFixedClassDetectorLabError("YOLOX frame slice changed")
|
||||
return result
|
||||
|
||||
|
||||
def _worker_by_frame(document: dict[str, Any]) -> dict[str, list[dict[str, Any]]]:
|
||||
frames = document.get("frames")
|
||||
if not isinstance(frames, list):
|
||||
raise M48SFixedClassDetectorLabError("candidate frame evidence is invalid")
|
||||
result: dict[str, list[dict[str, Any]]] = {}
|
||||
for row in _objects(frames, "candidate frames"):
|
||||
frame_id = _frame_id(row.get("frame_name"))
|
||||
detections = row.get("detections")
|
||||
if frame_id is None or not isinstance(detections, list):
|
||||
raise M48SFixedClassDetectorLabError("candidate frame evidence is invalid")
|
||||
result[frame_id] = _objects(detections, "candidate detections")
|
||||
if tuple(sorted(result)) != tuple(sorted(FRAME_IDS)):
|
||||
raise M48SFixedClassDetectorLabError("candidate frame slice changed")
|
||||
return result
|
||||
|
||||
|
||||
def _frame_id(value: object) -> str | None:
|
||||
if not isinstance(value, str) or not value.startswith("frame-"):
|
||||
return None
|
||||
stem = Path(value).stem
|
||||
frame_id = stem.removeprefix("frame-")
|
||||
return frame_id if frame_id in FRAME_IDS else None
|
||||
|
||||
|
||||
def _artifact_manifest(root: Path) -> list[dict[str, object]]:
|
||||
artifacts: list[dict[str, object]] = []
|
||||
for path in sorted(item for item in root.rglob("*") if item.is_file()):
|
||||
relative = path.relative_to(root).as_posix()
|
||||
if relative == "manifest.json":
|
||||
continue
|
||||
media_type = "application/json"
|
||||
schema_version: str | None = None
|
||||
role = "supporting-evidence"
|
||||
if relative.endswith(".jpg"):
|
||||
media_type = "image/jpeg"
|
||||
role = "visual-evidence-camera"
|
||||
elif relative.startswith("frame-"):
|
||||
schema_version = FRAME_SCHEMA
|
||||
role = "visual-evidence-frame"
|
||||
elif relative == "catalog.json":
|
||||
schema_version = CATALOG_SCHEMA
|
||||
role = "visual-evidence-catalog"
|
||||
elif relative == "report.json":
|
||||
schema_version = REPORT_SCHEMA
|
||||
role = "laboratory-report"
|
||||
elif relative == "tournament.json":
|
||||
role = "upstream-tournament-evidence"
|
||||
elif relative == "deployment.json":
|
||||
role = "upstream-deployment-evidence"
|
||||
elif relative == "reference-graph.json":
|
||||
role = "upstream-reference-graph-evidence"
|
||||
elif relative == "reference-graph-worker-result.json":
|
||||
role = "upstream-reference-graph-worker-evidence"
|
||||
elif relative == "reference-graph-replay.json":
|
||||
role = "upstream-full-replay-evidence"
|
||||
elif relative == "reference-graph-replay-worker-result.json":
|
||||
role = "upstream-full-replay-worker-evidence"
|
||||
elif relative == "reference-graph-replay-frames.jsonl":
|
||||
media_type = "application/x-ndjson"
|
||||
schema_version = "missioncore.m48s-reference-graph-frame-evidence/v0"
|
||||
role = "visual-evidence-full-replay-world-state"
|
||||
artifacts.append(
|
||||
{
|
||||
"role": role,
|
||||
"path": relative,
|
||||
"byte_length": path.stat().st_size,
|
||||
"sha256": sha256_path(path),
|
||||
"media_type": media_type,
|
||||
"schema_version": schema_version,
|
||||
}
|
||||
)
|
||||
return artifacts
|
||||
|
||||
|
||||
def _read_object(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
value = json.loads(path.read_text("utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise M48SFixedClassDetectorLabError(f"invalid JSON evidence: {path.name}") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise M48SFixedClassDetectorLabError(f"JSON evidence must be an object: {path.name}")
|
||||
return value
|
||||
|
||||
|
||||
def _read_jsonl(path: Path) -> list[dict[str, Any]]:
|
||||
try:
|
||||
rows = [json.loads(line) for line in path.read_text("utf-8").splitlines() if line]
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise M48SFixedClassDetectorLabError("invalid YOLOX frame evidence") from exc
|
||||
return _objects(rows, "YOLOX frame evidence")
|
||||
|
||||
|
||||
def _objects(value: list[object], label: str) -> list[dict[str, Any]]:
|
||||
if not all(isinstance(item, dict) for item in value):
|
||||
raise M48SFixedClassDetectorLabError(f"{label} must contain objects")
|
||||
return [item for item in value if isinstance(item, dict)]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CATALOG_SCHEMA",
|
||||
"FRAME_SCHEMA",
|
||||
"LAB_SCHEMA",
|
||||
"REPORT_SCHEMA",
|
||||
"RESULT_PREFIX",
|
||||
"M48SFixedClassDetectorLabError",
|
||||
"M48SFixedClassDetectorLabResult",
|
||||
"build_m48s_fixed_class_detector_lab",
|
||||
]
|
||||
@@ -0,0 +1,454 @@
|
||||
"""Separate semantic-class evaluation over geometry-bound object projections.
|
||||
|
||||
This companion contour does not mutate the class-free M4.8 truth or score
|
||||
object presence. It evaluates canonical semantic resolution only after a
|
||||
separate two-reviewer, adjudicated semantic label set exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from k1link.perception.object_understanding import (
|
||||
ObjectSemanticVocabulary,
|
||||
ObjectUnderstanding,
|
||||
SemanticResolution,
|
||||
validate_object_understanding,
|
||||
)
|
||||
|
||||
SEMANTIC_TRUTH_LABEL_SCHEMA: Final = "missioncore.semantic-object-truth-label/v0"
|
||||
SEMANTIC_QUALITY_PROFILE_SCHEMA: Final = "missioncore.semantic-object-quality-profile/v0"
|
||||
SEMANTIC_QUALITY_REPORT_SCHEMA: Final = "missioncore.semantic-object-quality-report/v0"
|
||||
|
||||
_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$")
|
||||
_FALSE_AUTHORITY: Final = {
|
||||
"physical_live": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
class SemanticObjectQualityError(ValueError):
|
||||
"""A semantic truth, profile or evaluation input is incompatible."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticTruthLabel:
|
||||
"""One independently reviewed canonical class bound to existing geometry."""
|
||||
|
||||
label_id: str
|
||||
observation_id: str
|
||||
source_id: str
|
||||
frame_id: str
|
||||
class_id: str
|
||||
reviewer_count: int
|
||||
adjudicated: bool
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
for value, label in (
|
||||
(self.label_id, "semantic truth label id"),
|
||||
(self.observation_id, "semantic truth observation id"),
|
||||
(self.source_id, "semantic truth source id"),
|
||||
(self.frame_id, "semantic truth frame id"),
|
||||
(self.class_id, "semantic truth class id"),
|
||||
):
|
||||
_identifier(value, label)
|
||||
if (
|
||||
not isinstance(self.reviewer_count, int)
|
||||
or isinstance(self.reviewer_count, bool)
|
||||
or self.reviewer_count < 2
|
||||
):
|
||||
raise SemanticObjectQualityError("semantic truth requires two independent reviewers")
|
||||
if self.adjudicated is not True:
|
||||
raise SemanticObjectQualityError("semantic truth must be adjudicated")
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"schema_version": SEMANTIC_TRUTH_LABEL_SCHEMA,
|
||||
"label_id": self.label_id,
|
||||
"observation_id": self.observation_id,
|
||||
"source_id": self.source_id,
|
||||
"frame_id": self.frame_id,
|
||||
"class_id": self.class_id,
|
||||
"reviewer_count": self.reviewer_count,
|
||||
"adjudicated": self.adjudicated,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value: object) -> SemanticTruthLabel:
|
||||
document = _object(value, "semantic truth label")
|
||||
_exact_keys(
|
||||
document,
|
||||
{
|
||||
"schema_version",
|
||||
"label_id",
|
||||
"observation_id",
|
||||
"source_id",
|
||||
"frame_id",
|
||||
"class_id",
|
||||
"reviewer_count",
|
||||
"adjudicated",
|
||||
},
|
||||
"semantic truth label",
|
||||
)
|
||||
if document.get("schema_version") != SEMANTIC_TRUTH_LABEL_SCHEMA:
|
||||
raise SemanticObjectQualityError("semantic truth label schema is incompatible")
|
||||
return cls(
|
||||
label_id=_string(document, "label_id"),
|
||||
observation_id=_string(document, "observation_id"),
|
||||
source_id=_string(document, "source_id"),
|
||||
frame_id=_string(document, "frame_id"),
|
||||
class_id=_string(document, "class_id"),
|
||||
reviewer_count=_integer(document, "reviewer_count"),
|
||||
adjudicated=_boolean(document, "adjudicated"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticObjectQualityProfile:
|
||||
"""Bounded evaluation policy for a frozen semantic provider candidate."""
|
||||
|
||||
profile_id: str
|
||||
vocabulary_id: str
|
||||
top_k: int
|
||||
minimum_prediction_coverage: float
|
||||
minimum_exact_top1_accuracy: float
|
||||
minimum_coarse_group_accuracy: float
|
||||
minimum_exact_top_k_recall: float
|
||||
maximum_unresolved_fraction: float
|
||||
maximum_conflict_fraction: float
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_identifier(self.profile_id, "semantic quality profile id")
|
||||
_identifier(self.vocabulary_id, "semantic quality vocabulary id")
|
||||
if (
|
||||
not isinstance(self.top_k, int)
|
||||
or isinstance(self.top_k, bool)
|
||||
or not 1 <= self.top_k <= 5
|
||||
):
|
||||
raise SemanticObjectQualityError("semantic quality top-k is invalid")
|
||||
for value, label in (
|
||||
(self.minimum_prediction_coverage, "minimum prediction coverage"),
|
||||
(self.minimum_exact_top1_accuracy, "minimum exact top-1 accuracy"),
|
||||
(self.minimum_coarse_group_accuracy, "minimum coarse group accuracy"),
|
||||
(self.minimum_exact_top_k_recall, "minimum exact top-k recall"),
|
||||
(self.maximum_unresolved_fraction, "maximum unresolved fraction"),
|
||||
(self.maximum_conflict_fraction, "maximum conflict fraction"),
|
||||
):
|
||||
_fraction(value, label)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticQualityCase:
|
||||
"""One deterministic truth/prediction comparison row."""
|
||||
|
||||
label_id: str
|
||||
observation_id: str
|
||||
truth_class_id: str
|
||||
resolution: str
|
||||
selected_class_id: str | None
|
||||
exact_top1_correct: bool
|
||||
coarse_group_correct: bool
|
||||
exact_top_k_hit: bool
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"label_id": self.label_id,
|
||||
"observation_id": self.observation_id,
|
||||
"truth_class_id": self.truth_class_id,
|
||||
"resolution": self.resolution,
|
||||
"selected_class_id": self.selected_class_id,
|
||||
"exact_top1_correct": self.exact_top1_correct,
|
||||
"coarse_group_correct": self.coarse_group_correct,
|
||||
"exact_top_k_hit": self.exact_top_k_hit,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticObjectQualityResult:
|
||||
"""In-memory deterministic semantic report and comparison ledger."""
|
||||
|
||||
report: dict[str, object]
|
||||
cases: tuple[SemanticQualityCase, ...]
|
||||
|
||||
|
||||
def load_semantic_object_quality_profile(path: Path) -> SemanticObjectQualityProfile:
|
||||
"""Read a strict semantic evaluation profile."""
|
||||
|
||||
try:
|
||||
document = json.loads(path.expanduser().resolve(strict=True).read_text("utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise SemanticObjectQualityError("semantic quality profile cannot be read") from exc
|
||||
root = _object(document, "semantic quality profile")
|
||||
_exact_keys(
|
||||
root,
|
||||
{
|
||||
"schema_version",
|
||||
"profile_id",
|
||||
"vocabulary_id",
|
||||
"top_k",
|
||||
"thresholds",
|
||||
"scope",
|
||||
"authority",
|
||||
},
|
||||
"semantic quality profile",
|
||||
)
|
||||
if root.get("schema_version") != SEMANTIC_QUALITY_PROFILE_SCHEMA:
|
||||
raise SemanticObjectQualityError("semantic quality profile schema is incompatible")
|
||||
scope = _object(root.get("scope"), "semantic quality scope")
|
||||
_exact_keys(
|
||||
scope,
|
||||
{
|
||||
"object_presence_scored",
|
||||
"semantic_class_scored",
|
||||
"risk_policy_scored",
|
||||
"requires_separate_adjudicated_semantic_truth",
|
||||
},
|
||||
"semantic quality scope",
|
||||
)
|
||||
if scope != {
|
||||
"object_presence_scored": False,
|
||||
"semantic_class_scored": True,
|
||||
"risk_policy_scored": False,
|
||||
"requires_separate_adjudicated_semantic_truth": True,
|
||||
}:
|
||||
raise SemanticObjectQualityError("semantic quality scope changed")
|
||||
if _object(root.get("authority"), "semantic quality authority") != _FALSE_AUTHORITY:
|
||||
raise SemanticObjectQualityError("semantic quality authority changed")
|
||||
thresholds = _object(root.get("thresholds"), "semantic quality thresholds")
|
||||
_exact_keys(
|
||||
thresholds,
|
||||
{
|
||||
"minimum_prediction_coverage",
|
||||
"minimum_exact_top1_accuracy",
|
||||
"minimum_coarse_group_accuracy",
|
||||
"minimum_exact_top_k_recall",
|
||||
"maximum_unresolved_fraction",
|
||||
"maximum_conflict_fraction",
|
||||
},
|
||||
"semantic quality thresholds",
|
||||
)
|
||||
return SemanticObjectQualityProfile(
|
||||
profile_id=_string(root, "profile_id"),
|
||||
vocabulary_id=_string(root, "vocabulary_id"),
|
||||
top_k=_integer(root, "top_k"),
|
||||
minimum_prediction_coverage=_number(thresholds, "minimum_prediction_coverage"),
|
||||
minimum_exact_top1_accuracy=_number(thresholds, "minimum_exact_top1_accuracy"),
|
||||
minimum_coarse_group_accuracy=_number(thresholds, "minimum_coarse_group_accuracy"),
|
||||
minimum_exact_top_k_recall=_number(thresholds, "minimum_exact_top_k_recall"),
|
||||
maximum_unresolved_fraction=_number(thresholds, "maximum_unresolved_fraction"),
|
||||
maximum_conflict_fraction=_number(thresholds, "maximum_conflict_fraction"),
|
||||
)
|
||||
|
||||
|
||||
def score_semantic_object_quality(
|
||||
*,
|
||||
predictions: tuple[ObjectUnderstanding, ...],
|
||||
truth: tuple[SemanticTruthLabel, ...],
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
profile: SemanticObjectQualityProfile,
|
||||
) -> SemanticObjectQualityResult:
|
||||
"""Score semantics on geometry-bound truth without scoring object presence."""
|
||||
|
||||
if not truth or any(not isinstance(item, SemanticTruthLabel) for item in truth):
|
||||
raise SemanticObjectQualityError("semantic truth set is invalid")
|
||||
if any(not isinstance(item, ObjectUnderstanding) for item in predictions):
|
||||
raise SemanticObjectQualityError("semantic prediction set is invalid")
|
||||
if profile.vocabulary_id != vocabulary.vocabulary_id:
|
||||
raise SemanticObjectQualityError("semantic quality vocabulary changed")
|
||||
truth_ids = tuple(item.observation_id for item in truth)
|
||||
if len(set(truth_ids)) != len(truth_ids):
|
||||
raise SemanticObjectQualityError("semantic truth observations must be unique")
|
||||
prediction_ids = tuple(item.observation.observation_id for item in predictions)
|
||||
if len(set(prediction_ids)) != len(prediction_ids):
|
||||
raise SemanticObjectQualityError("semantic prediction observations must be unique")
|
||||
declared_classes = {item.class_id for item in vocabulary.classes}
|
||||
if any(item.class_id not in declared_classes for item in truth):
|
||||
raise SemanticObjectQualityError("semantic truth uses an undeclared class")
|
||||
for candidate in predictions:
|
||||
validate_object_understanding(candidate, vocabulary)
|
||||
|
||||
by_observation = {item.observation.observation_id: item for item in predictions}
|
||||
cases: list[SemanticQualityCase] = []
|
||||
predicted_count = 0
|
||||
selected_count = 0
|
||||
conflict_count = 0
|
||||
for label in truth:
|
||||
prediction = by_observation.get(label.observation_id)
|
||||
if prediction is None:
|
||||
cases.append(
|
||||
SemanticQualityCase(
|
||||
label_id=label.label_id,
|
||||
observation_id=label.observation_id,
|
||||
truth_class_id=label.class_id,
|
||||
resolution="unavailable",
|
||||
selected_class_id=None,
|
||||
exact_top1_correct=False,
|
||||
coarse_group_correct=False,
|
||||
exact_top_k_hit=False,
|
||||
)
|
||||
)
|
||||
continue
|
||||
predicted_count += 1
|
||||
observation = prediction.observation
|
||||
if observation.source_id != label.source_id or observation.frame_id != label.frame_id:
|
||||
raise SemanticObjectQualityError("semantic prediction escaped its truth source frame")
|
||||
selected = prediction.semantic.selected_class_id
|
||||
if prediction.semantic.resolution is SemanticResolution.SELECTED:
|
||||
selected_count += 1
|
||||
if prediction.semantic.resolution is SemanticResolution.CONFLICT:
|
||||
conflict_count += 1
|
||||
exact = selected == label.class_id
|
||||
coarse = selected is not None and _coarse_group(selected, vocabulary) == _coarse_group(
|
||||
label.class_id, vocabulary
|
||||
)
|
||||
top_k_ids = {item.class_id for item in prediction.hypotheses[: profile.top_k]}
|
||||
cases.append(
|
||||
SemanticQualityCase(
|
||||
label_id=label.label_id,
|
||||
observation_id=label.observation_id,
|
||||
truth_class_id=label.class_id,
|
||||
resolution=prediction.semantic.resolution.value,
|
||||
selected_class_id=selected,
|
||||
exact_top1_correct=exact,
|
||||
coarse_group_correct=coarse,
|
||||
exact_top_k_hit=label.class_id in top_k_ids,
|
||||
)
|
||||
)
|
||||
|
||||
truth_count = len(truth)
|
||||
exact_accuracy = sum(item.exact_top1_correct for item in cases) / truth_count
|
||||
coarse_accuracy = sum(item.coarse_group_correct for item in cases) / truth_count
|
||||
top_k_recall = sum(item.exact_top_k_hit for item in cases) / truth_count
|
||||
prediction_coverage = predicted_count / truth_count
|
||||
unresolved_fraction = (truth_count - selected_count) / truth_count
|
||||
conflict_fraction = conflict_count / truth_count
|
||||
gates = {
|
||||
"prediction_coverage": (prediction_coverage >= profile.minimum_prediction_coverage),
|
||||
"exact_top1_accuracy": (exact_accuracy >= profile.minimum_exact_top1_accuracy),
|
||||
"coarse_group_accuracy": (coarse_accuracy >= profile.minimum_coarse_group_accuracy),
|
||||
"exact_top_k_recall": (top_k_recall >= profile.minimum_exact_top_k_recall),
|
||||
"unresolved_fraction": (unresolved_fraction <= profile.maximum_unresolved_fraction),
|
||||
"conflict_fraction": (conflict_fraction <= profile.maximum_conflict_fraction),
|
||||
}
|
||||
report: dict[str, object] = {
|
||||
"schema_version": SEMANTIC_QUALITY_REPORT_SCHEMA,
|
||||
"profile_id": profile.profile_id,
|
||||
"vocabulary_id": vocabulary.vocabulary_id,
|
||||
"scope": {
|
||||
"object_presence_scored": False,
|
||||
"semantic_class_scored": True,
|
||||
"risk_policy_scored": False,
|
||||
},
|
||||
"metrics": {
|
||||
"truth_count": truth_count,
|
||||
"prediction_count": predicted_count,
|
||||
"selected_count": selected_count,
|
||||
"conflict_count": conflict_count,
|
||||
"prediction_coverage": prediction_coverage,
|
||||
"exact_top1_accuracy": exact_accuracy,
|
||||
"coarse_group_accuracy": coarse_accuracy,
|
||||
"exact_top_k_recall": top_k_recall,
|
||||
"unresolved_fraction": unresolved_fraction,
|
||||
"conflict_fraction": conflict_fraction,
|
||||
},
|
||||
"gates": gates,
|
||||
"candidate_semantic_gate_passed": all(gates.values()),
|
||||
"limitations": [
|
||||
"Object presence and geometry quality remain owned by the class-free contour.",
|
||||
"Semantic qualification does not qualify risk policy or physical motion.",
|
||||
"No navigation, safety, command or actuation authority is granted.",
|
||||
],
|
||||
"authority": dict(_FALSE_AUTHORITY),
|
||||
}
|
||||
return SemanticObjectQualityResult(report=report, cases=tuple(cases))
|
||||
|
||||
|
||||
def _coarse_group(
|
||||
class_id: str,
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
) -> str:
|
||||
ancestors = vocabulary.ancestors(class_id)
|
||||
if not ancestors:
|
||||
return class_id
|
||||
non_root = tuple(item for item in ancestors if item != "object.unknown")
|
||||
return non_root[-1] if non_root else class_id
|
||||
|
||||
|
||||
def _object(value: object, label: str) -> dict[str, object]:
|
||||
if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
|
||||
raise SemanticObjectQualityError(f"{label} must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _exact_keys(document: dict[str, object], expected: set[str], label: str) -> None:
|
||||
if set(document) != expected:
|
||||
raise SemanticObjectQualityError(f"{label} fields are incompatible")
|
||||
|
||||
|
||||
def _string(document: dict[str, object], key: str) -> str:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, str) or not value:
|
||||
raise SemanticObjectQualityError(f"{key} must be a nonempty string")
|
||||
return value
|
||||
|
||||
|
||||
def _integer(document: dict[str, object], key: str) -> int:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, int) or isinstance(value, bool):
|
||||
raise SemanticObjectQualityError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
|
||||
def _boolean(document: dict[str, object], key: str) -> bool:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, bool):
|
||||
raise SemanticObjectQualityError(f"{key} must be boolean")
|
||||
return value
|
||||
|
||||
|
||||
def _number(document: dict[str, object], key: str) -> float:
|
||||
value = document.get(key)
|
||||
if (
|
||||
not isinstance(value, (int, float))
|
||||
or isinstance(value, bool)
|
||||
or not math.isfinite(float(value))
|
||||
):
|
||||
raise SemanticObjectQualityError(f"{key} must be finite")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _fraction(value: object, label: str) -> float:
|
||||
if (
|
||||
not isinstance(value, (int, float))
|
||||
or isinstance(value, bool)
|
||||
or not math.isfinite(float(value))
|
||||
or not 0.0 <= float(value) <= 1.0
|
||||
):
|
||||
raise SemanticObjectQualityError(f"{label} must be within [0, 1]")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _identifier(value: str, label: str) -> None:
|
||||
if not isinstance(value, str) or _IDENTIFIER.fullmatch(value) is None:
|
||||
raise SemanticObjectQualityError(f"{label} is not a safe identifier")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"SEMANTIC_QUALITY_PROFILE_SCHEMA",
|
||||
"SEMANTIC_QUALITY_REPORT_SCHEMA",
|
||||
"SEMANTIC_TRUTH_LABEL_SCHEMA",
|
||||
"SemanticObjectQualityError",
|
||||
"SemanticObjectQualityProfile",
|
||||
"SemanticObjectQualityResult",
|
||||
"SemanticQualityCase",
|
||||
"SemanticTruthLabel",
|
||||
"load_semantic_object_quality_profile",
|
||||
"score_semantic_object_quality",
|
||||
]
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Frozen raw-KB4 YOLOX provider for class-agnostic object proposals."""
|
||||
"""Versioned fixed-class detector providers for raw-KB4 object proposals."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -14,10 +14,22 @@ from numpy.typing import NDArray
|
||||
|
||||
from .contracts import BoundingRegion2D, ObjectProposal2D
|
||||
from .providers import SourcePacket
|
||||
from .rf_detr_object_detector import (
|
||||
RF_DETR_CONFIG,
|
||||
RF_DETR_MODEL_ID,
|
||||
RF_DETR_MODEL_VERSION,
|
||||
RfDetrConfig,
|
||||
RfDetrDetection,
|
||||
RfDetrInferenceBackend,
|
||||
postprocess_rf_detr,
|
||||
preprocess_raw_kb4_rf_detr,
|
||||
)
|
||||
from .yolox_object_detector import (
|
||||
ALL_COCO_YOLOX_CONFIG,
|
||||
FROZEN_YOLOX_CONFIG,
|
||||
YOLOX_MODEL_ID,
|
||||
YOLOX_MODEL_VERSION,
|
||||
AllCocoYoloxConfig,
|
||||
FrozenYoloxConfig,
|
||||
ImageResizer,
|
||||
InferenceBackend,
|
||||
@@ -27,8 +39,12 @@ from .yolox_object_detector import (
|
||||
)
|
||||
|
||||
FROZEN_YOLOX_PROVIDER_ID: Final = "triton-yolox-s-raw-kb4/v1"
|
||||
ALL_COCO_YOLOX_PROVIDER_ID: Final = "triton-yolox-s-raw-kb4-all-coco/v2"
|
||||
FROZEN_YOLOX_MODEL_ID: Final = f"{YOLOX_MODEL_ID}:{YOLOX_MODEL_VERSION}"
|
||||
FROZEN_YOLOX_PREPROCESS_ID: Final = "raw-kb4-valid-fov-letterbox/v1"
|
||||
RF_DETR_SHADOW_PROVIDER_ID: Final = "triton-rf-detr-large-coco-risk-fp16-shadow/v0"
|
||||
RF_DETR_SHADOW_MODEL_ID: Final = f"{RF_DETR_MODEL_ID}:{RF_DETR_MODEL_VERSION}"
|
||||
RF_DETR_SHADOW_PREPROCESS_ID: Final = "raw-kb4-valid-fov-rgb-stretch-imagenet/v0"
|
||||
|
||||
|
||||
class DetectorProviderError(RuntimeError):
|
||||
@@ -57,7 +73,7 @@ class FrozenYoloxDetectorProvider:
|
||||
mask: NDArray[np.bool_],
|
||||
backend: InferenceBackend,
|
||||
resizer: ImageResizer | None = None,
|
||||
config: FrozenYoloxConfig = FROZEN_YOLOX_CONFIG,
|
||||
config: FrozenYoloxConfig | AllCocoYoloxConfig = FROZEN_YOLOX_CONFIG,
|
||||
clock_ns: Callable[[], int] = time.perf_counter_ns,
|
||||
) -> None:
|
||||
if mask.shape != (600, 800) or mask.dtype != np.bool_ or not np.any(mask):
|
||||
@@ -95,7 +111,11 @@ class FrozenYoloxDetectorProvider:
|
||||
)
|
||||
output = self.backend.infer(tensor)
|
||||
postprocessed = postprocess_yolox(output, self.mask, config=self.config)
|
||||
proposals = proposals_from_detections(packet, postprocessed.detections)
|
||||
proposals = proposals_from_detections(
|
||||
packet,
|
||||
postprocessed.detections,
|
||||
provider_id=self.provider_id,
|
||||
)
|
||||
except Exception:
|
||||
with self._lock:
|
||||
self._failed_frames += 1
|
||||
@@ -125,6 +145,8 @@ class FrozenYoloxDetectorProvider:
|
||||
def proposals_from_detections(
|
||||
packet: SourcePacket,
|
||||
detections: tuple[YoloxDetection, ...],
|
||||
*,
|
||||
provider_id: str = FROZEN_YOLOX_PROVIDER_ID,
|
||||
) -> tuple[ObjectProposal2D, ...]:
|
||||
envelope = packet.envelope
|
||||
return tuple(
|
||||
@@ -134,7 +156,7 @@ def proposals_from_detections(
|
||||
frame_id=envelope.frame_id,
|
||||
region=BoundingRegion2D(*detection.bbox_xyxy),
|
||||
objectness=detection.score,
|
||||
provider_id=FROZEN_YOLOX_PROVIDER_ID,
|
||||
provider_id=provider_id,
|
||||
model_id=FROZEN_YOLOX_MODEL_ID,
|
||||
preprocess_id=FROZEN_YOLOX_PREPROCESS_ID,
|
||||
semantic_hint=detection.label,
|
||||
@@ -144,12 +166,140 @@ def proposals_from_detections(
|
||||
)
|
||||
|
||||
|
||||
class AllCocoYoloxDetectorProvider(FrozenYoloxDetectorProvider):
|
||||
"""Emit every qualified COCO class without adding another inference pass."""
|
||||
|
||||
provider_id: str = ALL_COCO_YOLOX_PROVIDER_ID
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
mask: NDArray[np.bool_],
|
||||
backend: InferenceBackend,
|
||||
resizer: ImageResizer | None = None,
|
||||
config: AllCocoYoloxConfig = ALL_COCO_YOLOX_CONFIG,
|
||||
clock_ns: Callable[[], int] = time.perf_counter_ns,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
mask=mask,
|
||||
backend=backend,
|
||||
resizer=resizer,
|
||||
config=config,
|
||||
clock_ns=clock_ns,
|
||||
)
|
||||
|
||||
|
||||
class RfDetrShadowDetectorProvider:
|
||||
"""Emit behavior-relevant fixed classes from one RF-DETR inference pass."""
|
||||
|
||||
provider_id: str = RF_DETR_SHADOW_PROVIDER_ID
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
mask: NDArray[np.bool_],
|
||||
backend: RfDetrInferenceBackend,
|
||||
resizer: ImageResizer | None = None,
|
||||
config: RfDetrConfig = RF_DETR_CONFIG,
|
||||
clock_ns: Callable[[], int] = time.perf_counter_ns,
|
||||
) -> None:
|
||||
if mask.shape != (600, 800) or mask.dtype != np.bool_ or not np.any(mask):
|
||||
raise DetectorProviderError("RF-DETR valid-FOV mask is incompatible")
|
||||
self.mask = np.asarray(mask, dtype=np.bool_)
|
||||
self.backend = backend
|
||||
self.resizer = resizer
|
||||
self.config = config
|
||||
self._clock_ns = clock_ns
|
||||
self._lock = Lock()
|
||||
self._input_frames = 0
|
||||
self._completed_frames = 0
|
||||
self._failed_frames = 0
|
||||
self._zero_proposal_frames = 0
|
||||
self._proposal_count = 0
|
||||
self._rejected: Counter[str] = Counter()
|
||||
self._core_duration_ns = 0
|
||||
|
||||
def detect(self, packet: SourcePacket) -> tuple[ObjectProposal2D, ...]:
|
||||
payload = packet.image_payload
|
||||
with self._lock:
|
||||
self._input_frames += 1
|
||||
started_ns = int(self._clock_ns())
|
||||
try:
|
||||
if not isinstance(payload, np.ndarray):
|
||||
raise DetectorProviderError("RF-DETR requires a decoded BGR image payload")
|
||||
image = np.asarray(payload)
|
||||
if image.dtype != np.uint8:
|
||||
raise DetectorProviderError("decoded BGR image must be uint8")
|
||||
tensor = preprocess_raw_kb4_rf_detr(
|
||||
image,
|
||||
self.mask,
|
||||
config=self.config,
|
||||
resizer=self.resizer,
|
||||
)
|
||||
output = self.backend.infer(tensor)
|
||||
postprocessed = postprocess_rf_detr(output, self.mask, config=self.config)
|
||||
proposals = proposals_from_rf_detr_detections(packet, postprocessed.detections)
|
||||
except Exception:
|
||||
with self._lock:
|
||||
self._failed_frames += 1
|
||||
self._core_duration_ns += max(0, int(self._clock_ns()) - started_ns)
|
||||
raise
|
||||
with self._lock:
|
||||
self._completed_frames += 1
|
||||
self._proposal_count += len(proposals)
|
||||
self._zero_proposal_frames += not proposals
|
||||
self._rejected.update(dict(postprocessed.rejected))
|
||||
self._core_duration_ns += max(0, int(self._clock_ns()) - started_ns)
|
||||
return proposals
|
||||
|
||||
def snapshot(self) -> DetectorProviderSnapshot:
|
||||
with self._lock:
|
||||
return DetectorProviderSnapshot(
|
||||
input_frames=self._input_frames,
|
||||
completed_frames=self._completed_frames,
|
||||
failed_frames=self._failed_frames,
|
||||
zero_proposal_frames=self._zero_proposal_frames,
|
||||
proposal_count=self._proposal_count,
|
||||
rejected=tuple(sorted(self._rejected.items())),
|
||||
core_duration_ns=self._core_duration_ns,
|
||||
)
|
||||
|
||||
|
||||
def proposals_from_rf_detr_detections(
|
||||
packet: SourcePacket,
|
||||
detections: tuple[RfDetrDetection, ...],
|
||||
) -> tuple[ObjectProposal2D, ...]:
|
||||
envelope = packet.envelope
|
||||
return tuple(
|
||||
ObjectProposal2D(
|
||||
proposal_id=f"proposal-{envelope.sequence}-{index}",
|
||||
source_id=envelope.source_id,
|
||||
frame_id=envelope.frame_id,
|
||||
region=BoundingRegion2D(*detection.bbox_xyxy),
|
||||
objectness=detection.score,
|
||||
provider_id=RF_DETR_SHADOW_PROVIDER_ID,
|
||||
model_id=RF_DETR_SHADOW_MODEL_ID,
|
||||
preprocess_id=RF_DETR_SHADOW_PREPROCESS_ID,
|
||||
semantic_hint=detection.label,
|
||||
provider_tracklet=None,
|
||||
)
|
||||
for index, detection in enumerate(detections)
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ALL_COCO_YOLOX_PROVIDER_ID",
|
||||
"FROZEN_YOLOX_MODEL_ID",
|
||||
"FROZEN_YOLOX_PREPROCESS_ID",
|
||||
"FROZEN_YOLOX_PROVIDER_ID",
|
||||
"RF_DETR_SHADOW_MODEL_ID",
|
||||
"RF_DETR_SHADOW_PREPROCESS_ID",
|
||||
"RF_DETR_SHADOW_PROVIDER_ID",
|
||||
"DetectorProviderError",
|
||||
"DetectorProviderSnapshot",
|
||||
"AllCocoYoloxDetectorProvider",
|
||||
"FrozenYoloxDetectorProvider",
|
||||
"RfDetrShadowDetectorProvider",
|
||||
"proposals_from_detections",
|
||||
"proposals_from_rf_detr_detections",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
"""Contracts for the bounded M48S fixed-class detector tournament."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections import Counter
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Final
|
||||
|
||||
WORKER_RUN_SCHEMA: Final = "missioncore.m48s-fixed-detector-candidate-worker/v0"
|
||||
TOURNAMENT_SCHEMA: Final = "missioncore.m48s-fixed-detector-tournament/v0"
|
||||
EXACT_FRAME_NAMES: Final = (
|
||||
"frame-000121.png",
|
||||
"frame-000131.png",
|
||||
"frame-000253.png",
|
||||
"frame-000275.png",
|
||||
"frame-000443.png",
|
||||
"frame-000463.png",
|
||||
"frame-001094.png",
|
||||
"frame-001228.png",
|
||||
"frame-001454.png",
|
||||
"frame-001856.png",
|
||||
"frame-002386.png",
|
||||
)
|
||||
RISK_GROUPS: Final[Mapping[str, frozenset[str]]] = {
|
||||
"person": frozenset({"person"}),
|
||||
"animal": frozenset(
|
||||
{"bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe"}
|
||||
),
|
||||
"light-road-user": frozenset({"bicycle", "motorcycle", "skateboard"}),
|
||||
"vehicle": frozenset({"car", "bus", "truck"}),
|
||||
}
|
||||
_RISK_LABELS: Final = frozenset().union(*RISK_GROUPS.values())
|
||||
_FALSE_AUTHORITY: Final = {
|
||||
"ground_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
class FixedClassTournamentError(ValueError):
|
||||
"""Raised when tournament evidence violates its bounded contract."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CandidateDetection:
|
||||
"""One normalized COCO detection emitted by a candidate."""
|
||||
|
||||
class_id: int
|
||||
label: str
|
||||
score: float
|
||||
bbox_xyxy: tuple[float, float, float, float]
|
||||
valid_fov_fraction: float
|
||||
|
||||
@classmethod
|
||||
def from_document(cls, document: object) -> CandidateDetection:
|
||||
item = _mapping(document, "detection")
|
||||
box = item.get("bbox_xyxy")
|
||||
if not isinstance(box, list) or len(box) != 4:
|
||||
raise FixedClassTournamentError("detection bbox_xyxy must contain four numbers")
|
||||
values = (
|
||||
_number(box[0], "bbox coordinate"),
|
||||
_number(box[1], "bbox coordinate"),
|
||||
_number(box[2], "bbox coordinate"),
|
||||
_number(box[3], "bbox coordinate"),
|
||||
)
|
||||
x1, y1, x2, y2 = values
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
raise FixedClassTournamentError("detection box must have positive area")
|
||||
score = _number(item.get("score"), "detection score")
|
||||
valid_fov_fraction = _number(
|
||||
item.get("valid_fov_fraction"), "detection valid-FOV fraction"
|
||||
)
|
||||
if not 0.0 <= score <= 1.0:
|
||||
raise FixedClassTournamentError("detection score must be in [0, 1]")
|
||||
if not 0.0 <= valid_fov_fraction <= 1.0:
|
||||
raise FixedClassTournamentError("valid-FOV fraction must be in [0, 1]")
|
||||
return cls(
|
||||
class_id=_integer(item.get("class_id"), "detection class id"),
|
||||
label=_text(item.get("label"), "detection label"),
|
||||
score=score,
|
||||
bbox_xyxy=values,
|
||||
valid_fov_fraction=valid_fov_fraction,
|
||||
)
|
||||
|
||||
@property
|
||||
def risk_group(self) -> str | None:
|
||||
for group, labels in RISK_GROUPS.items():
|
||||
if self.label in labels:
|
||||
return group
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CandidateFrame:
|
||||
"""One exact-frame candidate result."""
|
||||
|
||||
frame_name: str
|
||||
source_sha256: str
|
||||
detections: tuple[CandidateDetection, ...]
|
||||
end_to_end_ms: float
|
||||
|
||||
@classmethod
|
||||
def from_document(cls, document: object) -> CandidateFrame:
|
||||
item = _mapping(document, "frame")
|
||||
detections = item.get("detections")
|
||||
if not isinstance(detections, list):
|
||||
raise FixedClassTournamentError("frame detections must be a list")
|
||||
return cls(
|
||||
frame_name=_text(item.get("frame_name"), "frame name"),
|
||||
source_sha256=_digest(item.get("source_sha256"), "source digest"),
|
||||
detections=tuple(CandidateDetection.from_document(value) for value in detections),
|
||||
end_to_end_ms=_nonnegative_number(
|
||||
_mapping(item.get("timing_ms"), "frame timing").get("end_to_end"),
|
||||
"frame end-to-end timing",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CandidateWorkerRun:
|
||||
"""Validated raw Worker result for one candidate."""
|
||||
|
||||
profile_id: str
|
||||
provider_id: str
|
||||
upstream_revision: str
|
||||
checkpoint_sha256: str
|
||||
frames: tuple[CandidateFrame, ...]
|
||||
metrics: Mapping[str, object]
|
||||
authority: Mapping[str, bool]
|
||||
|
||||
@classmethod
|
||||
def from_document(cls, document: object) -> CandidateWorkerRun:
|
||||
root = _mapping(document, "worker result")
|
||||
if root.get("schema_version") != WORKER_RUN_SCHEMA:
|
||||
raise FixedClassTournamentError("unexpected candidate Worker schema")
|
||||
frames_raw = root.get("frames")
|
||||
if not isinstance(frames_raw, list):
|
||||
raise FixedClassTournamentError("worker result frames must be a list")
|
||||
frames = tuple(CandidateFrame.from_document(value) for value in frames_raw)
|
||||
if tuple(sorted(frame.frame_name for frame in frames)) != EXACT_FRAME_NAMES:
|
||||
raise FixedClassTournamentError("worker result does not contain the exact M48S slice")
|
||||
if len({frame.frame_name for frame in frames}) != len(EXACT_FRAME_NAMES):
|
||||
raise FixedClassTournamentError("worker result contains duplicate frames")
|
||||
execution = _mapping(root.get("execution"), "worker execution")
|
||||
if execution.get("inference_passes_per_evidence_frame") != 1:
|
||||
raise FixedClassTournamentError(
|
||||
"candidate must use one inference pass per evidence frame"
|
||||
)
|
||||
authority = _boolean_mapping(root.get("authority"), "worker authority")
|
||||
if authority != _FALSE_AUTHORITY:
|
||||
raise FixedClassTournamentError("candidate Worker result must retain false authority")
|
||||
completed = root.get("completed")
|
||||
if completed is not True:
|
||||
raise FixedClassTournamentError("candidate Worker result is incomplete")
|
||||
return cls(
|
||||
profile_id=_text(root.get("profile_id"), "profile id"),
|
||||
provider_id=_text(root.get("provider_id"), "provider id"),
|
||||
upstream_revision=_text(root.get("upstream_revision"), "upstream revision"),
|
||||
checkpoint_sha256=_digest(root.get("checkpoint_sha256"), "checkpoint digest"),
|
||||
frames=frames,
|
||||
metrics=_mapping(root.get("metrics"), "worker metrics"),
|
||||
authority=authority,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_path(cls, path: Path) -> CandidateWorkerRun:
|
||||
try:
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as error:
|
||||
raise FixedClassTournamentError(
|
||||
f"cannot read candidate Worker result: {path}"
|
||||
) from error
|
||||
return cls.from_document(document)
|
||||
|
||||
def quality_summary(self, *, threshold: float) -> dict[str, object]:
|
||||
if not 0.0 <= threshold <= 1.0:
|
||||
raise FixedClassTournamentError("quality threshold must be in [0, 1]")
|
||||
selected = tuple(
|
||||
detection
|
||||
for frame in self.frames
|
||||
for detection in frame.detections
|
||||
if detection.score >= threshold
|
||||
)
|
||||
class_counts = Counter(item.label for item in selected)
|
||||
risk_counts = Counter(item.risk_group for item in selected if item.risk_group is not None)
|
||||
dog_frame = next(frame for frame in self.frames if frame.frame_name == "frame-000253.png")
|
||||
dog_detections = tuple(
|
||||
detection
|
||||
for detection in dog_frame.detections
|
||||
if detection.label == "dog" and detection.score >= threshold
|
||||
)
|
||||
return {
|
||||
"threshold": threshold,
|
||||
"detection_count": len(selected),
|
||||
"class_counts": dict(sorted(class_counts.items())),
|
||||
"risk_group_counts": dict(sorted(risk_counts.items())),
|
||||
"risk_detection_count": sum(1 for item in selected if item.label in _RISK_LABELS),
|
||||
"frame_000253_dog_detected": bool(dog_detections),
|
||||
"frame_000253_dog_max_score": (
|
||||
round(max(item.score for item in dog_detections), 6) if dog_detections else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def canonical_json(value: object) -> bytes:
|
||||
"""Return deterministic JSON bytes for immutable evidence identities."""
|
||||
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
def sha256_path(path: Path) -> str:
|
||||
"""Hash a file without loading it into memory."""
|
||||
|
||||
digest = hashlib.sha256()
|
||||
try:
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
except OSError as error:
|
||||
raise FixedClassTournamentError(f"cannot hash evidence file: {path}") from error
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def false_authority() -> dict[str, bool]:
|
||||
"""Return a fresh false-authority document."""
|
||||
|
||||
return dict(_FALSE_AUTHORITY)
|
||||
|
||||
|
||||
def _mapping(value: object, name: str) -> Mapping[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
raise FixedClassTournamentError(f"{name} must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _boolean_mapping(value: object, name: str) -> Mapping[str, bool]:
|
||||
mapping = _mapping(value, name)
|
||||
if set(mapping) != set(_FALSE_AUTHORITY) or not all(
|
||||
isinstance(item, bool) for item in mapping.values()
|
||||
):
|
||||
raise FixedClassTournamentError(f"{name} must contain the exact boolean authority fields")
|
||||
return mapping
|
||||
|
||||
|
||||
def _text(value: object, name: str) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise FixedClassTournamentError(f"{name} must be non-empty text")
|
||||
return value
|
||||
|
||||
|
||||
def _digest(value: object, name: str) -> str:
|
||||
text = _text(value, name)
|
||||
if len(text) != 64 or any(character not in "0123456789abcdef" for character in text):
|
||||
raise FixedClassTournamentError(f"{name} must be a lowercase SHA-256 digest")
|
||||
return text
|
||||
|
||||
|
||||
def _integer(value: object, name: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise FixedClassTournamentError(f"{name} must be an integer")
|
||||
return value
|
||||
|
||||
|
||||
def _number(value: object, name: str) -> float:
|
||||
if isinstance(value, bool) or not isinstance(value, int | float):
|
||||
raise FixedClassTournamentError(f"{name} must be numeric")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _nonnegative_number(value: object, name: str) -> float:
|
||||
result = _number(value, name)
|
||||
if result < 0.0:
|
||||
raise FixedClassTournamentError(f"{name} must be non-negative")
|
||||
return result
|
||||
@@ -0,0 +1,272 @@
|
||||
"""Geometry-first raw-KB4 regions for semantic classification shadows."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from .contracts import BoundingRegion2D, ObstacleObservation
|
||||
from .geometry import GeometryFrame
|
||||
from .geometry_math import project_map_points_kb4
|
||||
from .open_vocabulary_semantics import OpenVocabularyDetection, SemanticFusionResult
|
||||
|
||||
|
||||
class GeometrySemanticRoiError(ValueError):
|
||||
"""A geometry-owned semantic ROI or crop is incompatible."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeometrySemanticRoiProfile:
|
||||
minimum_projected_points: int = 4
|
||||
minimum_crop_width: int = 96
|
||||
minimum_crop_height: int = 96
|
||||
padding_fraction: float = 0.25
|
||||
minimum_padding_pixels: int = 16
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (
|
||||
self.minimum_projected_points < 2
|
||||
or self.minimum_crop_width < 32
|
||||
or self.minimum_crop_height < 32
|
||||
or not math.isfinite(self.padding_fraction)
|
||||
or not 0.0 <= self.padding_fraction <= 1.0
|
||||
or self.minimum_padding_pixels < 0
|
||||
):
|
||||
raise GeometrySemanticRoiError("geometry semantic ROI profile is invalid")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeometrySemanticRoi:
|
||||
roi_id: str
|
||||
frame_index: int
|
||||
observation: ObstacleObservation
|
||||
core_region: BoundingRegion2D
|
||||
crop_region: BoundingRegion2D
|
||||
projected_point_count: int
|
||||
crop_name: str
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"roi_id": self.roi_id,
|
||||
"frame_index": self.frame_index,
|
||||
"observation": self.observation.to_dict(),
|
||||
"core_region": self.core_region.to_dict(),
|
||||
"crop_region": self.crop_region.to_dict(),
|
||||
"projected_point_count": self.projected_point_count,
|
||||
"crop_name": self.crop_name,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeometrySemanticRoiFrame:
|
||||
frame_index: int
|
||||
rois: tuple[GeometrySemanticRoi, ...]
|
||||
not_projected_observations: tuple[ObstacleObservation, ...]
|
||||
|
||||
|
||||
def build_geometry_semantic_rois(
|
||||
*,
|
||||
frame: GeometryFrame,
|
||||
observations: tuple[ObstacleObservation, ...],
|
||||
profile: GeometrySemanticRoiProfile | None = None,
|
||||
) -> GeometrySemanticRoiFrame:
|
||||
"""Project geometry-owned point identities into bounded semantic crops."""
|
||||
|
||||
selected_profile = profile or GeometrySemanticRoiProfile()
|
||||
if frame.frame_index < 0 or not frame.surface_valid:
|
||||
raise GeometrySemanticRoiError("geometry semantic ROI frame is unavailable")
|
||||
if any(
|
||||
item.frame_id != f"frame-{frame.frame_index:06d}"
|
||||
or item.metric_geometry is None
|
||||
or not item.occupied_support
|
||||
for item in observations
|
||||
):
|
||||
raise GeometrySemanticRoiError("geometry semantic ROI observations are incompatible")
|
||||
projected = project_map_points_kb4(
|
||||
frame.points_map,
|
||||
position_map_xyz=frame.sensor_position_map,
|
||||
orientation_map_from_lidar_xyzw=frame.sensor_orientation_xyzw,
|
||||
profile=frame.projection,
|
||||
)
|
||||
rois: list[GeometrySemanticRoi] = []
|
||||
missing: list[ObstacleObservation] = []
|
||||
for observation in observations:
|
||||
source_ids = np.asarray(observation.source_point_ids, dtype=np.int64)
|
||||
selected = np.isin(projected.source_indices, source_ids)
|
||||
pixels = projected.pixels_xy[selected]
|
||||
if pixels.shape[0] < selected_profile.minimum_projected_points:
|
||||
missing.append(observation)
|
||||
continue
|
||||
x_min, y_min = pixels.min(axis=0)
|
||||
x_max, y_max = pixels.max(axis=0)
|
||||
core = _nonempty_region(
|
||||
float(x_min),
|
||||
float(y_min),
|
||||
float(x_max),
|
||||
float(y_max),
|
||||
width=frame.projection.width,
|
||||
height=frame.projection.height,
|
||||
)
|
||||
crop = _crop_region(
|
||||
core,
|
||||
width=frame.projection.width,
|
||||
height=frame.projection.height,
|
||||
profile=selected_profile,
|
||||
)
|
||||
ordinal = len(rois)
|
||||
roi_id = f"{observation.frame_id}:geometry-roi-{ordinal:03d}"
|
||||
rois.append(
|
||||
GeometrySemanticRoi(
|
||||
roi_id=roi_id,
|
||||
frame_index=frame.frame_index,
|
||||
observation=observation,
|
||||
core_region=core,
|
||||
crop_region=crop,
|
||||
projected_point_count=int(pixels.shape[0]),
|
||||
crop_name=(
|
||||
f"frame-{frame.frame_index:06d}-geometry-roi-{ordinal:03d}.png"
|
||||
),
|
||||
)
|
||||
)
|
||||
return GeometrySemanticRoiFrame(
|
||||
frame_index=frame.frame_index,
|
||||
rois=tuple(rois),
|
||||
not_projected_observations=tuple(missing),
|
||||
)
|
||||
|
||||
|
||||
def materialize_geometry_semantic_crop(
|
||||
*,
|
||||
image_path: Path,
|
||||
roi: GeometrySemanticRoi,
|
||||
destination: Path,
|
||||
) -> None:
|
||||
"""Write one lossless crop while retaining raw-image coordinate lineage."""
|
||||
|
||||
try:
|
||||
with Image.open(image_path.resolve(strict=True)) as opened:
|
||||
if opened.size != (800, 600):
|
||||
raise GeometrySemanticRoiError("semantic crop source raster changed")
|
||||
image = opened.convert("RGB")
|
||||
crop = image.crop(_integer_box(roi.crop_region))
|
||||
except OSError as exc:
|
||||
raise GeometrySemanticRoiError("semantic crop source cannot be read") from exc
|
||||
target = destination.resolve()
|
||||
if target.exists() or target.name != roi.crop_name:
|
||||
raise GeometrySemanticRoiError("semantic crop destination is invalid")
|
||||
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
crop.save(target, format="PNG", optimize=False)
|
||||
|
||||
|
||||
def select_geometry_roi_detections(
|
||||
roi: GeometrySemanticRoi,
|
||||
fusion: SemanticFusionResult,
|
||||
) -> tuple[OpenVocabularyDetection, ...]:
|
||||
"""Select the semantic cluster covering the geometry-owned core, if any."""
|
||||
|
||||
center_x = (roi.core_region.x_min + roi.core_region.x_max) / 2.0
|
||||
center_y = (roi.core_region.y_min + roi.core_region.y_max) / 2.0
|
||||
candidates = []
|
||||
for binding in fusion.bindings:
|
||||
region = binding.proposal.region
|
||||
center_inside = (
|
||||
region.x_min <= center_x <= region.x_max
|
||||
and region.y_min <= center_y <= region.y_max
|
||||
)
|
||||
core_coverage = _intersection_area(region, roi.core_region) / _area(roi.core_region)
|
||||
if center_inside or core_coverage >= 0.25:
|
||||
candidates.append((binding.proposal.objectness, core_coverage, binding))
|
||||
if not candidates:
|
||||
return ()
|
||||
selected = max(candidates, key=lambda item: (item[0], item[1], item[2].proposal.proposal_id))
|
||||
return selected[2].detections
|
||||
|
||||
|
||||
def _nonempty_region(
|
||||
x_min: float,
|
||||
y_min: float,
|
||||
x_max: float,
|
||||
y_max: float,
|
||||
*,
|
||||
width: int,
|
||||
height: int,
|
||||
) -> BoundingRegion2D:
|
||||
if x_max - x_min < 1.0:
|
||||
center = (x_min + x_max) / 2.0
|
||||
x_min, x_max = center - 0.5, center + 0.5
|
||||
if y_max - y_min < 1.0:
|
||||
center = (y_min + y_max) / 2.0
|
||||
y_min, y_max = center - 0.5, center + 0.5
|
||||
x_min = max(0.0, min(x_min, width - 1.0))
|
||||
y_min = max(0.0, min(y_min, height - 1.0))
|
||||
x_max = min(float(width), max(x_max, x_min + 1.0))
|
||||
y_max = min(float(height), max(y_max, y_min + 1.0))
|
||||
return BoundingRegion2D(x_min, y_min, x_max, y_max)
|
||||
|
||||
|
||||
def _crop_region(
|
||||
core: BoundingRegion2D,
|
||||
*,
|
||||
width: int,
|
||||
height: int,
|
||||
profile: GeometrySemanticRoiProfile,
|
||||
) -> BoundingRegion2D:
|
||||
core_width = core.x_max - core.x_min
|
||||
core_height = core.y_max - core.y_min
|
||||
padding_x = max(profile.minimum_padding_pixels, core_width * profile.padding_fraction)
|
||||
padding_y = max(profile.minimum_padding_pixels, core_height * profile.padding_fraction)
|
||||
target_width = min(
|
||||
width,
|
||||
max(profile.minimum_crop_width, math.ceil(core_width + 2.0 * padding_x)),
|
||||
)
|
||||
target_height = min(
|
||||
height,
|
||||
max(profile.minimum_crop_height, math.ceil(core_height + 2.0 * padding_y)),
|
||||
)
|
||||
center_x = (core.x_min + core.x_max) / 2.0
|
||||
center_y = (core.y_min + core.y_max) / 2.0
|
||||
x_min = int(round(center_x - target_width / 2.0))
|
||||
y_min = int(round(center_y - target_height / 2.0))
|
||||
x_min = min(max(0, x_min), width - target_width)
|
||||
y_min = min(max(0, y_min), height - target_height)
|
||||
return BoundingRegion2D(
|
||||
float(x_min),
|
||||
float(y_min),
|
||||
float(x_min + target_width),
|
||||
float(y_min + target_height),
|
||||
)
|
||||
|
||||
|
||||
def _integer_box(region: BoundingRegion2D) -> tuple[int, int, int, int]:
|
||||
return (
|
||||
int(region.x_min),
|
||||
int(region.y_min),
|
||||
int(region.x_max),
|
||||
int(region.y_max),
|
||||
)
|
||||
|
||||
|
||||
def _area(region: BoundingRegion2D) -> float:
|
||||
return (region.x_max - region.x_min) * (region.y_max - region.y_min)
|
||||
|
||||
|
||||
def _intersection_area(left: BoundingRegion2D, right: BoundingRegion2D) -> float:
|
||||
return max(0.0, min(left.x_max, right.x_max) - max(left.x_min, right.x_min)) * max(
|
||||
0.0,
|
||||
min(left.y_max, right.y_max) - max(left.y_min, right.y_min),
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GeometrySemanticRoi",
|
||||
"GeometrySemanticRoiError",
|
||||
"GeometrySemanticRoiFrame",
|
||||
"GeometrySemanticRoiProfile",
|
||||
"build_geometry_semantic_rois",
|
||||
"materialize_geometry_semantic_crop",
|
||||
"select_geometry_roi_detections",
|
||||
]
|
||||
@@ -0,0 +1,580 @@
|
||||
"""Immutable geometry-first M48S semantic shadow replay."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from .detector_replay_result import (
|
||||
read_detector_replay_result,
|
||||
require_m4_detector_replay_acceptance,
|
||||
)
|
||||
from .geometry import Ravnoves00GeometryAssociationProvider, RecordedGeometryStore
|
||||
from .geometry_semantic_roi import (
|
||||
GeometrySemanticRoi,
|
||||
build_geometry_semantic_rois,
|
||||
select_geometry_roi_detections,
|
||||
)
|
||||
from .graph_validation import validate_observations
|
||||
from .object_understanding import (
|
||||
ObjectUnderstanding,
|
||||
SemanticResolution,
|
||||
load_object_semantic_vocabulary,
|
||||
)
|
||||
from .open_vocabulary_semantics import (
|
||||
OpenVocabularyDetection,
|
||||
fuse_open_vocabulary_detections,
|
||||
load_open_vocabulary_semantic_profile,
|
||||
parse_tao_grounding_dino_labels,
|
||||
understand_geometry_observation,
|
||||
)
|
||||
from .semantic_shadow_replay import semantic_replay_packet
|
||||
from .yolox_object_detector import load_valid_fov_mask
|
||||
|
||||
GEOMETRY_SEMANTIC_SHADOW_REPLAY_SCHEMA: Final = (
|
||||
"missioncore.m48s-geometry-semantic-shadow-replay/v0"
|
||||
)
|
||||
GEOMETRY_SEMANTIC_SHADOW_FRAME_SCHEMA: Final = (
|
||||
"missioncore.m48s-geometry-semantic-shadow-frame/v0"
|
||||
)
|
||||
GEOMETRY_SEMANTIC_ROI_PACKAGE_SCHEMA: Final = (
|
||||
"missioncore.m48s-geometry-semantic-roi-package/v0"
|
||||
)
|
||||
RESULT_PREFIX: Final = "m48s-geometry-semantic-shadow-"
|
||||
|
||||
|
||||
class GeometrySemanticShadowReplayError(RuntimeError):
|
||||
"""Geometry-first semantic evidence is incomplete or incompatible."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeometrySemanticShadowReplayResult:
|
||||
result_id: str
|
||||
result_root: Path
|
||||
completed: bool
|
||||
accepted: bool
|
||||
metrics: dict[str, object]
|
||||
report: dict[str, object]
|
||||
manifest: dict[str, object]
|
||||
|
||||
|
||||
def build_geometry_semantic_shadow_replay(
|
||||
*,
|
||||
repository_root: Path,
|
||||
profile_path: Path,
|
||||
vocabulary_path: Path,
|
||||
detector_result_root: Path,
|
||||
roi_package_root: Path,
|
||||
valid_fov_mask_path: Path,
|
||||
worker_result_roots: Mapping[str, Path],
|
||||
frame_indices: tuple[int, ...],
|
||||
worker_execution: Mapping[str, object],
|
||||
output_root: Path,
|
||||
) -> GeometrySemanticShadowReplayResult:
|
||||
"""Name geometry-owned obstacles while leaving occupancy and authority untouched."""
|
||||
|
||||
repository = repository_root.resolve(strict=True)
|
||||
profile = load_open_vocabulary_semantic_profile(profile_path)
|
||||
vocabulary = load_object_semantic_vocabulary(vocabulary_path)
|
||||
if vocabulary.vocabulary_id != profile.vocabulary_id:
|
||||
raise GeometrySemanticShadowReplayError("semantic profile and vocabulary disagree")
|
||||
frames = _validate_frame_indices(frame_indices)
|
||||
roi_root = roi_package_root.resolve(strict=True)
|
||||
roi_manifest = _read_object(roi_root / "manifest.json", "ROI package manifest")
|
||||
roi_identity = _validate_roi_manifest(roi_manifest, frames=frames)
|
||||
crop_names = tuple(
|
||||
_string(_object(roi, "ROI"), "crop_name")
|
||||
for frame in _array(roi_identity, "frames")
|
||||
for roi in _array(_object(frame, "ROI frame"), "rois")
|
||||
)
|
||||
_validate_worker_results(worker_result_roots, profile=profile, crop_names=crop_names)
|
||||
valid_fov_mask = load_valid_fov_mask(
|
||||
valid_fov_mask_path,
|
||||
expected_sha256=profile.valid_fov_mask_sha256,
|
||||
)
|
||||
detector = read_detector_replay_result(detector_result_root)
|
||||
require_m4_detector_replay_acceptance(detector)
|
||||
detector_by_sequence = {item.sequence: item for item in detector.frames}
|
||||
if any(index not in detector_by_sequence for index in frames):
|
||||
raise GeometrySemanticShadowReplayError("semantic frame escaped detector timeline")
|
||||
store = RecordedGeometryStore.from_repository(repository)
|
||||
geometry = Ravnoves00GeometryAssociationProvider(store=store)
|
||||
|
||||
output = output_root.expanduser().absolute()
|
||||
output.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
staging = output / f".geometry-semantic-shadow.{uuid.uuid4().hex}.tmp"
|
||||
staging.mkdir(mode=0o700, exist_ok=False)
|
||||
totals: Counter[str] = Counter()
|
||||
resolution_counts: Counter[str] = Counter()
|
||||
class_counts: Counter[str] = Counter()
|
||||
try:
|
||||
frames_path = staging / "frames.jsonl"
|
||||
with frames_path.open("wb") as ledger:
|
||||
for frame_index in frames:
|
||||
detector_frame = detector_by_sequence[frame_index]
|
||||
if detector_frame.outcome != "completed":
|
||||
raise GeometrySemanticShadowReplayError("accepted detector frame failed")
|
||||
packet = semantic_replay_packet(detector_frame.envelope)
|
||||
observations = geometry.associate(packet, ())
|
||||
validate_observations(packet, (), observations)
|
||||
geometry_frame = store.frame(packet)
|
||||
if geometry_frame is None:
|
||||
raise GeometrySemanticShadowReplayError("selected geometry frame unavailable")
|
||||
roi_frame = build_geometry_semantic_rois(
|
||||
frame=geometry_frame,
|
||||
observations=observations,
|
||||
)
|
||||
stored_frame = _roi_manifest_frame(roi_identity, frame_index)
|
||||
if [item.to_dict() for item in roi_frame.rois] != [
|
||||
_roi_without_materialization(_object(item, "stored ROI"))
|
||||
for item in _array(stored_frame, "rois")
|
||||
]:
|
||||
raise GeometrySemanticShadowReplayError("stored ROI geometry changed")
|
||||
understandings_by_observation: dict[str, ObjectUnderstanding] = {}
|
||||
roi_documents: list[dict[str, object]] = []
|
||||
for roi in roi_frame.rois:
|
||||
detections = _roi_detections(
|
||||
roi,
|
||||
worker_result_roots=worker_result_roots,
|
||||
profile=profile,
|
||||
)
|
||||
fusion = fuse_open_vocabulary_detections(
|
||||
detections,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
valid_fov_mask=valid_fov_mask,
|
||||
)
|
||||
selected = select_geometry_roi_detections(roi, fusion)
|
||||
understanding = understand_geometry_observation(
|
||||
roi.observation,
|
||||
detections=selected,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=detector_frame.envelope.timestamps.monotonic_ns,
|
||||
)
|
||||
understandings_by_observation[roi.observation.observation_id] = understanding
|
||||
totals["roi_count"] += 1
|
||||
totals["raw_detection_count"] += len(detections)
|
||||
totals["below_confidence_count"] += fusion.below_confidence_count
|
||||
totals["invalid_area_count"] += fusion.invalid_area_count
|
||||
totals["outside_valid_fov_count"] += fusion.outside_valid_fov_count
|
||||
totals["retained_detection_count"] += fusion.retained_detection_count
|
||||
totals["fused_proposal_count"] += len(fusion.proposals)
|
||||
totals["selected_cluster_detection_count"] += len(selected)
|
||||
totals["roi_with_selected_cluster_count"] += bool(selected)
|
||||
roi_documents.append(
|
||||
{
|
||||
"roi": roi.to_dict(),
|
||||
"detections": [_detection_document(item) for item in detections],
|
||||
"fused_proposals": [item.to_dict() for item in fusion.proposals],
|
||||
"selected_detection_ids": [item.detection_id for item in selected],
|
||||
"understanding": understanding.to_dict(),
|
||||
}
|
||||
)
|
||||
for observation in roi_frame.not_projected_observations:
|
||||
understandings_by_observation[observation.observation_id] = (
|
||||
understand_geometry_observation(
|
||||
observation,
|
||||
detections=(),
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=(
|
||||
detector_frame.envelope.timestamps.monotonic_ns
|
||||
),
|
||||
)
|
||||
)
|
||||
totals["not_projected_observation_count"] += 1
|
||||
ordered = tuple(
|
||||
understandings_by_observation[item.observation_id] for item in observations
|
||||
)
|
||||
if len(ordered) != len(observations):
|
||||
raise GeometrySemanticShadowReplayError("geometry obstacle accounting changed")
|
||||
for understanding in ordered:
|
||||
resolution_counts[understanding.semantic.resolution.value] += 1
|
||||
if (
|
||||
understanding.semantic.resolution is SemanticResolution.SELECTED
|
||||
and understanding.semantic.selected_class_id is not None
|
||||
):
|
||||
class_counts[understanding.semantic.selected_class_id] += 1
|
||||
totals["geometry_observation_count"] += len(observations)
|
||||
frame_document = {
|
||||
"schema_version": GEOMETRY_SEMANTIC_SHADOW_FRAME_SCHEMA,
|
||||
"frame_index": frame_index,
|
||||
"frame_id": detector_frame.envelope.frame_id,
|
||||
"geometry_observation_count": len(observations),
|
||||
"roi_count": len(roi_frame.rois),
|
||||
"not_projected_observation_count": len(
|
||||
roi_frame.not_projected_observations
|
||||
),
|
||||
"rois": roi_documents,
|
||||
"understandings": [item.to_dict() for item in ordered],
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
ledger.write(_canonical_json(frame_document) + b"\n")
|
||||
metrics: dict[str, object] = {
|
||||
"frames": {"requested": len(frames), "completed": len(frames)},
|
||||
"geometry": {
|
||||
"observation_count": totals["geometry_observation_count"],
|
||||
"roi_count": totals["roi_count"],
|
||||
"not_projected_observation_count": totals[
|
||||
"not_projected_observation_count"
|
||||
],
|
||||
},
|
||||
"semantic_inference": {
|
||||
"raw_detection_count": totals["raw_detection_count"],
|
||||
"below_confidence_count": totals["below_confidence_count"],
|
||||
"invalid_area_count": totals["invalid_area_count"],
|
||||
"outside_valid_fov_count": totals["outside_valid_fov_count"],
|
||||
"retained_detection_count": totals["retained_detection_count"],
|
||||
"fused_proposal_count": totals["fused_proposal_count"],
|
||||
"roi_with_selected_cluster_count": totals[
|
||||
"roi_with_selected_cluster_count"
|
||||
],
|
||||
"selected_cluster_detection_count": totals[
|
||||
"selected_cluster_detection_count"
|
||||
],
|
||||
},
|
||||
"semantics": {
|
||||
"resolution_counts": dict(sorted(resolution_counts.items())),
|
||||
"selected_class_counts": dict(sorted(class_counts.items())),
|
||||
},
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
completed = (
|
||||
totals["geometry_observation_count"]
|
||||
== totals["roi_count"] + totals["not_projected_observation_count"]
|
||||
and sum(resolution_counts.values()) == totals["geometry_observation_count"]
|
||||
)
|
||||
identity = {
|
||||
"schema_version": GEOMETRY_SEMANTIC_SHADOW_REPLAY_SCHEMA,
|
||||
"profile_id": profile.profile_id,
|
||||
"profile_sha256": _sha256(profile_path),
|
||||
"vocabulary_id": vocabulary.vocabulary_id,
|
||||
"vocabulary_sha256": _sha256(vocabulary_path),
|
||||
"detector_result_id": detector.result_id,
|
||||
"roi_package_id": _string(roi_manifest, "package_id"),
|
||||
"roi_package_sha256": _sha256(roi_root / "manifest.json"),
|
||||
"frame_indices": list(frames),
|
||||
"worker_execution": dict(worker_execution),
|
||||
"worker_artifacts": _worker_artifacts(worker_result_roots, profile, crop_names),
|
||||
"producer_sha256": {
|
||||
name: _sha256(repository / "src/k1link/perception" / name)
|
||||
for name in (
|
||||
"geometry_semantic_roi.py",
|
||||
"geometry_semantic_shadow_replay.py",
|
||||
"object_understanding.py",
|
||||
"open_vocabulary_semantics.py",
|
||||
)
|
||||
},
|
||||
"frames_sha256": _sha256(frames_path),
|
||||
"metrics": metrics,
|
||||
"completed": completed,
|
||||
"accepted": False,
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
identity_sha256 = hashlib.sha256(_canonical_json(identity)).hexdigest()
|
||||
result_id = f"{RESULT_PREFIX}{identity_sha256}"
|
||||
report = {
|
||||
"schema_version": GEOMETRY_SEMANTIC_SHADOW_REPLAY_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"created_at_utc": datetime.now(UTC).isoformat(timespec="milliseconds").replace(
|
||||
"+00:00", "Z"
|
||||
),
|
||||
"completed": completed,
|
||||
"accepted": False,
|
||||
"metrics": metrics,
|
||||
"decision": {
|
||||
"geometry_first_binding_completed": completed,
|
||||
"semantic_quality_accepted": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
"reason_codes": [
|
||||
"two-reviewer-independent-truth-unavailable",
|
||||
"open-vocabulary-geometry-roi-remains-experimental-shadow",
|
||||
"unknown-and-unresolved-objects-remain-route-around-obstacles",
|
||||
],
|
||||
},
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
manifest: dict[str, object] = {
|
||||
"schema_version": GEOMETRY_SEMANTIC_SHADOW_REPLAY_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"identity_sha256": identity_sha256,
|
||||
"identity": identity,
|
||||
"artifacts": {
|
||||
"frames.jsonl": _sha256(frames_path),
|
||||
"report.json": hashlib.sha256(_canonical_json(report) + b"\n").hexdigest(),
|
||||
},
|
||||
}
|
||||
(staging / "report.json").write_bytes(_canonical_json(report) + b"\n")
|
||||
(staging / "manifest.json").write_bytes(_canonical_json(manifest) + b"\n")
|
||||
destination = output / result_id
|
||||
if destination.exists():
|
||||
shutil.rmtree(staging)
|
||||
else:
|
||||
staging.rename(destination)
|
||||
except Exception:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
raise
|
||||
return GeometrySemanticShadowReplayResult(
|
||||
result_id=result_id,
|
||||
result_root=destination,
|
||||
completed=completed,
|
||||
accepted=False,
|
||||
metrics=metrics,
|
||||
report=report,
|
||||
manifest=manifest,
|
||||
)
|
||||
|
||||
|
||||
def read_geometry_semantic_shadow_replay(
|
||||
result_root: Path,
|
||||
) -> GeometrySemanticShadowReplayResult:
|
||||
"""Read and revalidate one immutable geometry-first semantic result."""
|
||||
|
||||
root = result_root.resolve(strict=True)
|
||||
manifest = _read_object(root / "manifest.json", "geometry semantic manifest")
|
||||
report = _read_object(root / "report.json", "geometry semantic report")
|
||||
identity = _object(manifest.get("identity"), "geometry semantic identity")
|
||||
identity_sha256 = hashlib.sha256(_canonical_json(identity)).hexdigest()
|
||||
result_id = f"{RESULT_PREFIX}{identity_sha256}"
|
||||
artifacts = _object(manifest.get("artifacts"), "geometry semantic artifacts")
|
||||
if (
|
||||
manifest.get("schema_version") != GEOMETRY_SEMANTIC_SHADOW_REPLAY_SCHEMA
|
||||
or manifest.get("identity_sha256") != identity_sha256
|
||||
or manifest.get("result_id") != result_id
|
||||
or root.name != result_id
|
||||
or report.get("schema_version") != GEOMETRY_SEMANTIC_SHADOW_REPLAY_SCHEMA
|
||||
or report.get("result_id") != result_id
|
||||
or artifacts
|
||||
!= {
|
||||
"frames.jsonl": _sha256(root / "frames.jsonl"),
|
||||
"report.json": _sha256(root / "report.json"),
|
||||
}
|
||||
):
|
||||
raise GeometrySemanticShadowReplayError("geometry semantic result identity changed")
|
||||
metrics = _object(report.get("metrics"), "geometry semantic metrics")
|
||||
completed = report.get("completed")
|
||||
accepted = report.get("accepted")
|
||||
if not isinstance(completed, bool) or not isinstance(accepted, bool):
|
||||
raise GeometrySemanticShadowReplayError("geometry semantic result state changed")
|
||||
if identity.get("metrics") != metrics or identity.get("completed") != completed:
|
||||
raise GeometrySemanticShadowReplayError("geometry semantic result accounting changed")
|
||||
return GeometrySemanticShadowReplayResult(
|
||||
result_id=result_id,
|
||||
result_root=root,
|
||||
completed=completed,
|
||||
accepted=accepted,
|
||||
metrics=metrics,
|
||||
report=report,
|
||||
manifest=manifest,
|
||||
)
|
||||
|
||||
|
||||
def _roi_detections(
|
||||
roi: GeometrySemanticRoi,
|
||||
*,
|
||||
worker_result_roots: Mapping[str, Path],
|
||||
profile: object,
|
||||
) -> tuple[OpenVocabularyDetection, ...]:
|
||||
from .open_vocabulary_semantics import OpenVocabularySemanticProfile
|
||||
|
||||
if not isinstance(profile, OpenVocabularySemanticProfile):
|
||||
raise GeometrySemanticShadowReplayError("semantic profile is incompatible")
|
||||
width = int(roi.crop_region.x_max - roi.crop_region.x_min)
|
||||
height = int(roi.crop_region.y_max - roi.crop_region.y_min)
|
||||
detections: list[OpenVocabularyDetection] = []
|
||||
for group in profile.prompt_groups:
|
||||
labels = (
|
||||
worker_result_roots[group.prompt_set_id].resolve(strict=True)
|
||||
/ "labels"
|
||||
/ roi.crop_name.replace(".png", ".txt")
|
||||
)
|
||||
detections.extend(
|
||||
parse_tao_grounding_dino_labels(
|
||||
labels,
|
||||
source_id=profile.source_id,
|
||||
frame_id=roi.observation.frame_id,
|
||||
prompt_set_id=group.prompt_set_id,
|
||||
profile=profile,
|
||||
image_width=width,
|
||||
image_height=height,
|
||||
offset_x=roi.crop_region.x_min,
|
||||
offset_y=roi.crop_region.y_min,
|
||||
detection_scope_id=roi.roi_id,
|
||||
)
|
||||
)
|
||||
return tuple(detections)
|
||||
|
||||
|
||||
def _validate_worker_results(
|
||||
roots: Mapping[str, Path],
|
||||
*,
|
||||
profile: object,
|
||||
crop_names: tuple[str, ...],
|
||||
) -> None:
|
||||
from .open_vocabulary_semantics import OpenVocabularySemanticProfile
|
||||
|
||||
if not isinstance(profile, OpenVocabularySemanticProfile):
|
||||
raise GeometrySemanticShadowReplayError("semantic profile is incompatible")
|
||||
if set(roots) != {item.prompt_set_id for item in profile.prompt_groups}:
|
||||
raise GeometrySemanticShadowReplayError("Worker prompt roots changed")
|
||||
expected = {item.replace(".png", ".txt") for item in crop_names}
|
||||
for root in roots.values():
|
||||
resolved = root.resolve(strict=True)
|
||||
actual = {item.name for item in (resolved / "labels").glob("*.txt")}
|
||||
if actual != expected:
|
||||
raise GeometrySemanticShadowReplayError("Worker label coverage changed")
|
||||
status = (resolved / "status.json").read_text("utf-8")
|
||||
if '"status": "SUCCESS"' not in status:
|
||||
raise GeometrySemanticShadowReplayError("Worker semantic run did not succeed")
|
||||
|
||||
|
||||
def _worker_artifacts(
|
||||
roots: Mapping[str, Path],
|
||||
profile: object,
|
||||
crop_names: tuple[str, ...],
|
||||
) -> dict[str, object]:
|
||||
from .open_vocabulary_semantics import OpenVocabularySemanticProfile
|
||||
|
||||
if not isinstance(profile, OpenVocabularySemanticProfile):
|
||||
raise GeometrySemanticShadowReplayError("semantic profile is incompatible")
|
||||
artifacts: dict[str, object] = {}
|
||||
for group in profile.prompt_groups:
|
||||
root = roots[group.prompt_set_id].resolve(strict=True)
|
||||
labels = [
|
||||
{
|
||||
"name": crop_name.replace(".png", ".txt"),
|
||||
"sha256": _sha256(root / "labels" / crop_name.replace(".png", ".txt")),
|
||||
}
|
||||
for crop_name in crop_names
|
||||
]
|
||||
artifacts[group.prompt_set_id] = {
|
||||
"status_sha256": _sha256(root / "status.json"),
|
||||
"experiment_sha256": _sha256(root / "experiment.yaml"),
|
||||
"labels": labels,
|
||||
}
|
||||
return artifacts
|
||||
|
||||
|
||||
def _validate_roi_manifest(
|
||||
manifest: dict[str, object],
|
||||
*,
|
||||
frames: tuple[int, ...],
|
||||
) -> dict[str, object]:
|
||||
if manifest.get("schema_version") != GEOMETRY_SEMANTIC_ROI_PACKAGE_SCHEMA:
|
||||
raise GeometrySemanticShadowReplayError("ROI package schema changed")
|
||||
identity = _object(manifest.get("identity"), "ROI identity")
|
||||
if identity.get("frame_indices") != list(frames):
|
||||
raise GeometrySemanticShadowReplayError("ROI frame selection changed")
|
||||
if identity.get("roi_count") != 58 or identity.get("geometry_observation_count") != 73:
|
||||
raise GeometrySemanticShadowReplayError("bounded ROI package accounting changed")
|
||||
digest = hashlib.sha256(_canonical_json(identity)).hexdigest()
|
||||
if manifest.get("identity_sha256") != digest or manifest.get("package_id") != (
|
||||
f"m48s-geometry-semantic-rois-{digest}"
|
||||
):
|
||||
raise GeometrySemanticShadowReplayError("ROI package identity changed")
|
||||
return identity
|
||||
|
||||
|
||||
def _roi_manifest_frame(identity: dict[str, object], frame_index: int) -> dict[str, object]:
|
||||
matches = [
|
||||
_object(item, "ROI frame")
|
||||
for item in _array(identity, "frames")
|
||||
if _object(item, "ROI frame").get("frame_index") == frame_index
|
||||
]
|
||||
if len(matches) != 1:
|
||||
raise GeometrySemanticShadowReplayError("ROI frame manifest is ambiguous")
|
||||
return matches[0]
|
||||
|
||||
|
||||
def _roi_without_materialization(value: dict[str, object]) -> dict[str, object]:
|
||||
return {
|
||||
key: item
|
||||
for key, item in value.items()
|
||||
if key not in {"crop_sha256", "crop_width", "crop_height"}
|
||||
}
|
||||
|
||||
|
||||
def _validate_frame_indices(value: tuple[int, ...]) -> tuple[int, ...]:
|
||||
if not value or tuple(sorted(set(value))) != value or any(item < 0 for item in value):
|
||||
raise GeometrySemanticShadowReplayError("semantic frame selection is invalid")
|
||||
return value
|
||||
|
||||
|
||||
def _detection_document(value: OpenVocabularyDetection) -> dict[str, object]:
|
||||
return {
|
||||
"detection_id": value.detection_id,
|
||||
"source_id": value.source_id,
|
||||
"frame_id": value.frame_id,
|
||||
"prompt_set_id": value.prompt_set_id,
|
||||
"raw_label": value.raw_label,
|
||||
"confidence": value.confidence,
|
||||
"region": value.region.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def _read_object(path: Path, label: str) -> dict[str, object]:
|
||||
try:
|
||||
value = json.loads(path.resolve(strict=True).read_text("utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise GeometrySemanticShadowReplayError(f"{label} cannot be read") from exc
|
||||
return _object(value, label)
|
||||
|
||||
|
||||
def _object(value: object, label: str) -> dict[str, object]:
|
||||
if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
|
||||
raise GeometrySemanticShadowReplayError(f"{label} must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _array(value: dict[str, object], key: str) -> list[object]:
|
||||
item = value.get(key)
|
||||
if not isinstance(item, list):
|
||||
raise GeometrySemanticShadowReplayError(f"{key} must be an array")
|
||||
return item
|
||||
|
||||
|
||||
def _string(value: dict[str, object], key: str) -> str:
|
||||
item = value.get(key)
|
||||
if not isinstance(item, str) or not item:
|
||||
raise GeometrySemanticShadowReplayError(f"{key} must be a nonempty string")
|
||||
return item
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.resolve(strict=True).open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _false_authority() -> dict[str, bool]:
|
||||
return {
|
||||
"ground_truth": False,
|
||||
"independent_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GeometrySemanticShadowReplayError",
|
||||
"GeometrySemanticShadowReplayResult",
|
||||
"build_geometry_semantic_shadow_replay",
|
||||
"read_geometry_semantic_shadow_replay",
|
||||
]
|
||||
@@ -110,6 +110,10 @@ _RollingItem = _Temporal | _StopSignal
|
||||
_ThreatItem = _Temporal | _Rolled | _StopSignal
|
||||
_QueueItem = SourcePacket | _Detected | _Associated | _Temporal | _Rolled | _StopSignal
|
||||
_QueueItemT = TypeVar("_QueueItemT", bound=_QueueItem)
|
||||
DeliveryEvidenceObserver = Callable[
|
||||
[DeliveredFrame, SourcePacket, tuple[ObjectProposal2D, ...], frozenset[str], int],
|
||||
None,
|
||||
]
|
||||
|
||||
|
||||
class ReferencePerceptionGraphV1:
|
||||
@@ -127,6 +131,8 @@ class ReferencePerceptionGraphV1:
|
||||
threat: ThreatProvider,
|
||||
telemetry_identity: PipelineTelemetryIdentity | None = None,
|
||||
telemetry_sink: PipelineTelemetrySink | None = None,
|
||||
delivery_observer: Callable[[DeliveredFrame, int], None] | None = None,
|
||||
delivery_evidence_observer: DeliveryEvidenceObserver | None = None,
|
||||
clock_ns: Callable[[], int] = time.monotonic_ns,
|
||||
) -> None:
|
||||
if config.graph_id != REFERENCE_GRAPH_ID:
|
||||
@@ -145,6 +151,8 @@ class ReferencePerceptionGraphV1:
|
||||
run_mode=GraphRunMode.SOURCE_PACED_LATEST_WINS,
|
||||
telemetry_identity=telemetry_identity,
|
||||
telemetry_sink=telemetry_sink,
|
||||
delivery_observer=delivery_observer,
|
||||
delivery_evidence_observer=delivery_evidence_observer,
|
||||
clock_ns=clock_ns,
|
||||
)
|
||||
|
||||
@@ -162,6 +170,8 @@ class ReferencePerceptionGraphV1:
|
||||
run_mode: GraphRunMode,
|
||||
telemetry_identity: PipelineTelemetryIdentity | None,
|
||||
telemetry_sink: PipelineTelemetrySink | None,
|
||||
delivery_observer: Callable[[DeliveredFrame, int], None] | None,
|
||||
delivery_evidence_observer: DeliveryEvidenceObserver | None,
|
||||
clock_ns: Callable[[], int],
|
||||
) -> None:
|
||||
if (telemetry_identity is None) is not (telemetry_sink is None):
|
||||
@@ -177,6 +187,8 @@ class ReferencePerceptionGraphV1:
|
||||
self.run_mode = run_mode
|
||||
self.telemetry_identity = telemetry_identity
|
||||
self.telemetry_sink = telemetry_sink
|
||||
self.delivery_observer = delivery_observer
|
||||
self.delivery_evidence_observer = delivery_evidence_observer
|
||||
self._clock_ns = clock_ns
|
||||
self._state = GraphState.CREATED
|
||||
self._state_lock = Lock()
|
||||
@@ -510,6 +522,23 @@ class ReferencePerceptionGraphV1:
|
||||
obstacle_map=obstacle_map,
|
||||
threats=threats,
|
||||
)
|
||||
completed_ns = self._now()
|
||||
with self._result_lock:
|
||||
admitted_at_ns = self._admitted_at_ns[item.packet.envelope.sequence]
|
||||
completion_age_ns = item.packet.envelope.source_age_ns + max(
|
||||
0,
|
||||
completed_ns - admitted_at_ns,
|
||||
)
|
||||
if self.delivery_observer is not None:
|
||||
self.delivery_observer(delivery, completion_age_ns)
|
||||
if self.delivery_evidence_observer is not None:
|
||||
self.delivery_evidence_observer(
|
||||
delivery,
|
||||
item.packet,
|
||||
item.proposals,
|
||||
item.associated_proposal_ids,
|
||||
completion_age_ns,
|
||||
)
|
||||
with self._result_lock:
|
||||
self._deliveries.append(delivery)
|
||||
self._terminal(
|
||||
@@ -845,6 +874,8 @@ class ReferencePerceptionGraphV2(ReferencePerceptionGraphV1):
|
||||
run_mode: GraphRunMode,
|
||||
telemetry_identity: PipelineTelemetryIdentity | None = None,
|
||||
telemetry_sink: PipelineTelemetrySink | None = None,
|
||||
delivery_observer: Callable[[DeliveredFrame, int], None] | None = None,
|
||||
delivery_evidence_observer: DeliveryEvidenceObserver | None = None,
|
||||
clock_ns: Callable[[], int] = time.monotonic_ns,
|
||||
) -> None:
|
||||
if config.graph_id != REFERENCE_GRAPH_ID_V2:
|
||||
@@ -865,6 +896,8 @@ class ReferencePerceptionGraphV2(ReferencePerceptionGraphV1):
|
||||
run_mode=run_mode,
|
||||
telemetry_identity=telemetry_identity,
|
||||
telemetry_sink=telemetry_sink,
|
||||
delivery_observer=delivery_observer,
|
||||
delivery_evidence_observer=delivery_evidence_observer,
|
||||
clock_ns=clock_ns,
|
||||
)
|
||||
|
||||
@@ -903,6 +936,7 @@ __all__ = [
|
||||
"REFERENCE_GRAPH_ID_V2",
|
||||
"TERMINAL_OUTCOME_SCHEMA",
|
||||
"DeliveredFrame",
|
||||
"DeliveryEvidenceObserver",
|
||||
"GraphExecutionError",
|
||||
"GraphRunResult",
|
||||
"GraphRunResultV2",
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Class-aware advisory projection over one delivered reference-graph frame."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import Final
|
||||
|
||||
from .contracts import FalseAuthority, MotionState, ThreatDecision
|
||||
from .graph_contracts import DeliveredFrame
|
||||
from .object_understanding import AdvisoryResponse
|
||||
|
||||
M48S_ADVISORY_SCHEMA: Final = "missioncore.m48s-semantic-advisory/v0"
|
||||
M48S_ADVISORY_POLICY_ID: Final = "m48s-behavior-relevant-object-advisory/v0"
|
||||
_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$")
|
||||
|
||||
|
||||
class AdvisoryFamily(StrEnum):
|
||||
GENERIC_OBSTACLE = "generic-obstacle"
|
||||
PERSON = "person"
|
||||
ANIMAL = "animal"
|
||||
LIGHT_ROAD_USER = "light-road-user"
|
||||
VEHICLE = "vehicle"
|
||||
|
||||
|
||||
class M48sAdvisoryError(ValueError):
|
||||
"""A semantic advisory escaped its bounded shadow-only policy."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class M48sSemanticAdvisory:
|
||||
component_id: str
|
||||
semantic_hint: str | None
|
||||
family: AdvisoryFamily
|
||||
motion: MotionState
|
||||
threat_decision: ThreatDecision
|
||||
responses: tuple[AdvisoryResponse, ...]
|
||||
reason_codes: tuple[str, ...]
|
||||
policy_id: str = M48S_ADVISORY_POLICY_ID
|
||||
authority: FalseAuthority = FalseAuthority()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if _IDENTIFIER.fullmatch(self.component_id) is None:
|
||||
raise M48sAdvisoryError("advisory component id is invalid")
|
||||
if self.semantic_hint is not None and _IDENTIFIER.fullmatch(self.semantic_hint) is None:
|
||||
raise M48sAdvisoryError("advisory semantic hint is invalid")
|
||||
if self.policy_id != M48S_ADVISORY_POLICY_ID:
|
||||
raise M48sAdvisoryError("advisory policy identity changed")
|
||||
if not self.responses or len(set(self.responses)) != len(self.responses):
|
||||
raise M48sAdvisoryError("advisory responses must be unique and nonempty")
|
||||
if not self.reason_codes or len(set(self.reason_codes)) != len(self.reason_codes):
|
||||
raise M48sAdvisoryError("advisory reasons must be unique and nonempty")
|
||||
if self.threat_decision is ThreatDecision.THREAT and (
|
||||
AdvisoryResponse.STOP not in self.responses
|
||||
):
|
||||
raise M48sAdvisoryError("replay threat must retain a stop advisory")
|
||||
if self.family is AdvisoryFamily.GENERIC_OBSTACLE and (
|
||||
AdvisoryResponse.ROUTE_AROUND not in self.responses
|
||||
and AdvisoryResponse.STOP not in self.responses
|
||||
):
|
||||
raise M48sAdvisoryError("generic obstacles must remain route-around advisories")
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"schema_version": M48S_ADVISORY_SCHEMA,
|
||||
"policy_id": self.policy_id,
|
||||
"component_id": self.component_id,
|
||||
"semantic_hint": self.semantic_hint,
|
||||
"family": self.family.value,
|
||||
"motion": self.motion.value,
|
||||
"threat_decision": self.threat_decision.value,
|
||||
"responses": [item.value for item in self.responses],
|
||||
"reason_codes": list(self.reason_codes),
|
||||
"authority": self.authority.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def project_m48s_advisories(
|
||||
delivery: DeliveredFrame,
|
||||
) -> tuple[M48sSemanticAdvisory, ...]:
|
||||
"""Project class-specific caution without changing occupancy or graph threats."""
|
||||
|
||||
threat_by_component = {item.component_id: item.decision for item in delivery.threats}
|
||||
advisories = [
|
||||
_project(
|
||||
component_id=obstacle.component_id,
|
||||
semantic_hint=obstacle.semantic_hint,
|
||||
motion=obstacle.motion,
|
||||
threat_decision=threat_by_component[obstacle.component_id],
|
||||
)
|
||||
for obstacle in (*delivery.obstacle_map.occupied, *delivery.obstacle_map.unknown)
|
||||
]
|
||||
advisories.extend(
|
||||
_project(
|
||||
component_id=proposal.proposal_id,
|
||||
semantic_hint=proposal.semantic_hint,
|
||||
motion=MotionState.UNKNOWN,
|
||||
threat_decision=threat_by_component[proposal.proposal_id],
|
||||
)
|
||||
for proposal in delivery.obstacle_map.camera_uncertainty
|
||||
)
|
||||
return tuple(advisories)
|
||||
|
||||
|
||||
def advisory_policy_matrix() -> dict[AdvisoryFamily, tuple[AdvisoryResponse, ...]]:
|
||||
"""Expose the fixed class-family policy for executable contract checks."""
|
||||
|
||||
return {
|
||||
AdvisoryFamily.GENERIC_OBSTACLE: (AdvisoryResponse.ROUTE_AROUND,),
|
||||
AdvisoryFamily.PERSON: (
|
||||
AdvisoryResponse.YIELD,
|
||||
AdvisoryResponse.REDUCE_SPEED,
|
||||
),
|
||||
AdvisoryFamily.ANIMAL: (
|
||||
AdvisoryResponse.REDUCE_SPEED,
|
||||
AdvisoryResponse.STOP,
|
||||
),
|
||||
AdvisoryFamily.LIGHT_ROAD_USER: (
|
||||
AdvisoryResponse.YIELD,
|
||||
AdvisoryResponse.REDUCE_SPEED,
|
||||
AdvisoryResponse.MONITOR,
|
||||
),
|
||||
AdvisoryFamily.VEHICLE: (
|
||||
AdvisoryResponse.MONITOR,
|
||||
AdvisoryResponse.YIELD,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _project(
|
||||
*,
|
||||
component_id: str,
|
||||
semantic_hint: str | None,
|
||||
motion: MotionState,
|
||||
threat_decision: ThreatDecision,
|
||||
) -> M48sSemanticAdvisory:
|
||||
family = _family(semantic_hint)
|
||||
responses = list(advisory_policy_matrix()[family])
|
||||
reasons = [f"family-{family.value}"]
|
||||
if motion is MotionState.UNKNOWN:
|
||||
reasons.append("unknown-motion-conservative")
|
||||
elif motion is MotionState.MOVING:
|
||||
reasons.append("observed-moving")
|
||||
if AdvisoryResponse.REDUCE_SPEED not in responses:
|
||||
responses.append(AdvisoryResponse.REDUCE_SPEED)
|
||||
else:
|
||||
reasons.append("observed-stationary-not-permanent")
|
||||
if threat_decision is ThreatDecision.THREAT:
|
||||
reasons.append("reference-graph-replay-threat")
|
||||
responses.insert(0, AdvisoryResponse.STOP)
|
||||
elif threat_decision is ThreatDecision.UNKNOWN:
|
||||
reasons.append("reference-graph-threat-unknown")
|
||||
else:
|
||||
reasons.append("reference-graph-threat-clear-at-observation")
|
||||
return M48sSemanticAdvisory(
|
||||
component_id=component_id,
|
||||
semantic_hint=semantic_hint,
|
||||
family=family,
|
||||
motion=motion,
|
||||
threat_decision=threat_decision,
|
||||
responses=tuple(dict.fromkeys(responses)),
|
||||
reason_codes=tuple(reasons),
|
||||
)
|
||||
|
||||
|
||||
def _family(semantic_hint: str | None) -> AdvisoryFamily:
|
||||
if semantic_hint == "person":
|
||||
return AdvisoryFamily.PERSON
|
||||
if semantic_hint in {
|
||||
"bird",
|
||||
"cat",
|
||||
"dog",
|
||||
"horse",
|
||||
"sheep",
|
||||
"cow",
|
||||
"elephant",
|
||||
"bear",
|
||||
"zebra",
|
||||
"giraffe",
|
||||
}:
|
||||
return AdvisoryFamily.ANIMAL
|
||||
if semantic_hint in {"bicycle", "motorcycle", "skateboard"}:
|
||||
return AdvisoryFamily.LIGHT_ROAD_USER
|
||||
if semantic_hint in {"car", "bus", "truck"}:
|
||||
return AdvisoryFamily.VEHICLE
|
||||
return AdvisoryFamily.GENERIC_OBSTACLE
|
||||
|
||||
|
||||
__all__ = [
|
||||
"M48S_ADVISORY_POLICY_ID",
|
||||
"M48S_ADVISORY_SCHEMA",
|
||||
"AdvisoryFamily",
|
||||
"M48sAdvisoryError",
|
||||
"M48sSemanticAdvisory",
|
||||
"advisory_policy_matrix",
|
||||
"project_m48s_advisories",
|
||||
]
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Shadow assembly for RF-DETR inside the source-neutral reference graph."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from .baseline import load_m4_baseline
|
||||
from .detector import RF_DETR_SHADOW_PROVIDER_ID, RfDetrShadowDetectorProvider
|
||||
from .geometry import (
|
||||
Ravnoves00GeometryAssociationProvider,
|
||||
RecordedGeometryStore,
|
||||
load_geometry_profile,
|
||||
)
|
||||
from .graph import DeliveryEvidenceObserver, ReferencePerceptionGraphV2
|
||||
from .graph_contracts import DeliveredFrame, GraphRunMode
|
||||
from .motion import ClassIndependentMotionEstimator
|
||||
from .providers import (
|
||||
ProviderRole,
|
||||
ReferencePerceptionGraphConfigV2,
|
||||
SourcePacket,
|
||||
SourceProvider,
|
||||
)
|
||||
from .recorded_source import (
|
||||
DecodedRecordedSource,
|
||||
PyAvRecordedImageDecoder,
|
||||
RecordedRavnoves00Source,
|
||||
ReplayPacing,
|
||||
)
|
||||
from .reference_graph_runtime import ReferenceGraphRuntimePaths
|
||||
from .rf_detr_object_detector import (
|
||||
RF_DETR_ENGINE_SHA256,
|
||||
RF_DETR_MODEL_ID,
|
||||
RF_DETR_MODEL_VERSION,
|
||||
TritonRfDetrHttpInferenceBackend,
|
||||
)
|
||||
from .rolling_map import RollingLocalObstacleMapProvider, load_rolling_map_profile
|
||||
from .temporal import BoundedSpatialTemporalProvider, load_temporal_motion_profile
|
||||
from .threat import (
|
||||
DualEvidenceReplayThreatProvider,
|
||||
RecordedReplayBodyFrameResolver,
|
||||
load_replay_threat_profile,
|
||||
)
|
||||
from .yolox_object_detector import load_valid_fov_mask
|
||||
|
||||
|
||||
class M48sReferenceGraphRuntimeError(RuntimeError):
|
||||
"""The RF-DETR graph shadow cannot be assembled from its pinned inputs."""
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class M48sReferenceGraphRuntime:
|
||||
"""Own one RF-DETR shadow graph and its persistent inference transport."""
|
||||
|
||||
graph: ReferencePerceptionGraphV2
|
||||
inference_backend: TritonRfDetrHttpInferenceBackend
|
||||
|
||||
def close(self) -> None:
|
||||
self.inference_backend.close()
|
||||
|
||||
def __enter__(self) -> M48sReferenceGraphRuntime:
|
||||
return self
|
||||
|
||||
def __exit__(self, *args: object) -> None:
|
||||
self.close()
|
||||
|
||||
|
||||
def build_m48s_reference_graph_runtime(
|
||||
*,
|
||||
paths: ReferenceGraphRuntimePaths,
|
||||
detector_profile: Path,
|
||||
triton_origin: str,
|
||||
run_mode: GraphRunMode,
|
||||
delivery_observer: Callable[[DeliveredFrame, int], None] | None = None,
|
||||
delivery_evidence_observer: DeliveryEvidenceObserver | None = None,
|
||||
maximum_frames: int | None = None,
|
||||
) -> M48sReferenceGraphRuntime:
|
||||
"""Instantiate the complete graph with only its detector pin replaced."""
|
||||
|
||||
config = _load_graph_config(paths.graph_config)
|
||||
pinned_files = {
|
||||
ProviderRole.SOURCE: paths.baseline_profile,
|
||||
ProviderRole.DETECTOR: detector_profile,
|
||||
ProviderRole.GEOMETRY: paths.geometry_profile,
|
||||
ProviderRole.TEMPORAL: paths.temporal_motion_profile,
|
||||
ProviderRole.MOTION: paths.temporal_motion_profile,
|
||||
ProviderRole.ROLLING: paths.rolling_map_profile,
|
||||
ProviderRole.THREAT: paths.threat_profile,
|
||||
}
|
||||
_validate_provider_digests(config, pinned_files)
|
||||
_validate_detector_profile(detector_profile)
|
||||
|
||||
load_m4_baseline(paths.baseline_profile)
|
||||
geometry_profile = load_geometry_profile(paths.geometry_profile)
|
||||
temporal_motion_profile = load_temporal_motion_profile(paths.temporal_motion_profile)
|
||||
rolling_map_profile = load_rolling_map_profile(paths.rolling_map_profile)
|
||||
threat_profile = load_replay_threat_profile(paths.threat_profile)
|
||||
|
||||
if maximum_frames is not None and maximum_frames < 1:
|
||||
raise M48sReferenceGraphRuntimeError("maximum frame count must be positive")
|
||||
source: SourceProvider = DecodedRecordedSource(
|
||||
source=RecordedRavnoves00Source(
|
||||
camera_index_path=paths.camera_index,
|
||||
source_pack_path=paths.source_pack,
|
||||
pacing=(
|
||||
ReplayPacing.ONE_X
|
||||
if run_mode is GraphRunMode.SOURCE_PACED_LATEST_WINS
|
||||
else ReplayPacing.UNCAPPED
|
||||
),
|
||||
),
|
||||
decoder=PyAvRecordedImageDecoder(paths.video),
|
||||
)
|
||||
if maximum_frames is not None:
|
||||
source = _LimitedSource(source, maximum_frames)
|
||||
backend = TritonRfDetrHttpInferenceBackend(triton_origin)
|
||||
try:
|
||||
store = RecordedGeometryStore(
|
||||
source_pack_path=paths.source_pack,
|
||||
local_surface_path=paths.local_surface,
|
||||
profile=geometry_profile,
|
||||
)
|
||||
body_frame_resolver = RecordedReplayBodyFrameResolver(
|
||||
store,
|
||||
profile=threat_profile.body_frame,
|
||||
)
|
||||
graph = ReferencePerceptionGraphV2(
|
||||
config=config,
|
||||
source=source,
|
||||
detector=RfDetrShadowDetectorProvider(
|
||||
mask=load_valid_fov_mask(paths.valid_fov_mask),
|
||||
backend=backend,
|
||||
),
|
||||
geometry=Ravnoves00GeometryAssociationProvider(store=store),
|
||||
temporal=BoundedSpatialTemporalProvider(
|
||||
point_resolver=store,
|
||||
profile=temporal_motion_profile,
|
||||
),
|
||||
motion=ClassIndependentMotionEstimator(profile=temporal_motion_profile),
|
||||
rolling=RollingLocalObstacleMapProvider(
|
||||
pose_resolver=store,
|
||||
profile=rolling_map_profile,
|
||||
),
|
||||
threat=DualEvidenceReplayThreatProvider(
|
||||
body_frame_resolver=body_frame_resolver,
|
||||
profile=threat_profile,
|
||||
),
|
||||
run_mode=run_mode,
|
||||
delivery_observer=delivery_observer,
|
||||
delivery_evidence_observer=delivery_evidence_observer,
|
||||
)
|
||||
except Exception:
|
||||
backend.close()
|
||||
raise
|
||||
return M48sReferenceGraphRuntime(graph=graph, inference_backend=backend)
|
||||
|
||||
|
||||
class _LimitedSource:
|
||||
"""Bound a pilot without changing source or graph provider identity."""
|
||||
|
||||
def __init__(self, source: SourceProvider, maximum_frames: int) -> None:
|
||||
self.source = source
|
||||
self.maximum_frames = maximum_frames
|
||||
self.provider_id = source.provider_id
|
||||
|
||||
def packets(self, stop_event: Event) -> Iterator[SourcePacket]:
|
||||
packets = self.source.packets(stop_event)
|
||||
for _index in range(self.maximum_frames):
|
||||
try:
|
||||
packet = next(packets)
|
||||
except StopIteration:
|
||||
return
|
||||
yield packet
|
||||
|
||||
|
||||
def _load_graph_config(path: Path) -> ReferencePerceptionGraphConfigV2:
|
||||
try:
|
||||
document = json.loads(path.resolve(strict=True).read_text("utf-8"))
|
||||
return ReferencePerceptionGraphConfigV2.from_dict(document)
|
||||
except (OSError, json.JSONDecodeError, ValueError) as exc:
|
||||
raise M48sReferenceGraphRuntimeError("RF-DETR graph config is invalid") from exc
|
||||
|
||||
|
||||
def _validate_provider_digests(
|
||||
config: ReferencePerceptionGraphConfigV2,
|
||||
pinned_files: dict[ProviderRole, Path],
|
||||
) -> None:
|
||||
pins = {pin.role: pin for pin in config.providers}
|
||||
if set(pins) != set(pinned_files):
|
||||
raise M48sReferenceGraphRuntimeError("RF-DETR graph provider pins are incomplete")
|
||||
for role, path in pinned_files.items():
|
||||
if _sha256_file(path) != pins[role].sha256:
|
||||
raise M48sReferenceGraphRuntimeError(
|
||||
f"{role.value} provider profile digest changed"
|
||||
)
|
||||
|
||||
|
||||
def _validate_detector_profile(path: Path) -> None:
|
||||
try:
|
||||
document = json.loads(path.resolve(strict=True).read_text("utf-8"))
|
||||
model = document["model"]
|
||||
status = document["status"]
|
||||
authority = document["authority"]
|
||||
except (OSError, KeyError, TypeError, json.JSONDecodeError) as exc:
|
||||
raise M48sReferenceGraphRuntimeError("RF-DETR profile is incomplete") from exc
|
||||
if (
|
||||
document.get("schema_version")
|
||||
!= "missioncore.rf-detr-risk-shadow-profile/v0"
|
||||
or document.get("provider_id") != RF_DETR_SHADOW_PROVIDER_ID
|
||||
or model.get("model_id") != RF_DETR_MODEL_ID
|
||||
or model.get("model_version") != RF_DETR_MODEL_VERSION
|
||||
or model.get("worker_006_rtx4090_tensorrt_11_engine_sha256")
|
||||
!= RF_DETR_ENGINE_SHA256
|
||||
or status.get("detector_load_gate_passed") is not True
|
||||
or status.get("production_accepted") is not False
|
||||
or any(
|
||||
authority.get(key) is not False
|
||||
for key in (
|
||||
"candidate_accepted",
|
||||
"commands_enabled",
|
||||
"actuation_allowed",
|
||||
"navigation_or_safety_accepted",
|
||||
)
|
||||
)
|
||||
):
|
||||
raise M48sReferenceGraphRuntimeError("RF-DETR shadow profile identity changed")
|
||||
|
||||
|
||||
def _sha256_file(path: Path) -> str:
|
||||
try:
|
||||
resolved = path.resolve(strict=True)
|
||||
except OSError as exc:
|
||||
raise M48sReferenceGraphRuntimeError("pinned RF-DETR graph input is missing") from exc
|
||||
if resolved.is_symlink() or not resolved.is_file():
|
||||
raise M48sReferenceGraphRuntimeError(
|
||||
"pinned RF-DETR graph input must be a regular file"
|
||||
)
|
||||
digest = hashlib.sha256()
|
||||
with resolved.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"M48sReferenceGraphRuntime",
|
||||
"M48sReferenceGraphRuntimeError",
|
||||
"build_m48s_reference_graph_runtime",
|
||||
]
|
||||
@@ -0,0 +1,426 @@
|
||||
"""Bounded camera, LiDAR, and world-state projection of sealed M4.8S replay evidence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import math
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from itertools import pairwise
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from typing import Final
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .geometry import RecordedGeometryStore
|
||||
from .geometry_math import project_map_points_kb4
|
||||
from .recorded_source import RECORDED_REPRESENTATION_ID
|
||||
from .spatial_evidence import project_metric_obstacles_to_body, sample_points_in_body_frame
|
||||
from .threat import (
|
||||
DEFAULT_REPLAY_THREAT_PROFILE_PATH,
|
||||
RecordedReplayBodyFrameResolver,
|
||||
load_replay_threat_profile,
|
||||
)
|
||||
from .threat_timeline import (
|
||||
RECORDED_LOCAL_SURFACE_POINT_LIMIT,
|
||||
RECORDED_LOCAL_SURFACE_RADIUS_M,
|
||||
RECORDED_LOCAL_SURFACE_VOXEL_SIZE_M,
|
||||
RECORDED_LOCAL_SURFACE_WINDOW_SECONDS,
|
||||
RECORDED_SPATIAL_CHUNK_SCHEMA,
|
||||
RECORDED_SPATIAL_FRAME_SCHEMA,
|
||||
RECORDED_SPATIAL_MAX_CHUNK_FRAMES,
|
||||
RECORDED_SPATIAL_POINT_LIMIT,
|
||||
RECORDED_SPATIAL_TIMELINE_SCHEMA,
|
||||
)
|
||||
|
||||
FRAME_EVIDENCE_SCHEMA: Final = "missioncore.m48s-reference-graph-frame-evidence/v0"
|
||||
EXPECTED_FRAME_COUNT: Final = 4_489
|
||||
|
||||
|
||||
class M48sReplayTimelineError(RuntimeError):
|
||||
"""The sealed M4.8S evidence cannot produce an exact bounded timeline."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _LedgerIndex:
|
||||
offsets_by_sequence: dict[int, int]
|
||||
|
||||
|
||||
class M48sReplayTimeline:
|
||||
"""Read source-indexed chunks while preserving latest-wins world-state gaps."""
|
||||
|
||||
def __init__(self, *, repository_root: Path, result_root: Path, result_id: str) -> None:
|
||||
self.repository_root = repository_root.resolve(strict=True)
|
||||
self.result_root = result_root.resolve(strict=True)
|
||||
self.result_id = result_id
|
||||
self.frames_path = (
|
||||
self.result_root / "reference-graph-replay-frames.jsonl"
|
||||
).resolve(strict=True)
|
||||
self.worker_path = (
|
||||
self.result_root / "reference-graph-replay-worker-result.json"
|
||||
).resolve(strict=True)
|
||||
if (
|
||||
self.frames_path.parent != self.result_root
|
||||
or self.worker_path.parent != self.result_root
|
||||
or self.frames_path.is_symlink()
|
||||
or self.worker_path.is_symlink()
|
||||
):
|
||||
raise M48sReplayTimelineError("M4.8S replay artifacts are invalid")
|
||||
self.profile = load_replay_threat_profile(
|
||||
self.repository_root / DEFAULT_REPLAY_THREAT_PROFILE_PATH
|
||||
)
|
||||
self.store = RecordedGeometryStore.from_repository(self.repository_root)
|
||||
if self.store.profile.frame_count != EXPECTED_FRAME_COUNT:
|
||||
raise M48sReplayTimelineError("M4.8S source frame count changed")
|
||||
self.body_frames = RecordedReplayBodyFrameResolver(
|
||||
self.store,
|
||||
profile=self.profile.body_frame,
|
||||
)
|
||||
self.source_times_ns = tuple(
|
||||
self.store.temporal_binding_for_index(sequence).source_time_ns
|
||||
for sequence in range(EXPECTED_FRAME_COUNT)
|
||||
)
|
||||
if any(right <= left for left, right in pairwise(self.source_times_ns)):
|
||||
raise M48sReplayTimelineError("M4.8S source clock is not monotonic")
|
||||
worker = _object(json.loads(self.worker_path.read_text("utf-8")), "worker result")
|
||||
self.outcomes = _terminal_outcomes(worker)
|
||||
self.index = _index_ledger(self.frames_path, self.source_times_ns, self.outcomes)
|
||||
self._lock = RLock()
|
||||
|
||||
def metadata(self) -> dict[str, object]:
|
||||
intervals = [
|
||||
(current - previous) / 1_000_000_000
|
||||
for previous, current in pairwise(self.source_times_ns)
|
||||
]
|
||||
nominal_interval = statistics.median(intervals)
|
||||
return {
|
||||
"schema_version": RECORDED_SPATIAL_TIMELINE_SCHEMA,
|
||||
"result_id": self.result_id,
|
||||
"recorded_source": {
|
||||
"session_id": self.profile.session_id,
|
||||
"source_id": self.profile.source_id,
|
||||
"representation_id": RECORDED_REPRESENTATION_ID,
|
||||
"synchronization": "host-arrival-best-effort",
|
||||
},
|
||||
"frame_count": EXPECTED_FRAME_COUNT,
|
||||
"frame_times_ns": list(self.source_times_ns),
|
||||
"timeline_start_seconds": self.source_times_ns[0] / 1_000_000_000,
|
||||
"timeline_end_seconds": self.source_times_ns[-1] / 1_000_000_000,
|
||||
"nominal_frame_interval_seconds": nominal_interval,
|
||||
"nominal_rate_hz": 1 / nominal_interval,
|
||||
"max_chunk_frames": RECORDED_SPATIAL_MAX_CHUNK_FRAMES,
|
||||
"point_sample_limit": RECORDED_SPATIAL_POINT_LIMIT,
|
||||
"maximum_source_points_per_frame": self.store.maximum_current_point_count,
|
||||
"point_delivery": "exact-current-increment",
|
||||
"camera_point_delivery": "factory-kb4-projected-current-increment",
|
||||
"camera_point_sample_limit": RECORDED_SPATIAL_POINT_LIMIT,
|
||||
"world_state_delivery": "source-paced-latest-wins",
|
||||
"world_state_frame_count": len(self.index.offsets_by_sequence),
|
||||
"superseded_frame_count": sum(value == "superseded" for value in self.outcomes.values()),
|
||||
"local_surface_visualization": {
|
||||
"derivation": "bounded-registered-increment-accumulation",
|
||||
"window_seconds": RECORDED_LOCAL_SURFACE_WINDOW_SECONDS,
|
||||
"voxel_size_m": RECORDED_LOCAL_SURFACE_VOXEL_SIZE_M,
|
||||
"radius_m": RECORDED_LOCAL_SURFACE_RADIUS_M,
|
||||
"point_limit": RECORDED_LOCAL_SURFACE_POINT_LIMIT,
|
||||
"authority": "visual-derived",
|
||||
},
|
||||
"image_width": 800,
|
||||
"image_height": 600,
|
||||
"rig": {
|
||||
"length_m": self.profile.rig.body_length_m,
|
||||
"width_m": self.profile.rig.body_width_m,
|
||||
"nominal_sensor_height_m": self.profile.rig.nominal_sensor_height_m,
|
||||
},
|
||||
"corridor": {
|
||||
"forward_length_m": self.profile.corridor.forward_length_m,
|
||||
"rear_margin_m": self.profile.corridor.rear_margin_m,
|
||||
"occupied_voxel_size_m": self.profile.corridor.occupied_voxel_size_m,
|
||||
"half_width_m": (
|
||||
self.profile.rig.body_width_m / 2
|
||||
+ self.profile.corridor.lateral_clearance_m
|
||||
),
|
||||
"prediction_horizon_seconds": self.profile.corridor.prediction_horizon_seconds,
|
||||
},
|
||||
"ground_truth": False,
|
||||
"authority": "replay-simulated",
|
||||
"access": "read-only-bounded-recorded-replay",
|
||||
}
|
||||
|
||||
def chunk(self, *, start_sequence: int, frame_count: int) -> dict[str, object]:
|
||||
if not 0 <= start_sequence < EXPECTED_FRAME_COUNT:
|
||||
raise M48sReplayTimelineError("M4.8S timeline start is invalid")
|
||||
if not 1 <= frame_count <= RECORDED_SPATIAL_MAX_CHUNK_FRAMES:
|
||||
raise M48sReplayTimelineError("M4.8S timeline chunk size is invalid")
|
||||
stop = min(EXPECTED_FRAME_COUNT, start_sequence + frame_count)
|
||||
with self._lock:
|
||||
frames = [self._project_frame(sequence) for sequence in range(start_sequence, stop)]
|
||||
return {
|
||||
"schema_version": RECORDED_SPATIAL_CHUNK_SCHEMA,
|
||||
"result_id": self.result_id,
|
||||
"start_sequence": start_sequence,
|
||||
"frame_count": len(frames),
|
||||
"next_sequence": stop if stop < EXPECTED_FRAME_COUNT else None,
|
||||
"frames": frames,
|
||||
"ground_truth": False,
|
||||
"authority": "replay-simulated",
|
||||
"access": "read-only-bounded-recorded-replay",
|
||||
}
|
||||
|
||||
def _project_frame(self, sequence: int) -> dict[str, object]:
|
||||
terminal_outcome = self.outcomes[sequence]
|
||||
row = self._row(sequence)
|
||||
frame_id = (
|
||||
_text(_object(row["source_envelope"], "source envelope").get("frame_id"), "frame id")
|
||||
if row is not None
|
||||
else f"frame-{sequence:06d}"
|
||||
)
|
||||
binding = self.store.temporal_binding_for_index(sequence)
|
||||
frame = self.store.frame_for_index(sequence)
|
||||
body_frame = self.body_frames.body_frame_for_frame(frame_id)
|
||||
point_cloud: list[list[float]] = []
|
||||
point_source_count = 0
|
||||
projected_points: list[list[float]] = []
|
||||
projected_source_count = 0
|
||||
projected_front_count = 0
|
||||
projected_total = 0
|
||||
if frame is not None:
|
||||
projected = project_map_points_kb4(
|
||||
frame.points_map,
|
||||
position_map_xyz=frame.sensor_position_map,
|
||||
orientation_map_from_lidar_xyzw=frame.sensor_orientation_xyzw,
|
||||
profile=frame.projection,
|
||||
)
|
||||
projected_source_count = projected.source_point_count
|
||||
projected_front_count = projected.camera_front_point_count
|
||||
projected_total = projected.projected_point_count
|
||||
stride = max(1, math.ceil(projected_total / RECORDED_SPATIAL_POINT_LIMIT))
|
||||
indices = np.arange(0, projected_total, stride, dtype=np.int64)[
|
||||
:RECORDED_SPATIAL_POINT_LIMIT
|
||||
]
|
||||
if indices.size:
|
||||
xy = projected.pixels_xy[indices]
|
||||
depth = projected.depths_m[indices, None]
|
||||
projected_points = np.round(np.concatenate((xy, depth), axis=1), 4).tolist()
|
||||
if body_frame is not None:
|
||||
point_cloud, point_source_count = sample_points_in_body_frame(
|
||||
frame.points_map,
|
||||
body_frame,
|
||||
point_limit=RECORDED_SPATIAL_POINT_LIMIT,
|
||||
)
|
||||
|
||||
metric_visuals: list[dict[str, object]] = []
|
||||
camera_proposals: list[dict[str, object]] = []
|
||||
assessments: list[dict[str, object]] = []
|
||||
if row is not None:
|
||||
envelope = _object(row.get("source_envelope"), "source envelope")
|
||||
timestamps = _object(envelope.get("timestamps"), "source timestamps")
|
||||
if (
|
||||
envelope.get("sequence") != sequence
|
||||
or timestamps.get("source_ns") != binding.source_time_ns
|
||||
or terminal_outcome != "delivered"
|
||||
):
|
||||
raise M48sReplayTimelineError("M4.8S delivered frame binding changed")
|
||||
delivery = _object(row.get("delivery"), "delivery")
|
||||
obstacle_map = _object(delivery.get("obstacle_map"), "obstacle map")
|
||||
assessments = _objects(delivery.get("threats"), "threats")
|
||||
assessment_by_component = {
|
||||
_text(item.get("component_id"), "assessment component"): item
|
||||
for item in assessments
|
||||
}
|
||||
metric_rows: list[dict[str, object]] = []
|
||||
for obstacle in (
|
||||
*_objects(obstacle_map.get("occupied"), "occupied obstacles"),
|
||||
*_objects(obstacle_map.get("unknown"), "unknown obstacles"),
|
||||
):
|
||||
component_id = _text(obstacle.get("component_id"), "component id")
|
||||
centroid = obstacle.get("last_centroid_xyz_m")
|
||||
if centroid is None:
|
||||
continue
|
||||
metric_rows.append(
|
||||
{
|
||||
"component_id": component_id,
|
||||
"state": obstacle.get("state"),
|
||||
"motion": obstacle.get("motion"),
|
||||
"centroid_map_xyz_m": centroid,
|
||||
"cells": obstacle.get("cells"),
|
||||
"assessment": assessment_by_component[component_id],
|
||||
}
|
||||
)
|
||||
if body_frame is not None:
|
||||
metric_visuals = project_metric_obstacles_to_body(
|
||||
metric_rows,
|
||||
body_frame,
|
||||
occupied_voxel_size_m=self.profile.corridor.occupied_voxel_size_m,
|
||||
)
|
||||
associated = set(_strings(row.get("associated_proposal_ids"), "associated ids"))
|
||||
for proposal in _objects(row.get("detector_proposals"), "detector proposals"):
|
||||
proposal_id = _text(proposal.get("proposal_id"), "proposal id")
|
||||
region = _object(proposal.get("region"), "proposal region")
|
||||
assessment = assessment_by_component.get(proposal_id)
|
||||
camera_proposals.append(
|
||||
{
|
||||
"proposal_id": proposal_id,
|
||||
"bbox_xyxy": [
|
||||
region.get("x_min"),
|
||||
region.get("y_min"),
|
||||
region.get("x_max"),
|
||||
region.get("y_max"),
|
||||
],
|
||||
"objectness": proposal.get("objectness"),
|
||||
"semantic_hint": proposal.get("semantic_hint"),
|
||||
"occupied_support": proposal_id in associated,
|
||||
"range_m": None,
|
||||
"threat_decision": None if assessment is None else assessment.get("decision"),
|
||||
"threat_reason_codes": []
|
||||
if assessment is None
|
||||
else assessment.get("reason_codes"),
|
||||
}
|
||||
)
|
||||
return {
|
||||
"schema_version": RECORDED_SPATIAL_FRAME_SCHEMA,
|
||||
"sequence": sequence,
|
||||
"frame_id": frame_id,
|
||||
"source_time_ns": binding.source_time_ns,
|
||||
"session_seconds": binding.source_time_ns / 1_000_000_000,
|
||||
"source_available": binding.source_available,
|
||||
"spatial_available": body_frame is not None and frame is not None,
|
||||
"world_state_available": row is not None,
|
||||
"terminal_outcome": terminal_outcome,
|
||||
"body_frame": None
|
||||
if body_frame is None
|
||||
else {
|
||||
"origin_map_xyz_m": list(body_frame.origin_map_xyz_m),
|
||||
"basis_map_from_body": [list(value) for value in body_frame.basis_map_from_body],
|
||||
},
|
||||
"point_cloud_body_xyz_m": point_cloud,
|
||||
"point_cloud_source_count": point_source_count,
|
||||
"point_cloud_sample_count": len(point_cloud),
|
||||
"point_cloud_layer": "current-increment",
|
||||
"camera_projected_points_xyd": projected_points,
|
||||
"camera_projected_source_count": projected_source_count,
|
||||
"camera_projected_front_count": projected_front_count,
|
||||
"camera_projected_point_count": projected_total,
|
||||
"camera_projected_sample_count": len(projected_points),
|
||||
"camera_projection": "factory-kb4-exact",
|
||||
"rolling_map_component_count": sum(
|
||||
item.get("state") == "retained" for item in metric_visuals
|
||||
),
|
||||
"metric_obstacles": metric_visuals,
|
||||
"camera_proposals": camera_proposals,
|
||||
"decision_counts": _decision_counts(assessments),
|
||||
"camera_url": (
|
||||
"/api/v1/laboratory/m48s/fixed-class-detector/"
|
||||
f"{self.result_id}/timeline/frames/{sequence}/camera"
|
||||
),
|
||||
"ground_truth": False,
|
||||
"authority": "replay-simulated",
|
||||
}
|
||||
|
||||
def _row(self, sequence: int) -> dict[str, object] | None:
|
||||
offset = self.index.offsets_by_sequence.get(sequence)
|
||||
if offset is None:
|
||||
return None
|
||||
with self.frames_path.open("rb") as stream:
|
||||
stream.seek(offset)
|
||||
line = stream.readline()
|
||||
value = json.loads(line)
|
||||
if not isinstance(value, dict) or value.get("schema_version") != FRAME_EVIDENCE_SCHEMA:
|
||||
raise M48sReplayTimelineError("M4.8S frame row is invalid")
|
||||
return value
|
||||
|
||||
|
||||
def _index_ledger(
|
||||
path: Path,
|
||||
source_times_ns: tuple[int, ...],
|
||||
outcomes: dict[int, str],
|
||||
) -> _LedgerIndex:
|
||||
offsets: dict[int, int] = {}
|
||||
with path.open("rb") as stream:
|
||||
while True:
|
||||
offset = stream.tell()
|
||||
line = stream.readline()
|
||||
if not line:
|
||||
break
|
||||
row = json.loads(line)
|
||||
if not isinstance(row, dict) or row.get("schema_version") != FRAME_EVIDENCE_SCHEMA:
|
||||
raise M48sReplayTimelineError("M4.8S ledger schema changed")
|
||||
envelope = _object(row.get("source_envelope"), "source envelope")
|
||||
timestamps = _object(envelope.get("timestamps"), "source timestamps")
|
||||
sequence = envelope.get("sequence")
|
||||
if (
|
||||
not isinstance(sequence, int)
|
||||
or isinstance(sequence, bool)
|
||||
or not 0 <= sequence < EXPECTED_FRAME_COUNT
|
||||
or sequence in offsets
|
||||
or outcomes.get(sequence) != "delivered"
|
||||
or timestamps.get("source_ns") != source_times_ns[sequence]
|
||||
):
|
||||
raise M48sReplayTimelineError("M4.8S ledger source binding changed")
|
||||
offsets[sequence] = offset
|
||||
delivered = {sequence for sequence, outcome in outcomes.items() if outcome == "delivered"}
|
||||
if set(offsets) != delivered:
|
||||
raise M48sReplayTimelineError("M4.8S ledger does not match delivered outcomes")
|
||||
return _LedgerIndex(offsets)
|
||||
|
||||
|
||||
def _terminal_outcomes(worker: dict[str, object]) -> dict[int, str]:
|
||||
execution = _object(worker.get("execution"), "execution")
|
||||
loops = execution.get("loops")
|
||||
if not isinstance(loops, list) or len(loops) != 1:
|
||||
raise M48sReplayTimelineError("M4.8S worker loop identity changed")
|
||||
details = _object(loops[0], "worker loop").get("terminal_outcome_details")
|
||||
result: dict[int, str] = {}
|
||||
for item in _objects(details, "terminal outcomes"):
|
||||
sequence = item.get("sequence")
|
||||
outcome = item.get("outcome")
|
||||
if (
|
||||
not isinstance(sequence, int)
|
||||
or isinstance(sequence, bool)
|
||||
or outcome not in {"delivered", "superseded"}
|
||||
or sequence in result
|
||||
):
|
||||
raise M48sReplayTimelineError("M4.8S terminal outcome is invalid")
|
||||
result[sequence] = outcome
|
||||
if sorted(result) != list(range(EXPECTED_FRAME_COUNT)):
|
||||
raise M48sReplayTimelineError("M4.8S terminal outcomes are incomplete")
|
||||
return result
|
||||
|
||||
|
||||
def _decision_counts(assessments: list[dict[str, object]]) -> dict[str, int]:
|
||||
result = {"threat": 0, "not-threat": 0, "unknown": 0}
|
||||
for assessment in assessments:
|
||||
decision = assessment.get("decision")
|
||||
if not isinstance(decision, str) or decision not in result:
|
||||
raise M48sReplayTimelineError("M4.8S threat decision is invalid")
|
||||
result[decision] += 1
|
||||
return result
|
||||
|
||||
|
||||
def _object(value: object, label: str) -> dict[str, object]:
|
||||
if not isinstance(value, dict):
|
||||
raise M48sReplayTimelineError(f"M4.8S {label} is invalid")
|
||||
return value
|
||||
|
||||
|
||||
def _objects(value: object, label: str) -> list[dict[str, object]]:
|
||||
if not isinstance(value, list) or any(not isinstance(item, dict) for item in value):
|
||||
raise M48sReplayTimelineError(f"M4.8S {label} are invalid")
|
||||
return copy.deepcopy(value)
|
||||
|
||||
|
||||
def _strings(value: object, label: str) -> list[str]:
|
||||
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
|
||||
raise M48sReplayTimelineError(f"M4.8S {label} are invalid")
|
||||
return value
|
||||
|
||||
|
||||
def _text(value: object, label: str) -> str:
|
||||
if not isinstance(value, str) or not value:
|
||||
raise M48sReplayTimelineError(f"M4.8S {label} is invalid")
|
||||
return value
|
||||
|
||||
|
||||
__all__ = ["M48sReplayTimeline", "M48sReplayTimelineError"]
|
||||
@@ -0,0 +1,436 @@
|
||||
"""Fail-closed Mask Grounding DINO evidence and geometry binding.
|
||||
|
||||
The mask model is allowed to suggest instance masks and class hypotheses. It
|
||||
cannot create occupied geometry, and contradictory captions for one pixel mask
|
||||
remain explicitly ambiguous.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
import numpy as np
|
||||
import numpy.typing as npt
|
||||
|
||||
from .contracts import ObstacleObservation
|
||||
from .geometry_math import ProjectedPointCloud
|
||||
|
||||
MASK_GROUNDING_EVIDENCE_SCHEMA: Final = (
|
||||
"missioncore.m48s-mask-grounding-dino-evidence/v0"
|
||||
)
|
||||
|
||||
BoolArray = npt.NDArray[np.bool_]
|
||||
|
||||
|
||||
class MaskGroundingSemanticError(ValueError):
|
||||
"""Mask semantic evidence is malformed or cannot be bound safely."""
|
||||
|
||||
|
||||
class MaskBindingResolution(StrEnum):
|
||||
SELECTED = "selected"
|
||||
AMBIGUOUS = "ambiguous"
|
||||
UNRESOLVED = "unresolved"
|
||||
|
||||
|
||||
class MaskLabelResolution(StrEnum):
|
||||
SELECTED = "selected"
|
||||
AMBIGUOUS = "ambiguous"
|
||||
UNRESOLVED = "unresolved"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MaskGroundingDetection:
|
||||
detection_id: str
|
||||
prompt_set_id: str
|
||||
class_id: int
|
||||
class_name: str
|
||||
confidence: float
|
||||
box_xyxy: tuple[float, float, float, float]
|
||||
mask_sha256: str
|
||||
mask: BoolArray
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (
|
||||
not self.detection_id
|
||||
or not self.prompt_set_id
|
||||
or not self.class_name
|
||||
or self.class_id < 0
|
||||
or not math.isfinite(self.confidence)
|
||||
or not 0.0 <= self.confidence <= 1.0
|
||||
or len(self.box_xyxy) != 4
|
||||
or not np.isfinite(self.box_xyxy).all()
|
||||
or self.box_xyxy[2] <= self.box_xyxy[0]
|
||||
or self.box_xyxy[3] <= self.box_xyxy[1]
|
||||
or self.mask.shape != (600, 800)
|
||||
or not self.mask.any()
|
||||
or len(self.mask_sha256) != 64
|
||||
):
|
||||
raise MaskGroundingSemanticError("mask grounding detection is invalid")
|
||||
frozen = np.asarray(self.mask, dtype=np.bool_).copy()
|
||||
frozen.setflags(write=False)
|
||||
object.__setattr__(self, "mask", frozen)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MaskGroundingEvidence:
|
||||
source_file_sha256: str
|
||||
source_pixel_sha256: str
|
||||
detections: tuple[MaskGroundingDetection, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MaskInstance:
|
||||
instance_id: str
|
||||
detections: tuple[MaskGroundingDetection, ...]
|
||||
|
||||
@property
|
||||
def ranked_labels(self) -> tuple[tuple[str, float], ...]:
|
||||
confidence_by_label: dict[str, float] = {}
|
||||
for item in self.detections:
|
||||
confidence_by_label[item.class_name] = max(
|
||||
item.confidence,
|
||||
confidence_by_label.get(item.class_name, 0.0),
|
||||
)
|
||||
return tuple(
|
||||
sorted(
|
||||
confidence_by_label.items(),
|
||||
key=lambda item: (-item[1], item[0]),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MaskObservationSupport:
|
||||
observation_id: str
|
||||
projected_point_count: int
|
||||
support_fraction: float
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MaskGeometryBinding:
|
||||
instance_id: str
|
||||
resolution: MaskBindingResolution
|
||||
selected_observation_id: str | None
|
||||
supports: tuple[MaskObservationSupport, ...]
|
||||
reason_code: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MaskLabelDecision:
|
||||
instance_id: str
|
||||
resolution: MaskLabelResolution
|
||||
selected_label: str | None
|
||||
ranked_labels: tuple[tuple[str, float], ...]
|
||||
reason_code: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MaskGeometryBindingProfile:
|
||||
minimum_mask_iou: float = 0.9
|
||||
minimum_projected_points: int = 4
|
||||
minimum_support_fraction: float = 0.5
|
||||
maximum_secondary_support_fraction: float = 0.25
|
||||
minimum_label_confidence: float = 0.3
|
||||
minimum_label_margin: float = 0.1
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
fractions = (
|
||||
self.minimum_mask_iou,
|
||||
self.minimum_support_fraction,
|
||||
self.maximum_secondary_support_fraction,
|
||||
self.minimum_label_confidence,
|
||||
self.minimum_label_margin,
|
||||
)
|
||||
if (
|
||||
self.minimum_projected_points < 1
|
||||
or not all(math.isfinite(item) and 0.0 <= item <= 1.0 for item in fractions)
|
||||
or self.maximum_secondary_support_fraction
|
||||
>= self.minimum_support_fraction
|
||||
):
|
||||
raise MaskGroundingSemanticError("mask geometry binding profile is invalid")
|
||||
|
||||
|
||||
def load_mask_grounding_evidence(
|
||||
path: Path,
|
||||
*,
|
||||
prompt_set_id: str,
|
||||
) -> MaskGroundingEvidence:
|
||||
"""Load one lossless Worker ledger without allowing object arrays."""
|
||||
|
||||
if not prompt_set_id:
|
||||
raise MaskGroundingSemanticError("mask prompt set id is required")
|
||||
try:
|
||||
source = path.resolve(strict=True)
|
||||
with np.load(source, allow_pickle=False) as archive:
|
||||
expected = {
|
||||
"schema_version",
|
||||
"source_file_sha256",
|
||||
"source_pixel_sha256",
|
||||
"class_ids",
|
||||
"class_names",
|
||||
"scores",
|
||||
"boxes_xyxy",
|
||||
"masks",
|
||||
}
|
||||
if set(archive.files) != expected:
|
||||
raise MaskGroundingSemanticError("mask evidence fields changed")
|
||||
schema = str(archive["schema_version"].item())
|
||||
source_file_sha256 = str(archive["source_file_sha256"].item())
|
||||
source_pixel_sha256 = str(archive["source_pixel_sha256"].item())
|
||||
class_ids = np.asarray(archive["class_ids"], dtype=np.int64)
|
||||
class_names = np.asarray(archive["class_names"])
|
||||
scores = np.asarray(archive["scores"], dtype=np.float64)
|
||||
boxes = np.asarray(archive["boxes_xyxy"], dtype=np.float64)
|
||||
masks = np.asarray(archive["masks"], dtype=np.uint8)
|
||||
except (OSError, ValueError) as exc:
|
||||
raise MaskGroundingSemanticError("mask evidence cannot be read") from exc
|
||||
if schema != MASK_GROUNDING_EVIDENCE_SCHEMA:
|
||||
raise MaskGroundingSemanticError("mask evidence schema changed")
|
||||
count = int(class_ids.size)
|
||||
if count == 0 and boxes.shape == (0,):
|
||||
# Early v0 shadow ledgers encoded an empty list before the writer was
|
||||
# tightened to (0, 4). No values are inferred by this normalization.
|
||||
boxes = boxes.reshape((0, 4))
|
||||
if (
|
||||
len(source_file_sha256) != 64
|
||||
or len(source_pixel_sha256) != 64
|
||||
or class_ids.shape != (count,)
|
||||
or class_names.shape != (count,)
|
||||
or scores.shape != (count,)
|
||||
or boxes.shape != (count, 4)
|
||||
or masks.shape != (count, 600, 800)
|
||||
or np.any((masks != 0) & (masks != 1))
|
||||
):
|
||||
raise MaskGroundingSemanticError("mask evidence tensors are incompatible")
|
||||
detections = []
|
||||
for index in range(count):
|
||||
mask = masks[index].astype(np.bool_)
|
||||
mask_sha256 = hashlib.sha256(masks[index].tobytes()).hexdigest()
|
||||
detections.append(
|
||||
MaskGroundingDetection(
|
||||
detection_id=f"{path.stem}:{prompt_set_id}:{index:04d}",
|
||||
prompt_set_id=prompt_set_id,
|
||||
class_id=int(class_ids[index]),
|
||||
class_name=str(class_names[index]),
|
||||
confidence=float(scores[index]),
|
||||
box_xyxy=tuple(float(item) for item in boxes[index]), # type: ignore[arg-type]
|
||||
mask_sha256=mask_sha256,
|
||||
mask=mask,
|
||||
)
|
||||
)
|
||||
return MaskGroundingEvidence(
|
||||
source_file_sha256=source_file_sha256,
|
||||
source_pixel_sha256=source_pixel_sha256,
|
||||
detections=tuple(detections),
|
||||
)
|
||||
|
||||
|
||||
def cluster_mask_instances(
|
||||
detections: tuple[MaskGroundingDetection, ...],
|
||||
*,
|
||||
profile: MaskGeometryBindingProfile | None = None,
|
||||
) -> tuple[MaskInstance, ...]:
|
||||
"""Collapse caption duplicates into deterministic pixel-owned instances."""
|
||||
|
||||
selected_profile = profile or MaskGeometryBindingProfile()
|
||||
ordered = tuple(sorted(detections, key=lambda item: item.detection_id))
|
||||
parent = list(range(len(ordered)))
|
||||
|
||||
def find(index: int) -> int:
|
||||
while parent[index] != index:
|
||||
parent[index] = parent[parent[index]]
|
||||
index = parent[index]
|
||||
return index
|
||||
|
||||
def union(left: int, right: int) -> None:
|
||||
left_root, right_root = find(left), find(right)
|
||||
if left_root != right_root:
|
||||
parent[max(left_root, right_root)] = min(left_root, right_root)
|
||||
|
||||
for left in range(len(ordered)):
|
||||
for right in range(left):
|
||||
if _mask_iou(ordered[left].mask, ordered[right].mask) >= (
|
||||
selected_profile.minimum_mask_iou
|
||||
):
|
||||
union(left, right)
|
||||
grouped: dict[int, list[MaskGroundingDetection]] = defaultdict(list)
|
||||
for index, detection in enumerate(ordered):
|
||||
grouped[find(index)].append(detection)
|
||||
instances = []
|
||||
for ordinal, members in enumerate(grouped.values()):
|
||||
member_ids = "\n".join(item.detection_id for item in members).encode()
|
||||
digest = hashlib.sha256(member_ids).hexdigest()[:16]
|
||||
instances.append(
|
||||
MaskInstance(
|
||||
instance_id=f"mask-instance-{ordinal:03d}-{digest}",
|
||||
detections=tuple(members),
|
||||
)
|
||||
)
|
||||
return tuple(instances)
|
||||
|
||||
|
||||
def bind_mask_instances_to_geometry(
|
||||
instances: tuple[MaskInstance, ...],
|
||||
*,
|
||||
observations: tuple[ObstacleObservation, ...],
|
||||
projected: ProjectedPointCloud,
|
||||
profile: MaskGeometryBindingProfile | None = None,
|
||||
) -> tuple[MaskGeometryBinding, ...]:
|
||||
"""Bind masks only to exclusively supported occupied-geometry observations."""
|
||||
|
||||
selected_profile = profile or MaskGeometryBindingProfile()
|
||||
preliminary = tuple(
|
||||
_bind_instance(
|
||||
instance,
|
||||
observations=observations,
|
||||
projected=projected,
|
||||
profile=selected_profile,
|
||||
)
|
||||
for instance in instances
|
||||
)
|
||||
claims: dict[str, list[int]] = defaultdict(list)
|
||||
for index, binding in enumerate(preliminary):
|
||||
if binding.selected_observation_id is not None:
|
||||
claims[binding.selected_observation_id].append(index)
|
||||
collisions = {index for indices in claims.values() if len(indices) > 1 for index in indices}
|
||||
return tuple(
|
||||
MaskGeometryBinding(
|
||||
instance_id=item.instance_id,
|
||||
resolution=MaskBindingResolution.AMBIGUOUS,
|
||||
selected_observation_id=None,
|
||||
supports=item.supports,
|
||||
reason_code="observation-claimed-by-multiple-mask-instances",
|
||||
)
|
||||
if index in collisions
|
||||
else item
|
||||
for index, item in enumerate(preliminary)
|
||||
)
|
||||
|
||||
|
||||
def resolve_mask_instance_label(
|
||||
instance: MaskInstance,
|
||||
*,
|
||||
profile: MaskGeometryBindingProfile | None = None,
|
||||
) -> MaskLabelDecision:
|
||||
"""Resolve a name only when confidence and inter-label margin both pass."""
|
||||
|
||||
selected_profile = profile or MaskGeometryBindingProfile()
|
||||
ranked = instance.ranked_labels
|
||||
if not ranked or ranked[0][1] < selected_profile.minimum_label_confidence:
|
||||
return MaskLabelDecision(
|
||||
instance.instance_id,
|
||||
MaskLabelResolution.UNRESOLVED,
|
||||
None,
|
||||
ranked,
|
||||
"top-label-below-confidence",
|
||||
)
|
||||
runner_up = ranked[1][1] if len(ranked) > 1 else 0.0
|
||||
if ranked[0][1] - runner_up < selected_profile.minimum_label_margin:
|
||||
return MaskLabelDecision(
|
||||
instance.instance_id,
|
||||
MaskLabelResolution.AMBIGUOUS,
|
||||
None,
|
||||
ranked,
|
||||
"top-label-margin-insufficient",
|
||||
)
|
||||
return MaskLabelDecision(
|
||||
instance.instance_id,
|
||||
MaskLabelResolution.SELECTED,
|
||||
ranked[0][0],
|
||||
ranked,
|
||||
"confidence-and-margin-passed",
|
||||
)
|
||||
|
||||
|
||||
def _bind_instance(
|
||||
instance: MaskInstance,
|
||||
*,
|
||||
observations: tuple[ObstacleObservation, ...],
|
||||
projected: ProjectedPointCloud,
|
||||
profile: MaskGeometryBindingProfile,
|
||||
) -> MaskGeometryBinding:
|
||||
supports = []
|
||||
for observation in observations:
|
||||
selected = np.isin(
|
||||
projected.source_indices,
|
||||
np.asarray(observation.source_point_ids, dtype=np.int64),
|
||||
)
|
||||
pixels = projected.pixels_xy[selected]
|
||||
if pixels.shape[0] < profile.minimum_projected_points:
|
||||
continue
|
||||
integer_pixels = np.floor(pixels).astype(np.int64)
|
||||
x = integer_pixels[:, 0]
|
||||
y = integer_pixels[:, 1]
|
||||
support = max(
|
||||
float(detection.mask[y, x].mean()) for detection in instance.detections
|
||||
)
|
||||
supports.append(
|
||||
MaskObservationSupport(
|
||||
observation_id=observation.observation_id,
|
||||
projected_point_count=int(pixels.shape[0]),
|
||||
support_fraction=support,
|
||||
)
|
||||
)
|
||||
ordered = tuple(
|
||||
sorted(
|
||||
supports,
|
||||
key=lambda item: (-item.support_fraction, item.observation_id),
|
||||
)
|
||||
)
|
||||
if not ordered or ordered[0].support_fraction < profile.minimum_support_fraction:
|
||||
return MaskGeometryBinding(
|
||||
instance.instance_id,
|
||||
MaskBindingResolution.UNRESOLVED,
|
||||
None,
|
||||
ordered,
|
||||
"occupied-geometry-support-insufficient",
|
||||
)
|
||||
if (
|
||||
len(ordered) > 1
|
||||
and ordered[1].support_fraction > profile.maximum_secondary_support_fraction
|
||||
):
|
||||
return MaskGeometryBinding(
|
||||
instance.instance_id,
|
||||
MaskBindingResolution.AMBIGUOUS,
|
||||
None,
|
||||
ordered,
|
||||
"mask-covers-multiple-geometry-observations",
|
||||
)
|
||||
return MaskGeometryBinding(
|
||||
instance.instance_id,
|
||||
MaskBindingResolution.SELECTED,
|
||||
ordered[0].observation_id,
|
||||
ordered,
|
||||
"exclusive-occupied-geometry-support-passed",
|
||||
)
|
||||
|
||||
|
||||
def _mask_iou(left: BoolArray, right: BoolArray) -> float:
|
||||
intersection = int(np.logical_and(left, right).sum())
|
||||
union = int(np.logical_or(left, right).sum())
|
||||
return intersection / union if union else 0.0
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MASK_GROUNDING_EVIDENCE_SCHEMA",
|
||||
"MaskBindingResolution",
|
||||
"MaskGeometryBinding",
|
||||
"MaskGeometryBindingProfile",
|
||||
"MaskGroundingDetection",
|
||||
"MaskGroundingEvidence",
|
||||
"MaskGroundingSemanticError",
|
||||
"MaskInstance",
|
||||
"MaskLabelDecision",
|
||||
"MaskLabelResolution",
|
||||
"MaskObservationSupport",
|
||||
"bind_mask_instances_to_geometry",
|
||||
"cluster_mask_instances",
|
||||
"load_mask_grounding_evidence",
|
||||
"resolve_mask_instance_label",
|
||||
]
|
||||
@@ -0,0 +1,929 @@
|
||||
"""Versioned semantic, state and advisory-risk projection for an obstacle.
|
||||
|
||||
The projection composes an immutable :class:`ObstacleObservation` instead of
|
||||
changing the strict v1 geometry contract. Semantic identity, observed state,
|
||||
class priors and advisory risk remain separate claims with explicit evidence.
|
||||
None of them can create occupancy or acquire navigation, safety or actuation
|
||||
authority.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from .contracts import FalseAuthority, MotionState, ObstacleObservation
|
||||
|
||||
OBJECT_UNDERSTANDING_SCHEMA: Final = "missioncore.object-understanding/v1"
|
||||
OBJECT_SEMANTIC_VOCABULARY_SCHEMA: Final = "missioncore.object-semantic-vocabulary/v0"
|
||||
MAX_SEMANTIC_HYPOTHESES: Final = 5
|
||||
|
||||
_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$")
|
||||
_NORMALIZED_LABEL = re.compile(r"^[a-z0-9][a-z0-9_]{0,79}$")
|
||||
|
||||
|
||||
class ObjectUnderstandingError(ValueError):
|
||||
"""An object-understanding document or vocabulary is incompatible."""
|
||||
|
||||
|
||||
class EvidenceKind(StrEnum):
|
||||
DETECTOR = "detector"
|
||||
SEMANTIC_MASK = "semantic-mask"
|
||||
HUMAN_REVIEW = "human-review"
|
||||
GEOMETRY = "geometry"
|
||||
TEMPORAL = "temporal"
|
||||
POLICY = "policy"
|
||||
|
||||
|
||||
class SemanticResolution(StrEnum):
|
||||
UNRESOLVED = "unresolved"
|
||||
SELECTED = "selected"
|
||||
AMBIGUOUS = "ambiguous"
|
||||
CONFLICT = "conflict"
|
||||
|
||||
|
||||
class AgencyState(StrEnum):
|
||||
UNKNOWN = "unknown"
|
||||
INERT = "inert"
|
||||
ANIMATE = "animate"
|
||||
SELF_PROPELLED = "self-propelled"
|
||||
|
||||
|
||||
class StateBasis(StrEnum):
|
||||
UNKNOWN = "unknown"
|
||||
OBSERVED = "observed"
|
||||
CLASS_PRIOR = "class-prior"
|
||||
FUSED = "fused"
|
||||
|
||||
|
||||
class RiskLevel(StrEnum):
|
||||
UNKNOWN = "unknown"
|
||||
LOW = "low"
|
||||
ELEVATED = "elevated"
|
||||
HIGH = "high"
|
||||
CRITICAL = "critical"
|
||||
|
||||
|
||||
class RiskBasis(StrEnum):
|
||||
UNKNOWN = "unknown"
|
||||
SEMANTIC_PRIOR = "semantic-prior"
|
||||
OBSERVED_STATE = "observed-state"
|
||||
GEOMETRY = "geometry"
|
||||
FUSED = "fused"
|
||||
|
||||
|
||||
class AdvisoryResponse(StrEnum):
|
||||
MONITOR = "monitor"
|
||||
REDUCE_SPEED = "reduce-speed"
|
||||
YIELD = "yield"
|
||||
STOP = "stop"
|
||||
ROUTE_AROUND = "route-around"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class EvidenceProvenance:
|
||||
"""One source-bound evidence item used by semantic, state or risk claims."""
|
||||
|
||||
evidence_id: str
|
||||
kind: EvidenceKind
|
||||
source_id: str
|
||||
frame_id: str
|
||||
provider_id: str
|
||||
model_id: str | None
|
||||
model_revision: str | None
|
||||
preprocess_id: str | None
|
||||
prompt_set_id: str | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.kind, EvidenceKind):
|
||||
raise ObjectUnderstandingError("evidence kind is invalid")
|
||||
for value, label in (
|
||||
(self.evidence_id, "evidence id"),
|
||||
(self.source_id, "evidence source id"),
|
||||
(self.frame_id, "evidence frame id"),
|
||||
(self.provider_id, "evidence provider id"),
|
||||
):
|
||||
_identifier(value, label)
|
||||
for optional_value, label in (
|
||||
(self.model_id, "evidence model id"),
|
||||
(self.model_revision, "evidence model revision"),
|
||||
(self.preprocess_id, "evidence preprocess id"),
|
||||
(self.prompt_set_id, "evidence prompt-set id"),
|
||||
):
|
||||
_optional_identifier(optional_value, label)
|
||||
if self.kind in {EvidenceKind.DETECTOR, EvidenceKind.SEMANTIC_MASK} and (
|
||||
self.model_id is None or self.model_revision is None or self.preprocess_id is None
|
||||
):
|
||||
raise ObjectUnderstandingError(
|
||||
"model evidence requires model, revision and preprocess identity"
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"evidence_id": self.evidence_id,
|
||||
"kind": self.kind.value,
|
||||
"source_id": self.source_id,
|
||||
"frame_id": self.frame_id,
|
||||
"provider_id": self.provider_id,
|
||||
"model_id": self.model_id,
|
||||
"model_revision": self.model_revision,
|
||||
"preprocess_id": self.preprocess_id,
|
||||
"prompt_set_id": self.prompt_set_id,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value: object) -> EvidenceProvenance:
|
||||
document = _object(value, "evidence provenance")
|
||||
_exact_keys(
|
||||
document,
|
||||
{
|
||||
"evidence_id",
|
||||
"kind",
|
||||
"source_id",
|
||||
"frame_id",
|
||||
"provider_id",
|
||||
"model_id",
|
||||
"model_revision",
|
||||
"preprocess_id",
|
||||
"prompt_set_id",
|
||||
},
|
||||
"evidence provenance",
|
||||
)
|
||||
return cls(
|
||||
evidence_id=_string(document, "evidence_id"),
|
||||
kind=_enum(EvidenceKind, document.get("kind"), "evidence kind"),
|
||||
source_id=_string(document, "source_id"),
|
||||
frame_id=_string(document, "frame_id"),
|
||||
provider_id=_string(document, "provider_id"),
|
||||
model_id=_optional_string(document.get("model_id"), "model id"),
|
||||
model_revision=_optional_string(document.get("model_revision"), "model revision"),
|
||||
preprocess_id=_optional_string(document.get("preprocess_id"), "preprocess id"),
|
||||
prompt_set_id=_optional_string(document.get("prompt_set_id"), "prompt-set id"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticHypothesis:
|
||||
"""One ranked canonical class hypothesis, never an occupancy identity."""
|
||||
|
||||
rank: int
|
||||
class_id: str
|
||||
raw_label: str
|
||||
confidence: float
|
||||
evidence_ids: tuple[str, ...]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_positive_integer(self.rank, "semantic rank")
|
||||
_identifier(self.class_id, "semantic class id")
|
||||
_label(self.raw_label, "raw semantic label")
|
||||
_confidence(self.confidence, "semantic confidence")
|
||||
_unique_identifiers(self.evidence_ids, "semantic evidence ids")
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"rank": self.rank,
|
||||
"class_id": self.class_id,
|
||||
"raw_label": self.raw_label,
|
||||
"confidence": self.confidence,
|
||||
"evidence_ids": list(self.evidence_ids),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value: object) -> SemanticHypothesis:
|
||||
document = _object(value, "semantic hypothesis")
|
||||
_exact_keys(
|
||||
document,
|
||||
{"rank", "class_id", "raw_label", "confidence", "evidence_ids"},
|
||||
"semantic hypothesis",
|
||||
)
|
||||
return cls(
|
||||
rank=_integer(document, "rank"),
|
||||
class_id=_string(document, "class_id"),
|
||||
raw_label=_string(document, "raw_label"),
|
||||
confidence=_number(document, "confidence"),
|
||||
evidence_ids=_string_tuple(document.get("evidence_ids"), "evidence ids"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticDecision:
|
||||
"""Resolution over ranked hypotheses; ambiguity remains first-class."""
|
||||
|
||||
resolution: SemanticResolution
|
||||
selected_class_id: str | None
|
||||
selected_confidence: float | None
|
||||
reason_codes: tuple[str, ...]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.resolution, SemanticResolution):
|
||||
raise ObjectUnderstandingError("semantic resolution is invalid")
|
||||
_optional_identifier(self.selected_class_id, "selected semantic class id")
|
||||
if self.selected_confidence is not None:
|
||||
_confidence(self.selected_confidence, "selected semantic confidence")
|
||||
_unique_identifiers(self.reason_codes, "semantic decision reasons")
|
||||
has_selection = self.selected_class_id is not None and self.selected_confidence is not None
|
||||
if self.resolution is SemanticResolution.SELECTED:
|
||||
if not has_selection:
|
||||
raise ObjectUnderstandingError("selected semantics require class and confidence")
|
||||
elif self.selected_class_id is not None or self.selected_confidence is not None:
|
||||
raise ObjectUnderstandingError("non-selected semantics cannot publish a selected class")
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"resolution": self.resolution.value,
|
||||
"selected_class_id": self.selected_class_id,
|
||||
"selected_confidence": self.selected_confidence,
|
||||
"reason_codes": list(self.reason_codes),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value: object) -> SemanticDecision:
|
||||
document = _object(value, "semantic decision")
|
||||
_exact_keys(
|
||||
document,
|
||||
{
|
||||
"resolution",
|
||||
"selected_class_id",
|
||||
"selected_confidence",
|
||||
"reason_codes",
|
||||
},
|
||||
"semantic decision",
|
||||
)
|
||||
return cls(
|
||||
resolution=_enum(
|
||||
SemanticResolution,
|
||||
document.get("resolution"),
|
||||
"semantic resolution",
|
||||
),
|
||||
selected_class_id=_optional_string(
|
||||
document.get("selected_class_id"), "selected class id"
|
||||
),
|
||||
selected_confidence=_optional_number(
|
||||
document.get("selected_confidence"), "selected confidence"
|
||||
),
|
||||
reason_codes=_string_tuple(document.get("reason_codes"), "reason codes"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ObjectStateEstimate:
|
||||
"""Observed motion and agency prior, with their bases kept explicit."""
|
||||
|
||||
motion: MotionState
|
||||
motion_confidence: float
|
||||
agency: AgencyState
|
||||
agency_basis: StateBasis
|
||||
evidence_ids: tuple[str, ...]
|
||||
reason_codes: tuple[str, ...]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.motion, MotionState):
|
||||
raise ObjectUnderstandingError("motion state is invalid")
|
||||
if not isinstance(self.agency, AgencyState):
|
||||
raise ObjectUnderstandingError("agency state is invalid")
|
||||
if not isinstance(self.agency_basis, StateBasis):
|
||||
raise ObjectUnderstandingError("agency basis is invalid")
|
||||
_confidence(self.motion_confidence, "motion confidence")
|
||||
_unique_identifiers(self.evidence_ids, "state evidence ids", allow_empty=True)
|
||||
_unique_identifiers(self.reason_codes, "state reason codes")
|
||||
if self.agency is AgencyState.UNKNOWN:
|
||||
if self.agency_basis is not StateBasis.UNKNOWN:
|
||||
raise ObjectUnderstandingError("unknown agency must retain unknown evidence basis")
|
||||
elif self.agency_basis is StateBasis.UNKNOWN:
|
||||
raise ObjectUnderstandingError("agency claim requires an explicit basis")
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"motion": self.motion.value,
|
||||
"motion_confidence": self.motion_confidence,
|
||||
"agency": self.agency.value,
|
||||
"agency_basis": self.agency_basis.value,
|
||||
"evidence_ids": list(self.evidence_ids),
|
||||
"reason_codes": list(self.reason_codes),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value: object) -> ObjectStateEstimate:
|
||||
document = _object(value, "object state")
|
||||
_exact_keys(
|
||||
document,
|
||||
{
|
||||
"motion",
|
||||
"motion_confidence",
|
||||
"agency",
|
||||
"agency_basis",
|
||||
"evidence_ids",
|
||||
"reason_codes",
|
||||
},
|
||||
"object state",
|
||||
)
|
||||
return cls(
|
||||
motion=_enum(MotionState, document.get("motion"), "motion state"),
|
||||
motion_confidence=_number(document, "motion_confidence"),
|
||||
agency=_enum(AgencyState, document.get("agency"), "agency state"),
|
||||
agency_basis=_enum(StateBasis, document.get("agency_basis"), "agency basis"),
|
||||
evidence_ids=_string_tuple(document.get("evidence_ids"), "evidence ids"),
|
||||
reason_codes=_string_tuple(document.get("reason_codes"), "reason codes"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AdvisoryRiskAssessment:
|
||||
"""Evidence-qualified risk hint that is never a planner command."""
|
||||
|
||||
policy_id: str
|
||||
level: RiskLevel
|
||||
confidence: float
|
||||
basis: RiskBasis
|
||||
responses: tuple[AdvisoryResponse, ...]
|
||||
evidence_ids: tuple[str, ...]
|
||||
reason_codes: tuple[str, ...]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.level, RiskLevel):
|
||||
raise ObjectUnderstandingError("risk level is invalid")
|
||||
if not isinstance(self.basis, RiskBasis):
|
||||
raise ObjectUnderstandingError("risk basis is invalid")
|
||||
_identifier(self.policy_id, "risk policy id")
|
||||
_confidence(self.confidence, "risk confidence")
|
||||
_unique_enum_values(self.responses, "advisory responses", allow_empty=True)
|
||||
_unique_identifiers(self.evidence_ids, "risk evidence ids", allow_empty=True)
|
||||
_unique_identifiers(self.reason_codes, "risk reason codes")
|
||||
if self.level is RiskLevel.UNKNOWN:
|
||||
if self.basis is not RiskBasis.UNKNOWN or self.confidence != 0.0:
|
||||
raise ObjectUnderstandingError(
|
||||
"unknown risk must retain unknown basis and zero confidence"
|
||||
)
|
||||
elif self.basis is RiskBasis.UNKNOWN:
|
||||
raise ObjectUnderstandingError("risk claim requires an explicit basis")
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"policy_id": self.policy_id,
|
||||
"level": self.level.value,
|
||||
"confidence": self.confidence,
|
||||
"basis": self.basis.value,
|
||||
"responses": [item.value for item in self.responses],
|
||||
"evidence_ids": list(self.evidence_ids),
|
||||
"reason_codes": list(self.reason_codes),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value: object) -> AdvisoryRiskAssessment:
|
||||
document = _object(value, "advisory risk")
|
||||
_exact_keys(
|
||||
document,
|
||||
{
|
||||
"policy_id",
|
||||
"level",
|
||||
"confidence",
|
||||
"basis",
|
||||
"responses",
|
||||
"evidence_ids",
|
||||
"reason_codes",
|
||||
},
|
||||
"advisory risk",
|
||||
)
|
||||
return cls(
|
||||
policy_id=_string(document, "policy_id"),
|
||||
level=_enum(RiskLevel, document.get("level"), "risk level"),
|
||||
confidence=_number(document, "confidence"),
|
||||
basis=_enum(RiskBasis, document.get("basis"), "risk basis"),
|
||||
responses=tuple(
|
||||
_enum(AdvisoryResponse, item, "advisory response")
|
||||
for item in _array(document, "responses")
|
||||
),
|
||||
evidence_ids=_string_tuple(document.get("evidence_ids"), "evidence ids"),
|
||||
reason_codes=_string_tuple(document.get("reason_codes"), "reason codes"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ObjectUnderstanding:
|
||||
"""Complete machine projection: geometry, semantics, state, risk and lineage."""
|
||||
|
||||
understanding_id: str
|
||||
vocabulary_id: str
|
||||
generated_monotonic_ns: int
|
||||
observation: ObstacleObservation
|
||||
hypotheses: tuple[SemanticHypothesis, ...]
|
||||
semantic: SemanticDecision
|
||||
state: ObjectStateEstimate
|
||||
risk: AdvisoryRiskAssessment
|
||||
provenance: tuple[EvidenceProvenance, ...]
|
||||
authority: FalseAuthority = FalseAuthority()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_identifier(self.understanding_id, "understanding id")
|
||||
_identifier(self.vocabulary_id, "semantic vocabulary id")
|
||||
_nonnegative_integer(self.generated_monotonic_ns, "generation time")
|
||||
if not isinstance(self.observation, ObstacleObservation):
|
||||
raise ObjectUnderstandingError("object geometry observation is invalid")
|
||||
if (
|
||||
not isinstance(self.hypotheses, tuple)
|
||||
or any(not isinstance(item, SemanticHypothesis) for item in self.hypotheses)
|
||||
or len(self.hypotheses) > MAX_SEMANTIC_HYPOTHESES
|
||||
):
|
||||
raise ObjectUnderstandingError("semantic hypothesis set is invalid")
|
||||
if tuple(item.rank for item in self.hypotheses) != tuple(
|
||||
range(1, len(self.hypotheses) + 1)
|
||||
):
|
||||
raise ObjectUnderstandingError("semantic hypotheses must have contiguous ranks")
|
||||
class_ids = tuple(item.class_id for item in self.hypotheses)
|
||||
if len(set(class_ids)) != len(class_ids):
|
||||
raise ObjectUnderstandingError("semantic hypothesis classes must be unique")
|
||||
if any(
|
||||
self.hypotheses[index].confidence < self.hypotheses[index + 1].confidence
|
||||
for index in range(len(self.hypotheses) - 1)
|
||||
):
|
||||
raise ObjectUnderstandingError("semantic hypotheses must be ordered by confidence")
|
||||
if not isinstance(self.semantic, SemanticDecision):
|
||||
raise ObjectUnderstandingError("semantic decision is invalid")
|
||||
if not isinstance(self.state, ObjectStateEstimate):
|
||||
raise ObjectUnderstandingError("object state is invalid")
|
||||
if not isinstance(self.risk, AdvisoryRiskAssessment):
|
||||
raise ObjectUnderstandingError("advisory risk is invalid")
|
||||
if not isinstance(self.authority, FalseAuthority):
|
||||
raise ObjectUnderstandingError("object understanding authority is invalid")
|
||||
if not isinstance(self.provenance, tuple) or any(
|
||||
not isinstance(item, EvidenceProvenance) for item in self.provenance
|
||||
):
|
||||
raise ObjectUnderstandingError("evidence provenance is invalid")
|
||||
evidence_ids = tuple(item.evidence_id for item in self.provenance)
|
||||
if len(set(evidence_ids)) != len(evidence_ids):
|
||||
raise ObjectUnderstandingError("evidence provenance ids must be unique")
|
||||
if any(
|
||||
item.source_id != self.observation.source_id
|
||||
or item.frame_id != self.observation.frame_id
|
||||
for item in self.provenance
|
||||
):
|
||||
raise ObjectUnderstandingError("object evidence escaped its geometry source frame")
|
||||
known_evidence = set(evidence_ids)
|
||||
claimed_evidence = (
|
||||
{evidence_id for item in self.hypotheses for evidence_id in item.evidence_ids}
|
||||
| set(self.state.evidence_ids)
|
||||
| set(self.risk.evidence_ids)
|
||||
)
|
||||
if claimed_evidence - known_evidence:
|
||||
raise ObjectUnderstandingError("object claim references unknown evidence")
|
||||
if (
|
||||
self.semantic.resolution
|
||||
in {
|
||||
SemanticResolution.AMBIGUOUS,
|
||||
SemanticResolution.CONFLICT,
|
||||
}
|
||||
and not self.hypotheses
|
||||
):
|
||||
raise ObjectUnderstandingError("ambiguous or conflicting semantics require hypotheses")
|
||||
if self.semantic.resolution is SemanticResolution.CONFLICT and len(self.hypotheses) < 2:
|
||||
raise ObjectUnderstandingError("semantic conflict requires two hypotheses")
|
||||
if self.semantic.resolution is SemanticResolution.SELECTED:
|
||||
selected = next(
|
||||
(
|
||||
item
|
||||
for item in self.hypotheses
|
||||
if item.class_id == self.semantic.selected_class_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if selected is None or selected.confidence != self.semantic.selected_confidence:
|
||||
raise ObjectUnderstandingError(
|
||||
"selected semantics must match one ranked hypothesis"
|
||||
)
|
||||
|
||||
@property
|
||||
def occupancy_identity(self) -> str:
|
||||
"""Semantic or risk changes never replace the geometry-owned identity."""
|
||||
|
||||
return self.observation.occupancy_identity
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"schema_version": OBJECT_UNDERSTANDING_SCHEMA,
|
||||
"understanding_id": self.understanding_id,
|
||||
"vocabulary_id": self.vocabulary_id,
|
||||
"generated_monotonic_ns": self.generated_monotonic_ns,
|
||||
"observation": self.observation.to_dict(),
|
||||
"hypotheses": [item.to_dict() for item in self.hypotheses],
|
||||
"semantic": self.semantic.to_dict(),
|
||||
"state": self.state.to_dict(),
|
||||
"risk": self.risk.to_dict(),
|
||||
"provenance": [item.to_dict() for item in self.provenance],
|
||||
"authority": self.authority.to_dict(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value: object) -> ObjectUnderstanding:
|
||||
document = _contract(
|
||||
value,
|
||||
OBJECT_UNDERSTANDING_SCHEMA,
|
||||
{
|
||||
"understanding_id",
|
||||
"vocabulary_id",
|
||||
"generated_monotonic_ns",
|
||||
"observation",
|
||||
"hypotheses",
|
||||
"semantic",
|
||||
"state",
|
||||
"risk",
|
||||
"provenance",
|
||||
"authority",
|
||||
},
|
||||
"object understanding",
|
||||
)
|
||||
return cls(
|
||||
understanding_id=_string(document, "understanding_id"),
|
||||
vocabulary_id=_string(document, "vocabulary_id"),
|
||||
generated_monotonic_ns=_integer(document, "generated_monotonic_ns"),
|
||||
observation=ObstacleObservation.from_dict(document.get("observation")),
|
||||
hypotheses=tuple(
|
||||
SemanticHypothesis.from_dict(item) for item in _array(document, "hypotheses")
|
||||
),
|
||||
semantic=SemanticDecision.from_dict(document.get("semantic")),
|
||||
state=ObjectStateEstimate.from_dict(document.get("state")),
|
||||
risk=AdvisoryRiskAssessment.from_dict(document.get("risk")),
|
||||
provenance=tuple(
|
||||
EvidenceProvenance.from_dict(item) for item in _array(document, "provenance")
|
||||
),
|
||||
authority=FalseAuthority.from_dict(document.get("authority")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CanonicalObjectClass:
|
||||
"""One class in the bounded experimental object vocabulary."""
|
||||
|
||||
class_id: str
|
||||
parent_id: str | None
|
||||
aliases: tuple[str, ...]
|
||||
agency_prior: AgencyState
|
||||
risk_traits: tuple[str, ...]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.agency_prior, AgencyState):
|
||||
raise ObjectUnderstandingError("canonical agency prior is invalid")
|
||||
_identifier(self.class_id, "canonical class id")
|
||||
_optional_identifier(self.parent_id, "canonical parent id")
|
||||
if not self.aliases:
|
||||
raise ObjectUnderstandingError("canonical class aliases must be nonempty")
|
||||
normalized = tuple(normalize_raw_label(item) for item in self.aliases)
|
||||
if len(set(normalized)) != len(normalized):
|
||||
raise ObjectUnderstandingError("canonical class aliases must be unique")
|
||||
_unique_identifiers(self.risk_traits, "class risk traits", allow_empty=True)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ObjectSemanticVocabulary:
|
||||
"""Loaded executable vocabulary profile; not a runtime ontology service."""
|
||||
|
||||
vocabulary_id: str
|
||||
status: str
|
||||
scope: str
|
||||
classes: tuple[CanonicalObjectClass, ...]
|
||||
max_hypotheses: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_identifier(self.vocabulary_id, "vocabulary id")
|
||||
if self.status != "experimental":
|
||||
raise ObjectUnderstandingError("object vocabulary must remain experimental")
|
||||
_identifier(self.scope, "vocabulary scope")
|
||||
if not 1 <= self.max_hypotheses <= MAX_SEMANTIC_HYPOTHESES:
|
||||
raise ObjectUnderstandingError("vocabulary top-k bound is invalid")
|
||||
if not self.classes:
|
||||
raise ObjectUnderstandingError("object vocabulary must declare classes")
|
||||
by_id = {item.class_id: item for item in self.classes}
|
||||
if len(by_id) != len(self.classes):
|
||||
raise ObjectUnderstandingError("canonical class ids must be unique")
|
||||
for item in self.classes:
|
||||
if item.parent_id is not None and item.parent_id not in by_id:
|
||||
raise ObjectUnderstandingError("canonical class parent is undeclared")
|
||||
seen = {item.class_id}
|
||||
parent_id = item.parent_id
|
||||
while parent_id is not None:
|
||||
if parent_id in seen:
|
||||
raise ObjectUnderstandingError("canonical class hierarchy is cyclic")
|
||||
seen.add(parent_id)
|
||||
parent_id = by_id[parent_id].parent_id
|
||||
aliases = [normalize_raw_label(alias) for item in self.classes for alias in item.aliases]
|
||||
if len(set(aliases)) != len(aliases):
|
||||
raise ObjectUnderstandingError("canonical aliases must be globally unique")
|
||||
|
||||
def class_definition(self, class_id: str) -> CanonicalObjectClass:
|
||||
for item in self.classes:
|
||||
if item.class_id == class_id:
|
||||
return item
|
||||
raise ObjectUnderstandingError("canonical class is undeclared")
|
||||
|
||||
def resolve_label(self, raw_label: str) -> str | None:
|
||||
normalized = normalize_raw_label(raw_label)
|
||||
for item in self.classes:
|
||||
if normalized in {normalize_raw_label(alias) for alias in item.aliases}:
|
||||
return item.class_id
|
||||
return None
|
||||
|
||||
def ancestors(self, class_id: str) -> tuple[str, ...]:
|
||||
by_id = {item.class_id: item for item in self.classes}
|
||||
current = self.class_definition(class_id)
|
||||
result: list[str] = []
|
||||
while current.parent_id is not None:
|
||||
result.append(current.parent_id)
|
||||
current = by_id[current.parent_id]
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def load_object_semantic_vocabulary(path: Path) -> ObjectSemanticVocabulary:
|
||||
"""Load and fail-close an executable vocabulary profile."""
|
||||
|
||||
try:
|
||||
document = json.loads(path.expanduser().resolve(strict=True).read_text("utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise ObjectUnderstandingError("object vocabulary cannot be read") from exc
|
||||
root = _object(document, "object semantic vocabulary")
|
||||
_exact_keys(
|
||||
root,
|
||||
{
|
||||
"schema_version",
|
||||
"vocabulary_id",
|
||||
"status",
|
||||
"scope",
|
||||
"classes",
|
||||
"policies",
|
||||
},
|
||||
"object semantic vocabulary",
|
||||
)
|
||||
if root.get("schema_version") != OBJECT_SEMANTIC_VOCABULARY_SCHEMA:
|
||||
raise ObjectUnderstandingError("object vocabulary schema is incompatible")
|
||||
policies = _object(root.get("policies"), "object vocabulary policies")
|
||||
_exact_keys(
|
||||
policies,
|
||||
{
|
||||
"occupancy_independent_of_semantics",
|
||||
"unknown_preserves_obstacle",
|
||||
"class_prior_is_not_observed_state",
|
||||
"risk_is_advisory_only",
|
||||
"planner_command_authority",
|
||||
"max_hypotheses",
|
||||
},
|
||||
"object vocabulary policies",
|
||||
)
|
||||
required_true = (
|
||||
"occupancy_independent_of_semantics",
|
||||
"unknown_preserves_obstacle",
|
||||
"class_prior_is_not_observed_state",
|
||||
"risk_is_advisory_only",
|
||||
)
|
||||
if (
|
||||
any(policies.get(key) is not True for key in required_true)
|
||||
or policies.get("planner_command_authority") is not False
|
||||
):
|
||||
raise ObjectUnderstandingError("object vocabulary authority policy changed")
|
||||
classes: list[CanonicalObjectClass] = []
|
||||
for raw in _array(root, "classes"):
|
||||
row = _object(raw, "canonical object class")
|
||||
_exact_keys(
|
||||
row,
|
||||
{"class_id", "parent_id", "aliases", "agency_prior", "risk_traits"},
|
||||
"canonical object class",
|
||||
)
|
||||
classes.append(
|
||||
CanonicalObjectClass(
|
||||
class_id=_string(row, "class_id"),
|
||||
parent_id=_optional_string(row.get("parent_id"), "parent id"),
|
||||
aliases=_string_tuple(row.get("aliases"), "aliases"),
|
||||
agency_prior=_enum(AgencyState, row.get("agency_prior"), "agency prior"),
|
||||
risk_traits=_string_tuple(row.get("risk_traits"), "risk traits"),
|
||||
)
|
||||
)
|
||||
return ObjectSemanticVocabulary(
|
||||
vocabulary_id=_string(root, "vocabulary_id"),
|
||||
status=_string(root, "status"),
|
||||
scope=_string(root, "scope"),
|
||||
classes=tuple(classes),
|
||||
max_hypotheses=_integer(policies, "max_hypotheses"),
|
||||
)
|
||||
|
||||
|
||||
def validate_object_understanding(
|
||||
value: ObjectUnderstanding,
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
) -> None:
|
||||
"""Validate canonical class references without changing the document."""
|
||||
|
||||
if not isinstance(value, ObjectUnderstanding):
|
||||
raise ObjectUnderstandingError("object understanding is invalid")
|
||||
if value.vocabulary_id != vocabulary.vocabulary_id:
|
||||
raise ObjectUnderstandingError("object understanding vocabulary changed")
|
||||
declared = {item.class_id for item in vocabulary.classes}
|
||||
referenced = {item.class_id for item in value.hypotheses}
|
||||
if value.semantic.selected_class_id is not None:
|
||||
referenced.add(value.semantic.selected_class_id)
|
||||
if referenced - declared:
|
||||
raise ObjectUnderstandingError("object understanding uses undeclared classes")
|
||||
if len(value.hypotheses) > vocabulary.max_hypotheses:
|
||||
raise ObjectUnderstandingError("object understanding exceeds vocabulary top-k")
|
||||
|
||||
|
||||
def normalize_raw_label(value: str) -> str:
|
||||
"""Normalize a provider label only for alias lookup, never as class truth."""
|
||||
|
||||
_label(value, "raw semantic label")
|
||||
normalized = re.sub(r"[_\s-]+", "_", value.strip().lower())
|
||||
if _NORMALIZED_LABEL.fullmatch(normalized) is None:
|
||||
raise ObjectUnderstandingError("raw semantic label cannot be normalized")
|
||||
return normalized
|
||||
|
||||
|
||||
def _contract(
|
||||
value: object,
|
||||
schema: str,
|
||||
fields: set[str],
|
||||
label: str,
|
||||
) -> dict[str, object]:
|
||||
document = _object(value, label)
|
||||
_exact_keys(document, {"schema_version", *fields}, label)
|
||||
if document.get("schema_version") != schema:
|
||||
raise ObjectUnderstandingError(f"{label} schema is incompatible")
|
||||
return document
|
||||
|
||||
|
||||
def _object(value: object, label: str) -> dict[str, object]:
|
||||
if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
|
||||
raise ObjectUnderstandingError(f"{label} must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _exact_keys(document: dict[str, object], expected: set[str], label: str) -> None:
|
||||
if set(document) != expected:
|
||||
raise ObjectUnderstandingError(f"{label} fields are incompatible")
|
||||
|
||||
|
||||
def _array(document: dict[str, object], key: str) -> list[object]:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, list):
|
||||
raise ObjectUnderstandingError(f"{key} must be an array")
|
||||
return value
|
||||
|
||||
|
||||
def _string(document: dict[str, object], key: str) -> str:
|
||||
return _string_value(document.get(key), key)
|
||||
|
||||
|
||||
def _string_value(value: object, label: str) -> str:
|
||||
if not isinstance(value, str) or not value:
|
||||
raise ObjectUnderstandingError(f"{label} must be a nonempty string")
|
||||
return value
|
||||
|
||||
|
||||
def _optional_string(value: object, label: str) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
return _string_value(value, label)
|
||||
|
||||
|
||||
def _integer(document: dict[str, object], key: str) -> int:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, int) or isinstance(value, bool):
|
||||
raise ObjectUnderstandingError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
|
||||
def _number(document: dict[str, object], key: str) -> float:
|
||||
value = document.get(key)
|
||||
if (
|
||||
not isinstance(value, (int, float))
|
||||
or isinstance(value, bool)
|
||||
or not math.isfinite(float(value))
|
||||
):
|
||||
raise ObjectUnderstandingError(f"{key} must be finite")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _optional_number(value: object, label: str) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
if (
|
||||
not isinstance(value, (int, float))
|
||||
or isinstance(value, bool)
|
||||
or not math.isfinite(float(value))
|
||||
):
|
||||
raise ObjectUnderstandingError(f"{label} must be finite")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _identifier(value: str, label: str) -> None:
|
||||
if not isinstance(value, str) or _IDENTIFIER.fullmatch(value) is None:
|
||||
raise ObjectUnderstandingError(f"{label} is not a safe identifier")
|
||||
|
||||
|
||||
def _optional_identifier(value: str | None, label: str) -> None:
|
||||
if value is not None:
|
||||
_identifier(value, label)
|
||||
|
||||
|
||||
def _label(value: str, label: str) -> None:
|
||||
if (
|
||||
not isinstance(value, str)
|
||||
or not value
|
||||
or value != value.strip()
|
||||
or len(value) > 120
|
||||
or any(ord(character) < 32 for character in value)
|
||||
):
|
||||
raise ObjectUnderstandingError(f"{label} is invalid")
|
||||
|
||||
|
||||
def _nonnegative_integer(value: object, label: str) -> int:
|
||||
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
||||
raise ObjectUnderstandingError(f"{label} must be a nonnegative integer")
|
||||
return value
|
||||
|
||||
|
||||
def _positive_integer(value: object, label: str) -> int:
|
||||
result = _nonnegative_integer(value, label)
|
||||
if result == 0:
|
||||
raise ObjectUnderstandingError(f"{label} must be positive")
|
||||
return result
|
||||
|
||||
|
||||
def _confidence(value: object, label: str) -> float:
|
||||
if (
|
||||
not isinstance(value, (int, float))
|
||||
or isinstance(value, bool)
|
||||
or not math.isfinite(float(value))
|
||||
or not 0.0 <= float(value) <= 1.0
|
||||
):
|
||||
raise ObjectUnderstandingError(f"{label} must be within [0, 1]")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _unique_identifiers(
|
||||
values: tuple[str, ...],
|
||||
label: str,
|
||||
*,
|
||||
allow_empty: bool = False,
|
||||
) -> None:
|
||||
if (not values and not allow_empty) or len(set(values)) != len(values):
|
||||
raise ObjectUnderstandingError(f"{label} must be unique")
|
||||
for value in values:
|
||||
_identifier(value, label)
|
||||
|
||||
|
||||
def _unique_enum_values(
|
||||
values: tuple[AdvisoryResponse, ...],
|
||||
label: str,
|
||||
*,
|
||||
allow_empty: bool,
|
||||
) -> None:
|
||||
if (not values and not allow_empty) or len(set(values)) != len(values):
|
||||
raise ObjectUnderstandingError(f"{label} must be unique")
|
||||
if any(not isinstance(value, AdvisoryResponse) for value in values):
|
||||
raise ObjectUnderstandingError(f"{label} are invalid")
|
||||
|
||||
|
||||
def _string_tuple(value: object, label: str) -> tuple[str, ...]:
|
||||
if not isinstance(value, list):
|
||||
raise ObjectUnderstandingError(f"{label} must be an array")
|
||||
return tuple(_string_value(item, label) for item in value)
|
||||
|
||||
|
||||
def _enum[ENUM: StrEnum](
|
||||
enum_type: type[ENUM],
|
||||
value: object,
|
||||
label: str,
|
||||
) -> ENUM:
|
||||
if not isinstance(value, str):
|
||||
raise ObjectUnderstandingError(f"{label} must be a string")
|
||||
try:
|
||||
return enum_type(value)
|
||||
except ValueError as exc:
|
||||
raise ObjectUnderstandingError(f"{label} is incompatible") from exc
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MAX_SEMANTIC_HYPOTHESES",
|
||||
"OBJECT_SEMANTIC_VOCABULARY_SCHEMA",
|
||||
"OBJECT_UNDERSTANDING_SCHEMA",
|
||||
"AdvisoryResponse",
|
||||
"AdvisoryRiskAssessment",
|
||||
"AgencyState",
|
||||
"CanonicalObjectClass",
|
||||
"EvidenceKind",
|
||||
"EvidenceProvenance",
|
||||
"ObjectSemanticVocabulary",
|
||||
"ObjectStateEstimate",
|
||||
"ObjectUnderstanding",
|
||||
"ObjectUnderstandingError",
|
||||
"RiskBasis",
|
||||
"RiskLevel",
|
||||
"SemanticDecision",
|
||||
"SemanticHypothesis",
|
||||
"SemanticResolution",
|
||||
"StateBasis",
|
||||
"load_object_semantic_vocabulary",
|
||||
"normalize_raw_label",
|
||||
"validate_object_understanding",
|
||||
]
|
||||
@@ -0,0 +1,784 @@
|
||||
"""Bounded open-vocabulary detections projected onto immutable obstacle geometry.
|
||||
|
||||
The adapter deliberately consumes detections in the raw KB4 image coordinate
|
||||
space used by the admitted geometry provider. It fuses prompt collisions into
|
||||
one spatial proposal, retains ranked canonical hypotheses and never turns a
|
||||
semantic label into occupancy, risk authority or a planner command.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from .contracts import BoundingRegion2D, MotionState, ObjectProposal2D, ObstacleObservation
|
||||
from .object_understanding import (
|
||||
AdvisoryResponse,
|
||||
AdvisoryRiskAssessment,
|
||||
AgencyState,
|
||||
EvidenceKind,
|
||||
EvidenceProvenance,
|
||||
ObjectSemanticVocabulary,
|
||||
ObjectStateEstimate,
|
||||
ObjectUnderstanding,
|
||||
RiskBasis,
|
||||
RiskLevel,
|
||||
SemanticDecision,
|
||||
SemanticHypothesis,
|
||||
SemanticResolution,
|
||||
StateBasis,
|
||||
normalize_raw_label,
|
||||
validate_object_understanding,
|
||||
)
|
||||
|
||||
OPEN_VOCABULARY_SEMANTIC_SHADOW_PROFILE_SCHEMA: Final = (
|
||||
"missioncore.open-vocabulary-semantic-shadow-profile/v0"
|
||||
)
|
||||
TAO_GROUNDING_DINO_TRAILING_FIELDS: Final = 15
|
||||
|
||||
|
||||
class OpenVocabularySemanticError(ValueError):
|
||||
"""An open-vocabulary profile, label ledger or binding is incompatible."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PromptGroup:
|
||||
prompt_set_id: str
|
||||
captions: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OpenVocabularySemanticProfile:
|
||||
profile_id: str
|
||||
session_id: str
|
||||
source_id: str
|
||||
camera_source_id: str
|
||||
coordinate_space: str
|
||||
width: int
|
||||
height: int
|
||||
valid_fov_result_id: str
|
||||
valid_fov_mask_sha256: str
|
||||
valid_fov_fill_value: int
|
||||
provider_id: str
|
||||
provider_name: str
|
||||
model_id: str
|
||||
model_revision: str
|
||||
model_sha256: str
|
||||
engine_sha256: str
|
||||
container_reference: str
|
||||
container_image_id: str
|
||||
preprocess_id: str
|
||||
engine_input_width: int
|
||||
engine_input_height: int
|
||||
minimum_input_confidence: float
|
||||
minimum_box_area_fraction: float
|
||||
maximum_box_area_fraction: float
|
||||
minimum_valid_fov_fraction: float
|
||||
require_center_inside_valid_fov: bool
|
||||
fusion_iou_threshold: float
|
||||
selected_minimum_confidence: float
|
||||
selected_minimum_margin: float
|
||||
max_hypotheses: int
|
||||
prompt_groups: tuple[PromptGroup, ...]
|
||||
vocabulary_id: str
|
||||
risk_policy_id: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.coordinate_space != "raw-kb4" or (self.width, self.height) != (800, 600):
|
||||
raise OpenVocabularySemanticError("semantic shadow must remain in raw KB4 800x600")
|
||||
if self.width < 1 or self.height < 1:
|
||||
raise OpenVocabularySemanticError("semantic shadow raster is invalid")
|
||||
if self.valid_fov_fill_value != 114 or len(self.valid_fov_mask_sha256) != 64:
|
||||
raise OpenVocabularySemanticError("semantic valid-FOV preprocessing changed")
|
||||
if (self.engine_input_width, self.engine_input_height) != (960, 544):
|
||||
raise OpenVocabularySemanticError("semantic engine input raster changed")
|
||||
for value, label in (
|
||||
(self.minimum_input_confidence, "minimum input confidence"),
|
||||
(self.minimum_box_area_fraction, "minimum box area fraction"),
|
||||
(self.maximum_box_area_fraction, "maximum box area fraction"),
|
||||
(self.minimum_valid_fov_fraction, "minimum valid-FOV fraction"),
|
||||
(self.fusion_iou_threshold, "fusion IoU threshold"),
|
||||
(self.selected_minimum_confidence, "selection confidence"),
|
||||
(self.selected_minimum_margin, "selection margin"),
|
||||
):
|
||||
if not math.isfinite(value) or not 0.0 <= value <= 1.0:
|
||||
raise OpenVocabularySemanticError(f"{label} must be within [0, 1]")
|
||||
if (
|
||||
self.minimum_box_area_fraction <= 0.0
|
||||
or self.maximum_box_area_fraction <= self.minimum_box_area_fraction
|
||||
or not 1 <= self.max_hypotheses <= 5
|
||||
or not self.prompt_groups
|
||||
or self.require_center_inside_valid_fov is not True
|
||||
):
|
||||
raise OpenVocabularySemanticError("semantic shadow postprocessing is invalid")
|
||||
prompt_ids = tuple(item.prompt_set_id for item in self.prompt_groups)
|
||||
if len(set(prompt_ids)) != len(prompt_ids):
|
||||
raise OpenVocabularySemanticError("semantic prompt-set ids are duplicated")
|
||||
captions = tuple(
|
||||
normalize_raw_label(caption)
|
||||
for group in self.prompt_groups
|
||||
for caption in group.captions
|
||||
)
|
||||
if len(set(captions)) != len(captions):
|
||||
raise OpenVocabularySemanticError("semantic captions are duplicated")
|
||||
|
||||
def prompt_group(self, prompt_set_id: str) -> PromptGroup:
|
||||
for item in self.prompt_groups:
|
||||
if item.prompt_set_id == prompt_set_id:
|
||||
return item
|
||||
raise OpenVocabularySemanticError("semantic prompt set is undeclared")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OpenVocabularyDetection:
|
||||
detection_id: str
|
||||
source_id: str
|
||||
frame_id: str
|
||||
prompt_set_id: str
|
||||
raw_label: str
|
||||
confidence: float
|
||||
region: BoundingRegion2D
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.detection_id or not self.source_id or not self.frame_id:
|
||||
raise OpenVocabularySemanticError("semantic detection identity is invalid")
|
||||
normalize_raw_label(self.raw_label)
|
||||
if not math.isfinite(self.confidence) or not 0.0 <= self.confidence <= 1.0:
|
||||
raise OpenVocabularySemanticError("semantic detection confidence is invalid")
|
||||
|
||||
@property
|
||||
def evidence_id(self) -> str:
|
||||
return f"evidence:{self.detection_id}"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticProposalBinding:
|
||||
proposal: ObjectProposal2D
|
||||
detections: tuple[OpenVocabularyDetection, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticFusionResult:
|
||||
bindings: tuple[SemanticProposalBinding, ...]
|
||||
input_detection_count: int
|
||||
below_confidence_count: int
|
||||
invalid_area_count: int
|
||||
outside_valid_fov_count: int
|
||||
|
||||
@property
|
||||
def proposals(self) -> tuple[ObjectProposal2D, ...]:
|
||||
return tuple(item.proposal for item in self.bindings)
|
||||
|
||||
@property
|
||||
def retained_detection_count(self) -> int:
|
||||
return sum(len(item.detections) for item in self.bindings)
|
||||
|
||||
|
||||
def load_open_vocabulary_semantic_profile(path: Path) -> OpenVocabularySemanticProfile:
|
||||
"""Load the experimental shadow profile and fail closed on authority drift."""
|
||||
|
||||
try:
|
||||
root = json.loads(path.expanduser().resolve(strict=True).read_text("utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise OpenVocabularySemanticError("semantic shadow profile cannot be read") from exc
|
||||
if not isinstance(root, dict) or root.get("schema_version") != (
|
||||
OPEN_VOCABULARY_SEMANTIC_SHADOW_PROFILE_SCHEMA
|
||||
):
|
||||
raise OpenVocabularySemanticError("semantic shadow profile schema changed")
|
||||
expected_root = {
|
||||
"schema_version",
|
||||
"profile_id",
|
||||
"status",
|
||||
"source",
|
||||
"provider",
|
||||
"postprocessing",
|
||||
"prompt_groups",
|
||||
"semantic_vocabulary_id",
|
||||
"risk_policy_id",
|
||||
"authority",
|
||||
}
|
||||
if set(root) != expected_root or root.get("status") != "experimental-shadow":
|
||||
raise OpenVocabularySemanticError("semantic shadow profile fields changed")
|
||||
source = _object(root.get("source"), "semantic source")
|
||||
provider = _object(root.get("provider"), "semantic provider")
|
||||
postprocessing = _object(root.get("postprocessing"), "semantic postprocessing")
|
||||
authority = _object(root.get("authority"), "semantic authority")
|
||||
if authority != _false_authority():
|
||||
raise OpenVocabularySemanticError("semantic shadow acquired authority")
|
||||
raw_groups = root.get("prompt_groups")
|
||||
if not isinstance(raw_groups, list):
|
||||
raise OpenVocabularySemanticError("semantic prompt groups must be an array")
|
||||
groups: list[PromptGroup] = []
|
||||
for raw_group in raw_groups:
|
||||
group = _object(raw_group, "semantic prompt group")
|
||||
if set(group) != {"prompt_set_id", "captions"}:
|
||||
raise OpenVocabularySemanticError("semantic prompt group fields changed")
|
||||
raw_captions = group.get("captions")
|
||||
if (
|
||||
not isinstance(raw_captions, list)
|
||||
or not raw_captions
|
||||
or any(not isinstance(item, str) or not item for item in raw_captions)
|
||||
):
|
||||
raise OpenVocabularySemanticError("semantic prompt captions are invalid")
|
||||
groups.append(
|
||||
PromptGroup(
|
||||
prompt_set_id=_string(group, "prompt_set_id"),
|
||||
captions=tuple(raw_captions),
|
||||
)
|
||||
)
|
||||
return OpenVocabularySemanticProfile(
|
||||
profile_id=_string(root, "profile_id"),
|
||||
session_id=_string(source, "session_id"),
|
||||
source_id=_string(source, "source_id"),
|
||||
camera_source_id=_string(source, "camera_source_id"),
|
||||
coordinate_space=_string(source, "coordinate_space"),
|
||||
width=_integer(source, "width"),
|
||||
height=_integer(source, "height"),
|
||||
valid_fov_result_id=_string(source, "valid_fov_result_id"),
|
||||
valid_fov_mask_sha256=_string(source, "valid_fov_mask_sha256"),
|
||||
valid_fov_fill_value=_integer(source, "valid_fov_fill_value"),
|
||||
provider_id=_string(provider, "provider_id"),
|
||||
provider_name=_string(provider, "name"),
|
||||
model_id=_string(provider, "model_id"),
|
||||
model_revision=_string(provider, "model_revision"),
|
||||
model_sha256=_string(provider, "model_sha256"),
|
||||
engine_sha256=_string(provider, "engine_sha256"),
|
||||
container_reference=_string(provider, "container_reference"),
|
||||
container_image_id=_string(provider, "container_image_id"),
|
||||
preprocess_id=_string(provider, "preprocess_id"),
|
||||
engine_input_width=_integer(provider, "engine_input_width"),
|
||||
engine_input_height=_integer(provider, "engine_input_height"),
|
||||
minimum_input_confidence=_number(postprocessing, "minimum_input_confidence"),
|
||||
minimum_box_area_fraction=_number(postprocessing, "minimum_box_area_fraction"),
|
||||
maximum_box_area_fraction=_number(postprocessing, "maximum_box_area_fraction"),
|
||||
minimum_valid_fov_fraction=_number(postprocessing, "minimum_valid_fov_fraction"),
|
||||
require_center_inside_valid_fov=_boolean(postprocessing, "require_center_inside_valid_fov"),
|
||||
fusion_iou_threshold=_number(postprocessing, "fusion_iou_threshold"),
|
||||
selected_minimum_confidence=_number(postprocessing, "selected_minimum_confidence"),
|
||||
selected_minimum_margin=_number(postprocessing, "selected_minimum_margin"),
|
||||
max_hypotheses=_integer(postprocessing, "max_hypotheses"),
|
||||
prompt_groups=tuple(groups),
|
||||
vocabulary_id=_string(root, "semantic_vocabulary_id"),
|
||||
risk_policy_id=_string(root, "risk_policy_id"),
|
||||
)
|
||||
|
||||
|
||||
def parse_tao_grounding_dino_labels(
|
||||
path: Path,
|
||||
*,
|
||||
source_id: str,
|
||||
frame_id: str,
|
||||
prompt_set_id: str,
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
image_width: int | None = None,
|
||||
image_height: int | None = None,
|
||||
offset_x: float = 0.0,
|
||||
offset_y: float = 0.0,
|
||||
detection_scope_id: str | None = None,
|
||||
) -> tuple[OpenVocabularyDetection, ...]:
|
||||
"""Parse one TAO label file while preserving original source-image boxes."""
|
||||
|
||||
group = profile.prompt_group(prompt_set_id)
|
||||
allowed = {normalize_raw_label(item) for item in group.captions}
|
||||
local_width = profile.width if image_width is None else image_width
|
||||
local_height = profile.height if image_height is None else image_height
|
||||
if (
|
||||
local_width < 1
|
||||
or local_height < 1
|
||||
or offset_x < 0.0
|
||||
or offset_y < 0.0
|
||||
or offset_x + local_width > profile.width
|
||||
or offset_y + local_height > profile.height
|
||||
):
|
||||
raise OpenVocabularySemanticError("semantic label image window is invalid")
|
||||
scope_id = frame_id if detection_scope_id is None else detection_scope_id
|
||||
if not scope_id:
|
||||
raise OpenVocabularySemanticError("semantic detection scope is invalid")
|
||||
resolved = path.resolve(strict=True)
|
||||
if resolved.is_symlink() or not resolved.is_file():
|
||||
raise OpenVocabularySemanticError("semantic label ledger must be a regular file")
|
||||
detections: list[OpenVocabularyDetection] = []
|
||||
for line_number, raw_line in enumerate(resolved.read_text("utf-8").splitlines(), start=1):
|
||||
if not raw_line.strip():
|
||||
continue
|
||||
parts = raw_line.split()
|
||||
if len(parts) <= TAO_GROUNDING_DINO_TRAILING_FIELDS:
|
||||
raise OpenVocabularySemanticError("TAO semantic label row is incomplete")
|
||||
label_parts = parts[:-TAO_GROUNDING_DINO_TRAILING_FIELDS]
|
||||
numeric_parts = parts[-TAO_GROUNDING_DINO_TRAILING_FIELDS:]
|
||||
raw_label = " ".join(label_parts)
|
||||
if normalize_raw_label(raw_label) not in allowed:
|
||||
raise OpenVocabularySemanticError("TAO semantic label escaped its prompt set")
|
||||
try:
|
||||
values = tuple(float(item) for item in numeric_parts)
|
||||
except ValueError as exc:
|
||||
raise OpenVocabularySemanticError("TAO semantic label row is not numeric") from exc
|
||||
if any(not math.isfinite(item) for item in values):
|
||||
raise OpenVocabularySemanticError("TAO semantic label row is not finite")
|
||||
x_min, y_min, x_max, y_max = values[3:7]
|
||||
if x_min < 0.0 or y_min < 0.0 or x_max > local_width or y_max > local_height:
|
||||
raise OpenVocabularySemanticError(
|
||||
"TAO semantic box is not in the declared raw image coordinate space"
|
||||
)
|
||||
detections.append(
|
||||
OpenVocabularyDetection(
|
||||
detection_id=(f"{scope_id}:{prompt_set_id}:label-{line_number:04d}"),
|
||||
source_id=source_id,
|
||||
frame_id=frame_id,
|
||||
prompt_set_id=prompt_set_id,
|
||||
raw_label=raw_label,
|
||||
confidence=values[-1],
|
||||
region=BoundingRegion2D(
|
||||
x_min + offset_x,
|
||||
y_min + offset_y,
|
||||
x_max + offset_x,
|
||||
y_max + offset_y,
|
||||
),
|
||||
)
|
||||
)
|
||||
return tuple(detections)
|
||||
|
||||
|
||||
def fuse_open_vocabulary_detections(
|
||||
detections: tuple[OpenVocabularyDetection, ...],
|
||||
*,
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
valid_fov_mask: NDArray[np.bool_],
|
||||
) -> SemanticFusionResult:
|
||||
"""Fuse prompt collisions spatially before the geometry provider owns points."""
|
||||
|
||||
if vocabulary.vocabulary_id != profile.vocabulary_id:
|
||||
raise OpenVocabularySemanticError("semantic profile and vocabulary disagree")
|
||||
if profile.max_hypotheses > vocabulary.max_hypotheses:
|
||||
raise OpenVocabularySemanticError("semantic profile exceeds vocabulary top-k")
|
||||
if not detections:
|
||||
return SemanticFusionResult((), 0, 0, 0, 0)
|
||||
if valid_fov_mask.shape != (profile.height, profile.width) or valid_fov_mask.dtype != np.bool_:
|
||||
raise OpenVocabularySemanticError("semantic valid-FOV mask is incompatible")
|
||||
source_ids = {item.source_id for item in detections}
|
||||
frame_ids = {item.frame_id for item in detections}
|
||||
if source_ids != {profile.source_id} or len(frame_ids) != 1:
|
||||
raise OpenVocabularySemanticError("semantic detections escaped one source frame")
|
||||
below_confidence = 0
|
||||
invalid_area = 0
|
||||
outside_valid_fov = 0
|
||||
retained: list[OpenVocabularyDetection] = []
|
||||
raster_area = float(profile.width * profile.height)
|
||||
for detection in detections:
|
||||
profile.prompt_group(detection.prompt_set_id)
|
||||
if vocabulary.resolve_label(detection.raw_label) is None:
|
||||
raise OpenVocabularySemanticError("semantic label is not in the vocabulary")
|
||||
if detection.confidence < profile.minimum_input_confidence:
|
||||
below_confidence += 1
|
||||
continue
|
||||
area_fraction = _area(detection.region) / raster_area
|
||||
if not (
|
||||
profile.minimum_box_area_fraction <= area_fraction <= profile.maximum_box_area_fraction
|
||||
):
|
||||
invalid_area += 1
|
||||
continue
|
||||
valid_fraction, center_inside = _valid_fov_support(detection.region, valid_fov_mask)
|
||||
if valid_fraction < profile.minimum_valid_fov_fraction or (
|
||||
profile.require_center_inside_valid_fov and not center_inside
|
||||
):
|
||||
outside_valid_fov += 1
|
||||
continue
|
||||
retained.append(detection)
|
||||
retained.sort(key=_detection_priority)
|
||||
clusters: list[list[OpenVocabularyDetection]] = []
|
||||
for detection in retained:
|
||||
spatial_candidates = tuple(
|
||||
(index, max(_iou(detection.region, item.region) for item in cluster))
|
||||
for index, cluster in enumerate(clusters)
|
||||
)
|
||||
match = max(spatial_candidates, key=lambda item: (item[1], -item[0]), default=None)
|
||||
if match is not None and match[1] >= profile.fusion_iou_threshold:
|
||||
clusters[match[0]].append(detection)
|
||||
else:
|
||||
clusters.append([detection])
|
||||
frame_id = next(iter(frame_ids))
|
||||
bindings: list[SemanticProposalBinding] = []
|
||||
for ordinal, cluster in enumerate(clusters):
|
||||
ordered = tuple(sorted(cluster, key=_detection_priority))
|
||||
semantic_candidates = _canonical_candidates(ordered, vocabulary, profile.max_hypotheses)
|
||||
if not semantic_candidates:
|
||||
raise OpenVocabularySemanticError("semantic cluster lost all hypotheses")
|
||||
anchor = ordered[0]
|
||||
proposal_id = f"semantic-{frame_id}-{ordinal:04d}"
|
||||
proposal = ObjectProposal2D(
|
||||
proposal_id=proposal_id,
|
||||
source_id=anchor.source_id,
|
||||
frame_id=anchor.frame_id,
|
||||
region=anchor.region,
|
||||
objectness=anchor.confidence,
|
||||
provider_id=profile.provider_id,
|
||||
model_id=profile.model_id,
|
||||
preprocess_id=profile.preprocess_id,
|
||||
semantic_hint=semantic_candidates[0][0],
|
||||
)
|
||||
bindings.append(SemanticProposalBinding(proposal=proposal, detections=ordered))
|
||||
return SemanticFusionResult(
|
||||
bindings=tuple(bindings),
|
||||
input_detection_count=len(detections),
|
||||
below_confidence_count=below_confidence,
|
||||
invalid_area_count=invalid_area,
|
||||
outside_valid_fov_count=outside_valid_fov,
|
||||
)
|
||||
|
||||
|
||||
def bind_object_understandings(
|
||||
observations: tuple[ObstacleObservation, ...],
|
||||
*,
|
||||
bindings: tuple[SemanticProposalBinding, ...],
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
generated_monotonic_ns: int,
|
||||
) -> tuple[ObjectUnderstanding, ...]:
|
||||
"""Compose semantic hypotheses around geometry-owned obstacle observations."""
|
||||
|
||||
by_proposal = {item.proposal.proposal_id: item for item in bindings}
|
||||
if len(by_proposal) != len(bindings):
|
||||
raise OpenVocabularySemanticError("semantic proposal bindings are duplicated")
|
||||
understandings: list[ObjectUnderstanding] = []
|
||||
seen_proposals: set[str] = set()
|
||||
for observation in observations:
|
||||
if not observation.proposal_ids:
|
||||
understanding = _unknown_understanding(
|
||||
observation,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=generated_monotonic_ns,
|
||||
reason="geometry-only-semantic-evidence-unavailable",
|
||||
)
|
||||
else:
|
||||
if len(observation.proposal_ids) != 1:
|
||||
raise OpenVocabularySemanticError("semantic observation ownership is ambiguous")
|
||||
proposal_id = observation.proposal_ids[0]
|
||||
binding = by_proposal.get(proposal_id)
|
||||
if binding is None:
|
||||
raise OpenVocabularySemanticError(
|
||||
"geometry references an unknown semantic proposal"
|
||||
)
|
||||
seen_proposals.add(proposal_id)
|
||||
understanding = _semantic_understanding(
|
||||
observation,
|
||||
detections=binding.detections,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=generated_monotonic_ns,
|
||||
)
|
||||
validate_object_understanding(understanding, vocabulary)
|
||||
understandings.append(understanding)
|
||||
if seen_proposals != set(by_proposal):
|
||||
raise OpenVocabularySemanticError("a semantic proposal has no geometry observation")
|
||||
return tuple(understandings)
|
||||
|
||||
|
||||
def understand_geometry_observation(
|
||||
observation: ObstacleObservation,
|
||||
*,
|
||||
detections: tuple[OpenVocabularyDetection, ...],
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
generated_monotonic_ns: int,
|
||||
) -> ObjectUnderstanding:
|
||||
"""Attach ROI semantics directly to geometry without changing its identity."""
|
||||
|
||||
if not detections:
|
||||
result = _unknown_understanding(
|
||||
observation,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=generated_monotonic_ns,
|
||||
reason="geometry-roi-semantic-evidence-unavailable",
|
||||
)
|
||||
else:
|
||||
result = _semantic_understanding(
|
||||
observation,
|
||||
detections=detections,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=generated_monotonic_ns,
|
||||
)
|
||||
validate_object_understanding(result, vocabulary)
|
||||
return result
|
||||
|
||||
|
||||
def _semantic_understanding(
|
||||
observation: ObstacleObservation,
|
||||
*,
|
||||
detections: tuple[OpenVocabularyDetection, ...],
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
generated_monotonic_ns: int,
|
||||
) -> ObjectUnderstanding:
|
||||
candidates = _canonical_candidates(
|
||||
detections,
|
||||
vocabulary,
|
||||
profile.max_hypotheses,
|
||||
)
|
||||
hypotheses: list[SemanticHypothesis] = []
|
||||
referenced: dict[str, OpenVocabularyDetection] = {}
|
||||
for rank, (class_id, raw_label, confidence, evidence) in enumerate(candidates, start=1):
|
||||
for detection in evidence:
|
||||
referenced[detection.evidence_id] = detection
|
||||
hypotheses.append(
|
||||
SemanticHypothesis(
|
||||
rank=rank,
|
||||
class_id=class_id,
|
||||
raw_label=raw_label,
|
||||
confidence=confidence,
|
||||
evidence_ids=tuple(item.evidence_id for item in evidence),
|
||||
)
|
||||
)
|
||||
top = hypotheses[0]
|
||||
runner_up = hypotheses[1] if len(hypotheses) > 1 else None
|
||||
if top.confidence < profile.selected_minimum_confidence:
|
||||
semantic = SemanticDecision(
|
||||
resolution=SemanticResolution.UNRESOLVED,
|
||||
selected_class_id=None,
|
||||
selected_confidence=None,
|
||||
reason_codes=("top-hypothesis-below-selection-threshold",),
|
||||
)
|
||||
elif (
|
||||
runner_up is not None
|
||||
and top.confidence - runner_up.confidence < profile.selected_minimum_margin
|
||||
):
|
||||
semantic = SemanticDecision(
|
||||
resolution=SemanticResolution.AMBIGUOUS,
|
||||
selected_class_id=None,
|
||||
selected_confidence=None,
|
||||
reason_codes=("top-hypothesis-margin-insufficient",),
|
||||
)
|
||||
else:
|
||||
semantic = SemanticDecision(
|
||||
resolution=SemanticResolution.SELECTED,
|
||||
selected_class_id=top.class_id,
|
||||
selected_confidence=top.confidence,
|
||||
reason_codes=("top-hypothesis-qualified",),
|
||||
)
|
||||
if semantic.resolution is SemanticResolution.SELECTED:
|
||||
definition = vocabulary.class_definition(top.class_id)
|
||||
agency = definition.agency_prior
|
||||
if agency is AgencyState.UNKNOWN:
|
||||
agency_basis = StateBasis.UNKNOWN
|
||||
state_evidence: tuple[str, ...] = ()
|
||||
state_reasons: tuple[str, ...] = (
|
||||
"observed-motion-unavailable",
|
||||
"selected-class-has-no-agency-prior",
|
||||
)
|
||||
else:
|
||||
agency_basis = StateBasis.CLASS_PRIOR
|
||||
state_evidence = top.evidence_ids
|
||||
state_reasons = (
|
||||
"observed-motion-unavailable",
|
||||
"agency-from-selected-class-prior",
|
||||
)
|
||||
else:
|
||||
agency = AgencyState.UNKNOWN
|
||||
agency_basis = StateBasis.UNKNOWN
|
||||
state_evidence = ()
|
||||
state_reasons = ("observed-motion-and-resolved-agency-unavailable",)
|
||||
provenance = tuple(
|
||||
EvidenceProvenance(
|
||||
evidence_id=detection.evidence_id,
|
||||
kind=EvidenceKind.DETECTOR,
|
||||
source_id=observation.source_id,
|
||||
frame_id=observation.frame_id,
|
||||
provider_id=profile.provider_id,
|
||||
model_id=profile.model_id,
|
||||
model_revision=profile.model_revision,
|
||||
preprocess_id=profile.preprocess_id,
|
||||
prompt_set_id=detection.prompt_set_id,
|
||||
)
|
||||
for detection in sorted(referenced.values(), key=lambda item: item.evidence_id)
|
||||
)
|
||||
return ObjectUnderstanding(
|
||||
understanding_id=f"{observation.observation_id}:understanding",
|
||||
vocabulary_id=vocabulary.vocabulary_id,
|
||||
generated_monotonic_ns=generated_monotonic_ns,
|
||||
observation=observation,
|
||||
hypotheses=tuple(hypotheses),
|
||||
semantic=semantic,
|
||||
state=ObjectStateEstimate(
|
||||
motion=MotionState.UNKNOWN,
|
||||
motion_confidence=0.0,
|
||||
agency=agency,
|
||||
agency_basis=agency_basis,
|
||||
evidence_ids=state_evidence,
|
||||
reason_codes=state_reasons,
|
||||
),
|
||||
risk=_unknown_risk(profile, "semantic-shadow-has-no-risk-authority"),
|
||||
provenance=provenance,
|
||||
)
|
||||
|
||||
|
||||
def _unknown_understanding(
|
||||
observation: ObstacleObservation,
|
||||
*,
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
generated_monotonic_ns: int,
|
||||
reason: str,
|
||||
) -> ObjectUnderstanding:
|
||||
return ObjectUnderstanding(
|
||||
understanding_id=f"{observation.observation_id}:understanding",
|
||||
vocabulary_id=vocabulary.vocabulary_id,
|
||||
generated_monotonic_ns=generated_monotonic_ns,
|
||||
observation=observation,
|
||||
hypotheses=(),
|
||||
semantic=SemanticDecision(
|
||||
resolution=SemanticResolution.UNRESOLVED,
|
||||
selected_class_id=None,
|
||||
selected_confidence=None,
|
||||
reason_codes=(reason,),
|
||||
),
|
||||
state=ObjectStateEstimate(
|
||||
motion=MotionState.UNKNOWN,
|
||||
motion_confidence=0.0,
|
||||
agency=AgencyState.UNKNOWN,
|
||||
agency_basis=StateBasis.UNKNOWN,
|
||||
evidence_ids=(),
|
||||
reason_codes=("state-evidence-unavailable",),
|
||||
),
|
||||
risk=_unknown_risk(profile, "unknown-object-remains-route-around-obstacle"),
|
||||
provenance=(),
|
||||
)
|
||||
|
||||
|
||||
def _unknown_risk(
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
reason: str,
|
||||
) -> AdvisoryRiskAssessment:
|
||||
return AdvisoryRiskAssessment(
|
||||
policy_id=profile.risk_policy_id,
|
||||
level=RiskLevel.UNKNOWN,
|
||||
confidence=0.0,
|
||||
basis=RiskBasis.UNKNOWN,
|
||||
responses=(AdvisoryResponse.ROUTE_AROUND,),
|
||||
evidence_ids=(),
|
||||
reason_codes=(reason,),
|
||||
)
|
||||
|
||||
|
||||
def _canonical_candidates(
|
||||
detections: tuple[OpenVocabularyDetection, ...],
|
||||
vocabulary: ObjectSemanticVocabulary,
|
||||
maximum: int,
|
||||
) -> tuple[tuple[str, str, float, tuple[OpenVocabularyDetection, ...]], ...]:
|
||||
by_class: dict[str, list[OpenVocabularyDetection]] = {}
|
||||
for detection in detections:
|
||||
class_id = vocabulary.resolve_label(detection.raw_label)
|
||||
if class_id is None:
|
||||
raise OpenVocabularySemanticError("semantic label is not in the vocabulary")
|
||||
by_class.setdefault(class_id, []).append(detection)
|
||||
candidates: list[tuple[str, str, float, tuple[OpenVocabularyDetection, ...]]] = []
|
||||
for class_id, evidence in by_class.items():
|
||||
ordered = tuple(sorted(evidence, key=_detection_priority))
|
||||
candidates.append((class_id, ordered[0].raw_label, ordered[0].confidence, ordered))
|
||||
candidates.sort(key=lambda item: (-item[2], item[0], normalize_raw_label(item[1])))
|
||||
return tuple(candidates[:maximum])
|
||||
|
||||
|
||||
def _detection_priority(item: OpenVocabularyDetection) -> tuple[float, float, str]:
|
||||
return (-item.confidence, _area(item.region), item.detection_id)
|
||||
|
||||
|
||||
def _area(region: BoundingRegion2D) -> float:
|
||||
return (region.x_max - region.x_min) * (region.y_max - region.y_min)
|
||||
|
||||
|
||||
def _iou(left: BoundingRegion2D, right: BoundingRegion2D) -> float:
|
||||
x_min = max(left.x_min, right.x_min)
|
||||
y_min = max(left.y_min, right.y_min)
|
||||
x_max = min(left.x_max, right.x_max)
|
||||
y_max = min(left.y_max, right.y_max)
|
||||
intersection = max(0.0, x_max - x_min) * max(0.0, y_max - y_min)
|
||||
union = _area(left) + _area(right) - intersection
|
||||
return 0.0 if union <= 0.0 else intersection / union
|
||||
|
||||
|
||||
def _valid_fov_support(
|
||||
region: BoundingRegion2D,
|
||||
mask: NDArray[np.bool_],
|
||||
) -> tuple[float, bool]:
|
||||
height, width = mask.shape
|
||||
x_min = int(np.clip(math.floor(region.x_min), 0, width))
|
||||
y_min = int(np.clip(math.floor(region.y_min), 0, height))
|
||||
x_max = int(np.clip(math.ceil(region.x_max), 0, width))
|
||||
y_max = int(np.clip(math.ceil(region.y_max), 0, height))
|
||||
area = max(0, x_max - x_min) * max(0, y_max - y_min)
|
||||
if area == 0:
|
||||
return 0.0, False
|
||||
valid_fraction = float(np.count_nonzero(mask[y_min:y_max, x_min:x_max])) / area
|
||||
center_x = int(np.clip(round((region.x_min + region.x_max) / 2.0), 0, width - 1))
|
||||
center_y = int(np.clip(round((region.y_min + region.y_max) / 2.0), 0, height - 1))
|
||||
return valid_fraction, bool(mask[center_y, center_x])
|
||||
|
||||
|
||||
def _false_authority() -> dict[str, bool]:
|
||||
return {
|
||||
"ground_truth": False,
|
||||
"independent_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
def _object(value: object, label: str) -> dict[str, object]:
|
||||
if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
|
||||
raise OpenVocabularySemanticError(f"{label} must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _string(document: dict[str, object], key: str) -> str:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, str) or not value:
|
||||
raise OpenVocabularySemanticError(f"{key} must be a nonempty string")
|
||||
return value
|
||||
|
||||
|
||||
def _integer(document: dict[str, object], key: str) -> int:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, int) or isinstance(value, bool):
|
||||
raise OpenVocabularySemanticError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
|
||||
def _number(document: dict[str, object], key: str) -> float:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, (int, float)) or isinstance(value, bool):
|
||||
raise OpenVocabularySemanticError(f"{key} must be numeric")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _boolean(document: dict[str, object], key: str) -> bool:
|
||||
value = document.get(key)
|
||||
if not isinstance(value, bool):
|
||||
raise OpenVocabularySemanticError(f"{key} must be boolean")
|
||||
return value
|
||||
|
||||
|
||||
__all__ = [
|
||||
"OPEN_VOCABULARY_SEMANTIC_SHADOW_PROFILE_SCHEMA",
|
||||
"OpenVocabularyDetection",
|
||||
"OpenVocabularySemanticError",
|
||||
"OpenVocabularySemanticProfile",
|
||||
"PromptGroup",
|
||||
"SemanticFusionResult",
|
||||
"SemanticProposalBinding",
|
||||
"bind_object_understandings",
|
||||
"fuse_open_vocabulary_detections",
|
||||
"load_open_vocabulary_semantic_profile",
|
||||
"parse_tao_grounding_dino_labels",
|
||||
"understand_geometry_observation",
|
||||
]
|
||||
@@ -188,20 +188,26 @@ class DecodedRecordedSource:
|
||||
|
||||
def packets(self, stop_event: Event) -> Iterator[SourcePacket]:
|
||||
images = self.decoder.frames(stop_event)
|
||||
try:
|
||||
image: NDArray[np.uint8] | None = next(images)
|
||||
except StopIteration as exc:
|
||||
if stop_event.is_set():
|
||||
return
|
||||
raise RecordedSourceError("decoded image stream is empty") from exc
|
||||
for packet in self.source.packets(stop_event):
|
||||
try:
|
||||
image = next(images)
|
||||
except StopIteration as exc:
|
||||
if image is None:
|
||||
raise RecordedSourceError(
|
||||
"decoded image stream ended before source timeline"
|
||||
) from exc
|
||||
)
|
||||
if image.shape != (600, 800, 3) or image.dtype != np.uint8:
|
||||
raise RecordedSourceError("decoded image raster is incompatible")
|
||||
yield replace(packet, image_payload=image)
|
||||
if not stop_event.is_set():
|
||||
try:
|
||||
next(images)
|
||||
image = next(images)
|
||||
except StopIteration:
|
||||
image = None
|
||||
if not stop_event.is_set():
|
||||
if image is None:
|
||||
return
|
||||
raise RecordedSourceError("decoded image stream exceeds source timeline")
|
||||
|
||||
|
||||
@@ -0,0 +1,401 @@
|
||||
"""Pinned RF-DETR-L TensorRT shadow detector for behavior-relevant COCO classes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import math
|
||||
import urllib.parse
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
from typing import Final, Protocol, cast
|
||||
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from .yolox_object_detector import COCO_CLASSES, ImageResizer, OpenCvBilinearResizer
|
||||
|
||||
RF_DETR_MODEL_ID: Final = "rf_detr_large"
|
||||
RF_DETR_MODEL_VERSION: Final = 1
|
||||
RF_DETR_CHECKPOINT_SHA256: Final = (
|
||||
"0f4e20e19a99c0f8a62b5685f57f6c8b5c371c59081feda6752a0561a79ccf38"
|
||||
)
|
||||
RF_DETR_ONNX_SHA256: Final = (
|
||||
"9c1948e56bbb6ff03349012b8bb334cacaf8ae480f22caa0704ee70de9a72300"
|
||||
)
|
||||
RF_DETR_FP16_ONNX_SHA256: Final = (
|
||||
"9015fcc1317f268ce866bed6b5a33132c24963e1502b02f145fa184e11de5ecb"
|
||||
)
|
||||
RF_DETR_ENGINE_SHA256: Final = (
|
||||
"986399ce706b7380472cf5e473232249fed6e628971d8007f6609e83128d46b8"
|
||||
)
|
||||
COCO_SPARSE_IDS: Final = (
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21,
|
||||
22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
|
||||
43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
|
||||
61, 62, 63, 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
|
||||
82, 84, 85, 86, 87, 88, 89, 90,
|
||||
)
|
||||
COCO_SPARSE_TO_CONTIGUOUS: Final = {
|
||||
sparse_id: contiguous_id for contiguous_id, sparse_id in enumerate(COCO_SPARSE_IDS)
|
||||
}
|
||||
RISK_CLASS_IDS: Final = (
|
||||
0, # person
|
||||
1, # bicycle
|
||||
2, # car
|
||||
3, # motorcycle
|
||||
5, # bus
|
||||
7, # truck
|
||||
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, # animals
|
||||
36, # skateboard / light road user proxy
|
||||
)
|
||||
_MEANS: Final = np.asarray((0.485, 0.456, 0.406), dtype=np.float32)
|
||||
_STDS: Final = np.asarray((0.229, 0.224, 0.225), dtype=np.float32)
|
||||
|
||||
|
||||
class RfDetrDetectorError(RuntimeError):
|
||||
"""The RF-DETR profile, tensor or inference response is incompatible."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RfDetrConfig:
|
||||
source_width: int = 800
|
||||
source_height: int = 600
|
||||
input_width: int = 704
|
||||
input_height: int = 704
|
||||
fill_value: int = 114
|
||||
minimum_score: float = 0.25
|
||||
target_class_ids: tuple[int, ...] = RISK_CLASS_IDS
|
||||
maximum_detections: int = 300
|
||||
minimum_box_area_pixels: float = 64.0
|
||||
maximum_box_area_fraction: float = 0.5
|
||||
minimum_valid_fov_fraction: float = 0.5
|
||||
require_center_inside_valid_fov: bool = True
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (
|
||||
self.source_width,
|
||||
self.source_height,
|
||||
self.input_width,
|
||||
self.input_height,
|
||||
self.fill_value,
|
||||
self.minimum_score,
|
||||
self.target_class_ids,
|
||||
self.maximum_detections,
|
||||
self.minimum_box_area_pixels,
|
||||
self.maximum_box_area_fraction,
|
||||
self.minimum_valid_fov_fraction,
|
||||
self.require_center_inside_valid_fov,
|
||||
) != (
|
||||
800,
|
||||
600,
|
||||
704,
|
||||
704,
|
||||
114,
|
||||
0.25,
|
||||
RISK_CLASS_IDS,
|
||||
300,
|
||||
64.0,
|
||||
0.5,
|
||||
0.5,
|
||||
True,
|
||||
):
|
||||
raise RfDetrDetectorError("RF-DETR shadow profile cannot be tuned in place")
|
||||
|
||||
|
||||
RF_DETR_CONFIG: Final = RfDetrConfig()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RfDetrRawOutput:
|
||||
boxes: NDArray[np.float16]
|
||||
logits: NDArray[np.float16]
|
||||
|
||||
|
||||
class RfDetrInferenceBackend(Protocol):
|
||||
def infer(self, tensor: NDArray[np.float32]) -> RfDetrRawOutput: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RfDetrDetection:
|
||||
class_id: int
|
||||
label: str
|
||||
score: float
|
||||
bbox_xyxy: tuple[float, float, float, float]
|
||||
valid_fov_fraction: float
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not 0 <= self.class_id < len(COCO_CLASSES):
|
||||
raise RfDetrDetectorError("RF-DETR class id is invalid")
|
||||
if self.label != COCO_CLASSES[self.class_id]:
|
||||
raise RfDetrDetectorError("RF-DETR class label is invalid")
|
||||
if not math.isfinite(self.score) or not 0.0 <= self.score <= 1.0:
|
||||
raise RfDetrDetectorError("RF-DETR score is invalid")
|
||||
x1, y1, x2, y2 = self.bbox_xyxy
|
||||
if not all(math.isfinite(value) for value in self.bbox_xyxy) or not (
|
||||
0.0 <= x1 < x2 <= 800.0 and 0.0 <= y1 < y2 <= 600.0
|
||||
):
|
||||
raise RfDetrDetectorError("RF-DETR source bounding box is invalid")
|
||||
if not 0.0 <= self.valid_fov_fraction <= 1.0:
|
||||
raise RfDetrDetectorError("RF-DETR valid-FOV fraction is invalid")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RfDetrPostprocessResult:
|
||||
detections: tuple[RfDetrDetection, ...]
|
||||
rejected: tuple[tuple[str, int], ...]
|
||||
|
||||
|
||||
class TritonRfDetrHttpInferenceBackend:
|
||||
"""Persistent Triton V2 HTTP transport for the strongly typed FP16 engine."""
|
||||
|
||||
def __init__(self, endpoint: str, *, timeout_seconds: float = 60.0) -> None:
|
||||
parsed = urllib.parse.urlsplit(endpoint)
|
||||
if (
|
||||
parsed.scheme != "http"
|
||||
or not parsed.hostname
|
||||
or parsed.username is not None
|
||||
or parsed.password is not None
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
):
|
||||
raise RfDetrDetectorError("Triton endpoint must be an explicit HTTP origin")
|
||||
if not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
|
||||
raise RfDetrDetectorError("Triton timeout must be positive")
|
||||
self.path = (
|
||||
f"{parsed.path.rstrip('/')}/v2/models/{RF_DETR_MODEL_ID}"
|
||||
f"/versions/{RF_DETR_MODEL_VERSION}/infer"
|
||||
)
|
||||
self.connection = http.client.HTTPConnection(
|
||||
parsed.hostname,
|
||||
parsed.port or 80,
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self.connection.close()
|
||||
|
||||
def infer(self, tensor: NDArray[np.float32]) -> RfDetrRawOutput:
|
||||
contiguous = np.ascontiguousarray(tensor, dtype=np.float32)
|
||||
if contiguous.shape != (1, 3, 704, 704) or not np.isfinite(contiguous).all():
|
||||
raise RfDetrDetectorError("Triton RF-DETR input tensor is incompatible")
|
||||
binary = contiguous.tobytes()
|
||||
header = {
|
||||
"inputs": [
|
||||
{
|
||||
"name": "input",
|
||||
"shape": [1, 3, 704, 704],
|
||||
"datatype": "FP32",
|
||||
"parameters": {"binary_data_size": len(binary)},
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{"name": "dets", "parameters": {"binary_data": True}},
|
||||
{"name": "labels", "parameters": {"binary_data": True}},
|
||||
],
|
||||
}
|
||||
encoded = json.dumps(header, sort_keys=True, separators=(",", ":")).encode()
|
||||
self.connection.request(
|
||||
"POST",
|
||||
self.path,
|
||||
body=encoded + binary,
|
||||
headers={
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Inference-Header-Content-Length": str(len(encoded)),
|
||||
},
|
||||
)
|
||||
response = self.connection.getresponse()
|
||||
payload = response.read()
|
||||
if response.status != 200:
|
||||
raise RfDetrDetectorError(
|
||||
f"Triton RF-DETR inference failed with HTTP {response.status}"
|
||||
)
|
||||
header_value = response.getheader("Inference-Header-Content-Length")
|
||||
try:
|
||||
header_length = int(header_value or "")
|
||||
descriptor = json.loads(payload[:header_length])
|
||||
outputs = descriptor["outputs"]
|
||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
|
||||
raise RfDetrDetectorError("Triton RF-DETR output descriptor is invalid") from exc
|
||||
if not isinstance(outputs, list) or len(outputs) != 2:
|
||||
raise RfDetrDetectorError("Triton RF-DETR output count changed")
|
||||
offset = header_length
|
||||
arrays: dict[str, NDArray[np.float16]] = {}
|
||||
for output, expected_name, expected_shape in zip(
|
||||
outputs,
|
||||
("dets", "labels"),
|
||||
((1, 300, 4), (1, 300, 91)),
|
||||
strict=True,
|
||||
):
|
||||
try:
|
||||
name = output["name"]
|
||||
datatype = output["datatype"]
|
||||
shape = tuple(int(value) for value in output["shape"])
|
||||
byte_length = int(output["parameters"]["binary_data_size"])
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise RfDetrDetectorError(
|
||||
"Triton RF-DETR output descriptor is incomplete"
|
||||
) from exc
|
||||
expected_bytes = math.prod(expected_shape) * np.dtype("<f2").itemsize
|
||||
if (
|
||||
name != expected_name
|
||||
or datatype != "FP16"
|
||||
or shape != expected_shape
|
||||
or byte_length != expected_bytes
|
||||
or offset + byte_length > len(payload)
|
||||
):
|
||||
raise RfDetrDetectorError("Triton RF-DETR output identity changed")
|
||||
array = np.frombuffer(payload[offset : offset + byte_length], dtype="<f2")
|
||||
arrays[name] = np.asarray(array.reshape(shape), dtype=np.float16)
|
||||
offset += byte_length
|
||||
if offset != len(payload):
|
||||
raise RfDetrDetectorError("Triton RF-DETR output byte length changed")
|
||||
return RfDetrRawOutput(boxes=arrays["dets"], logits=arrays["labels"])
|
||||
|
||||
|
||||
def preprocess_raw_kb4_rf_detr(
|
||||
image_bgr: NDArray[np.uint8],
|
||||
mask: NDArray[np.bool_],
|
||||
*,
|
||||
config: RfDetrConfig = RF_DETR_CONFIG,
|
||||
resizer: ImageResizer | None = None,
|
||||
) -> NDArray[np.float32]:
|
||||
if image_bgr.shape != (config.source_height, config.source_width, 3):
|
||||
raise RfDetrDetectorError("raw KB4 image raster changed")
|
||||
if image_bgr.dtype != np.uint8 or mask.shape != image_bgr.shape[:2] or mask.dtype != np.bool_:
|
||||
raise RfDetrDetectorError("raw KB4 image or valid-FOV mask type changed")
|
||||
masked_bgr = np.where(mask[..., None], image_bgr, config.fill_value).astype(np.uint8)
|
||||
rgb = np.ascontiguousarray(masked_bgr[:, :, ::-1])
|
||||
resized = (resizer or OpenCvBilinearResizer()).resize(
|
||||
rgb,
|
||||
config.input_width,
|
||||
config.input_height,
|
||||
)
|
||||
if resized.shape != (config.input_height, config.input_width, 3):
|
||||
raise RfDetrDetectorError("resize backend returned an incompatible raster")
|
||||
normalized = resized.astype(np.float32) / 255.0
|
||||
normalized = (normalized - _MEANS) / _STDS
|
||||
return np.ascontiguousarray(normalized.transpose(2, 0, 1), dtype=np.float32)[None]
|
||||
|
||||
|
||||
def postprocess_rf_detr(
|
||||
output: RfDetrRawOutput,
|
||||
mask: NDArray[np.bool_],
|
||||
*,
|
||||
config: RfDetrConfig = RF_DETR_CONFIG,
|
||||
) -> RfDetrPostprocessResult:
|
||||
if output.boxes.shape != (1, 300, 4) or output.logits.shape != (1, 300, 91):
|
||||
raise RfDetrDetectorError("RF-DETR output tensor shapes are incompatible")
|
||||
if output.boxes.dtype != np.float16 or output.logits.dtype != np.float16:
|
||||
raise RfDetrDetectorError("RF-DETR output tensor types are incompatible")
|
||||
if not np.isfinite(output.boxes).all() or not np.isfinite(output.logits).all():
|
||||
raise RfDetrDetectorError("RF-DETR output contains non-finite values")
|
||||
if mask.shape != (config.source_height, config.source_width) or mask.dtype != np.bool_:
|
||||
raise RfDetrDetectorError("valid-FOV mask is incompatible")
|
||||
logits = output.logits[0].astype(np.float32)
|
||||
probabilities = 1.0 / (1.0 + np.exp(-np.clip(logits, -80.0, 80.0)))
|
||||
flattened = probabilities.reshape(-1)
|
||||
topk = np.argsort(-flattened, kind="stable")[: config.maximum_detections]
|
||||
integral = np.pad(mask.astype(np.int64), ((1, 0), (1, 0))).cumsum(0).cumsum(1)
|
||||
rejected: Counter[str] = Counter()
|
||||
result: list[RfDetrDetection] = []
|
||||
for flat_index in topk:
|
||||
score = float(flattened[flat_index])
|
||||
if score <= config.minimum_score:
|
||||
continue
|
||||
query_index = int(flat_index // output.logits.shape[2])
|
||||
sparse_class_id = int(flat_index % output.logits.shape[2])
|
||||
class_id = COCO_SPARSE_TO_CONTIGUOUS.get(sparse_class_id)
|
||||
if class_id is None:
|
||||
rejected["unmapped-class-slot"] += 1
|
||||
continue
|
||||
if class_id not in config.target_class_ids:
|
||||
rejected["non-risk-class"] += 1
|
||||
continue
|
||||
center_x, center_y, box_width, box_height = (
|
||||
float(value) for value in output.boxes[0, query_index].astype(np.float32)
|
||||
)
|
||||
box = np.asarray(
|
||||
(
|
||||
(center_x - box_width / 2.0) * config.source_width,
|
||||
(center_y - box_height / 2.0) * config.source_height,
|
||||
(center_x + box_width / 2.0) * config.source_width,
|
||||
(center_y + box_height / 2.0) * config.source_height,
|
||||
),
|
||||
dtype=np.float32,
|
||||
)
|
||||
box[[0, 2]] = np.clip(box[[0, 2]], 0, config.source_width)
|
||||
box[[1, 3]] = np.clip(box[[1, 3]], 0, config.source_height)
|
||||
fraction, center_inside, area = _valid_fraction(box, integral)
|
||||
if area < config.minimum_box_area_pixels:
|
||||
rejected["small-box"] += 1
|
||||
continue
|
||||
if area / (config.source_width * config.source_height) > config.maximum_box_area_fraction:
|
||||
rejected["large-box"] += 1
|
||||
continue
|
||||
if fraction < config.minimum_valid_fov_fraction:
|
||||
rejected["outside-valid-fov"] += 1
|
||||
continue
|
||||
if config.require_center_inside_valid_fov and not center_inside:
|
||||
rejected["center-outside-valid-fov"] += 1
|
||||
continue
|
||||
result.append(
|
||||
RfDetrDetection(
|
||||
class_id=class_id,
|
||||
label=COCO_CLASSES[class_id],
|
||||
score=round(score, 9),
|
||||
bbox_xyxy=cast(
|
||||
tuple[float, float, float, float],
|
||||
tuple(round(float(value), 6) for value in box),
|
||||
),
|
||||
valid_fov_fraction=round(fraction, 6),
|
||||
)
|
||||
)
|
||||
result.sort(key=lambda item: (-item.score, item.class_id))
|
||||
return RfDetrPostprocessResult(tuple(result), tuple(sorted(rejected.items())))
|
||||
|
||||
|
||||
def _valid_fraction(
|
||||
box: NDArray[np.float32], integral: NDArray[np.int64]
|
||||
) -> tuple[float, bool, float]:
|
||||
height = integral.shape[0] - 1
|
||||
width = integral.shape[1] - 1
|
||||
x1 = int(np.clip(math.floor(float(box[0])), 0, width))
|
||||
y1 = int(np.clip(math.floor(float(box[1])), 0, height))
|
||||
x2 = int(np.clip(math.ceil(float(box[2])), 0, width))
|
||||
y2 = int(np.clip(math.ceil(float(box[3])), 0, height))
|
||||
area = float(max(0, x2 - x1) * max(0, y2 - y1))
|
||||
if area <= 0:
|
||||
return 0.0, False, 0.0
|
||||
inside = integral[y2, x2] - integral[y1, x2] - integral[y2, x1] + integral[y1, x1]
|
||||
center_x = int(np.clip(round((float(box[0]) + float(box[2])) / 2.0), 0, width - 1))
|
||||
center_y = int(np.clip(round((float(box[1]) + float(box[3])) / 2.0), 0, height - 1))
|
||||
center_inside = bool(
|
||||
integral[center_y + 1, center_x + 1]
|
||||
- integral[center_y, center_x + 1]
|
||||
- integral[center_y + 1, center_x]
|
||||
+ integral[center_y, center_x]
|
||||
)
|
||||
return float(inside) / area, center_inside, area
|
||||
|
||||
|
||||
__all__ = [
|
||||
"COCO_SPARSE_IDS",
|
||||
"RF_DETR_CHECKPOINT_SHA256",
|
||||
"RF_DETR_CONFIG",
|
||||
"RF_DETR_ENGINE_SHA256",
|
||||
"RF_DETR_FP16_ONNX_SHA256",
|
||||
"RF_DETR_MODEL_ID",
|
||||
"RF_DETR_MODEL_VERSION",
|
||||
"RF_DETR_ONNX_SHA256",
|
||||
"RISK_CLASS_IDS",
|
||||
"RfDetrConfig",
|
||||
"RfDetrDetection",
|
||||
"RfDetrDetectorError",
|
||||
"RfDetrInferenceBackend",
|
||||
"RfDetrPostprocessResult",
|
||||
"RfDetrRawOutput",
|
||||
"TritonRfDetrHttpInferenceBackend",
|
||||
"postprocess_rf_detr",
|
||||
"preprocess_raw_kb4_rf_detr",
|
||||
]
|
||||
@@ -0,0 +1,768 @@
|
||||
"""Immutable bounded M48S replay for raw-KB4 semantic object understanding."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
import numpy as np
|
||||
import yaml
|
||||
from numpy.typing import NDArray
|
||||
from PIL import Image
|
||||
|
||||
from .baseline import BASELINE_RECORDED_JOB_ID
|
||||
from .contracts import EvidenceBasis, ObstacleObservation, SourceEnvelope
|
||||
from .detector_replay_result import (
|
||||
read_detector_replay_result,
|
||||
require_m4_detector_replay_acceptance,
|
||||
)
|
||||
from .geometry import (
|
||||
DEFAULT_GEOMETRY_PROFILE_PATH,
|
||||
Ravnoves00GeometryAssociationProvider,
|
||||
RecordedGeometryStore,
|
||||
load_geometry_profile,
|
||||
)
|
||||
from .graph_validation import validate_observations
|
||||
from .object_understanding import (
|
||||
ObjectUnderstanding,
|
||||
SemanticResolution,
|
||||
load_object_semantic_vocabulary,
|
||||
)
|
||||
from .open_vocabulary_semantics import (
|
||||
OpenVocabularyDetection,
|
||||
OpenVocabularySemanticError,
|
||||
OpenVocabularySemanticProfile,
|
||||
bind_object_understandings,
|
||||
fuse_open_vocabulary_detections,
|
||||
load_open_vocabulary_semantic_profile,
|
||||
parse_tao_grounding_dino_labels,
|
||||
)
|
||||
from .providers import SourcePacket
|
||||
from .recorded_source import RECORDED_SOURCE_PACK_ID, RecordedFrameReference
|
||||
from .yolox_object_detector import load_valid_fov_mask
|
||||
|
||||
SEMANTIC_SHADOW_REPLAY_SCHEMA: Final = "missioncore.m48s-semantic-shadow-replay/v0"
|
||||
SEMANTIC_SHADOW_REPORT_SCHEMA: Final = "missioncore.m48s-semantic-shadow-report/v0"
|
||||
SEMANTIC_WORKER_EXECUTION_SCHEMA: Final = "missioncore.m48s-semantic-worker-execution/v0"
|
||||
SEMANTIC_SHADOW_RESULT_PREFIX: Final = "m48s-semantic-shadow-"
|
||||
SEMANTIC_SHADOW_FRAMES_NAME: Final = "frames.jsonl"
|
||||
SEMANTIC_SHADOW_REPORT_NAME: Final = "report.json"
|
||||
SEMANTIC_SHADOW_MANIFEST_NAME: Final = "manifest.json"
|
||||
|
||||
|
||||
class SemanticShadowReplayError(RuntimeError):
|
||||
"""Bounded semantic shadow evidence is incomplete or internally inconsistent."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemanticShadowReplayResult:
|
||||
result_id: str
|
||||
result_root: Path
|
||||
completed: bool
|
||||
accepted: bool
|
||||
metrics: dict[str, object]
|
||||
report: dict[str, object]
|
||||
manifest: dict[str, object]
|
||||
|
||||
|
||||
def build_semantic_shadow_replay(
|
||||
*,
|
||||
repository_root: Path,
|
||||
profile_path: Path,
|
||||
vocabulary_path: Path,
|
||||
detector_result_root: Path,
|
||||
source_frames_root: Path,
|
||||
inference_frames_root: Path,
|
||||
valid_fov_mask_path: Path,
|
||||
worker_result_roots: Mapping[str, Path],
|
||||
worker_identity_path: Path,
|
||||
frame_indices: tuple[int, ...],
|
||||
output_root: Path,
|
||||
) -> SemanticShadowReplayResult:
|
||||
"""Bind exact Worker labels to admitted geometry for a bounded frame set."""
|
||||
|
||||
repository = repository_root.resolve(strict=True)
|
||||
profile = load_open_vocabulary_semantic_profile(profile_path)
|
||||
vocabulary = load_object_semantic_vocabulary(vocabulary_path)
|
||||
if profile.vocabulary_id != vocabulary.vocabulary_id:
|
||||
raise SemanticShadowReplayError("semantic profile and vocabulary disagree")
|
||||
frames = _frame_selection(frame_indices)
|
||||
worker_identity = _validate_worker_identity(
|
||||
worker_identity_path,
|
||||
profile=profile,
|
||||
frame_indices=frames,
|
||||
)
|
||||
worker_artifacts = _validate_worker_results(
|
||||
worker_result_roots,
|
||||
profile=profile,
|
||||
frame_indices=frames,
|
||||
)
|
||||
valid_fov_mask = load_valid_fov_mask(
|
||||
valid_fov_mask_path,
|
||||
expected_sha256=profile.valid_fov_mask_sha256,
|
||||
)
|
||||
source_artifacts = _validate_source_frames(
|
||||
source_frames_root,
|
||||
profile=profile,
|
||||
frame_indices=frames,
|
||||
)
|
||||
inference_artifacts = _validate_inference_frames(
|
||||
inference_frames_root,
|
||||
source_frames_root=source_frames_root,
|
||||
valid_fov_mask=valid_fov_mask,
|
||||
profile=profile,
|
||||
frame_indices=frames,
|
||||
)
|
||||
detector = read_detector_replay_result(detector_result_root)
|
||||
require_m4_detector_replay_acceptance(detector)
|
||||
detector_by_sequence = {item.sequence: item for item in detector.frames}
|
||||
if any(index not in detector_by_sequence for index in frames):
|
||||
raise SemanticShadowReplayError("semantic frame escaped the detector timeline")
|
||||
geometry_profile = load_geometry_profile(repository / DEFAULT_GEOMETRY_PROFILE_PATH)
|
||||
store = RecordedGeometryStore.from_repository(repository, profile=geometry_profile)
|
||||
geometry = Ravnoves00GeometryAssociationProvider(store=store)
|
||||
|
||||
output = output_root.expanduser().absolute()
|
||||
output.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
staging = output / f".semantic-shadow.{uuid.uuid4().hex}.tmp"
|
||||
staging.mkdir(mode=0o700, exist_ok=False)
|
||||
class_counts: Counter[str] = Counter()
|
||||
resolution_counts: Counter[str] = Counter()
|
||||
totals: Counter[str] = Counter()
|
||||
try:
|
||||
frames_path = staging / SEMANTIC_SHADOW_FRAMES_NAME
|
||||
with frames_path.open("wb") as ledger:
|
||||
for frame_index in frames:
|
||||
detector_frame = detector_by_sequence[frame_index]
|
||||
if detector_frame.outcome != "completed":
|
||||
raise SemanticShadowReplayError("accepted detector source frame failed")
|
||||
envelope = detector_frame.envelope
|
||||
detections = _frame_detections(
|
||||
worker_result_roots,
|
||||
frame_index=frame_index,
|
||||
envelope=envelope,
|
||||
profile=profile,
|
||||
)
|
||||
fusion = fuse_open_vocabulary_detections(
|
||||
detections,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
valid_fov_mask=valid_fov_mask,
|
||||
)
|
||||
packet = semantic_replay_packet(envelope)
|
||||
observations = geometry.associate(packet, fusion.proposals)
|
||||
validate_observations(packet, fusion.proposals, observations)
|
||||
understandings = bind_object_understandings(
|
||||
observations,
|
||||
bindings=fusion.bindings,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=envelope.timestamps.monotonic_ns,
|
||||
)
|
||||
frame_metrics = _frame_metrics(
|
||||
detections=detections,
|
||||
fusion_input_count=fusion.input_detection_count,
|
||||
below_confidence_count=fusion.below_confidence_count,
|
||||
invalid_area_count=fusion.invalid_area_count,
|
||||
outside_valid_fov_count=fusion.outside_valid_fov_count,
|
||||
retained_detection_count=fusion.retained_detection_count,
|
||||
proposal_count=len(fusion.proposals),
|
||||
observations=observations,
|
||||
understandings=understandings,
|
||||
)
|
||||
for key, value in frame_metrics.items():
|
||||
totals[key] += value
|
||||
for understanding in understandings:
|
||||
resolution_counts[understanding.semantic.resolution.value] += 1
|
||||
if (
|
||||
understanding.semantic.resolution is SemanticResolution.SELECTED
|
||||
and understanding.semantic.selected_class_id is not None
|
||||
):
|
||||
class_counts[understanding.semantic.selected_class_id] += 1
|
||||
document = {
|
||||
"schema_version": "missioncore.m48s-semantic-shadow-frame/v0",
|
||||
"sequence": frame_index,
|
||||
"frame_id": envelope.frame_id,
|
||||
"source_envelope": envelope.to_dict(),
|
||||
"source_frame": source_artifacts[frame_index],
|
||||
"inference_frame": inference_artifacts[frame_index],
|
||||
"detections": [_detection_document(item) for item in detections],
|
||||
"proposals": [item.to_dict() for item in fusion.proposals],
|
||||
"understandings": [item.to_dict() for item in understandings],
|
||||
"metrics": frame_metrics,
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
ledger.write(_canonical_json(document) + b"\n")
|
||||
metrics = {
|
||||
"frames": {
|
||||
"requested": len(frames),
|
||||
"completed": len(frames),
|
||||
"source_available": sum(
|
||||
detector_by_sequence[index].envelope.registered_point_increment.available
|
||||
for index in frames
|
||||
),
|
||||
},
|
||||
"detections": {
|
||||
"raw": totals["raw_detection_count"],
|
||||
"below_confidence": totals["below_confidence_count"],
|
||||
"invalid_area": totals["invalid_area_count"],
|
||||
"outside_valid_fov": totals["outside_valid_fov_count"],
|
||||
"retained": totals["retained_detection_count"],
|
||||
"fused_proposals": totals["proposal_count"],
|
||||
},
|
||||
"geometry": {
|
||||
"proposal_observations": totals["proposal_observation_count"],
|
||||
"ranged_proposal_observations": totals["ranged_proposal_observation_count"],
|
||||
"camera_only_proposal_observations": totals[
|
||||
"camera_only_proposal_observation_count"
|
||||
],
|
||||
"conflict_proposal_observations": totals["conflict_proposal_observation_count"],
|
||||
"geometry_only_observations": totals["geometry_only_observation_count"],
|
||||
},
|
||||
"semantics": {
|
||||
"resolution_counts": dict(sorted(resolution_counts.items())),
|
||||
"selected_class_counts": dict(sorted(class_counts.items())),
|
||||
},
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
completed = (
|
||||
metrics["frames"]["completed"] == len(frames) # type: ignore[index]
|
||||
and totals["proposal_observation_count"] == totals["proposal_count"]
|
||||
and sum(resolution_counts.values())
|
||||
== totals["proposal_observation_count"] + totals["geometry_only_observation_count"]
|
||||
)
|
||||
frames_sha256 = _file_sha256(frames_path)
|
||||
detector_identity = _object(detector.manifest.get("identity"), "detector identity")
|
||||
identity = {
|
||||
"schema_version": SEMANTIC_SHADOW_REPLAY_SCHEMA,
|
||||
"profile_id": profile.profile_id,
|
||||
"profile_sha256": _file_sha256(profile_path),
|
||||
"vocabulary_id": vocabulary.vocabulary_id,
|
||||
"vocabulary_sha256": _file_sha256(vocabulary_path),
|
||||
"frame_indices": list(frames),
|
||||
"detector_result_id": detector.result_id,
|
||||
"detector_frames_sha256": detector_identity.get("frames_sha256"),
|
||||
"geometry_profile_id": geometry_profile.profile_id,
|
||||
"geometry_profile_sha256": geometry_profile.profile_sha256,
|
||||
"source_pack_id": geometry_profile.source_pack_id,
|
||||
"source_pack_sha256": geometry_profile.source_pack_sha256,
|
||||
"valid_fov": {
|
||||
"result_id": profile.valid_fov_result_id,
|
||||
"mask_sha256": profile.valid_fov_mask_sha256,
|
||||
"fill_value": profile.valid_fov_fill_value,
|
||||
},
|
||||
"source_frames": [source_artifacts[index] for index in frames],
|
||||
"inference_frames": [inference_artifacts[index] for index in frames],
|
||||
"worker_execution": worker_identity,
|
||||
"worker_execution_sha256": _file_sha256(worker_identity_path),
|
||||
"worker_artifacts": worker_artifacts,
|
||||
"producer_sha256": {
|
||||
name: _file_sha256(repository / "src/k1link/perception" / name)
|
||||
for name in (
|
||||
"object_understanding.py",
|
||||
"open_vocabulary_semantics.py",
|
||||
"semantic_shadow_replay.py",
|
||||
)
|
||||
},
|
||||
"frames_sha256": frames_sha256,
|
||||
"metrics": metrics,
|
||||
"completed": completed,
|
||||
"accepted": False,
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
identity_sha256 = hashlib.sha256(_canonical_json(identity)).hexdigest()
|
||||
result_id = f"{SEMANTIC_SHADOW_RESULT_PREFIX}{identity_sha256}"
|
||||
created = datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
report = {
|
||||
"schema_version": SEMANTIC_SHADOW_REPORT_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"identity_sha256": identity_sha256,
|
||||
"created_at_utc": created,
|
||||
"status": (
|
||||
"completed-shadow-evidence-not-accepted"
|
||||
if completed
|
||||
else "rejected-incomplete-shadow"
|
||||
),
|
||||
"completed": completed,
|
||||
"accepted": False,
|
||||
"metrics": metrics,
|
||||
"decision": {
|
||||
"raw_kb4_coordinate_binding_completed": completed,
|
||||
"semantic_quality_accepted": False,
|
||||
"risk_policy_accepted": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
"next_gate": "M48S human-reviewed semantic object quality slice",
|
||||
},
|
||||
"known_limits": [
|
||||
"bounded 11-frame diagnostic slice is not representative route truth",
|
||||
"Grounding DINO confidence is not calibrated class probability",
|
||||
"motion is intentionally unresolved without temporal evidence",
|
||||
"risk remains unknown and route-around advisory only",
|
||||
"TAO performed network metadata requests during tokenizer startup",
|
||||
],
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
report_path = staging / SEMANTIC_SHADOW_REPORT_NAME
|
||||
_write_json(report_path, report)
|
||||
manifest = {
|
||||
"schema_version": SEMANTIC_SHADOW_REPLAY_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"identity_sha256": identity_sha256,
|
||||
"identity": identity,
|
||||
"created_at_utc": created,
|
||||
"completed": completed,
|
||||
"accepted": False,
|
||||
"artifacts": [
|
||||
_artifact(frames_path, "semantic-shadow-frames"),
|
||||
_artifact(report_path, "semantic-shadow-report"),
|
||||
],
|
||||
"authority": _false_authority(),
|
||||
}
|
||||
_write_json(staging / SEMANTIC_SHADOW_MANIFEST_NAME, manifest)
|
||||
destination = output / result_id
|
||||
if destination.exists():
|
||||
shutil.rmtree(staging)
|
||||
return read_semantic_shadow_replay(destination)
|
||||
os.replace(staging, destination)
|
||||
return read_semantic_shadow_replay(destination)
|
||||
except (OpenVocabularySemanticError, OSError, ValueError) as exc:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
raise SemanticShadowReplayError("semantic shadow replay failed closed") from exc
|
||||
except BaseException:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
raise
|
||||
|
||||
|
||||
def read_semantic_shadow_replay(root: Path) -> SemanticShadowReplayResult:
|
||||
"""Read and verify one immutable semantic shadow replay result."""
|
||||
|
||||
resolved = root.resolve(strict=True)
|
||||
if resolved.is_symlink() or not resolved.name.startswith(SEMANTIC_SHADOW_RESULT_PREFIX):
|
||||
raise SemanticShadowReplayError("semantic shadow result root is invalid")
|
||||
manifest = _read_json(resolved / SEMANTIC_SHADOW_MANIFEST_NAME)
|
||||
identity = _object(manifest.get("identity"), "semantic shadow identity")
|
||||
identity_sha256 = hashlib.sha256(_canonical_json(identity)).hexdigest()
|
||||
if (
|
||||
manifest.get("schema_version") != SEMANTIC_SHADOW_REPLAY_SCHEMA
|
||||
or manifest.get("result_id") != resolved.name
|
||||
or manifest.get("identity_sha256") != identity_sha256
|
||||
or resolved.name != f"{SEMANTIC_SHADOW_RESULT_PREFIX}{identity_sha256}"
|
||||
or manifest.get("accepted") is not False
|
||||
or manifest.get("authority") != _false_authority()
|
||||
):
|
||||
raise SemanticShadowReplayError("semantic shadow manifest changed")
|
||||
frames_path = resolved / SEMANTIC_SHADOW_FRAMES_NAME
|
||||
report_path = resolved / SEMANTIC_SHADOW_REPORT_NAME
|
||||
if _file_sha256(frames_path) != identity.get("frames_sha256") or not _artifact_matches(
|
||||
manifest.get("artifacts"), frames_path, report_path
|
||||
):
|
||||
raise SemanticShadowReplayError("semantic shadow artifacts changed")
|
||||
report = _read_json(report_path)
|
||||
if (
|
||||
report.get("schema_version") != SEMANTIC_SHADOW_REPORT_SCHEMA
|
||||
or report.get("result_id") != resolved.name
|
||||
or report.get("identity_sha256") != identity_sha256
|
||||
or report.get("metrics") != identity.get("metrics")
|
||||
or report.get("completed") != identity.get("completed")
|
||||
or report.get("accepted") is not False
|
||||
or report.get("authority") != _false_authority()
|
||||
):
|
||||
raise SemanticShadowReplayError("semantic shadow report changed")
|
||||
metrics = _object(identity.get("metrics"), "semantic shadow metrics")
|
||||
return SemanticShadowReplayResult(
|
||||
result_id=resolved.name,
|
||||
result_root=resolved,
|
||||
completed=identity.get("completed") is True,
|
||||
accepted=False,
|
||||
metrics=metrics,
|
||||
report=report,
|
||||
manifest=manifest,
|
||||
)
|
||||
|
||||
|
||||
def _frame_selection(value: tuple[int, ...]) -> tuple[int, ...]:
|
||||
if (
|
||||
not value
|
||||
or tuple(sorted(set(value))) != value
|
||||
or any(isinstance(item, bool) or item < 0 or item >= 4489 for item in value)
|
||||
):
|
||||
raise SemanticShadowReplayError("semantic shadow frame selection is invalid")
|
||||
return value
|
||||
|
||||
|
||||
def _validate_worker_identity(
|
||||
path: Path,
|
||||
*,
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
frame_indices: tuple[int, ...],
|
||||
) -> dict[str, object]:
|
||||
document = _read_json(path.resolve(strict=True))
|
||||
if (
|
||||
document.get("schema_version") != SEMANTIC_WORKER_EXECUTION_SCHEMA
|
||||
or document.get("model_sha256") != profile.model_sha256
|
||||
or document.get("engine_sha256") != profile.engine_sha256
|
||||
or document.get("container_reference") != profile.container_reference
|
||||
or document.get("container_image_id") != profile.container_image_id
|
||||
or document.get("coordinate_space") != "raw-kb4-800x600"
|
||||
or document.get("preprocess_id") != profile.preprocess_id
|
||||
or document.get("valid_fov_mask_sha256") != profile.valid_fov_mask_sha256
|
||||
or document.get("frame_indices") != list(frame_indices)
|
||||
or document.get("authority") != _false_authority()
|
||||
):
|
||||
raise SemanticShadowReplayError("semantic Worker execution identity changed")
|
||||
prompt_runs = _object(document.get("prompt_runs"), "semantic prompt runs")
|
||||
if set(prompt_runs) != {item.prompt_set_id for item in profile.prompt_groups} or any(
|
||||
_object(value, "semantic prompt run").get("status") != "SUCCESS"
|
||||
for value in prompt_runs.values()
|
||||
):
|
||||
raise SemanticShadowReplayError("semantic Worker prompt run failed")
|
||||
return document
|
||||
|
||||
|
||||
def _validate_worker_results(
|
||||
roots: Mapping[str, Path],
|
||||
*,
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
frame_indices: tuple[int, ...],
|
||||
) -> list[dict[str, object]]:
|
||||
if set(roots) != {item.prompt_set_id for item in profile.prompt_groups}:
|
||||
raise SemanticShadowReplayError("semantic Worker result groups changed")
|
||||
expected_names = {f"frame-{index:06d}.txt" for index in frame_indices}
|
||||
result: list[dict[str, object]] = []
|
||||
for group in profile.prompt_groups:
|
||||
root = roots[group.prompt_set_id].resolve(strict=True)
|
||||
if root.is_symlink() or not root.is_dir():
|
||||
raise SemanticShadowReplayError("semantic Worker result root is invalid")
|
||||
status_path = root / "status.json"
|
||||
status_rows = _read_jsonl(status_path)
|
||||
if not status_rows or status_rows[-1].get("status") != "SUCCESS":
|
||||
raise SemanticShadowReplayError("semantic Worker result did not succeed")
|
||||
experiment_path = root / "experiment.yaml"
|
||||
try:
|
||||
experiment = yaml.safe_load(experiment_path.read_text("utf-8"))
|
||||
except (OSError, yaml.YAMLError) as exc:
|
||||
raise SemanticShadowReplayError("semantic Worker experiment cannot be read") from exc
|
||||
experiment_root = _object(experiment, "semantic Worker experiment")
|
||||
dataset = _object(experiment_root.get("dataset"), "semantic Worker dataset")
|
||||
sources = _object(dataset.get("infer_data_sources"), "semantic Worker sources")
|
||||
inference = _object(experiment_root.get("inference"), "semantic Worker inference")
|
||||
if (
|
||||
sources.get("captions") != list(group.captions)
|
||||
or sources.get("image_dir") != ["/workspace/probe/input"]
|
||||
or inference.get("conf_threshold") != profile.minimum_input_confidence
|
||||
or inference.get("input_width") != profile.engine_input_width
|
||||
or inference.get("input_height") != profile.engine_input_height
|
||||
or not str(inference.get("trt_engine", "")).endswith(
|
||||
"/grounding_dino_swin_tiny_commercial_fp16.engine"
|
||||
)
|
||||
):
|
||||
raise SemanticShadowReplayError("semantic Worker experiment drifted")
|
||||
labels_root = root / "labels"
|
||||
label_paths = tuple(sorted(labels_root.glob("*.txt")))
|
||||
if {item.name for item in label_paths} != expected_names or any(
|
||||
item.is_symlink() or not item.is_file() for item in label_paths
|
||||
):
|
||||
raise SemanticShadowReplayError("semantic Worker label accounting changed")
|
||||
result.append(
|
||||
{
|
||||
"prompt_set_id": group.prompt_set_id,
|
||||
"experiment_sha256": _file_sha256(experiment_path),
|
||||
"status_sha256": _file_sha256(status_path),
|
||||
"labels": [
|
||||
{
|
||||
"name": item.name,
|
||||
"byte_length": item.stat().st_size,
|
||||
"sha256": _file_sha256(item),
|
||||
}
|
||||
for item in label_paths
|
||||
],
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _validate_source_frames(
|
||||
root: Path,
|
||||
*,
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
frame_indices: tuple[int, ...],
|
||||
) -> dict[int, dict[str, object]]:
|
||||
resolved = root.resolve(strict=True)
|
||||
expected_names = {f"frame-{index:06d}.jpg" for index in frame_indices}
|
||||
paths = tuple(sorted(resolved.glob("*.jpg")))
|
||||
if {item.name for item in paths} != expected_names:
|
||||
raise SemanticShadowReplayError("semantic raw frame accounting changed")
|
||||
result: dict[int, dict[str, object]] = {}
|
||||
for index in frame_indices:
|
||||
path = resolved / f"frame-{index:06d}.jpg"
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise SemanticShadowReplayError("semantic raw frame is invalid")
|
||||
try:
|
||||
with Image.open(path) as image:
|
||||
image.verify()
|
||||
with Image.open(path) as image:
|
||||
dimensions = image.size
|
||||
image_format = image.format
|
||||
except OSError as exc:
|
||||
raise SemanticShadowReplayError("semantic raw frame cannot be decoded") from exc
|
||||
if dimensions != (profile.width, profile.height) or image_format != "JPEG":
|
||||
raise SemanticShadowReplayError("semantic raw frame coordinate space changed")
|
||||
result[index] = {
|
||||
"source_frame_index": index,
|
||||
"camera_sequence": index + 1,
|
||||
"name": path.name,
|
||||
"width": profile.width,
|
||||
"height": profile.height,
|
||||
"byte_length": path.stat().st_size,
|
||||
"sha256": _file_sha256(path),
|
||||
"coordinate_space": profile.coordinate_space,
|
||||
"exact_source_frame": True,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def _validate_inference_frames(
|
||||
root: Path,
|
||||
*,
|
||||
source_frames_root: Path,
|
||||
valid_fov_mask: NDArray[np.bool_],
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
frame_indices: tuple[int, ...],
|
||||
) -> dict[int, dict[str, object]]:
|
||||
resolved = root.resolve(strict=True)
|
||||
source_root = source_frames_root.resolve(strict=True)
|
||||
expected_names = {f"frame-{index:06d}.png" for index in frame_indices}
|
||||
paths = tuple(sorted(resolved.glob("*.png")))
|
||||
if {item.name for item in paths} != expected_names:
|
||||
raise SemanticShadowReplayError("semantic inference frame accounting changed")
|
||||
result: dict[int, dict[str, object]] = {}
|
||||
for index in frame_indices:
|
||||
path = resolved / f"frame-{index:06d}.png"
|
||||
source_path = source_root / f"frame-{index:06d}.jpg"
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise SemanticShadowReplayError("semantic inference frame is invalid")
|
||||
try:
|
||||
with Image.open(path) as opened:
|
||||
image_format = opened.format
|
||||
inference = np.asarray(opened.convert("RGB"), dtype=np.uint8)
|
||||
with Image.open(source_path) as opened:
|
||||
source = np.asarray(opened.convert("RGB"), dtype=np.uint8)
|
||||
except OSError as exc:
|
||||
raise SemanticShadowReplayError("semantic inference frame cannot be decoded") from exc
|
||||
expected = np.where(
|
||||
valid_fov_mask[..., None],
|
||||
source,
|
||||
profile.valid_fov_fill_value,
|
||||
).astype(np.uint8)
|
||||
if (
|
||||
image_format != "PNG"
|
||||
or inference.shape != (profile.height, profile.width, 3)
|
||||
or not np.array_equal(inference, expected)
|
||||
):
|
||||
raise SemanticShadowReplayError(
|
||||
"semantic inference frame valid-FOV preprocessing changed"
|
||||
)
|
||||
result[index] = {
|
||||
"source_frame_index": index,
|
||||
"name": path.name,
|
||||
"width": profile.width,
|
||||
"height": profile.height,
|
||||
"byte_length": path.stat().st_size,
|
||||
"sha256": _file_sha256(path),
|
||||
"coordinate_space": profile.coordinate_space,
|
||||
"preprocess_id": profile.preprocess_id,
|
||||
"valid_fov_mask_sha256": profile.valid_fov_mask_sha256,
|
||||
"valid_fov_fill_value": profile.valid_fov_fill_value,
|
||||
"derived_from_source_sha256": _file_sha256(source_path),
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def _frame_detections(
|
||||
roots: Mapping[str, Path],
|
||||
*,
|
||||
frame_index: int,
|
||||
envelope: SourceEnvelope,
|
||||
profile: OpenVocabularySemanticProfile,
|
||||
) -> tuple[OpenVocabularyDetection, ...]:
|
||||
detections: list[OpenVocabularyDetection] = []
|
||||
for group in profile.prompt_groups:
|
||||
labels = (
|
||||
roots[group.prompt_set_id].resolve(strict=True)
|
||||
/ "labels"
|
||||
/ f"frame-{frame_index:06d}.txt"
|
||||
)
|
||||
detections.extend(
|
||||
parse_tao_grounding_dino_labels(
|
||||
labels,
|
||||
source_id=envelope.source_id,
|
||||
frame_id=envelope.frame_id,
|
||||
prompt_set_id=group.prompt_set_id,
|
||||
profile=profile,
|
||||
)
|
||||
)
|
||||
return tuple(detections)
|
||||
|
||||
|
||||
def semantic_replay_packet(envelope: SourceEnvelope) -> SourcePacket:
|
||||
"""Rebuild the exact digest-bound source packet used by semantic replays."""
|
||||
|
||||
image = RecordedFrameReference(BASELINE_RECORDED_JOB_ID, envelope.sequence)
|
||||
geometry = (
|
||||
RecordedFrameReference(RECORDED_SOURCE_PACK_ID, envelope.sequence)
|
||||
if envelope.registered_point_increment.available
|
||||
else None
|
||||
)
|
||||
return SourcePacket(
|
||||
envelope=envelope,
|
||||
image_payload=image,
|
||||
registered_point_increment_payload=geometry,
|
||||
pose_payload=geometry,
|
||||
)
|
||||
|
||||
|
||||
def _frame_metrics(
|
||||
*,
|
||||
detections: tuple[OpenVocabularyDetection, ...],
|
||||
fusion_input_count: int,
|
||||
below_confidence_count: int,
|
||||
invalid_area_count: int,
|
||||
outside_valid_fov_count: int,
|
||||
retained_detection_count: int,
|
||||
proposal_count: int,
|
||||
observations: tuple[ObstacleObservation, ...],
|
||||
understandings: tuple[ObjectUnderstanding, ...],
|
||||
) -> dict[str, int]:
|
||||
proposal_observations = tuple(item for item in observations if item.proposal_ids)
|
||||
geometry_only = tuple(item for item in observations if not item.proposal_ids)
|
||||
if len(detections) != fusion_input_count or len(understandings) != len(observations):
|
||||
raise SemanticShadowReplayError("semantic frame accounting changed")
|
||||
ranged = sum(item.metric_geometry is not None for item in proposal_observations)
|
||||
conflict = sum(item.basis is EvidenceBasis.CONFLICT for item in proposal_observations)
|
||||
return {
|
||||
"raw_detection_count": len(detections),
|
||||
"below_confidence_count": below_confidence_count,
|
||||
"invalid_area_count": invalid_area_count,
|
||||
"outside_valid_fov_count": outside_valid_fov_count,
|
||||
"retained_detection_count": retained_detection_count,
|
||||
"proposal_count": proposal_count,
|
||||
"proposal_observation_count": len(proposal_observations),
|
||||
"ranged_proposal_observation_count": ranged,
|
||||
"camera_only_proposal_observation_count": (len(proposal_observations) - ranged - conflict),
|
||||
"conflict_proposal_observation_count": conflict,
|
||||
"geometry_only_observation_count": len(geometry_only),
|
||||
}
|
||||
|
||||
|
||||
def _detection_document(value: OpenVocabularyDetection) -> dict[str, object]:
|
||||
return {
|
||||
"detection_id": value.detection_id,
|
||||
"source_id": value.source_id,
|
||||
"frame_id": value.frame_id,
|
||||
"prompt_set_id": value.prompt_set_id,
|
||||
"raw_label": value.raw_label,
|
||||
"confidence": value.confidence,
|
||||
"region": value.region.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def _artifact(path: Path, role: str) -> dict[str, object]:
|
||||
return {
|
||||
"role": role,
|
||||
"path": path.name,
|
||||
"byte_length": path.stat().st_size,
|
||||
"sha256": _file_sha256(path),
|
||||
}
|
||||
|
||||
|
||||
def _artifact_matches(value: object, frames_path: Path, report_path: Path) -> bool:
|
||||
if not isinstance(value, list) or len(value) != 2:
|
||||
return False
|
||||
expected = {
|
||||
path.name: (path.stat().st_size, _file_sha256(path)) for path in (frames_path, report_path)
|
||||
}
|
||||
seen: set[str] = set()
|
||||
for item in value:
|
||||
if not isinstance(item, dict):
|
||||
return False
|
||||
path = item.get("path")
|
||||
if not isinstance(path, str) or path not in expected:
|
||||
return False
|
||||
seen.add(path)
|
||||
if (item.get("byte_length"), item.get("sha256")) != expected[path]:
|
||||
return False
|
||||
return seen == set(expected)
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict[str, object]:
|
||||
try:
|
||||
value = json.loads(path.read_text("utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise SemanticShadowReplayError(f"cannot read semantic JSON: {path.name}") from exc
|
||||
return _object(value, path.name)
|
||||
|
||||
|
||||
def _read_jsonl(path: Path) -> list[dict[str, object]]:
|
||||
try:
|
||||
rows = [json.loads(line) for line in path.read_text("utf-8").splitlines() if line]
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise SemanticShadowReplayError(f"cannot read semantic JSONL: {path.name}") from exc
|
||||
return [_object(item, path.name) for item in rows]
|
||||
|
||||
|
||||
def _write_json(path: Path, value: object) -> None:
|
||||
path.write_bytes(_canonical_json(value) + b"\n")
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
def _file_sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.expanduser().resolve(strict=True).open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _object(value: object, label: str) -> dict[str, object]:
|
||||
if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
|
||||
raise SemanticShadowReplayError(f"{label} must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _false_authority() -> dict[str, bool]:
|
||||
return {
|
||||
"ground_truth": False,
|
||||
"independent_truth": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"SEMANTIC_SHADOW_REPLAY_SCHEMA",
|
||||
"SemanticShadowReplayError",
|
||||
"SemanticShadowReplayResult",
|
||||
"build_semantic_shadow_replay",
|
||||
"read_semantic_shadow_replay",
|
||||
"semantic_replay_packet",
|
||||
]
|
||||
@@ -43,6 +43,7 @@ COCO_CLASSES: Final = (
|
||||
"oven", "toaster", "sink", "refrigerator", "book", "clock", "vase",
|
||||
"scissors", "teddy bear", "hair drier", "toothbrush",
|
||||
)
|
||||
ALL_COCO_CLASS_IDS: Final = tuple(range(len(COCO_CLASSES)))
|
||||
|
||||
|
||||
class YoloxDetectorError(RuntimeError):
|
||||
@@ -93,6 +94,58 @@ class FrozenYoloxConfig:
|
||||
FROZEN_YOLOX_CONFIG: Final = FrozenYoloxConfig()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AllCocoYoloxConfig:
|
||||
"""Versioned all-COCO shadow profile using the exact frozen YOLOX tensor."""
|
||||
|
||||
source_width: int = 800
|
||||
source_height: int = 600
|
||||
input_width: int = 640
|
||||
input_height: int = 640
|
||||
fill_value: int = 114
|
||||
minimum_score: float = 0.5
|
||||
nms_iou_threshold: float = 0.45
|
||||
target_class_ids: tuple[int, ...] = ALL_COCO_CLASS_IDS
|
||||
minimum_box_area_pixels: float = 64.0
|
||||
maximum_box_area_fraction: float = 0.5
|
||||
minimum_valid_fov_fraction: float = 0.5
|
||||
require_center_inside_valid_fov: bool = True
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (
|
||||
self.source_width,
|
||||
self.source_height,
|
||||
self.input_width,
|
||||
self.input_height,
|
||||
self.fill_value,
|
||||
self.minimum_score,
|
||||
self.nms_iou_threshold,
|
||||
self.target_class_ids,
|
||||
self.minimum_box_area_pixels,
|
||||
self.maximum_box_area_fraction,
|
||||
self.minimum_valid_fov_fraction,
|
||||
self.require_center_inside_valid_fov,
|
||||
) != (
|
||||
800,
|
||||
600,
|
||||
640,
|
||||
640,
|
||||
114,
|
||||
0.5,
|
||||
0.45,
|
||||
ALL_COCO_CLASS_IDS,
|
||||
64.0,
|
||||
0.5,
|
||||
0.5,
|
||||
True,
|
||||
):
|
||||
raise YoloxDetectorError("all-COCO YOLOX profile cannot be tuned in place")
|
||||
|
||||
|
||||
ALL_COCO_YOLOX_CONFIG: Final = AllCocoYoloxConfig()
|
||||
type YoloxPostprocessConfig = FrozenYoloxConfig | AllCocoYoloxConfig
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class YoloxDetection:
|
||||
class_id: int
|
||||
@@ -231,7 +284,7 @@ def preprocess_raw_kb4(
|
||||
image_bgr: NDArray[np.uint8],
|
||||
mask: NDArray[np.bool_],
|
||||
*,
|
||||
config: FrozenYoloxConfig = FROZEN_YOLOX_CONFIG,
|
||||
config: YoloxPostprocessConfig = FROZEN_YOLOX_CONFIG,
|
||||
resizer: ImageResizer | None = None,
|
||||
) -> NDArray[np.float32]:
|
||||
if image_bgr.shape != (config.source_height, config.source_width, 3):
|
||||
@@ -261,7 +314,7 @@ def postprocess_yolox(
|
||||
output: NDArray[np.float32],
|
||||
mask: NDArray[np.bool_],
|
||||
*,
|
||||
config: FrozenYoloxConfig = FROZEN_YOLOX_CONFIG,
|
||||
config: YoloxPostprocessConfig = FROZEN_YOLOX_CONFIG,
|
||||
) -> YoloxPostprocessResult:
|
||||
if output.shape != (1, 8400, 85) or not np.isfinite(output).all():
|
||||
raise YoloxDetectorError("YOLOX output tensor is incompatible")
|
||||
@@ -420,9 +473,10 @@ def _sha256(path: Path) -> str:
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ALL_COCO_CLASS_IDS", "ALL_COCO_YOLOX_CONFIG", "COCO_CLASSES",
|
||||
"YOLOX_CONFIG_SHA256", "YOLOX_MODEL_ID", "YOLOX_MODEL_SHA256",
|
||||
"YOLOX_MODEL_VERSION", "YOLOX_VALID_FOV_SHA256", "FROZEN_YOLOX_CONFIG",
|
||||
"FrozenYoloxConfig",
|
||||
"AllCocoYoloxConfig", "FrozenYoloxConfig", "YoloxPostprocessConfig",
|
||||
"ImageResizer", "InferenceBackend", "OpenCvBilinearResizer",
|
||||
"TritonHttpInferenceBackend", "YoloxDetection", "YoloxDetectorError",
|
||||
"YoloxPostprocessResult", "load_valid_fov_mask", "postprocess_yolox",
|
||||
|
||||
@@ -125,6 +125,9 @@ from k1link.web.lidar_api import build_lidar_router
|
||||
from k1link.web.lidar_local_surface_service import K1LocalSurfaceReadService
|
||||
from k1link.web.m4_threat_replay_api import build_m4_threat_replay_router
|
||||
from k1link.web.m48_object_quality_api import build_m48_object_quality_router
|
||||
from k1link.web.m48s_fixed_class_detector_lab_api import (
|
||||
build_m48s_fixed_class_detector_lab_router,
|
||||
)
|
||||
from k1link.web.map_api import (
|
||||
MapGatewayConfiguration,
|
||||
MapGatewayProxy,
|
||||
@@ -944,6 +947,23 @@ app.include_router(
|
||||
),
|
||||
)
|
||||
)
|
||||
app.include_router(
|
||||
build_m48s_fixed_class_detector_lab_router(
|
||||
root_provider=lambda: (
|
||||
REPOSITORY_ROOT
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48s-semantic-shadow"
|
||||
/ "fixed-class-detector-lab-results"
|
||||
),
|
||||
repository_root_provider=lambda: REPOSITORY_ROOT,
|
||||
camera_frame_provider=(
|
||||
session_recorded_camera_frame_service.extract
|
||||
if session_recorded_camera_frame_service is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
)
|
||||
app.include_router(
|
||||
build_e47_semantic_slam_router(
|
||||
root_provider=lambda: (
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
"""Read-only API for the sealed M4.8S fixed-class detector LAB."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from functools import lru_cache
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Any, Final
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Response
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from k1link.laboratory.evidence_registry import LaboratoryEvidenceDefinition
|
||||
from k1link.laboratory.evidence_report import (
|
||||
LaboratoryEvidenceReportError,
|
||||
verify_laboratory_evidence_result,
|
||||
)
|
||||
from k1link.laboratory.m48s_fixed_class_detector_lab import (
|
||||
CATALOG_SCHEMA,
|
||||
FRAME_SCHEMA,
|
||||
INTEGRATED_STATUS,
|
||||
LAB_SCHEMA,
|
||||
RESULT_PREFIX,
|
||||
)
|
||||
from k1link.perception.fixed_class_detector_tournament import false_authority
|
||||
from k1link.perception.m48s_replay_timeline import (
|
||||
M48sReplayTimeline,
|
||||
M48sReplayTimelineError,
|
||||
)
|
||||
from k1link.perception.threat_timeline import RECORDED_SPATIAL_MAX_CHUNK_FRAMES
|
||||
from k1link.sessions import RecordedCameraFrame, SessionIntegrityError
|
||||
|
||||
RootProvider = Callable[[], Path | None]
|
||||
CameraFrameProvider = Callable[[str, int], RecordedCameraFrame]
|
||||
|
||||
RESULT_ID: Final = re.compile(rf"^{re.escape(RESULT_PREFIX)}[a-f0-9]{{64}}$")
|
||||
FRAME_ID: Final = re.compile(r"^[0-9]{6}$")
|
||||
SHA256: Final = re.compile(r"^[a-f0-9]{64}$")
|
||||
RESULT_PROJECTION_SCHEMA: Final = "missioncore.m48s-fixed-class-detector-result-view/v1"
|
||||
RESULT_CATALOG_SCHEMA: Final = "missioncore.m48s-fixed-class-detector-result-catalog/v1"
|
||||
MAX_JSON_BYTES: Final = 16 * 1024 * 1024
|
||||
MAX_FRAMES: Final = 32
|
||||
_DEFINITION: Final = LaboratoryEvidenceDefinition(
|
||||
work_id="m48s-fixed-class-detector",
|
||||
runtime_relative_root=PurePosixPath("m48s-semantic-shadow/fixed-class-detector-lab-results"),
|
||||
result_id_prefix="m48s-fixed-class-detector-lab",
|
||||
document_name="manifest.json",
|
||||
result_schema_version=LAB_SCHEMA,
|
||||
)
|
||||
|
||||
|
||||
def build_m48s_fixed_class_detector_lab_router(
|
||||
*,
|
||||
root_provider: RootProvider = lambda: None,
|
||||
repository_root_provider: RootProvider = lambda: None,
|
||||
camera_frame_provider: CameraFrameProvider | None = None,
|
||||
) -> APIRouter:
|
||||
router = APIRouter(
|
||||
prefix="/api/v1/laboratory/m48s/fixed-class-detector",
|
||||
tags=["laboratory"],
|
||||
)
|
||||
|
||||
def timeline(result_id: str) -> M48sReplayTimeline:
|
||||
candidate = _resolve_candidate(root_provider, result_id)
|
||||
repository_root = _configured_root(repository_root_provider)
|
||||
if repository_root is None:
|
||||
raise HTTPException(status_code=503, detail="M4.8S timeline source unavailable")
|
||||
try:
|
||||
return _read_timeline_cached(
|
||||
str(repository_root),
|
||||
str(candidate),
|
||||
result_id,
|
||||
_timeline_signature(candidate),
|
||||
)
|
||||
except (OSError, ValueError, M48sReplayTimelineError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="M4.8S bounded replay timeline failed verification",
|
||||
) from None
|
||||
|
||||
@router.get("/results")
|
||||
def list_results(limit: int = Query(default=1, ge=1, le=10)) -> dict[str, object]:
|
||||
root = _configured_root(root_provider)
|
||||
if root is None:
|
||||
return _empty_catalog(False)
|
||||
candidates = _candidates(root)
|
||||
items: list[dict[str, object]] = []
|
||||
invalid_total = 0
|
||||
for candidate in candidates:
|
||||
try:
|
||||
items.append(_project_result(candidate))
|
||||
except RuntimeError:
|
||||
invalid_total += 1
|
||||
items.sort(
|
||||
key=lambda item: (str(item["created_at_utc"]), str(item["result_id"])),
|
||||
reverse=True,
|
||||
)
|
||||
return {
|
||||
"schema_version": RESULT_CATALOG_SCHEMA,
|
||||
"configured": True,
|
||||
"items": items[:limit],
|
||||
"candidate_total": len(candidates),
|
||||
"invalid_total": invalid_total,
|
||||
"access": "read-only",
|
||||
}
|
||||
|
||||
@router.get("/{result_id}")
|
||||
def get_result(result_id: str) -> dict[str, object]:
|
||||
return _project_result(_resolve_candidate(root_provider, result_id))
|
||||
|
||||
@router.get("/{result_id}/frames/{frame_id}")
|
||||
def get_frame(result_id: str, frame_id: str) -> dict[str, object]:
|
||||
candidate, descriptor = _resolve_frame(
|
||||
root_provider,
|
||||
result_id=result_id,
|
||||
frame_id=frame_id,
|
||||
)
|
||||
path = candidate / str(descriptor["detail_path"])
|
||||
payload = _read_object(path)
|
||||
if (
|
||||
payload.get("schema_version") != FRAME_SCHEMA
|
||||
or payload.get("result_id") != result_id
|
||||
or payload.get("frame_id") != frame_id
|
||||
or descriptor.get("detail_sha256") != _sha256(path)
|
||||
or descriptor.get("detail_byte_length") != path.stat().st_size
|
||||
or not _valid_frame_payload(payload)
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="M4.8S frame not found")
|
||||
return {**copy.deepcopy(payload), "access": "read-only"}
|
||||
|
||||
@router.get("/{result_id}/frames/{frame_id}/camera")
|
||||
def get_camera(result_id: str, frame_id: str) -> FileResponse:
|
||||
candidate, descriptor = _resolve_frame(
|
||||
root_provider,
|
||||
result_id=result_id,
|
||||
frame_id=frame_id,
|
||||
)
|
||||
path = (candidate / str(descriptor["camera_path"])).resolve()
|
||||
if (
|
||||
not path.is_relative_to(candidate)
|
||||
or path.is_symlink()
|
||||
or not path.is_file()
|
||||
or descriptor.get("camera_sha256") != _sha256(path)
|
||||
or descriptor.get("camera_byte_length") != path.stat().st_size
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="M4.8S camera not found")
|
||||
return FileResponse(path, media_type="image/jpeg")
|
||||
|
||||
@router.get("/{result_id}/timeline")
|
||||
def get_timeline(result_id: str) -> dict[str, object]:
|
||||
return copy.deepcopy(timeline(result_id).metadata())
|
||||
|
||||
@router.get("/{result_id}/timeline/chunk")
|
||||
def get_timeline_chunk(
|
||||
result_id: str,
|
||||
start: int = Query(default=0, ge=0),
|
||||
count: int = Query(default=12, ge=1, le=RECORDED_SPATIAL_MAX_CHUNK_FRAMES),
|
||||
) -> dict[str, object]:
|
||||
try:
|
||||
return timeline(result_id).chunk(start_sequence=start, frame_count=count)
|
||||
except M48sReplayTimelineError:
|
||||
raise HTTPException(status_code=404, detail="M4.8S timeline chunk not found") from None
|
||||
|
||||
@router.get("/{result_id}/timeline/frames/{sequence}/camera")
|
||||
def get_timeline_camera(result_id: str, sequence: int) -> Response:
|
||||
if camera_frame_provider is None:
|
||||
raise HTTPException(status_code=503, detail="M4.8S camera decoder unavailable")
|
||||
projected = timeline(result_id)
|
||||
if not 0 <= sequence < len(projected.source_times_ns):
|
||||
raise HTTPException(status_code=404, detail="M4.8S timeline frame not found")
|
||||
try:
|
||||
camera = camera_frame_provider(projected.profile.session_id, sequence)
|
||||
except (OSError, SessionIntegrityError, ValueError):
|
||||
raise HTTPException(status_code=503, detail="M4.8S exact camera unavailable") from None
|
||||
if camera.width != 800 or camera.height != 600:
|
||||
raise HTTPException(status_code=503, detail="M4.8S camera size contract changed")
|
||||
return Response(
|
||||
content=camera.payload,
|
||||
media_type=camera.media_type,
|
||||
headers={
|
||||
"Cache-Control": "private, max-age=31536000, immutable",
|
||||
"ETag": f'"{camera.sha256}"',
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
)
|
||||
|
||||
return router
|
||||
|
||||
|
||||
@lru_cache(maxsize=4)
|
||||
def _read_timeline_cached(
|
||||
repository_root: str,
|
||||
result_root: str,
|
||||
result_id: str,
|
||||
signature: tuple[int, ...],
|
||||
) -> M48sReplayTimeline:
|
||||
del signature
|
||||
return M48sReplayTimeline(
|
||||
repository_root=Path(repository_root),
|
||||
result_root=Path(result_root),
|
||||
result_id=result_id,
|
||||
)
|
||||
|
||||
|
||||
def _timeline_signature(candidate: Path) -> tuple[int, ...]:
|
||||
signature: list[int] = []
|
||||
for name in (
|
||||
"manifest.json",
|
||||
"reference-graph-replay-frames.jsonl",
|
||||
"reference-graph-replay-worker-result.json",
|
||||
):
|
||||
path = candidate / name
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise ValueError("M4.8S replay artifact is unavailable")
|
||||
stat = path.stat()
|
||||
signature.extend((stat.st_size, stat.st_mtime_ns))
|
||||
return tuple(signature)
|
||||
|
||||
|
||||
def _project_result(candidate: Path) -> dict[str, object]:
|
||||
loaded = _load_result(candidate)
|
||||
manifest = loaded["manifest"]
|
||||
catalog = loaded["catalog"]
|
||||
identity = manifest["identity"]
|
||||
return {
|
||||
"schema_version": RESULT_PROJECTION_SCHEMA,
|
||||
"result_id": manifest["result_id"],
|
||||
"created_at_utc": manifest["created_at_utc"],
|
||||
"status": manifest["status"],
|
||||
"bounded_question_accepted": manifest["bounded_question_accepted"],
|
||||
"ground_truth": manifest["ground_truth"],
|
||||
"source": copy.deepcopy(identity["source"]),
|
||||
"configuration": copy.deepcopy(identity["configuration"]),
|
||||
"method": copy.deepcopy(manifest["method"]),
|
||||
"metrics": copy.deepcopy(manifest["metrics"]),
|
||||
"decision": copy.deepcopy(manifest["decision"]),
|
||||
"limitations": copy.deepcopy(manifest["limitations"]),
|
||||
"authority": copy.deepcopy(manifest["authority"]),
|
||||
"frames": copy.deepcopy(catalog["frames"]),
|
||||
"access": "read-only",
|
||||
}
|
||||
|
||||
|
||||
def _load_result(candidate: Path) -> dict[str, Any]:
|
||||
try:
|
||||
signature = _candidate_signature(candidate)
|
||||
except (OSError, RuntimeError, ValueError) as exc:
|
||||
raise RuntimeError("M4.8S result signature failed") from exc
|
||||
return _load_result_cached(str(candidate), signature)
|
||||
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
def _load_result_cached(candidate_value: str, signature: tuple[int, ...]) -> dict[str, Any]:
|
||||
del signature
|
||||
return _load_result_uncached(Path(candidate_value))
|
||||
|
||||
|
||||
def _load_result_uncached(candidate: Path) -> dict[str, Any]:
|
||||
if (
|
||||
not candidate.is_dir()
|
||||
or candidate.is_symlink()
|
||||
or RESULT_ID.fullmatch(candidate.name) is None
|
||||
):
|
||||
raise RuntimeError("M4.8S result candidate is invalid")
|
||||
try:
|
||||
verify_laboratory_evidence_result(_DEFINITION, candidate)
|
||||
except LaboratoryEvidenceReportError as exc:
|
||||
raise RuntimeError("M4.8S result integrity failed") from exc
|
||||
manifest = _read_object(candidate / "manifest.json")
|
||||
identity = manifest.get("identity")
|
||||
catalog_descriptor = manifest.get("catalog")
|
||||
decision = manifest.get("decision")
|
||||
method = manifest.get("method")
|
||||
metrics = manifest.get("metrics")
|
||||
status = manifest.get("status")
|
||||
integrated = status == INTEGRATED_STATUS
|
||||
if (
|
||||
manifest.get("schema_version") != LAB_SCHEMA
|
||||
or manifest.get("result_id") != candidate.name
|
||||
or status
|
||||
not in {
|
||||
"detector-load-passed-reference-graph-shadow-only",
|
||||
INTEGRATED_STATUS,
|
||||
}
|
||||
or manifest.get("completed") is not True
|
||||
or manifest.get("bounded_question_accepted") is not True
|
||||
or manifest.get("ground_truth") is not False
|
||||
or not isinstance(manifest.get("created_at_utc"), str)
|
||||
or not isinstance(identity, dict)
|
||||
or identity.get("schema_version") != LAB_SCHEMA
|
||||
or manifest.get("identity_sha256") != hashlib.sha256(_canonical_json(identity)).hexdigest()
|
||||
or not candidate.name.endswith(str(manifest.get("identity_sha256")))
|
||||
or identity.get("authority") != false_authority()
|
||||
or manifest.get("authority") != false_authority()
|
||||
or not isinstance(decision, dict)
|
||||
or decision.get("bounded_question_accepted") is not True
|
||||
or decision.get("ready_for_reference_graph_shadow") is not True
|
||||
or decision.get("integrated_world_state_gate_evaluated") is not integrated
|
||||
or (integrated and decision.get("integrated_world_state_gate_passed") is not True)
|
||||
or (integrated and decision.get("detector_replacement_authorized") is not False)
|
||||
or decision.get("production_accepted") is not False
|
||||
or not isinstance(method, dict)
|
||||
or method.get("schema_version") != "missioncore.laboratory-method/v1"
|
||||
or method.get("completeness") != "complete"
|
||||
or not isinstance(metrics, dict)
|
||||
or (integrated and not isinstance(metrics.get("integrated_world_state"), dict))
|
||||
or not isinstance(manifest.get("limitations"), list)
|
||||
or not isinstance(catalog_descriptor, dict)
|
||||
or catalog_descriptor.get("path") != "catalog.json"
|
||||
):
|
||||
raise RuntimeError("M4.8S manifest is invalid")
|
||||
catalog_path = candidate / "catalog.json"
|
||||
if (
|
||||
catalog_descriptor.get("sha256") != _sha256(catalog_path)
|
||||
or catalog_descriptor.get("byte_length") != catalog_path.stat().st_size
|
||||
):
|
||||
raise RuntimeError("M4.8S catalog changed")
|
||||
catalog = _read_object(catalog_path)
|
||||
frames = catalog.get("frames")
|
||||
if (
|
||||
catalog.get("schema_version") != CATALOG_SCHEMA
|
||||
or catalog.get("result_id") != candidate.name
|
||||
or not isinstance(frames, list)
|
||||
or not 1 <= len(frames) <= MAX_FRAMES
|
||||
or catalog.get("frame_count") != len(frames)
|
||||
or len({item.get("frame_id") for item in frames if isinstance(item, dict)}) != len(frames)
|
||||
or any(not _valid_descriptor(item) for item in frames)
|
||||
):
|
||||
raise RuntimeError("M4.8S catalog is invalid")
|
||||
return {"manifest": manifest, "catalog": catalog}
|
||||
|
||||
|
||||
def _candidate_signature(candidate: Path) -> tuple[int, ...]:
|
||||
if not candidate.is_dir() or candidate.is_symlink():
|
||||
raise RuntimeError("M4.8S result candidate is invalid")
|
||||
manifest_path = candidate / "manifest.json"
|
||||
manifest = _read_object(manifest_path)
|
||||
artifacts = manifest.get("artifacts")
|
||||
if not isinstance(artifacts, list):
|
||||
raise RuntimeError("M4.8S artifact manifest is invalid")
|
||||
signature = [manifest_path.stat().st_size, manifest_path.stat().st_mtime_ns]
|
||||
for descriptor in artifacts:
|
||||
if not isinstance(descriptor, dict) or not isinstance(descriptor.get("path"), str):
|
||||
raise RuntimeError("M4.8S artifact descriptor is invalid")
|
||||
path = (candidate / descriptor["path"]).resolve(strict=True)
|
||||
if not path.is_relative_to(candidate) or path.is_symlink() or not path.is_file():
|
||||
raise RuntimeError("M4.8S artifact path is invalid")
|
||||
stat = path.stat()
|
||||
signature.extend((stat.st_size, stat.st_mtime_ns))
|
||||
return tuple(signature)
|
||||
|
||||
|
||||
def _resolve_candidate(root_provider: RootProvider, result_id: str) -> Path:
|
||||
if RESULT_ID.fullmatch(result_id) is None:
|
||||
raise HTTPException(status_code=404, detail="M4.8S result not found")
|
||||
root = _configured_root(root_provider)
|
||||
if root is None:
|
||||
raise HTTPException(status_code=404, detail="M4.8S result not found")
|
||||
candidate = root / result_id
|
||||
try:
|
||||
_load_result(candidate)
|
||||
except RuntimeError:
|
||||
raise HTTPException(status_code=404, detail="M4.8S result not found") from None
|
||||
return candidate
|
||||
|
||||
|
||||
def _resolve_frame(
|
||||
root_provider: RootProvider,
|
||||
*,
|
||||
result_id: str,
|
||||
frame_id: str,
|
||||
) -> tuple[Path, dict[str, Any]]:
|
||||
if FRAME_ID.fullmatch(frame_id) is None:
|
||||
raise HTTPException(status_code=404, detail="M4.8S frame not found")
|
||||
candidate = _resolve_candidate(root_provider, result_id)
|
||||
loaded = _load_result(candidate)
|
||||
try:
|
||||
descriptor = next(
|
||||
item for item in loaded["catalog"]["frames"] if item["frame_id"] == frame_id
|
||||
)
|
||||
except StopIteration:
|
||||
raise HTTPException(status_code=404, detail="M4.8S frame not found") from None
|
||||
return candidate, descriptor
|
||||
|
||||
|
||||
def _valid_descriptor(value: object) -> bool:
|
||||
if not isinstance(value, dict):
|
||||
return False
|
||||
frame_id = value.get("frame_id")
|
||||
counts = value.get("counts")
|
||||
return (
|
||||
isinstance(frame_id, str)
|
||||
and FRAME_ID.fullmatch(frame_id) is not None
|
||||
and value.get("source_sequence") == int(frame_id)
|
||||
and value.get("camera_path") == f"frames/frame-{frame_id}.jpg"
|
||||
and isinstance(value.get("camera_sha256"), str)
|
||||
and SHA256.fullmatch(value["camera_sha256"]) is not None
|
||||
and isinstance(value.get("camera_byte_length"), int)
|
||||
and value["camera_byte_length"] > 0
|
||||
and value.get("detail_path") == f"frame-{frame_id}.json"
|
||||
and isinstance(value.get("detail_sha256"), str)
|
||||
and SHA256.fullmatch(value["detail_sha256"]) is not None
|
||||
and isinstance(value.get("detail_byte_length"), int)
|
||||
and 0 < value["detail_byte_length"] <= MAX_JSON_BYTES
|
||||
and isinstance(counts, dict)
|
||||
and set(counts) == {"yolox", "dfine", "rf-detr"}
|
||||
and all(isinstance(count, int) and count >= 0 for count in counts.values())
|
||||
)
|
||||
|
||||
|
||||
def _valid_frame_payload(value: dict[str, Any]) -> bool:
|
||||
camera = value.get("camera")
|
||||
detections = value.get("detections")
|
||||
return (
|
||||
isinstance(value.get("source_sequence"), int)
|
||||
and isinstance(camera, dict)
|
||||
and camera.get("media_type") == "image/jpeg"
|
||||
and camera.get("width") == 800
|
||||
and camera.get("height") == 600
|
||||
and camera.get("exact_source_frame") is True
|
||||
and isinstance(camera.get("sha256"), str)
|
||||
and SHA256.fullmatch(camera["sha256"]) is not None
|
||||
and value.get("comparison_threshold") == 0.5
|
||||
and isinstance(detections, dict)
|
||||
and set(detections) == {"yolox", "dfine", "rf-detr"}
|
||||
and all(
|
||||
isinstance(items, list) and all(_valid_detection(item) for item in items)
|
||||
for items in detections.values()
|
||||
)
|
||||
and value.get("ground_truth_available") is False
|
||||
and value.get("authority") == false_authority()
|
||||
)
|
||||
|
||||
|
||||
def _valid_detection(value: object) -> bool:
|
||||
if not isinstance(value, dict) or set(value) != {"label", "score", "bbox_xyxy"}:
|
||||
return False
|
||||
score = value.get("score")
|
||||
bbox = value.get("bbox_xyxy")
|
||||
return (
|
||||
isinstance(value.get("label"), str)
|
||||
and isinstance(score, (int, float))
|
||||
and not isinstance(score, bool)
|
||||
and 0.5 <= float(score) <= 1.0
|
||||
and isinstance(bbox, list)
|
||||
and len(bbox) == 4
|
||||
and all(isinstance(item, (int, float)) and not isinstance(item, bool) for item in bbox)
|
||||
and 0 <= float(bbox[0]) < float(bbox[2]) <= 800
|
||||
and 0 <= float(bbox[1]) < float(bbox[3]) <= 600
|
||||
)
|
||||
|
||||
|
||||
def _configured_root(provider: RootProvider) -> Path | None:
|
||||
value = provider()
|
||||
if value is None:
|
||||
return None
|
||||
candidate = value.expanduser().absolute()
|
||||
if candidate.is_symlink():
|
||||
return None
|
||||
try:
|
||||
resolved = candidate.resolve(strict=True)
|
||||
except OSError:
|
||||
return None
|
||||
return resolved if resolved.is_dir() else None
|
||||
|
||||
|
||||
def _candidates(root: Path) -> list[Path]:
|
||||
return [
|
||||
item
|
||||
for item in root.iterdir()
|
||||
if item.is_dir() and not item.is_symlink() and RESULT_ID.fullmatch(item.name)
|
||||
]
|
||||
|
||||
|
||||
def _empty_catalog(configured: bool) -> dict[str, object]:
|
||||
return {
|
||||
"schema_version": RESULT_CATALOG_SCHEMA,
|
||||
"configured": configured,
|
||||
"items": [],
|
||||
"candidate_total": 0,
|
||||
"invalid_total": 0,
|
||||
"access": "read-only",
|
||||
}
|
||||
|
||||
|
||||
def _read_object(path: Path) -> dict[str, Any]:
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_JSON_BYTES:
|
||||
raise RuntimeError("M4.8S JSON artifact is invalid")
|
||||
try:
|
||||
value = json.loads(path.read_text("utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise RuntimeError("M4.8S JSON artifact is invalid") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise RuntimeError("M4.8S JSON artifact is invalid")
|
||||
return value
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"RESULT_CATALOG_SCHEMA",
|
||||
"RESULT_PROJECTION_SCHEMA",
|
||||
"build_m48s_fixed_class_detector_lab_router",
|
||||
]
|
||||
@@ -0,0 +1,80 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.perception.fixed_class_detector_tournament import (
|
||||
EXACT_FRAME_NAMES,
|
||||
WORKER_RUN_SCHEMA,
|
||||
CandidateWorkerRun,
|
||||
FixedClassTournamentError,
|
||||
false_authority,
|
||||
)
|
||||
|
||||
|
||||
def _worker_document() -> dict[str, object]:
|
||||
frames = []
|
||||
for name in EXACT_FRAME_NAMES:
|
||||
detections = []
|
||||
if name == "frame-000253.png":
|
||||
detections = [
|
||||
{
|
||||
"class_id": 16,
|
||||
"label": "dog",
|
||||
"score": 0.72,
|
||||
"bbox_xyxy": [100.0, 200.0, 160.0, 280.0],
|
||||
"valid_fov_fraction": 1.0,
|
||||
}
|
||||
]
|
||||
frames.append(
|
||||
{
|
||||
"frame_name": name,
|
||||
"source_sha256": "a" * 64,
|
||||
"detections": detections,
|
||||
"timing_ms": {"end_to_end": 12.0},
|
||||
}
|
||||
)
|
||||
return {
|
||||
"schema_version": WORKER_RUN_SCHEMA,
|
||||
"profile_id": "candidate/v0",
|
||||
"provider_id": "shadow-candidate/v0",
|
||||
"upstream_revision": "revision",
|
||||
"checkpoint_sha256": "b" * 64,
|
||||
"completed": True,
|
||||
"execution": {"inference_passes_per_evidence_frame": 1},
|
||||
"frames": frames,
|
||||
"metrics": {"capacity_fps": 80.0},
|
||||
"authority": false_authority(),
|
||||
}
|
||||
|
||||
|
||||
def test_candidate_worker_run_reports_risk_only_quality() -> None:
|
||||
result = CandidateWorkerRun.from_document(_worker_document())
|
||||
|
||||
summary = result.quality_summary(threshold=0.5)
|
||||
|
||||
assert summary["detection_count"] == 1
|
||||
assert summary["risk_group_counts"] == {"animal": 1}
|
||||
assert summary["frame_000253_dog_detected"] is True
|
||||
assert summary["frame_000253_dog_max_score"] == 0.72
|
||||
|
||||
|
||||
def test_candidate_worker_run_rejects_missing_frame() -> None:
|
||||
document = _worker_document()
|
||||
frames = document["frames"]
|
||||
assert isinstance(frames, list)
|
||||
frames.pop()
|
||||
|
||||
with pytest.raises(FixedClassTournamentError, match="exact M48S slice"):
|
||||
CandidateWorkerRun.from_document(document)
|
||||
|
||||
|
||||
def test_candidate_worker_run_rejects_authority() -> None:
|
||||
document = deepcopy(_worker_document())
|
||||
authority = document["authority"]
|
||||
assert isinstance(authority, dict)
|
||||
authority["candidate_accepted"] = True
|
||||
|
||||
with pytest.raises(FixedClassTournamentError, match="false authority"):
|
||||
CandidateWorkerRun.from_document(document)
|
||||
@@ -0,0 +1,158 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from k1link.perception.contracts import (
|
||||
EvidenceBasis,
|
||||
EvidenceCurrentness,
|
||||
MetricGeometry,
|
||||
ObstacleObservation,
|
||||
)
|
||||
from k1link.perception.geometry import GeometryFrame
|
||||
from k1link.perception.geometry_math import Kb4ProjectionProfile
|
||||
from k1link.perception.geometry_semantic_roi import (
|
||||
build_geometry_semantic_rois,
|
||||
materialize_geometry_semantic_crop,
|
||||
select_geometry_roi_detections,
|
||||
)
|
||||
from k1link.perception.object_understanding import load_object_semantic_vocabulary
|
||||
from k1link.perception.open_vocabulary_semantics import (
|
||||
OpenVocabularyDetection,
|
||||
fuse_open_vocabulary_detections,
|
||||
load_open_vocabulary_semantic_profile,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
PROFILE_PATH = REPOSITORY_ROOT / "config/perception/open-vocabulary-semantic-shadow-v0.json"
|
||||
VOCABULARY_PATH = REPOSITORY_ROOT / "config/perception/object-semantic-vocabulary-v0.json"
|
||||
|
||||
|
||||
def _point_for_pixel(u: float, v: float, *, z: float = 5.0) -> tuple[float, float, float]:
|
||||
theta_x = (u - 400.0) / 100.0
|
||||
theta_y = (v - 300.0) / 100.0
|
||||
ray = np.asarray((np.tan(theta_x), np.tan(theta_y), 1.0), dtype=np.float64)
|
||||
return tuple(float(item) for item in ray * z) # type: ignore[return-value]
|
||||
|
||||
|
||||
def _frame() -> GeometryFrame:
|
||||
points = np.asarray(
|
||||
(
|
||||
_point_for_pixel(350.0, 250.0),
|
||||
_point_for_pixel(450.0, 250.0),
|
||||
_point_for_pixel(350.0, 350.0),
|
||||
_point_for_pixel(450.0, 350.0),
|
||||
_point_for_pixel(600.0, 300.0),
|
||||
),
|
||||
dtype=np.float64,
|
||||
)
|
||||
return GeometryFrame(
|
||||
frame_index=121,
|
||||
points_map=points,
|
||||
point_class=np.full(points.shape[0], 2, dtype=np.uint8),
|
||||
sensor_position_map=np.zeros(3, dtype=np.float64),
|
||||
sensor_orientation_xyzw=np.asarray((0.0, 0.0, 0.0, 1.0), dtype=np.float64),
|
||||
projection=Kb4ProjectionProfile(
|
||||
width=800,
|
||||
height=600,
|
||||
intrinsic_fx_fy_cx_cy=(100.0, 100.0, 400.0, 300.0),
|
||||
distortion_kb4=(0.0, 0.0, 0.0, 0.0),
|
||||
t_camera_from_lidar=np.eye(4, dtype=np.float64),
|
||||
),
|
||||
surface_valid=True,
|
||||
)
|
||||
|
||||
|
||||
def _observation(ordinal: int, source_point_ids: tuple[int, ...]) -> ObstacleObservation:
|
||||
return ObstacleObservation(
|
||||
observation_id=f"frame-000121:observation-{ordinal}",
|
||||
occupancy_key=f"frame-000121:occupancy-{ordinal}",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000121",
|
||||
evidence_time_ns=121,
|
||||
basis=EvidenceBasis.LIDAR,
|
||||
currentness=EvidenceCurrentness.CURRENT,
|
||||
occupied_support=True,
|
||||
source_point_ids=source_point_ids,
|
||||
metric_geometry=MetricGeometry(
|
||||
coordinate_frame="map",
|
||||
centroid_xyz_m=(1.0, 2.0, 0.5),
|
||||
range_m=2.2,
|
||||
covariance_diagonal_m2=(0.1, 0.1, 0.1),
|
||||
),
|
||||
proposal_ids=(),
|
||||
semantic_hint=None,
|
||||
reason_codes=("test-geometry-only",),
|
||||
)
|
||||
|
||||
|
||||
def test_geometry_points_own_crop_and_sparse_observation_stays_unprojected(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
result = build_geometry_semantic_rois(
|
||||
frame=_frame(),
|
||||
observations=(_observation(0, (0, 1, 2, 3)), _observation(1, (4,))),
|
||||
)
|
||||
|
||||
assert len(result.rois) == 1
|
||||
assert result.not_projected_observations[0].observation_id.endswith("observation-1")
|
||||
roi = result.rois[0]
|
||||
assert roi.observation.source_point_ids == (0, 1, 2, 3)
|
||||
assert roi.core_region.x_min < 400.0 < roi.core_region.x_max
|
||||
assert roi.core_region.y_min < 300.0 < roi.core_region.y_max
|
||||
assert roi.crop_region.x_min <= roi.core_region.x_min
|
||||
assert roi.crop_region.y_max >= roi.core_region.y_max
|
||||
|
||||
source = tmp_path / "frame-000121.png"
|
||||
Image.new("RGB", (800, 600), (114, 114, 114)).save(source)
|
||||
destination = tmp_path / roi.crop_name
|
||||
materialize_geometry_semantic_crop(
|
||||
image_path=source,
|
||||
roi=roi,
|
||||
destination=destination,
|
||||
)
|
||||
with Image.open(destination) as crop:
|
||||
assert crop.size == (
|
||||
int(roi.crop_region.x_max - roi.crop_region.x_min),
|
||||
int(roi.crop_region.y_max - roi.crop_region.y_min),
|
||||
)
|
||||
|
||||
|
||||
def test_roi_selection_returns_only_cluster_covering_geometry_core() -> None:
|
||||
profile = load_open_vocabulary_semantic_profile(PROFILE_PATH)
|
||||
vocabulary = load_object_semantic_vocabulary(VOCABULARY_PATH)
|
||||
roi = build_geometry_semantic_rois(
|
||||
frame=_frame(),
|
||||
observations=(_observation(0, (0, 1, 2, 3)),),
|
||||
).rois[0]
|
||||
fusion = fuse_open_vocabulary_detections(
|
||||
(
|
||||
OpenVocabularyDetection(
|
||||
detection_id="inside",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000121",
|
||||
prompt_set_id="urban-static/v0",
|
||||
raw_label="trash bin",
|
||||
confidence=0.8,
|
||||
region=roi.core_region,
|
||||
),
|
||||
OpenVocabularyDetection(
|
||||
detection_id="outside",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000121",
|
||||
prompt_set_id="urban-static/v0",
|
||||
raw_label="traffic cone",
|
||||
confidence=0.9,
|
||||
region=type(roi.core_region)(10.0, 10.0, 50.0, 50.0),
|
||||
),
|
||||
),
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
valid_fov_mask=np.ones((600, 800), dtype=np.bool_),
|
||||
)
|
||||
|
||||
selected = select_geometry_roi_detections(roi, fusion)
|
||||
|
||||
assert tuple(item.detection_id for item in selected) == ("inside",)
|
||||
@@ -0,0 +1,53 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.perception.geometry_semantic_shadow_replay import (
|
||||
read_geometry_semantic_shadow_replay,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULT_ROOT = (
|
||||
REPOSITORY_ROOT
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/geometry-first-results"
|
||||
/ (
|
||||
"m48s-geometry-semantic-shadow-"
|
||||
"1a6c5d04fb3f7aef4385ee28fc67d3e69f4528a77e8e1194b1283530ef73c7c2"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_geometry_first_semantic_shadow_is_complete_but_not_accepted() -> None:
|
||||
result = read_geometry_semantic_shadow_replay(RESULT_ROOT)
|
||||
|
||||
assert result.completed is True
|
||||
assert result.accepted is False
|
||||
assert result.metrics["geometry"] == {
|
||||
"not_projected_observation_count": 15,
|
||||
"observation_count": 73,
|
||||
"roi_count": 58,
|
||||
}
|
||||
semantics = result.metrics["semantics"]
|
||||
assert isinstance(semantics, dict)
|
||||
assert semantics["resolution_counts"] == {
|
||||
"ambiguous": 6,
|
||||
"selected": 11,
|
||||
"unresolved": 56,
|
||||
}
|
||||
assert semantics["selected_class_counts"] == {
|
||||
"human.adult": 1,
|
||||
"static.bollard": 1,
|
||||
"static.concrete-hemisphere": 1,
|
||||
"vehicle.car": 8,
|
||||
}
|
||||
assert result.report["decision"] == {
|
||||
"geometry_first_binding_completed": True,
|
||||
"navigation_or_safety_accepted": False,
|
||||
"reason_codes": [
|
||||
"two-reviewer-independent-truth-unavailable",
|
||||
"open-vocabulary-geometry-roi-remains-experimental-shadow",
|
||||
"unknown-and-unresolved-objects-remain-route-around-obstacles",
|
||||
],
|
||||
"semantic_quality_accepted": False,
|
||||
}
|
||||
assert result.report["authority"]["commands_enabled"] is False # type: ignore[index]
|
||||
@@ -127,7 +127,7 @@ def test_product_registry_declares_every_advanced_evidence_source() -> None:
|
||||
repository_root / "config" / "laboratories"
|
||||
)
|
||||
|
||||
assert len(registry.definitions) == 36
|
||||
assert len(registry.definitions) == 37
|
||||
assert {item.work_id for item in registry.definitions} >= {
|
||||
"e31-source-binding",
|
||||
"e46j-raw-fisheye-realtime",
|
||||
@@ -141,6 +141,7 @@ def test_product_registry_declares_every_advanced_evidence_source() -> None:
|
||||
"m47-reference-graph-shadow",
|
||||
"m48-object-centric-quality",
|
||||
"m48-small-static-passage-regression",
|
||||
"m48s-fixed-class-detector",
|
||||
}
|
||||
m48 = next(
|
||||
item for item in registry.definitions
|
||||
|
||||
@@ -98,6 +98,7 @@ def test_repository_registry_classifies_every_evidence_definition() -> None:
|
||||
"e35-degradation-recovery",
|
||||
"e46j-raw-fisheye-realtime",
|
||||
"e47-semantic-slam-shadow",
|
||||
"m48s-fixed-class-detector",
|
||||
}
|
||||
by_work_id = {row.work_id: row for row in execution.definitions}
|
||||
assert by_work_id["m48-small-static-passage-regression"].evidence_contract == (
|
||||
@@ -108,10 +109,12 @@ def test_repository_registry_classifies_every_evidence_definition() -> None:
|
||||
)
|
||||
assert by_work_id["e47-semantic-slam-shadow"].lifecycle == "experimental"
|
||||
assert by_work_id["e47-semantic-slam-shadow"].isolation == "bounded-adapter"
|
||||
assert by_work_id["m48s-fixed-class-detector"].lifecycle == "experimental"
|
||||
assert by_work_id["m48s-fixed-class-detector"].isolation == "bounded-adapter"
|
||||
assert all(
|
||||
row.lifecycle == "canonical"
|
||||
for row in execution.definitions
|
||||
if row.work_id != "e47-semantic-slam-shadow"
|
||||
if row.work_id not in {"e47-semantic-slam-shadow", "m48s-fixed-class-detector"}
|
||||
)
|
||||
assert len(execution.definitions) + len(execution.legacy_work_ids) == len(
|
||||
evidence.definitions
|
||||
|
||||
@@ -80,7 +80,7 @@ def test_product_value_review_registry_covers_reviewed_laboratory_families() ->
|
||||
root / "config" / "laboratory-value-review.json"
|
||||
)
|
||||
|
||||
assert len(registry.entries) == 35
|
||||
assert len(registry.entries) == 36
|
||||
assert {entry.catalog_id for entry in registry.entries} >= {
|
||||
"e28-local-surface",
|
||||
"e46d-temporal-failure-audit",
|
||||
@@ -88,4 +88,5 @@ def test_product_value_review_registry_covers_reviewed_laboratory_families() ->
|
||||
"l31-pointpillars-ravnoves",
|
||||
"l34f-adjudicated-reference",
|
||||
"m4-replay-threat",
|
||||
"m48s-fixed-class-detector",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.laboratory import LaboratoryEvidenceRegistry
|
||||
from k1link.laboratory.evidence_report import verify_laboratory_evidence_result
|
||||
from k1link.laboratory.m48s_fixed_class_detector_lab import (
|
||||
FRAME_IDS,
|
||||
LAB_SCHEMA,
|
||||
M48SFixedClassDetectorLabError,
|
||||
build_m48s_fixed_class_detector_lab,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def test_m48s_lab_seals_visual_comparison_and_load_evidence(tmp_path: Path) -> None:
|
||||
result = build_m48s_fixed_class_detector_lab(
|
||||
repository_root=REPOSITORY_ROOT,
|
||||
output_root=tmp_path / "results",
|
||||
)
|
||||
manifest = result.manifest
|
||||
identity = manifest["identity"]
|
||||
identity_digest = hashlib.sha256(
|
||||
json.dumps(
|
||||
identity,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
).hexdigest()
|
||||
|
||||
assert manifest["schema_version"] == LAB_SCHEMA
|
||||
assert manifest["result_id"] == result.result_id
|
||||
assert result.result_id.endswith(identity_digest)
|
||||
assert manifest["identity_sha256"] == identity_digest
|
||||
assert len(manifest["artifacts"]) == 31
|
||||
assert manifest["method"]["completeness"] == "complete"
|
||||
assert manifest["bounded_question_accepted"] is True
|
||||
assert manifest["ground_truth"] is False
|
||||
assert manifest["decision"] == {
|
||||
"bounded_question_accepted": True,
|
||||
"selected_candidate": "rf-detr",
|
||||
"ready_for_reference_graph_shadow": True,
|
||||
"integrated_world_state_gate_evaluated": True,
|
||||
"integrated_world_state_gate_passed": True,
|
||||
"full_replay_visual_published": True,
|
||||
"detector_replacement_authorized": False,
|
||||
"production_accepted": False,
|
||||
}
|
||||
assert manifest["authority"]["navigation_or_safety_accepted"] is False
|
||||
assert manifest["metrics"]["detector_load"]["source_frames_consumed"] == 18_008
|
||||
assert manifest["metrics"]["detector_load"]["source_frame_replacements"] == 0
|
||||
assert manifest["metrics"]["detector_load"]["effective_consumed_fps"] >= 9.5
|
||||
assert manifest["metrics"]["detector_load"]["completion_age_p95_ms"] <= 175.0
|
||||
integrated = manifest["metrics"]["integrated_world_state"]
|
||||
assert integrated["source_frames_admitted"] == 4_489
|
||||
assert integrated["delivered_world_states"] == 4_481
|
||||
assert integrated["superseded_frames"] == 8
|
||||
assert integrated["effective_world_state_fps"] >= 9.5
|
||||
assert integrated["world_state_completion_age_p95_ms"] <= 175.0
|
||||
assert max(integrated["queue_high_watermarks"].values()) <= 2
|
||||
assert integrated["additional_inference_passes"] == 0
|
||||
assert integrated["failures"] == 0
|
||||
|
||||
catalog = json.loads((result.result_root / "catalog.json").read_text("utf-8"))
|
||||
assert catalog["frame_count"] == len(FRAME_IDS) == 11
|
||||
frame = json.loads((result.result_root / "frame-000253.json").read_text("utf-8"))
|
||||
assert not any(item["label"] == "dog" for item in frame["detections"]["yolox"])
|
||||
assert not any(item["label"] == "dog" for item in frame["detections"]["dfine"])
|
||||
assert any(item["label"] == "skateboard" for item in frame["detections"]["dfine"])
|
||||
assert [item["score"] for item in frame["detections"]["rf-detr"] if item["label"] == "dog"] == [
|
||||
0.741674
|
||||
]
|
||||
|
||||
registry = LaboratoryEvidenceRegistry.from_directory(
|
||||
REPOSITORY_ROOT / "config" / "laboratories"
|
||||
)
|
||||
definition = next(
|
||||
item for item in registry.definitions if item.work_id == "m48s-fixed-class-detector"
|
||||
)
|
||||
proof = verify_laboratory_evidence_result(definition, result.result_root)
|
||||
assert proof["result_id"] == result.result_id
|
||||
assert proof["artifact_count"] == 31
|
||||
|
||||
with pytest.raises(M48SFixedClassDetectorLabError, match="already exists"):
|
||||
build_m48s_fixed_class_detector_lab(
|
||||
repository_root=REPOSITORY_ROOT,
|
||||
output_root=tmp_path / "results",
|
||||
)
|
||||
@@ -0,0 +1,109 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.laboratory.m48s_fixed_class_detector_lab import (
|
||||
build_m48s_fixed_class_detector_lab,
|
||||
)
|
||||
from k1link.web.m48s_fixed_class_detector_lab_api import (
|
||||
build_m48s_fixed_class_detector_lab_router,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _fixture(tmp_path: Path) -> tuple[TestClient, Path, str]:
|
||||
root = tmp_path / "results"
|
||||
result = build_m48s_fixed_class_detector_lab(
|
||||
repository_root=REPOSITORY_ROOT,
|
||||
output_root=root,
|
||||
)
|
||||
app = FastAPI()
|
||||
app.include_router(
|
||||
build_m48s_fixed_class_detector_lab_router(
|
||||
root_provider=lambda: root,
|
||||
repository_root_provider=lambda: REPOSITORY_ROOT,
|
||||
)
|
||||
)
|
||||
return TestClient(app), result.result_root, result.result_id
|
||||
|
||||
|
||||
def test_m48s_lab_api_projects_verified_result_frame_and_camera(tmp_path: Path) -> None:
|
||||
client, result_root, result_id = _fixture(tmp_path)
|
||||
|
||||
catalog = client.get("/api/v1/laboratory/m48s/fixed-class-detector/results")
|
||||
assert catalog.status_code == 200
|
||||
assert catalog.json()["items"][0]["result_id"] == result_id
|
||||
assert catalog.json()["invalid_total"] == 0
|
||||
|
||||
result = client.get(f"/api/v1/laboratory/m48s/fixed-class-detector/{result_id}")
|
||||
assert result.status_code == 200
|
||||
assert result.json()["decision"]["selected_candidate"] == "rf-detr"
|
||||
assert result.json()["decision"]["integrated_world_state_gate_passed"] is True
|
||||
assert (
|
||||
result.json()["metrics"]["integrated_world_state"]["world_state_completion_age_p95_ms"]
|
||||
== 74.733648
|
||||
)
|
||||
assert result.json()["ground_truth"] is False
|
||||
assert len(result.json()["frames"]) == 11
|
||||
|
||||
timeline = client.get(
|
||||
f"/api/v1/laboratory/m48s/fixed-class-detector/{result_id}/timeline"
|
||||
)
|
||||
assert timeline.status_code == 200
|
||||
assert timeline.json()["frame_count"] == 4_489
|
||||
assert timeline.json()["world_state_frame_count"] == 4_481
|
||||
assert timeline.json()["superseded_frame_count"] == 8
|
||||
assert (
|
||||
timeline.json()["camera_point_delivery"]
|
||||
== "factory-kb4-projected-current-increment"
|
||||
)
|
||||
chunk = client.get(
|
||||
f"/api/v1/laboratory/m48s/fixed-class-detector/{result_id}/timeline/chunk",
|
||||
params={"start": 253, "count": 1},
|
||||
)
|
||||
assert chunk.status_code == 200
|
||||
replay_frame = chunk.json()["frames"][0]
|
||||
assert replay_frame["world_state_available"] is True
|
||||
assert replay_frame["camera_projection"] == "factory-kb4-exact"
|
||||
assert replay_frame["camera_projected_sample_count"] > 0
|
||||
assert any(
|
||||
item["semantic_hint"] == "dog" for item in replay_frame["camera_proposals"]
|
||||
)
|
||||
|
||||
frame = client.get(f"/api/v1/laboratory/m48s/fixed-class-detector/{result_id}/frames/000253")
|
||||
assert frame.status_code == 200
|
||||
assert any(item["label"] == "dog" for item in frame.json()["detections"]["rf-detr"])
|
||||
assert frame.json()["access"] == "read-only"
|
||||
|
||||
camera = client.get(
|
||||
f"/api/v1/laboratory/m48s/fixed-class-detector/{result_id}/frames/000253/camera"
|
||||
)
|
||||
assert camera.status_code == 200
|
||||
assert camera.headers["content-type"] == "image/jpeg"
|
||||
assert camera.content == (result_root / "frames/frame-000253.jpg").read_bytes()
|
||||
|
||||
assert (
|
||||
client.get(
|
||||
f"/api/v1/laboratory/m48s/fixed-class-detector/{result_id}/frames/not-a-frame"
|
||||
).status_code
|
||||
== 404
|
||||
)
|
||||
assert (
|
||||
client.get("/api/v1/laboratory/m48s/fixed-class-detector/not-a-result").status_code == 404
|
||||
)
|
||||
|
||||
|
||||
def test_m48s_lab_api_fails_closed_after_artifact_tamper(tmp_path: Path) -> None:
|
||||
client, result_root, result_id = _fixture(tmp_path)
|
||||
(result_root / "frame-000253.json").write_text("{}\n", encoding="utf-8")
|
||||
|
||||
response = client.get(f"/api/v1/laboratory/m48s/fixed-class-detector/{result_id}")
|
||||
assert response.status_code == 404
|
||||
|
||||
catalog = client.get("/api/v1/laboratory/m48s/fixed-class-detector/results")
|
||||
assert catalog.json()["items"] == []
|
||||
assert catalog.json()["invalid_total"] == 1
|
||||
@@ -0,0 +1,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.perception.detector import RF_DETR_SHADOW_PROVIDER_ID
|
||||
from k1link.perception.m48s_advisory import (
|
||||
AdvisoryFamily,
|
||||
advisory_policy_matrix,
|
||||
)
|
||||
from k1link.perception.object_understanding import AdvisoryResponse
|
||||
from k1link.perception.providers import ProviderRole, ReferencePerceptionGraphConfigV2
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
GRAPH_CONFIG = (
|
||||
REPOSITORY_ROOT
|
||||
/ "config/perception/m48s-rf-detr-reference-graph-shadow-v0.json"
|
||||
)
|
||||
|
||||
|
||||
def test_m48s_reference_graph_replaces_only_the_detector_pin() -> None:
|
||||
shadow_document = json.loads(GRAPH_CONFIG.read_text("utf-8"))
|
||||
canonical_document = json.loads(
|
||||
(REPOSITORY_ROOT / "config/perception/m4-reference-graph-v2.json").read_text(
|
||||
"utf-8"
|
||||
)
|
||||
)
|
||||
shadow = ReferencePerceptionGraphConfigV2.from_dict(shadow_document)
|
||||
canonical = ReferencePerceptionGraphConfigV2.from_dict(canonical_document)
|
||||
shadow_pins = {item.role: item for item in shadow.providers}
|
||||
canonical_pins = {item.role: item for item in canonical.providers}
|
||||
|
||||
assert shadow.graph_id == canonical.graph_id == "reference-perception-graph/v2"
|
||||
assert shadow.source_profile_id == canonical.source_profile_id
|
||||
assert shadow.queues == canonical.queues
|
||||
assert shadow.authority == canonical.authority
|
||||
assert shadow_pins[ProviderRole.DETECTOR].provider_id == RF_DETR_SHADOW_PROVIDER_ID
|
||||
assert shadow_pins[ProviderRole.DETECTOR] != canonical_pins[ProviderRole.DETECTOR]
|
||||
assert all(
|
||||
shadow_pins[role] == canonical_pins[role]
|
||||
for role in ProviderRole
|
||||
if role is not ProviderRole.DETECTOR
|
||||
)
|
||||
|
||||
|
||||
def test_m48s_reference_graph_pins_every_profile_digest() -> None:
|
||||
config = ReferencePerceptionGraphConfigV2.from_dict(
|
||||
json.loads(GRAPH_CONFIG.read_text("utf-8"))
|
||||
)
|
||||
paths = {
|
||||
ProviderRole.SOURCE: "m4-recorded-realtime-baseline-v1.json",
|
||||
ProviderRole.DETECTOR: "rf-detr-large-risk-shadow-v0.json",
|
||||
ProviderRole.GEOMETRY: "m4-geometry-association-v1.json",
|
||||
ProviderRole.TEMPORAL: "m4-temporal-motion-v1.json",
|
||||
ProviderRole.MOTION: "m4-temporal-motion-v1.json",
|
||||
ProviderRole.ROLLING: "m4-rolling-local-map-v1.json",
|
||||
ProviderRole.THREAT: "m4-replay-threat-v3.json",
|
||||
}
|
||||
pins = {item.role: item for item in config.providers}
|
||||
|
||||
for role, name in paths.items():
|
||||
payload = (REPOSITORY_ROOT / "config/perception" / name).read_bytes()
|
||||
assert pins[role].sha256 == hashlib.sha256(payload).hexdigest()
|
||||
|
||||
|
||||
def test_m48s_advisory_policy_is_bounded_distinct_and_commandless() -> None:
|
||||
matrix = advisory_policy_matrix()
|
||||
|
||||
assert set(matrix) == set(AdvisoryFamily)
|
||||
assert matrix[AdvisoryFamily.GENERIC_OBSTACLE] == (
|
||||
AdvisoryResponse.ROUTE_AROUND,
|
||||
)
|
||||
assert AdvisoryResponse.YIELD in matrix[AdvisoryFamily.PERSON]
|
||||
assert AdvisoryResponse.STOP in matrix[AdvisoryFamily.ANIMAL]
|
||||
assert AdvisoryResponse.REDUCE_SPEED in matrix[AdvisoryFamily.LIGHT_ROAD_USER]
|
||||
assert AdvisoryResponse.MONITOR in matrix[AdvisoryFamily.VEHICLE]
|
||||
assert len(set(matrix.values())) == len(matrix)
|
||||
@@ -0,0 +1,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULT_ID = (
|
||||
"m48s-reference-graph-shadow-gate-"
|
||||
"e8da7a521768daba0ead1a6e4803871ce3a85f91a7d8ee36c5719ac10433e791"
|
||||
)
|
||||
RESULT_ROOT = (
|
||||
REPOSITORY_ROOT
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/"
|
||||
"reference-graph-shadow-results"
|
||||
/ RESULT_ID
|
||||
)
|
||||
|
||||
|
||||
def test_m48s_complete_reference_graph_shadow_is_accepted_without_production_authority() -> None:
|
||||
manifest = json.loads((RESULT_ROOT / "manifest.json").read_text("utf-8"))
|
||||
identity = manifest["identity"]
|
||||
evidence = identity["evidence"]
|
||||
execution = evidence["execution"]
|
||||
completion = evidence["world_state_completion_age_ms"]
|
||||
|
||||
assert manifest["result_id"] == RESULT_ID
|
||||
assert identity["completed"] is True
|
||||
assert identity["accepted"] is True
|
||||
assert identity["production_accepted"] is False
|
||||
assert identity["decision"]["source_paced_runtime_gate_accepted"] is True
|
||||
assert identity["decision"]["detector_replacement_authorized"] is False
|
||||
assert execution["admitted_frames"] == 4489
|
||||
assert execution["delivered_world_states"] == 4481
|
||||
assert execution["terminal_outcomes"] == {"delivered": 4481, "superseded": 8}
|
||||
assert execution["effective_world_state_fps"] >= 9.5
|
||||
assert completion["p95"] <= 175.0
|
||||
assert all(evidence["checks"].values())
|
||||
assert evidence["semantic_advisory"]["additional_inference_passes"] == 0
|
||||
assert evidence["identity_continuity"]["duplicate_component_ids_within_frame"] == 0
|
||||
assert identity["authority"] == {
|
||||
"actuation_allowed": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"ground_truth": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
for name, expected_sha256 in manifest["artifacts"].items():
|
||||
assert hashlib.sha256((RESULT_ROOT / name).read_bytes()).hexdigest() == expected_sha256
|
||||
@@ -0,0 +1,60 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULT_ID = (
|
||||
"m48s-rf-detr-deployment-gate-"
|
||||
"2feb9e1b12a5588951ad35d63bf23cf6bdd579d54b5329d46d7696f88c444547"
|
||||
)
|
||||
RESULT_ROOT = (
|
||||
REPOSITORY_ROOT
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/rf-detr-deployment-results"
|
||||
/ RESULT_ID
|
||||
)
|
||||
|
||||
|
||||
def test_rf_detr_tensorrt_detector_is_ready_only_for_reference_graph_shadow() -> None:
|
||||
manifest = json.loads((RESULT_ROOT / "manifest.json").read_text("utf-8"))
|
||||
decision = manifest["decision"]
|
||||
evidence = manifest["evidence"]
|
||||
load = evidence["source_paced_load"]
|
||||
|
||||
assert manifest["result_id"] == RESULT_ID
|
||||
assert manifest["completed"] is True
|
||||
assert manifest["accepted"] is False
|
||||
assert decision == {
|
||||
"detector_source_paced_load_gate_passed": True,
|
||||
"integrated_world_state_gate_evaluated": False,
|
||||
"next_gate": (
|
||||
"run the RF-DETR shadow provider inside the complete reference graph and "
|
||||
"require world-state p95 <= 175 ms without changing false authority"
|
||||
),
|
||||
"production_accepted": False,
|
||||
"ready_for_reference_graph_shadow": True,
|
||||
"tensorrt_numeric_parity_passed": True,
|
||||
"tournament_finalist": True,
|
||||
}
|
||||
assert evidence["engine_sha256"] == (
|
||||
"986399ce706b7380472cf5e473232249fed6e628971d8007f6609e83128d46b8"
|
||||
)
|
||||
assert evidence["tensorrt_parity"]["passed"] is True
|
||||
assert evidence["tensorrt_parity"]["frame_000253_dog_present_in_tensorrt"] is True
|
||||
assert evidence["pytorch_quality_at_0_5"]["class_counts"] == evidence[
|
||||
"triton_quality_at_0_5"
|
||||
]["class_counts"]
|
||||
assert load["execution"]["source_frames_consumed"] == 18_008
|
||||
assert load["execution"]["source_frame_replacements"] == 0
|
||||
assert load["execution"]["effective_consumed_fps"] >= 9.5
|
||||
assert load["detector_completion_age_ms"]["p95"] <= 175.0
|
||||
assert load["gpu"]["gpu_memory_used_mib"]["maximum"] <= 20 * 1024
|
||||
assert load["gpu"]["longest_100_percent_gpu_sample_run"] == 0
|
||||
assert all(load["checks"].values())
|
||||
assert manifest["authority"] == {
|
||||
"actuation_allowed": False,
|
||||
"candidate_accepted": False,
|
||||
"commands_enabled": False,
|
||||
"ground_truth": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULT_ID = (
|
||||
"m48s-yolox-all-coco-shadow-"
|
||||
"7dbe6043b3fc12c7ddb162f609f883d86b34a4f2dd3785a632795f257e192d06"
|
||||
)
|
||||
RESULT_ROOT = (
|
||||
REPOSITORY_ROOT
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/yolox-all-coco-results"
|
||||
/ RESULT_ID
|
||||
)
|
||||
|
||||
|
||||
def test_all_coco_yolox_uses_one_inference_pass_with_bounded_postprocess_cost() -> None:
|
||||
manifest = json.loads((RESULT_ROOT / "manifest.json").read_text("utf-8"))
|
||||
metrics = manifest["metrics"]
|
||||
|
||||
assert manifest["result_id"] == RESULT_ID
|
||||
assert manifest["completed"] is True
|
||||
assert manifest["accepted"] is False
|
||||
assert metrics["frames"] == {"completed": 11, "requested": 11}
|
||||
assert metrics["inference_passes_per_frame"] == 1
|
||||
assert metrics["frozen_detection_count"] == 44
|
||||
assert metrics["all_coco_detection_count"] == 45
|
||||
assert metrics["added_detection_count"] == 1
|
||||
assert metrics["all_coco_class_counts"] == {
|
||||
"car": 36,
|
||||
"handbag": 1,
|
||||
"person": 3,
|
||||
"truck": 5,
|
||||
}
|
||||
benchmark = metrics["postprocess_benchmark"]
|
||||
assert benchmark["iterations_per_profile_per_frame"] == 20
|
||||
frozen_mean = benchmark["timing_ms"]["frozen_ms"]["mean"]
|
||||
all_coco_mean = benchmark["timing_ms"]["all_coco_ms"]["mean"]
|
||||
assert all_coco_mean - frozen_mean < 1.0
|
||||
assert metrics["all_coco_core_capacity_fps"] > 30.0
|
||||
assert manifest["authority"]["commands_enabled"] is False
|
||||
assert manifest["authority"]["navigation_or_safety_accepted"] is False
|
||||
@@ -0,0 +1,46 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULT_ID = (
|
||||
"m48s-mask-grounding-dino-shadow-"
|
||||
"b0a37f265223b4138754f76d5d7b8d17e7c4f5395481990f169fccc1645baba8"
|
||||
)
|
||||
RESULT_ROOT = (
|
||||
REPOSITORY_ROOT
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/mask-grounding-dino-results"
|
||||
/ RESULT_ID
|
||||
)
|
||||
|
||||
|
||||
def test_mask_grounding_dino_shadow_is_complete_but_semantically_rejected() -> None:
|
||||
manifest = json.loads((RESULT_ROOT / "manifest.json").read_text("utf-8"))
|
||||
report = json.loads((RESULT_ROOT / "report.json").read_text("utf-8"))
|
||||
|
||||
assert manifest["result_id"] == RESULT_ID
|
||||
assert manifest["completed"] is True
|
||||
assert manifest["accepted"] is False
|
||||
assert manifest["metrics"]["frames"] == {"completed": 11, "requested": 11}
|
||||
assert manifest["metrics"]["geometry_observation_count"] == 73
|
||||
assert manifest["metrics"]["raw_detection_count"] == 25
|
||||
assert manifest["metrics"]["mask_instance_count"] == 7
|
||||
assert manifest["metrics"]["geometry_binding_resolution_counts"] == {
|
||||
"ambiguous": 2,
|
||||
"selected": 4,
|
||||
"unresolved": 1,
|
||||
}
|
||||
assert manifest["metrics"]["combined_resolution_counts"] == {
|
||||
"ambiguous": 6,
|
||||
"unresolved": 1,
|
||||
}
|
||||
assert manifest["metrics"]["single_class_agent_probe"] == {
|
||||
"detection_counts": {"adult": 0, "child": 0, "dog": 0},
|
||||
"frame_indices": [253, 1228],
|
||||
"passed": False,
|
||||
}
|
||||
assert report["decision"]["semantic_quality_accepted"] is False
|
||||
assert report["decision"]["agent_semantics_accepted"] is False
|
||||
assert report["authority"]["commands_enabled"] is False
|
||||
assert report["authority"]["navigation_or_safety_accepted"] is False
|
||||
@@ -0,0 +1,175 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from k1link.perception.contracts import (
|
||||
EvidenceBasis,
|
||||
EvidenceCurrentness,
|
||||
MetricGeometry,
|
||||
ObstacleObservation,
|
||||
)
|
||||
from k1link.perception.geometry_math import ProjectedPointCloud
|
||||
from k1link.perception.mask_grounding_semantics import (
|
||||
MASK_GROUNDING_EVIDENCE_SCHEMA,
|
||||
MaskBindingResolution,
|
||||
MaskGroundingDetection,
|
||||
MaskLabelResolution,
|
||||
bind_mask_instances_to_geometry,
|
||||
cluster_mask_instances,
|
||||
load_mask_grounding_evidence,
|
||||
resolve_mask_instance_label,
|
||||
)
|
||||
|
||||
|
||||
def _observation(ordinal: int, source_ids: tuple[int, ...]) -> ObstacleObservation:
|
||||
return ObstacleObservation(
|
||||
observation_id=f"frame-000253:geometry:{ordinal}",
|
||||
occupancy_key=f"frame-000253:occupancy:{ordinal}",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000253",
|
||||
evidence_time_ns=253,
|
||||
basis=EvidenceBasis.LIDAR,
|
||||
currentness=EvidenceCurrentness.CURRENT,
|
||||
occupied_support=True,
|
||||
source_point_ids=source_ids,
|
||||
metric_geometry=MetricGeometry(
|
||||
coordinate_frame="map",
|
||||
centroid_xyz_m=(2.0 + ordinal, 0.0, 0.5),
|
||||
range_m=2.0 + ordinal,
|
||||
covariance_diagonal_m2=(0.1, 0.1, 0.1),
|
||||
),
|
||||
proposal_ids=(),
|
||||
semantic_hint=None,
|
||||
reason_codes=("test-geometry-only",),
|
||||
)
|
||||
|
||||
|
||||
def _projected() -> ProjectedPointCloud:
|
||||
return ProjectedPointCloud(
|
||||
pixels_xy=np.asarray(
|
||||
(
|
||||
(10.0, 10.0),
|
||||
(11.0, 10.0),
|
||||
(10.0, 11.0),
|
||||
(11.0, 11.0),
|
||||
(30.0, 30.0),
|
||||
(31.0, 30.0),
|
||||
(30.0, 31.0),
|
||||
(31.0, 31.0),
|
||||
),
|
||||
dtype=np.float64,
|
||||
),
|
||||
depths_m=np.ones(8, dtype=np.float64),
|
||||
source_indices=np.arange(8, dtype=np.int64),
|
||||
source_point_count=8,
|
||||
camera_front_point_count=8,
|
||||
)
|
||||
|
||||
|
||||
def _detection(
|
||||
detection_id: str,
|
||||
class_name: str,
|
||||
confidence: float,
|
||||
mask: np.ndarray,
|
||||
) -> MaskGroundingDetection:
|
||||
packed = mask.astype(np.uint8)
|
||||
return MaskGroundingDetection(
|
||||
detection_id=detection_id,
|
||||
prompt_set_id="urban-static/v0",
|
||||
class_id=0,
|
||||
class_name=class_name,
|
||||
confidence=confidence,
|
||||
box_xyxy=(1.0, 1.0, 40.0, 40.0),
|
||||
mask_sha256=hashlib.sha256(packed.tobytes()).hexdigest(),
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
|
||||
def test_empty_early_v0_ledger_is_read_without_inventing_boxes(tmp_path: Path) -> None:
|
||||
path = tmp_path / "frame-000253.npz"
|
||||
np.savez_compressed(
|
||||
path,
|
||||
schema_version=np.asarray(MASK_GROUNDING_EVIDENCE_SCHEMA),
|
||||
source_file_sha256=np.asarray("a" * 64),
|
||||
source_pixel_sha256=np.asarray("b" * 64),
|
||||
class_ids=np.empty(0, dtype=np.int16),
|
||||
class_names=np.empty(0, dtype="U128"),
|
||||
scores=np.empty(0, dtype=np.float32),
|
||||
boxes_xyxy=np.empty(0, dtype=np.float32),
|
||||
masks=np.empty((0, 600, 800), dtype=np.uint8),
|
||||
)
|
||||
|
||||
evidence = load_mask_grounding_evidence(path, prompt_set_id="urban-agents/v0")
|
||||
|
||||
assert evidence.detections == ()
|
||||
assert evidence.source_file_sha256 == "a" * 64
|
||||
|
||||
|
||||
def test_same_mask_becomes_one_instance_and_conflicting_name_stays_ambiguous() -> None:
|
||||
mask = np.zeros((600, 800), dtype=np.bool_)
|
||||
mask[5:20, 5:20] = True
|
||||
instances = cluster_mask_instances(
|
||||
(
|
||||
_detection("trash", "trash bin", 0.43, mask),
|
||||
_detection("cart", "shopping cart", 0.41, mask),
|
||||
)
|
||||
)
|
||||
|
||||
bindings = bind_mask_instances_to_geometry(
|
||||
instances,
|
||||
observations=(_observation(0, (0, 1, 2, 3)), _observation(1, (4, 5, 6, 7))),
|
||||
projected=_projected(),
|
||||
)
|
||||
label = resolve_mask_instance_label(instances[0])
|
||||
|
||||
assert len(instances) == 1
|
||||
assert bindings[0].resolution is MaskBindingResolution.SELECTED
|
||||
assert bindings[0].selected_observation_id == "frame-000253:geometry:0"
|
||||
assert label.resolution is MaskLabelResolution.AMBIGUOUS
|
||||
assert label.selected_label is None
|
||||
|
||||
|
||||
def test_mask_covering_two_obstacles_does_not_claim_either() -> None:
|
||||
mask = np.zeros((600, 800), dtype=np.bool_)
|
||||
mask[5:40, 5:40] = True
|
||||
instance = cluster_mask_instances((_detection("wide", "trash bin", 0.7, mask),))
|
||||
|
||||
binding = bind_mask_instances_to_geometry(
|
||||
instance,
|
||||
observations=(_observation(0, (0, 1, 2, 3)), _observation(1, (4, 5, 6, 7))),
|
||||
projected=_projected(),
|
||||
)[0]
|
||||
|
||||
assert binding.resolution is MaskBindingResolution.AMBIGUOUS
|
||||
assert binding.selected_observation_id is None
|
||||
assert binding.reason_code == "mask-covers-multiple-geometry-observations"
|
||||
|
||||
|
||||
def test_two_distinct_masks_cannot_claim_one_geometry_observation() -> None:
|
||||
narrow = np.zeros((600, 800), dtype=np.bool_)
|
||||
narrow[9:13, 9:13] = True
|
||||
wide = np.zeros((600, 800), dtype=np.bool_)
|
||||
wide[1:25, 1:25] = True
|
||||
instances = cluster_mask_instances(
|
||||
(
|
||||
_detection("narrow", "bollard", 0.8, narrow),
|
||||
_detection("wide", "post", 0.8, wide),
|
||||
)
|
||||
)
|
||||
|
||||
bindings = bind_mask_instances_to_geometry(
|
||||
instances,
|
||||
observations=(_observation(0, (0, 1, 2, 3)),),
|
||||
projected=_projected(),
|
||||
)
|
||||
|
||||
assert len(instances) == 2
|
||||
assert all(item.resolution is MaskBindingResolution.AMBIGUOUS for item in bindings)
|
||||
assert all(item.selected_observation_id is None for item in bindings)
|
||||
assert all(
|
||||
item.reason_code == "observation-claimed-by-multiple-mask-instances"
|
||||
for item in bindings
|
||||
)
|
||||
@@ -0,0 +1,317 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.perception.contracts import (
|
||||
EvidenceBasis,
|
||||
EvidenceCurrentness,
|
||||
MetricGeometry,
|
||||
MotionState,
|
||||
ObstacleObservation,
|
||||
)
|
||||
from k1link.perception.object_understanding import (
|
||||
AdvisoryResponse,
|
||||
AdvisoryRiskAssessment,
|
||||
AgencyState,
|
||||
EvidenceKind,
|
||||
EvidenceProvenance,
|
||||
ObjectStateEstimate,
|
||||
ObjectUnderstanding,
|
||||
ObjectUnderstandingError,
|
||||
RiskBasis,
|
||||
RiskLevel,
|
||||
SemanticDecision,
|
||||
SemanticHypothesis,
|
||||
SemanticResolution,
|
||||
StateBasis,
|
||||
load_object_semantic_vocabulary,
|
||||
validate_object_understanding,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
VOCABULARY_PATH = REPOSITORY_ROOT / "config/perception/object-semantic-vocabulary-v0.json"
|
||||
|
||||
|
||||
def _observation(*, semantic_hint: str | None = None) -> ObstacleObservation:
|
||||
return ObstacleObservation(
|
||||
observation_id="observation-vehicle-1",
|
||||
occupancy_key="occupied-component-17",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000253",
|
||||
evidence_time_ns=35_421_857_292,
|
||||
basis=EvidenceBasis.FUSED,
|
||||
currentness=EvidenceCurrentness.CURRENT,
|
||||
occupied_support=True,
|
||||
source_point_ids=(4, 7, 9),
|
||||
metric_geometry=MetricGeometry(
|
||||
coordinate_frame="map",
|
||||
centroid_xyz_m=(4.0, 1.0, 0.5),
|
||||
range_m=4.15,
|
||||
covariance_diagonal_m2=(0.04, 0.04, 0.09),
|
||||
),
|
||||
proposal_ids=("proposal-vehicle-1",),
|
||||
semantic_hint=semantic_hint,
|
||||
reason_codes=("current-qualified-points",),
|
||||
)
|
||||
|
||||
|
||||
def _detector_evidence(*, frame_id: str = "frame-000253") -> EvidenceProvenance:
|
||||
return EvidenceProvenance(
|
||||
evidence_id="evidence-grounding-dino-1",
|
||||
kind=EvidenceKind.DETECTOR,
|
||||
source_id="RAVNOVES00",
|
||||
frame_id=frame_id,
|
||||
provider_id="grounding-dino-open-vocabulary/v1",
|
||||
model_id="grounding-dino-tensorrt",
|
||||
model_revision="worker-006-probe-20260825",
|
||||
preprocess_id="kb4-rectified-rgb/v1",
|
||||
prompt_set_id="urban-risk-groups/v0",
|
||||
)
|
||||
|
||||
|
||||
def _temporal_evidence() -> EvidenceProvenance:
|
||||
return EvidenceProvenance(
|
||||
evidence_id="evidence-temporal-1",
|
||||
kind=EvidenceKind.TEMPORAL,
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000253",
|
||||
provider_id="temporal-occupied/v1",
|
||||
model_id=None,
|
||||
model_revision=None,
|
||||
preprocess_id=None,
|
||||
)
|
||||
|
||||
|
||||
def _car_understanding() -> ObjectUnderstanding:
|
||||
detector = _detector_evidence()
|
||||
temporal = _temporal_evidence()
|
||||
return ObjectUnderstanding(
|
||||
understanding_id="understanding-vehicle-1",
|
||||
vocabulary_id="missioncore.urban-object-semantics/v0",
|
||||
generated_monotonic_ns=1_020_000,
|
||||
observation=_observation(semantic_hint="car"),
|
||||
hypotheses=(
|
||||
SemanticHypothesis(
|
||||
rank=1,
|
||||
class_id="vehicle.car",
|
||||
raw_label="car",
|
||||
confidence=0.79,
|
||||
evidence_ids=(detector.evidence_id,),
|
||||
),
|
||||
SemanticHypothesis(
|
||||
rank=2,
|
||||
class_id="vehicle.heavy",
|
||||
raw_label="heavy vehicle",
|
||||
confidence=0.12,
|
||||
evidence_ids=(detector.evidence_id,),
|
||||
),
|
||||
),
|
||||
semantic=SemanticDecision(
|
||||
resolution=SemanticResolution.SELECTED,
|
||||
selected_class_id="vehicle.car",
|
||||
selected_confidence=0.79,
|
||||
reason_codes=("top-hypothesis-qualified",),
|
||||
),
|
||||
state=ObjectStateEstimate(
|
||||
motion=MotionState.STATIONARY,
|
||||
motion_confidence=0.85,
|
||||
agency=AgencyState.SELF_PROPELLED,
|
||||
agency_basis=StateBasis.CLASS_PRIOR,
|
||||
evidence_ids=(detector.evidence_id, temporal.evidence_id),
|
||||
reason_codes=("stationary-observed-vehicle-prior-retained",),
|
||||
),
|
||||
risk=AdvisoryRiskAssessment(
|
||||
policy_id="urban-object-risk/v0",
|
||||
level=RiskLevel.ELEVATED,
|
||||
confidence=0.71,
|
||||
basis=RiskBasis.FUSED,
|
||||
responses=(
|
||||
AdvisoryResponse.MONITOR,
|
||||
AdvisoryResponse.REDUCE_SPEED,
|
||||
AdvisoryResponse.ROUTE_AROUND,
|
||||
),
|
||||
evidence_ids=(detector.evidence_id, temporal.evidence_id),
|
||||
reason_codes=("stationary-vehicle-may-start-moving",),
|
||||
),
|
||||
provenance=(detector, temporal),
|
||||
)
|
||||
|
||||
|
||||
def _unknown_understanding() -> ObjectUnderstanding:
|
||||
return ObjectUnderstanding(
|
||||
understanding_id="understanding-unknown-1",
|
||||
vocabulary_id="missioncore.urban-object-semantics/v0",
|
||||
generated_monotonic_ns=1_020_000,
|
||||
observation=_observation(),
|
||||
hypotheses=(),
|
||||
semantic=SemanticDecision(
|
||||
resolution=SemanticResolution.UNRESOLVED,
|
||||
selected_class_id=None,
|
||||
selected_confidence=None,
|
||||
reason_codes=("semantic-evidence-unavailable",),
|
||||
),
|
||||
state=ObjectStateEstimate(
|
||||
motion=MotionState.UNKNOWN,
|
||||
motion_confidence=0.0,
|
||||
agency=AgencyState.UNKNOWN,
|
||||
agency_basis=StateBasis.UNKNOWN,
|
||||
evidence_ids=(),
|
||||
reason_codes=("state-evidence-unavailable",),
|
||||
),
|
||||
risk=AdvisoryRiskAssessment(
|
||||
policy_id="urban-object-risk/v0",
|
||||
level=RiskLevel.UNKNOWN,
|
||||
confidence=0.0,
|
||||
basis=RiskBasis.UNKNOWN,
|
||||
responses=(AdvisoryResponse.ROUTE_AROUND,),
|
||||
evidence_ids=(),
|
||||
reason_codes=("unknown-object-remains-occupied",),
|
||||
),
|
||||
provenance=(),
|
||||
)
|
||||
|
||||
|
||||
def test_object_understanding_round_trip_is_strict_and_keeps_v1_geometry() -> None:
|
||||
value = _car_understanding()
|
||||
observation_before = value.observation.to_dict()
|
||||
document = json.loads(json.dumps(value.to_dict()))
|
||||
|
||||
restored = ObjectUnderstanding.from_dict(document)
|
||||
|
||||
assert restored == value
|
||||
assert restored.observation.to_dict() == observation_before
|
||||
assert restored.occupancy_identity == "occupied-component-17"
|
||||
assert restored.observation.metric_geometry is not None
|
||||
assert restored.observation.metric_geometry.range_m == pytest.approx(4.15)
|
||||
document["unexpected"] = True
|
||||
with pytest.raises(ObjectUnderstandingError, match="fields are incompatible"):
|
||||
ObjectUnderstanding.from_dict(document)
|
||||
|
||||
|
||||
def test_stationary_vehicle_keeps_separate_self_propelled_prior_and_advisory_risk() -> None:
|
||||
value = _car_understanding()
|
||||
|
||||
assert value.state.motion is MotionState.STATIONARY
|
||||
assert value.state.agency is AgencyState.SELF_PROPELLED
|
||||
assert value.state.agency_basis is StateBasis.CLASS_PRIOR
|
||||
assert value.risk.level is RiskLevel.ELEVATED
|
||||
assert AdvisoryResponse.REDUCE_SPEED in value.risk.responses
|
||||
assert value.authority.commands_enabled is False
|
||||
assert value.authority.actuation_allowed is False
|
||||
assert value.authority.navigation_or_safety_accepted is False
|
||||
|
||||
|
||||
def test_unknown_semantics_never_erase_metric_occupancy() -> None:
|
||||
value = _unknown_understanding()
|
||||
|
||||
assert value.semantic.resolution is SemanticResolution.UNRESOLVED
|
||||
assert value.hypotheses == ()
|
||||
assert value.observation.occupied_support is True
|
||||
assert value.observation.source_point_ids == (4, 7, 9)
|
||||
assert value.occupancy_identity == value.observation.occupancy_identity
|
||||
assert value.risk.responses == (AdvisoryResponse.ROUTE_AROUND,)
|
||||
|
||||
|
||||
def test_ranked_hypotheses_and_selected_class_must_agree() -> None:
|
||||
value = _car_understanding()
|
||||
with pytest.raises(ObjectUnderstandingError, match="ordered by confidence"):
|
||||
replace(
|
||||
value,
|
||||
hypotheses=(
|
||||
replace(value.hypotheses[0], confidence=0.10),
|
||||
replace(value.hypotheses[1], confidence=0.90),
|
||||
),
|
||||
)
|
||||
with pytest.raises(ObjectUnderstandingError, match="match one ranked hypothesis"):
|
||||
replace(
|
||||
value,
|
||||
semantic=replace(
|
||||
value.semantic,
|
||||
selected_class_id="animal.dog",
|
||||
selected_confidence=0.79,
|
||||
),
|
||||
)
|
||||
with pytest.raises(ObjectUnderstandingError, match="two hypotheses"):
|
||||
replace(
|
||||
value,
|
||||
hypotheses=value.hypotheses[:1],
|
||||
semantic=SemanticDecision(
|
||||
resolution=SemanticResolution.CONFLICT,
|
||||
selected_class_id=None,
|
||||
selected_confidence=None,
|
||||
reason_codes=("provider-disagreement",),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_evidence_cannot_escape_geometry_frame_or_be_fabricated() -> None:
|
||||
value = _car_understanding()
|
||||
with pytest.raises(ObjectUnderstandingError, match="escaped"):
|
||||
replace(value, provenance=(_detector_evidence(frame_id="frame-000254"),))
|
||||
with pytest.raises(ObjectUnderstandingError, match="unknown evidence"):
|
||||
replace(
|
||||
value,
|
||||
hypotheses=(
|
||||
replace(value.hypotheses[0], evidence_ids=("missing-evidence",)),
|
||||
value.hypotheses[1],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_executable_vocabulary_resolves_current_urban_labels_and_hierarchy() -> None:
|
||||
vocabulary = load_object_semantic_vocabulary(VOCABULARY_PATH)
|
||||
|
||||
assert vocabulary.vocabulary_id == "missioncore.urban-object-semantics/v0"
|
||||
assert vocabulary.resolve_label("trash bin") == "static.trash-bin"
|
||||
assert vocabulary.resolve_label("Dog") == "animal.dog"
|
||||
assert vocabulary.resolve_label("sidewalk-curb") == "terrain.curb"
|
||||
assert {
|
||||
label: vocabulary.resolve_label(label)
|
||||
for label in ("car", "person", "bicycle", "road sign")
|
||||
} == {
|
||||
"car": "vehicle.car",
|
||||
"person": "human.unknown",
|
||||
"bicycle": "vehicle.bicycle",
|
||||
"road sign": "static.road-sign",
|
||||
}
|
||||
assert vocabulary.resolve_label("unseen alien object") is None
|
||||
assert vocabulary.ancestors("human.child") == (
|
||||
"human.unknown",
|
||||
"object.unknown",
|
||||
)
|
||||
validate_object_understanding(_car_understanding(), vocabulary)
|
||||
|
||||
|
||||
def test_vocabulary_validation_rejects_undeclared_class_and_authority_change(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
vocabulary = load_object_semantic_vocabulary(VOCABULARY_PATH)
|
||||
value = _car_understanding()
|
||||
with pytest.raises(ObjectUnderstandingError, match="undeclared classes"):
|
||||
validate_object_understanding(
|
||||
replace(
|
||||
value,
|
||||
hypotheses=(
|
||||
replace(value.hypotheses[0], class_id="vehicle.hovercraft"),
|
||||
value.hypotheses[1],
|
||||
),
|
||||
semantic=replace(
|
||||
value.semantic,
|
||||
selected_class_id="vehicle.hovercraft",
|
||||
),
|
||||
),
|
||||
vocabulary,
|
||||
)
|
||||
|
||||
document = json.loads(VOCABULARY_PATH.read_text("utf-8"))
|
||||
incompatible = copy.deepcopy(document)
|
||||
incompatible["policies"]["planner_command_authority"] = True
|
||||
path = tmp_path / "vocabulary.json"
|
||||
path.write_text(json.dumps(incompatible), "utf-8")
|
||||
with pytest.raises(ObjectUnderstandingError, match="authority policy"):
|
||||
load_object_semantic_vocabulary(path)
|
||||
@@ -0,0 +1,281 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from k1link.perception.contracts import (
|
||||
BoundingRegion2D,
|
||||
EvidenceBasis,
|
||||
EvidenceCurrentness,
|
||||
MetricGeometry,
|
||||
ObstacleObservation,
|
||||
)
|
||||
from k1link.perception.object_understanding import (
|
||||
AdvisoryResponse,
|
||||
AgencyState,
|
||||
SemanticResolution,
|
||||
StateBasis,
|
||||
load_object_semantic_vocabulary,
|
||||
)
|
||||
from k1link.perception.open_vocabulary_semantics import (
|
||||
OpenVocabularyDetection,
|
||||
OpenVocabularySemanticError,
|
||||
bind_object_understandings,
|
||||
fuse_open_vocabulary_detections,
|
||||
load_open_vocabulary_semantic_profile,
|
||||
parse_tao_grounding_dino_labels,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
PROFILE_PATH = REPOSITORY_ROOT / "config/perception/open-vocabulary-semantic-shadow-v0.json"
|
||||
VOCABULARY_PATH = REPOSITORY_ROOT / "config/perception/object-semantic-vocabulary-v0.json"
|
||||
VALID_FOV_MASK = np.ones((600, 800), dtype=np.bool_)
|
||||
|
||||
|
||||
def _detection(
|
||||
detection_id: str,
|
||||
raw_label: str,
|
||||
confidence: float,
|
||||
region: tuple[float, float, float, float],
|
||||
*,
|
||||
prompt_set_id: str = "urban-static/v0",
|
||||
) -> OpenVocabularyDetection:
|
||||
return OpenVocabularyDetection(
|
||||
detection_id=detection_id,
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000121",
|
||||
prompt_set_id=prompt_set_id,
|
||||
raw_label=raw_label,
|
||||
confidence=confidence,
|
||||
region=BoundingRegion2D(*region),
|
||||
)
|
||||
|
||||
|
||||
def _observation(
|
||||
proposal_id: str | None,
|
||||
*,
|
||||
ordinal: int,
|
||||
) -> ObstacleObservation:
|
||||
return ObstacleObservation(
|
||||
observation_id=f"frame-000121:observation-{ordinal}",
|
||||
occupancy_key=f"frame-000121:occupancy-{ordinal}",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000121",
|
||||
evidence_time_ns=121,
|
||||
basis=EvidenceBasis.FUSED if proposal_id else EvidenceBasis.LIDAR,
|
||||
currentness=EvidenceCurrentness.CURRENT,
|
||||
occupied_support=True,
|
||||
source_point_ids=(ordinal,),
|
||||
metric_geometry=MetricGeometry(
|
||||
coordinate_frame="map",
|
||||
centroid_xyz_m=(1.0, 2.0, 0.5),
|
||||
range_m=2.2,
|
||||
covariance_diagonal_m2=(0.1, 0.1, 0.1),
|
||||
),
|
||||
proposal_ids=(proposal_id,) if proposal_id else (),
|
||||
semantic_hint="static.trash-bin" if proposal_id else None,
|
||||
reason_codes=("test-current-occupied-support",),
|
||||
)
|
||||
|
||||
|
||||
def test_profile_is_raw_kb4_and_preserves_false_authority() -> None:
|
||||
profile = load_open_vocabulary_semantic_profile(PROFILE_PATH)
|
||||
|
||||
assert profile.coordinate_space == "raw-kb4"
|
||||
assert (profile.width, profile.height) == (800, 600)
|
||||
assert profile.provider_id == "nvidia-tao-grounding-dino-trt/v1"
|
||||
assert profile.model_sha256 == (
|
||||
"6895acdc6b588e923f753e37b3bd18869e064256e5ecc1b2b9853e8c51125f94"
|
||||
)
|
||||
assert tuple(item.prompt_set_id for item in profile.prompt_groups) == (
|
||||
"urban-static/v0",
|
||||
"urban-agents/v0",
|
||||
"urban-vehicles/v0",
|
||||
)
|
||||
|
||||
|
||||
def test_tao_parser_keeps_source_coordinates_and_rejects_rectified_boxes(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
profile = load_open_vocabulary_semantic_profile(PROFILE_PATH)
|
||||
labels = tmp_path / "frame-000121.txt"
|
||||
labels.write_text(
|
||||
"trash bin 0.00 0 0.00 336.0 123.0 359.0 160.0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.826\n",
|
||||
"utf-8",
|
||||
)
|
||||
|
||||
parsed = parse_tao_grounding_dino_labels(
|
||||
labels,
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000121",
|
||||
prompt_set_id="urban-static/v0",
|
||||
profile=profile,
|
||||
)
|
||||
|
||||
assert len(parsed) == 1
|
||||
assert parsed[0].raw_label == "trash bin"
|
||||
assert parsed[0].region.as_tuple() == (336.0, 123.0, 359.0, 160.0)
|
||||
labels.write_text(
|
||||
"trash bin 0.00 0 0.00 336.0 123.0 900.0 160.0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.826\n",
|
||||
"utf-8",
|
||||
)
|
||||
with pytest.raises(OpenVocabularySemanticError, match="raw image coordinate space"):
|
||||
parse_tao_grounding_dino_labels(
|
||||
labels,
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000121",
|
||||
prompt_set_id="urban-static/v0",
|
||||
profile=profile,
|
||||
)
|
||||
|
||||
|
||||
def test_tao_parser_translates_geometry_crop_back_to_raw_coordinates(tmp_path: Path) -> None:
|
||||
profile = load_open_vocabulary_semantic_profile(PROFILE_PATH)
|
||||
labels = tmp_path / "frame-000121-geometry-roi-000.txt"
|
||||
labels.write_text(
|
||||
"dog 0.00 0 0.00 10.0 20.0 50.0 70.0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.714\n",
|
||||
"utf-8",
|
||||
)
|
||||
|
||||
parsed = parse_tao_grounding_dino_labels(
|
||||
labels,
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000121",
|
||||
prompt_set_id="urban-agents/v0",
|
||||
profile=profile,
|
||||
image_width=96,
|
||||
image_height=96,
|
||||
offset_x=200.0,
|
||||
offset_y=150.0,
|
||||
detection_scope_id="frame-000121:geometry-roi-000",
|
||||
)
|
||||
|
||||
assert parsed[0].detection_id.startswith("frame-000121:geometry-roi-000")
|
||||
assert parsed[0].region.as_tuple() == (210.0, 170.0, 250.0, 220.0)
|
||||
|
||||
|
||||
def test_prompt_collisions_fuse_before_geometry_and_background_box_is_removed() -> None:
|
||||
profile = load_open_vocabulary_semantic_profile(PROFILE_PATH)
|
||||
vocabulary = load_object_semantic_vocabulary(VOCABULARY_PATH)
|
||||
detections = (
|
||||
_detection("trash", "trash bin", 0.82, (300.0, 100.0, 360.0, 200.0)),
|
||||
_detection("cone", "traffic cone", 0.35, (301.0, 101.0, 361.0, 201.0)),
|
||||
_detection(
|
||||
"dog",
|
||||
"dog",
|
||||
0.71,
|
||||
(100.0, 250.0, 180.0, 340.0),
|
||||
prompt_set_id="urban-agents/v0",
|
||||
),
|
||||
_detection(
|
||||
"background",
|
||||
"concrete hemisphere",
|
||||
0.66,
|
||||
(0.0, 100.0, 800.0, 600.0),
|
||||
),
|
||||
)
|
||||
|
||||
result = fuse_open_vocabulary_detections(
|
||||
detections,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
valid_fov_mask=VALID_FOV_MASK,
|
||||
)
|
||||
|
||||
assert result.input_detection_count == 4
|
||||
assert result.invalid_area_count == 1
|
||||
assert len(result.bindings) == 2
|
||||
assert sum(len(item.detections) for item in result.bindings) == 3
|
||||
trash = next(
|
||||
item for item in result.bindings if item.proposal.semantic_hint == "static.trash-bin"
|
||||
)
|
||||
assert len(trash.detections) == 2
|
||||
assert trash.proposal.objectness == pytest.approx(0.82)
|
||||
|
||||
|
||||
def test_binding_keeps_ranked_semantics_separate_from_state_risk_and_occupancy() -> None:
|
||||
profile = load_open_vocabulary_semantic_profile(PROFILE_PATH)
|
||||
vocabulary = load_object_semantic_vocabulary(VOCABULARY_PATH)
|
||||
fusion = fuse_open_vocabulary_detections(
|
||||
(
|
||||
_detection("trash", "trash bin", 0.82, (300.0, 100.0, 360.0, 200.0)),
|
||||
_detection("cone", "traffic cone", 0.35, (301.0, 101.0, 361.0, 201.0)),
|
||||
),
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
valid_fov_mask=VALID_FOV_MASK,
|
||||
)
|
||||
proposal = fusion.proposals[0]
|
||||
observations = (
|
||||
_observation(proposal.proposal_id, ordinal=1),
|
||||
_observation(None, ordinal=2),
|
||||
)
|
||||
|
||||
understandings = bind_object_understandings(
|
||||
observations,
|
||||
bindings=fusion.bindings,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=121,
|
||||
)
|
||||
|
||||
semantic = understandings[0]
|
||||
assert tuple(item.class_id for item in semantic.hypotheses) == (
|
||||
"static.trash-bin",
|
||||
"static.traffic-cone",
|
||||
)
|
||||
assert semantic.semantic.resolution is SemanticResolution.SELECTED
|
||||
assert semantic.semantic.selected_class_id == "static.trash-bin"
|
||||
assert semantic.state.agency is AgencyState.INERT
|
||||
assert semantic.state.agency_basis is StateBasis.CLASS_PRIOR
|
||||
assert semantic.state.motion.value == "unknown"
|
||||
assert semantic.risk.level.value == "unknown"
|
||||
assert semantic.risk.responses == (AdvisoryResponse.ROUTE_AROUND,)
|
||||
assert semantic.authority.navigation_or_safety_accepted is False
|
||||
assert semantic.observation.source_point_ids == (1,)
|
||||
geometry_only = understandings[1]
|
||||
assert geometry_only.semantic.resolution is SemanticResolution.UNRESOLVED
|
||||
assert geometry_only.hypotheses == ()
|
||||
assert geometry_only.observation.source_point_ids == (2,)
|
||||
|
||||
|
||||
def test_close_semantic_scores_remain_ambiguous() -> None:
|
||||
profile = load_open_vocabulary_semantic_profile(PROFILE_PATH)
|
||||
vocabulary = load_object_semantic_vocabulary(VOCABULARY_PATH)
|
||||
fusion = fuse_open_vocabulary_detections(
|
||||
(
|
||||
_detection(
|
||||
"adult",
|
||||
"adult person",
|
||||
0.64,
|
||||
(100.0, 50.0, 200.0, 350.0),
|
||||
prompt_set_id="urban-agents/v0",
|
||||
),
|
||||
_detection(
|
||||
"child",
|
||||
"child",
|
||||
0.59,
|
||||
(101.0, 51.0, 201.0, 351.0),
|
||||
prompt_set_id="urban-agents/v0",
|
||||
),
|
||||
),
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
valid_fov_mask=VALID_FOV_MASK,
|
||||
)
|
||||
proposal = fusion.proposals[0]
|
||||
|
||||
result = bind_object_understandings(
|
||||
(_observation(proposal.proposal_id, ordinal=1),),
|
||||
bindings=fusion.bindings,
|
||||
profile=profile,
|
||||
vocabulary=vocabulary,
|
||||
generated_monotonic_ns=121,
|
||||
)[0]
|
||||
|
||||
assert result.semantic.resolution is SemanticResolution.AMBIGUOUS
|
||||
assert result.semantic.selected_class_id is None
|
||||
assert result.state.agency is AgencyState.UNKNOWN
|
||||
assert result.state.agency_basis is StateBasis.UNKNOWN
|
||||
@@ -4,7 +4,7 @@ import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from queue import Queue
|
||||
@@ -39,6 +39,7 @@ from k1link.perception.contracts import (
|
||||
TimestampBundle,
|
||||
)
|
||||
from k1link.perception.graph import (
|
||||
DeliveredFrame,
|
||||
GraphExecutionError,
|
||||
GraphRunMode,
|
||||
GraphRunResult,
|
||||
@@ -460,6 +461,8 @@ def _graph_v2(
|
||||
capacity: int = 8,
|
||||
run_mode: GraphRunMode = GraphRunMode.LOSSLESS_REPLAY,
|
||||
terminal_timeout_ns: int = 500_000_000,
|
||||
delivery_observer: Callable[[DeliveredFrame, int], None] | None = None,
|
||||
delivery_evidence_observer: Callable[..., None] | None = None,
|
||||
) -> ReferencePerceptionGraphV2:
|
||||
return ReferencePerceptionGraphV2(
|
||||
config=_config_v2(capacity, terminal_timeout_ns),
|
||||
@@ -471,6 +474,8 @@ def _graph_v2(
|
||||
rolling=_Rolling(),
|
||||
threat=_Threat(),
|
||||
run_mode=run_mode,
|
||||
delivery_observer=delivery_observer,
|
||||
delivery_evidence_observer=delivery_evidence_observer,
|
||||
clock_ns=lambda: 10_000,
|
||||
)
|
||||
|
||||
@@ -527,6 +532,50 @@ def test_reference_graph_v2_publishes_current_and_retained_occupancy() -> None:
|
||||
}
|
||||
|
||||
|
||||
def test_reference_graph_v2_observes_final_delivery_completion_age() -> None:
|
||||
observed: list[tuple[int, int, int]] = []
|
||||
|
||||
def observe(delivery: DeliveredFrame, completion_age_ns: int) -> None:
|
||||
observed.append(
|
||||
(
|
||||
delivery.sequence,
|
||||
delivery.obstacle_map.output_age_ns,
|
||||
completion_age_ns,
|
||||
)
|
||||
)
|
||||
|
||||
result = _graph_v2(
|
||||
_Source((_packet(0, source_age_ns=123),)),
|
||||
delivery_observer=observe,
|
||||
).run()
|
||||
|
||||
assert result.state is GraphState.STOPPED
|
||||
assert observed == [(0, 123, 123)]
|
||||
|
||||
|
||||
def test_reference_graph_v2_observes_exact_delivery_evidence_inputs() -> None:
|
||||
observed: list[tuple[int, int, tuple[str, ...], frozenset[str], int]] = []
|
||||
|
||||
def observe(delivery, packet, proposals, associated_ids, completion_age_ns) -> None:
|
||||
observed.append(
|
||||
(
|
||||
delivery.sequence,
|
||||
packet.envelope.sequence,
|
||||
tuple(proposal.proposal_id for proposal in proposals),
|
||||
associated_ids,
|
||||
completion_age_ns,
|
||||
)
|
||||
)
|
||||
|
||||
result = _graph_v2(
|
||||
_Source((_packet(0, source_age_ns=123),)),
|
||||
delivery_evidence_observer=observe,
|
||||
).run()
|
||||
|
||||
assert result.state is GraphState.STOPPED
|
||||
assert observed == [(0, 0, ("proposal-0",), frozenset({"proposal-0"}), 123)]
|
||||
|
||||
|
||||
def test_reference_graph_v2_lossless_mode_applies_bounded_backpressure() -> None:
|
||||
release = Event()
|
||||
|
||||
@@ -784,6 +833,32 @@ def test_decoded_recorded_source_attaches_images_without_detector_logic(tmp_path
|
||||
assert int(packets[1].image_payload[0, 0, 0]) == 7
|
||||
|
||||
|
||||
def test_decoded_recorded_source_primes_decoder_before_source_clock() -> None:
|
||||
events: list[str] = []
|
||||
|
||||
class Source(RecordedRavnoves00Source):
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
def packets(self, stop_event: Event) -> Iterator[SourcePacket]:
|
||||
events.append("source-clock-started")
|
||||
if not stop_event.is_set():
|
||||
yield _packet(0)
|
||||
|
||||
class Decoder:
|
||||
def frames(self, stop_event: Event) -> Iterator[np.ndarray]:
|
||||
events.append("decoder-primed")
|
||||
if not stop_event.is_set():
|
||||
yield np.zeros((600, 800, 3), dtype=np.uint8)
|
||||
|
||||
packets = list(
|
||||
DecodedRecordedSource(source=Source(), decoder=Decoder()).packets(Event())
|
||||
)
|
||||
|
||||
assert len(packets) == 1
|
||||
assert events == ["decoder-primed", "source-clock-started"]
|
||||
|
||||
|
||||
def test_camera_only_path_never_invents_metric_occupancy_or_free_space() -> None:
|
||||
result = _graph(_Source((_packet(0, lidar=False),))).run()
|
||||
delivery = result.deliveries[0]
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from k1link.perception.contracts import (
|
||||
ClockBasis,
|
||||
ModalityOutcome,
|
||||
ModalityStatus,
|
||||
SourceEnvelope,
|
||||
TimestampBundle,
|
||||
)
|
||||
from k1link.perception.detector import (
|
||||
RF_DETR_SHADOW_MODEL_ID,
|
||||
RF_DETR_SHADOW_PREPROCESS_ID,
|
||||
RF_DETR_SHADOW_PROVIDER_ID,
|
||||
RfDetrShadowDetectorProvider,
|
||||
)
|
||||
from k1link.perception.providers import SourcePacket
|
||||
from k1link.perception.rf_detr_object_detector import (
|
||||
RF_DETR_CONFIG,
|
||||
RF_DETR_ENGINE_SHA256,
|
||||
RF_DETR_FP16_ONNX_SHA256,
|
||||
RfDetrConfig,
|
||||
RfDetrDetectorError,
|
||||
RfDetrRawOutput,
|
||||
TritonRfDetrHttpInferenceBackend,
|
||||
postprocess_rf_detr,
|
||||
preprocess_raw_kb4_rf_detr,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _status() -> ModalityStatus:
|
||||
return ModalityStatus(True, ModalityOutcome.AVAILABLE, "test-available")
|
||||
|
||||
|
||||
def _packet(sequence: int, image: object) -> SourcePacket:
|
||||
return SourcePacket(
|
||||
envelope=SourceEnvelope(
|
||||
source_id="RAVNOVES00",
|
||||
session_id="20260720T065719Z_viewer_live",
|
||||
frame_id=f"frame-{sequence:06d}",
|
||||
sequence=sequence,
|
||||
timestamps=TimestampBundle(
|
||||
utc_ns=1_000 + sequence,
|
||||
monotonic_ns=2_000 + sequence,
|
||||
source_ns=3_000 + sequence,
|
||||
clock_basis=ClockBasis.RECORDED_HOST,
|
||||
),
|
||||
source_age_ns=0,
|
||||
binding_reason="test-recorded-source",
|
||||
calibration_id="camera-1-kb4-test",
|
||||
representation_id="registered-map-increment-v1",
|
||||
image=_status(),
|
||||
registered_point_increment=_status(),
|
||||
pose=_status(),
|
||||
),
|
||||
image_payload=image,
|
||||
registered_point_increment_payload=("points", sequence),
|
||||
pose_payload=("pose", sequence),
|
||||
)
|
||||
|
||||
|
||||
class _Resizer:
|
||||
def __init__(self) -> None:
|
||||
self.source: NDArray[np.uint8] | None = None
|
||||
|
||||
def resize(
|
||||
self, image: NDArray[np.uint8], width: int, height: int
|
||||
) -> NDArray[np.uint8]:
|
||||
self.source = image.copy()
|
||||
output = np.empty((height, width, 3), dtype=np.uint8)
|
||||
output[:, :, 0] = 255
|
||||
output[:, :, 1] = 0
|
||||
output[:, :, 2] = 127
|
||||
return output
|
||||
|
||||
|
||||
class _Backend:
|
||||
def __init__(self, output: RfDetrRawOutput) -> None:
|
||||
self.output = output
|
||||
self.calls = 0
|
||||
|
||||
def infer(self, tensor: NDArray[np.float32]) -> RfDetrRawOutput:
|
||||
assert tensor.shape == (1, 3, 704, 704)
|
||||
assert tensor.dtype == np.float32
|
||||
self.calls += 1
|
||||
return self.output
|
||||
|
||||
|
||||
def _output() -> RfDetrRawOutput:
|
||||
boxes = np.zeros((1, 300, 4), dtype=np.float16)
|
||||
logits = np.full((1, 300, 91), -20.0, dtype=np.float16)
|
||||
boxes[0, 0] = (0.5, 0.5, 0.25, np.float16(1 / 3))
|
||||
logits[0, 0, 18] = np.float16(math.log(3.0)) # dog, score 0.75
|
||||
boxes[0, 1] = (0.25, 0.25, 0.1, 0.2)
|
||||
logits[0, 1, 1] = np.float16(math.log(4.0)) # person, score 0.80
|
||||
boxes[0, 2] = (0.75, 0.25, 0.1, 0.2)
|
||||
logits[0, 2, 62] = np.float16(math.log(9.0)) # chair, non-risk
|
||||
logits[0, 3, 12] = np.float16(math.log(9.0)) # unused COCO slot
|
||||
return RfDetrRawOutput(boxes=boxes, logits=logits)
|
||||
|
||||
|
||||
def test_preprocess_masks_bgr_converts_rgb_stretches_and_normalizes() -> None:
|
||||
image = np.zeros((600, 800, 3), dtype=np.uint8)
|
||||
image[:, :] = (10, 20, 30)
|
||||
mask = np.ones((600, 800), dtype=np.bool_)
|
||||
mask[0, 0] = False
|
||||
resizer = _Resizer()
|
||||
|
||||
tensor = preprocess_raw_kb4_rf_detr(image, mask, resizer=resizer)
|
||||
|
||||
assert resizer.source is not None
|
||||
assert tuple(resizer.source[1, 1]) == (30, 20, 10)
|
||||
assert tuple(resizer.source[0, 0]) == (114, 114, 114)
|
||||
assert tensor.shape == (1, 3, 704, 704)
|
||||
assert tensor.dtype == np.float32
|
||||
assert tensor[0, 0, 0, 0] == pytest.approx((1.0 - 0.485) / 0.229)
|
||||
assert tensor[0, 1, 0, 0] == pytest.approx((0.0 - 0.456) / 0.224)
|
||||
assert tensor[0, 2, 0, 0] == pytest.approx((127 / 255.0 - 0.406) / 0.225)
|
||||
|
||||
|
||||
def test_postprocess_maps_sparse_coco_slots_and_emits_only_risk_classes() -> None:
|
||||
result = postprocess_rf_detr(_output(), np.ones((600, 800), dtype=np.bool_))
|
||||
|
||||
assert tuple(item.label for item in result.detections) == ("person", "dog")
|
||||
assert result.detections[0].score == pytest.approx(0.8, abs=0.001)
|
||||
assert result.detections[1].score == pytest.approx(0.75, abs=0.001)
|
||||
assert result.detections[1].bbox_xyxy == pytest.approx(
|
||||
(300.0, 200.0, 500.0, 400.0), abs=0.03
|
||||
)
|
||||
assert dict(result.rejected) == {"non-risk-class": 1, "unmapped-class-slot": 1}
|
||||
|
||||
with pytest.raises(RfDetrDetectorError, match="tensor types"):
|
||||
postprocess_rf_detr(
|
||||
RfDetrRawOutput(
|
||||
boxes=cast(NDArray[np.float16], _output().boxes.astype(np.float32)),
|
||||
logits=_output().logits,
|
||||
),
|
||||
np.ones((600, 800), dtype=np.bool_),
|
||||
)
|
||||
|
||||
|
||||
def test_shadow_provider_uses_one_pass_and_preserves_semantic_hints() -> None:
|
||||
backend = _Backend(_output())
|
||||
provider = RfDetrShadowDetectorProvider(
|
||||
mask=np.ones((600, 800), dtype=np.bool_),
|
||||
backend=backend,
|
||||
resizer=_Resizer(),
|
||||
clock_ns=iter((10, 30)).__next__,
|
||||
)
|
||||
|
||||
proposals = provider.detect(_packet(7, np.zeros((600, 800, 3), dtype=np.uint8)))
|
||||
|
||||
assert backend.calls == 1
|
||||
assert tuple(item.semantic_hint for item in proposals) == ("person", "dog")
|
||||
assert all(item.provider_id == RF_DETR_SHADOW_PROVIDER_ID for item in proposals)
|
||||
assert all(item.model_id == RF_DETR_SHADOW_MODEL_ID for item in proposals)
|
||||
assert all(item.preprocess_id == RF_DETR_SHADOW_PREPROCESS_ID for item in proposals)
|
||||
assert provider.snapshot().completed_frames == 1
|
||||
assert provider.snapshot().proposal_count == 2
|
||||
assert provider.snapshot().core_duration_ns == 20
|
||||
|
||||
|
||||
def test_shadow_profile_is_fixed_and_transport_pins_model_version() -> None:
|
||||
assert RF_DETR_CONFIG.minimum_score == 0.25
|
||||
with pytest.raises(RfDetrDetectorError, match="cannot be tuned"):
|
||||
RfDetrConfig(minimum_score=0.5)
|
||||
|
||||
backend = TritonRfDetrHttpInferenceBackend("http://127.0.0.1:8100")
|
||||
try:
|
||||
assert backend.path == "/v2/models/rf_detr_large/versions/1/infer"
|
||||
finally:
|
||||
backend.close()
|
||||
with pytest.raises(RfDetrDetectorError, match="explicit HTTP origin"):
|
||||
TritonRfDetrHttpInferenceBackend("http://user:secret@127.0.0.1:8100")
|
||||
|
||||
|
||||
def test_shadow_profile_pins_worker_engine_and_retains_false_authority() -> None:
|
||||
profile = json.loads(
|
||||
(REPOSITORY_ROOT / "config/perception/rf-detr-large-risk-shadow-v0.json").read_text(
|
||||
"utf-8"
|
||||
)
|
||||
)
|
||||
|
||||
assert profile["model"]["strongly_typed_fp16_onnx_sha256"] == RF_DETR_FP16_ONNX_SHA256
|
||||
assert (
|
||||
profile["model"]["worker_006_rtx4090_tensorrt_11_engine_sha256"]
|
||||
== RF_DETR_ENGINE_SHA256
|
||||
)
|
||||
assert profile["emission"]["single_inference_per_source_frame"] is True
|
||||
assert profile["emission"]["geometry_owns_static_occupancy"] is True
|
||||
assert profile["emission"]["unlisted_semantic_classes_emitted"] is False
|
||||
assert not any(profile["authority"].values())
|
||||
@@ -0,0 +1,263 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.laboratory.semantic_object_quality import (
|
||||
SemanticObjectQualityError,
|
||||
SemanticTruthLabel,
|
||||
load_semantic_object_quality_profile,
|
||||
score_semantic_object_quality,
|
||||
)
|
||||
from k1link.perception.contracts import (
|
||||
EvidenceBasis,
|
||||
EvidenceCurrentness,
|
||||
MetricGeometry,
|
||||
MotionState,
|
||||
ObstacleObservation,
|
||||
)
|
||||
from k1link.perception.object_understanding import (
|
||||
AdvisoryResponse,
|
||||
AdvisoryRiskAssessment,
|
||||
AgencyState,
|
||||
EvidenceKind,
|
||||
EvidenceProvenance,
|
||||
ObjectStateEstimate,
|
||||
ObjectUnderstanding,
|
||||
RiskBasis,
|
||||
RiskLevel,
|
||||
SemanticDecision,
|
||||
SemanticHypothesis,
|
||||
SemanticResolution,
|
||||
StateBasis,
|
||||
load_object_semantic_vocabulary,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
VOCABULARY_PATH = REPOSITORY_ROOT / "config/perception/object-semantic-vocabulary-v0.json"
|
||||
PROFILE_PATH = REPOSITORY_ROOT / "config/perception/m48s-semantic-object-quality-v0.json"
|
||||
|
||||
|
||||
def _observation(index: int) -> ObstacleObservation:
|
||||
return ObstacleObservation(
|
||||
observation_id=f"observation-{index}",
|
||||
occupancy_key=f"occupied-{index}",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id=f"frame-{index:06d}",
|
||||
evidence_time_ns=index * 1_000_000,
|
||||
basis=EvidenceBasis.FUSED,
|
||||
currentness=EvidenceCurrentness.CURRENT,
|
||||
occupied_support=True,
|
||||
source_point_ids=(index,),
|
||||
metric_geometry=MetricGeometry(
|
||||
coordinate_frame="map",
|
||||
centroid_xyz_m=(float(index), 0.0, 0.5),
|
||||
range_m=float(index + 1),
|
||||
covariance_diagonal_m2=(0.04, 0.04, 0.09),
|
||||
),
|
||||
proposal_ids=(f"proposal-{index}",),
|
||||
semantic_hint=None,
|
||||
reason_codes=("current-qualified-points",),
|
||||
)
|
||||
|
||||
|
||||
def _prediction(
|
||||
index: int,
|
||||
*,
|
||||
hypotheses: tuple[tuple[str, str, float], ...],
|
||||
selected_class_id: str | None,
|
||||
) -> ObjectUnderstanding:
|
||||
observation = _observation(index)
|
||||
evidence = EvidenceProvenance(
|
||||
evidence_id=f"semantic-evidence-{index}",
|
||||
kind=EvidenceKind.DETECTOR,
|
||||
source_id=observation.source_id,
|
||||
frame_id=observation.frame_id,
|
||||
provider_id="semantic-candidate/v0",
|
||||
model_id="semantic-model",
|
||||
model_revision="candidate-1",
|
||||
preprocess_id="rgb/v1",
|
||||
prompt_set_id="urban-risk-groups/v0",
|
||||
)
|
||||
ranked = tuple(
|
||||
SemanticHypothesis(
|
||||
rank=rank,
|
||||
class_id=class_id,
|
||||
raw_label=raw_label,
|
||||
confidence=confidence,
|
||||
evidence_ids=(evidence.evidence_id,),
|
||||
)
|
||||
for rank, (class_id, raw_label, confidence) in enumerate(hypotheses, start=1)
|
||||
)
|
||||
selected = next(
|
||||
(item for item in ranked if item.class_id == selected_class_id),
|
||||
None,
|
||||
)
|
||||
return ObjectUnderstanding(
|
||||
understanding_id=f"understanding-{index}",
|
||||
vocabulary_id="missioncore.urban-object-semantics/v0",
|
||||
generated_monotonic_ns=index * 1_000_000 + 1,
|
||||
observation=observation,
|
||||
hypotheses=ranked,
|
||||
semantic=SemanticDecision(
|
||||
resolution=(
|
||||
SemanticResolution.SELECTED
|
||||
if selected is not None
|
||||
else SemanticResolution.UNRESOLVED
|
||||
),
|
||||
selected_class_id=None if selected is None else selected.class_id,
|
||||
selected_confidence=None if selected is None else selected.confidence,
|
||||
reason_codes=(
|
||||
"top-hypothesis-qualified"
|
||||
if selected is not None
|
||||
else "semantic-evidence-insufficient",
|
||||
),
|
||||
),
|
||||
state=ObjectStateEstimate(
|
||||
motion=MotionState.UNKNOWN,
|
||||
motion_confidence=0.0,
|
||||
agency=AgencyState.UNKNOWN,
|
||||
agency_basis=StateBasis.UNKNOWN,
|
||||
evidence_ids=(),
|
||||
reason_codes=("motion-evidence-unavailable",),
|
||||
),
|
||||
risk=AdvisoryRiskAssessment(
|
||||
policy_id="urban-object-risk/v0",
|
||||
level=RiskLevel.UNKNOWN,
|
||||
confidence=0.0,
|
||||
basis=RiskBasis.UNKNOWN,
|
||||
responses=(AdvisoryResponse.ROUTE_AROUND,),
|
||||
evidence_ids=(),
|
||||
reason_codes=("semantic-quality-does-not-score-risk",),
|
||||
),
|
||||
provenance=(evidence,),
|
||||
)
|
||||
|
||||
|
||||
def _truth(index: int, class_id: str) -> SemanticTruthLabel:
|
||||
return SemanticTruthLabel(
|
||||
label_id=f"semantic-label-{index}",
|
||||
observation_id=f"observation-{index}",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id=f"frame-{index:06d}",
|
||||
class_id=class_id,
|
||||
reviewer_count=2,
|
||||
adjudicated=True,
|
||||
)
|
||||
|
||||
|
||||
def test_semantic_quality_scores_exact_group_topk_and_unresolved_separately() -> None:
|
||||
vocabulary = load_object_semantic_vocabulary(VOCABULARY_PATH)
|
||||
profile = load_semantic_object_quality_profile(PROFILE_PATH)
|
||||
predictions = (
|
||||
_prediction(
|
||||
1,
|
||||
hypotheses=(
|
||||
("human.unknown", "person", 0.70),
|
||||
("human.child", "child", 0.65),
|
||||
),
|
||||
selected_class_id="human.unknown",
|
||||
),
|
||||
_prediction(
|
||||
2,
|
||||
hypotheses=(("animal.dog", "dog", 0.80),),
|
||||
selected_class_id="animal.dog",
|
||||
),
|
||||
_prediction(3, hypotheses=(), selected_class_id=None),
|
||||
)
|
||||
truth = (
|
||||
_truth(1, "human.child"),
|
||||
_truth(2, "animal.dog"),
|
||||
_truth(3, "vehicle.car"),
|
||||
)
|
||||
|
||||
result = score_semantic_object_quality(
|
||||
predictions=predictions,
|
||||
truth=truth,
|
||||
vocabulary=vocabulary,
|
||||
profile=profile,
|
||||
)
|
||||
|
||||
metrics = result.report["metrics"]
|
||||
assert isinstance(metrics, dict)
|
||||
assert metrics["prediction_coverage"] == pytest.approx(1.0)
|
||||
assert metrics["exact_top1_accuracy"] == pytest.approx(1 / 3)
|
||||
assert metrics["coarse_group_accuracy"] == pytest.approx(2 / 3)
|
||||
assert metrics["exact_top_k_recall"] == pytest.approx(2 / 3)
|
||||
assert metrics["unresolved_fraction"] == pytest.approx(1 / 3)
|
||||
assert result.report["candidate_semantic_gate_passed"] is False
|
||||
assert result.cases[0].exact_top1_correct is False
|
||||
assert result.cases[0].coarse_group_correct is True
|
||||
assert result.cases[0].exact_top_k_hit is True
|
||||
|
||||
|
||||
def test_semantic_quality_reports_missing_projection_without_calling_it_detection() -> None:
|
||||
vocabulary = load_object_semantic_vocabulary(VOCABULARY_PATH)
|
||||
profile = load_semantic_object_quality_profile(PROFILE_PATH)
|
||||
result = score_semantic_object_quality(
|
||||
predictions=(
|
||||
_prediction(
|
||||
1,
|
||||
hypotheses=(("human.child", "child", 0.90),),
|
||||
selected_class_id="human.child",
|
||||
),
|
||||
),
|
||||
truth=(_truth(1, "human.child"), _truth(2, "animal.dog")),
|
||||
vocabulary=vocabulary,
|
||||
profile=profile,
|
||||
)
|
||||
|
||||
metrics = result.report["metrics"]
|
||||
assert isinstance(metrics, dict)
|
||||
assert metrics["prediction_coverage"] == pytest.approx(0.5)
|
||||
assert result.cases[1].resolution == "unavailable"
|
||||
scope = result.report["scope"]
|
||||
assert isinstance(scope, dict)
|
||||
assert scope["object_presence_scored"] is False
|
||||
|
||||
|
||||
def test_semantic_truth_is_strict_and_requires_independent_adjudication() -> None:
|
||||
label = _truth(1, "human.child")
|
||||
document = json.loads(json.dumps(label.to_dict()))
|
||||
assert SemanticTruthLabel.from_dict(document) == label
|
||||
document["category"] = "child"
|
||||
with pytest.raises(SemanticObjectQualityError, match="fields are incompatible"):
|
||||
SemanticTruthLabel.from_dict(document)
|
||||
with pytest.raises(SemanticObjectQualityError, match="two independent reviewers"):
|
||||
SemanticTruthLabel(
|
||||
label_id="semantic-label-1",
|
||||
observation_id="observation-1",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000001",
|
||||
class_id="human.child",
|
||||
reviewer_count=1,
|
||||
adjudicated=True,
|
||||
)
|
||||
with pytest.raises(SemanticObjectQualityError, match="must be adjudicated"):
|
||||
SemanticTruthLabel(
|
||||
label_id="semantic-label-1",
|
||||
observation_id="observation-1",
|
||||
source_id="RAVNOVES00",
|
||||
frame_id="frame-000001",
|
||||
class_id="human.child",
|
||||
reviewer_count=2,
|
||||
adjudicated=False,
|
||||
)
|
||||
|
||||
|
||||
def test_semantic_quality_profile_stays_separate_from_presence_and_risk(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
profile = load_semantic_object_quality_profile(PROFILE_PATH)
|
||||
assert profile.profile_id == "m48s-urban-semantic-object-quality/v0"
|
||||
assert profile.vocabulary_id == "missioncore.urban-object-semantics/v0"
|
||||
assert profile.top_k == 5
|
||||
|
||||
document = json.loads(PROFILE_PATH.read_text("utf-8"))
|
||||
document["scope"]["object_presence_scored"] = True
|
||||
changed = tmp_path / "m48s-profile-changed.json"
|
||||
changed.write_text(json.dumps(document), "utf-8")
|
||||
with pytest.raises(SemanticObjectQualityError, match="scope changed"):
|
||||
load_semantic_object_quality_profile(changed)
|
||||
@@ -0,0 +1,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.perception.semantic_shadow_replay import read_semantic_shadow_replay
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULT_ROOT = (
|
||||
REPOSITORY_ROOT
|
||||
/ ".runtime/compute-experiments/m48s-semantic-shadow/results"
|
||||
/ "m48s-semantic-shadow-a237a8860bd4655b4fae981ba23a5e4d86a560ed243ee7efdf867d87f5071739"
|
||||
)
|
||||
|
||||
|
||||
def test_bounded_raw_kb4_semantic_shadow_is_complete_but_not_accepted() -> None:
|
||||
result = read_semantic_shadow_replay(RESULT_ROOT)
|
||||
|
||||
assert result.completed is True
|
||||
assert result.accepted is False
|
||||
assert result.metrics["frames"] == {
|
||||
"completed": 11,
|
||||
"requested": 11,
|
||||
"source_available": 11,
|
||||
}
|
||||
assert result.metrics["detections"] == {
|
||||
"below_confidence": 0,
|
||||
"fused_proposals": 164,
|
||||
"invalid_area": 16,
|
||||
"outside_valid_fov": 0,
|
||||
"raw": 310,
|
||||
"retained": 294,
|
||||
}
|
||||
semantics = result.metrics["semantics"]
|
||||
assert isinstance(semantics, dict)
|
||||
assert semantics["resolution_counts"] == {
|
||||
"ambiguous": 4,
|
||||
"selected": 40,
|
||||
"unresolved": 165,
|
||||
}
|
||||
assert result.report["decision"] == {
|
||||
"navigation_or_safety_accepted": False,
|
||||
"next_gate": "M48S human-reviewed semantic object quality slice",
|
||||
"raw_kb4_coordinate_binding_completed": True,
|
||||
"risk_policy_accepted": False,
|
||||
"semantic_quality_accepted": False,
|
||||
}
|
||||
assert result.report["authority"]["commands_enabled"] is False
|
||||
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.perception.detector import ALL_COCO_YOLOX_PROVIDER_ID
|
||||
from k1link.perception.yolox_object_detector import (
|
||||
ALL_COCO_CLASS_IDS,
|
||||
ALL_COCO_YOLOX_CONFIG,
|
||||
COCO_CLASSES,
|
||||
YOLOX_MODEL_SHA256,
|
||||
)
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
PROFILE_PATH = REPOSITORY_ROOT / "config/perception/yolox-s-all-coco-shadow-v2.json"
|
||||
|
||||
|
||||
def test_all_coco_profile_matches_executable_provider_contract() -> None:
|
||||
profile = json.loads(PROFILE_PATH.read_text("utf-8"))
|
||||
|
||||
assert profile["schema_version"] == "missioncore.yolox-detector-profile/v2"
|
||||
assert profile["provider_id"] == ALL_COCO_YOLOX_PROVIDER_ID
|
||||
assert profile["model"]["model_sha256"] == YOLOX_MODEL_SHA256
|
||||
assert profile["model"]["additional_inference_passes"] == 0
|
||||
assert tuple(profile["postprocess"]["target_class_ids"]) == ALL_COCO_CLASS_IDS
|
||||
assert ALL_COCO_YOLOX_CONFIG.target_class_ids == tuple(range(len(COCO_CLASSES)))
|
||||
assert "dog" in profile["class_policy"]["risk_groups"]["animal"]
|
||||
assert profile["authority"]["commands_enabled"] is False
|
||||
assert profile["authority"]["navigation_or_safety_accepted"] is False
|
||||
@@ -17,13 +17,19 @@ from k1link.perception.contracts import (
|
||||
TimestampBundle,
|
||||
)
|
||||
from k1link.perception.detector import (
|
||||
ALL_COCO_YOLOX_PROVIDER_ID,
|
||||
FROZEN_YOLOX_PROVIDER_ID,
|
||||
AllCocoYoloxDetectorProvider,
|
||||
DetectorProviderError,
|
||||
FrozenYoloxDetectorProvider,
|
||||
proposals_from_detections,
|
||||
)
|
||||
from k1link.perception.providers import SourcePacket
|
||||
from k1link.perception.yolox_object_detector import (
|
||||
ALL_COCO_CLASS_IDS,
|
||||
ALL_COCO_YOLOX_CONFIG,
|
||||
COCO_CLASSES,
|
||||
AllCocoYoloxConfig,
|
||||
FrozenYoloxConfig,
|
||||
TritonHttpInferenceBackend,
|
||||
YoloxDetection,
|
||||
@@ -102,6 +108,14 @@ def _one_person_output() -> NDArray[np.float32]:
|
||||
return output
|
||||
|
||||
|
||||
def _one_dog_output() -> NDArray[np.float32]:
|
||||
output = np.zeros((1, 8400, 85), dtype=np.float32)
|
||||
output[0, 0, :4] = [40.0, 30.0, math.log(10.0), math.log(10.0)]
|
||||
output[0, 0, 4] = 0.9
|
||||
output[0, 0, 5 + 16] = 0.9
|
||||
return output
|
||||
|
||||
|
||||
def test_frozen_preprocess_and_postprocess_match_the_e46j_contract() -> None:
|
||||
image = np.full((600, 800, 3), 7, dtype=np.uint8)
|
||||
mask = np.ones((600, 800), dtype=np.bool_)
|
||||
@@ -174,6 +188,39 @@ def test_frozen_profile_rejects_in_place_threshold_tuning() -> None:
|
||||
FrozenYoloxConfig(minimum_score=0.51)
|
||||
|
||||
|
||||
def test_all_coco_profile_emits_dog_without_another_inference_pass() -> None:
|
||||
mask = np.ones((600, 800), dtype=np.bool_)
|
||||
|
||||
assert postprocess_yolox(_one_dog_output(), mask).detections == ()
|
||||
all_coco = postprocess_yolox(
|
||||
_one_dog_output(),
|
||||
mask,
|
||||
config=ALL_COCO_YOLOX_CONFIG,
|
||||
)
|
||||
backend = _Backend(_one_dog_output())
|
||||
provider = AllCocoYoloxDetectorProvider(
|
||||
mask=mask,
|
||||
backend=backend,
|
||||
resizer=_Resizer(),
|
||||
)
|
||||
proposals = provider.detect(
|
||||
_packet(16, np.zeros((600, 800, 3), dtype=np.uint8))
|
||||
)
|
||||
|
||||
assert tuple(range(80)) == ALL_COCO_CLASS_IDS
|
||||
assert len(COCO_CLASSES) == 80
|
||||
assert tuple(item.label for item in all_coco.detections) == ("dog",)
|
||||
assert backend.calls == 1
|
||||
assert len(proposals) == 1
|
||||
assert proposals[0].provider_id == ALL_COCO_YOLOX_PROVIDER_ID
|
||||
assert proposals[0].semantic_hint == "dog"
|
||||
|
||||
|
||||
def test_all_coco_profile_is_versioned_and_cannot_be_tuned_in_place() -> None:
|
||||
with pytest.raises(YoloxDetectorError, match="all-COCO.*cannot be tuned"):
|
||||
AllCocoYoloxConfig(target_class_ids=(0, 16))
|
||||
|
||||
|
||||
def test_triton_transport_pins_the_frozen_model_version() -> None:
|
||||
backend = TritonHttpInferenceBackend("http://127.0.0.1:8000")
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user