feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
# Shared first-pass semantic evidence
|
||||
|
||||
This is the active first-pass semantic stage as of the owner-authorized integration
|
||||
on 2026-10-16 (Worker release `fd9350739b785225`).
|
||||
It replaces repeated image encodings in `orthophoto/ortho_segment.py` and
|
||||
`full_plan/semantic_layers.py`. Each identical crop is encoded once; the
|
||||
existing per-class prompts, threshold, output precision, overlap aggregation,
|
||||
opacity admission and output file layout are retained. It adds no persistent
|
||||
embedding cache, extra renders, retained object geometry or recovery passes.
|
||||
|
||||
`semantic_survey.py` separates the common crop schedule and model inference
|
||||
from the output consumers. `semantic_survey_stage.py` loads the existing pinned
|
||||
SAM3 model and writes the normal/ground surface and paint/building masks.
|
||||
The `semantic-survey.json` receipt distinguishes image encodings from prompt
|
||||
decodes and marks completion explicitly. Per-consumer timings are joint timings
|
||||
and must not be added together.
|
||||
|
||||
Run `evaluation/qualify_shared_survey.py CONFIG.json` from the canonical
|
||||
repository virtual environment. The harness reserves the Core simulation queue,
|
||||
uses the installed Worker006 images, creates an immutable session and releases
|
||||
only its own containers and reservation after cleanup is confirmed. It compares
|
||||
fresh control outputs to fresh candidate outputs against the same read-only
|
||||
Gaussian renders. `test_semantic_survey.py` runs in the existing mapper image;
|
||||
it does not require installing scientific dependencies on the operator Mac.
|
||||
|
||||
The configuration selects an installed release, its definition SHA-256, and
|
||||
named scene observation directories. Use a new `shared-survey-*` session ID for
|
||||
every attempt. A completed session cannot be overwritten. An optional
|
||||
`consumer_comparison` replays the unchanged first full-map assembler using the
|
||||
previously verified semantic pair and the original immutable geometric prefix.
|
||||
It checks every feature ID, property and geometry; it does not replay the entire
|
||||
refinement chain or establish object recall.
|
||||
|
||||
Qualification on 2026-10-16: both Maroseyka (68 tiles) and Smolensk 6.3 (21 tiles)
|
||||
had exact array, coverage and model parity. Image encodings fell from 5,004 to
|
||||
2,545; all 11,935 prompt decodes were preserved. Fresh paired semantic runs took
|
||||
684.437 -> 513.359 seconds and 342.407 -> 251.484 seconds respectively, including
|
||||
container/model startup. The unchanged Smolensk first assembler produced the
|
||||
same 108 features, including exact geometry and properties. This is a single
|
||||
paired run on development scenes, not a full-chain timing or holdout result.
|
||||
|
||||
Evidence sessions in the canonical `.runtime/simulation-qualifications/`:
|
||||
|
||||
- `shared-survey-pilot-20261016142916`: four unit tests and a two-tile pilot.
|
||||
- `shared-survey-full-20261016143244`: both complete scene semantic comparisons.
|
||||
- `shared-survey-consumers-20261016150544`: the real first assembler comparison.
|
||||
|
||||
The integrated graph contains 90 stages, previously 91. A scoped release keeps
|
||||
the installed predecessor intact and changes only the coordinator, definition,
|
||||
two shared-semantic modules and timing profile. The real Windows layout and
|
||||
provider identity, worker startup, Core health and queue/API tests passed. The
|
||||
new stage uses the measured 251.484-second Smolensk seed; it is an approximate
|
||||
ETA weight, not a new whole-street timing measurement. The owner will run the
|
||||
first full product calculation. Full downstream equivalence/timing is still
|
||||
unmeasured; existing downstream admission and refinement stages are unchanged.
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Exact arrays, previews and consumer coverage, independent of stage exit codes."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def run():
|
||||
control = Path("/control")
|
||||
candidate = Path("/candidate_result")
|
||||
files = sorted(
|
||||
p.relative_to(control) for p in control.rglob("*") if p.suffix in [".npz", ".jpg"]
|
||||
)
|
||||
other = sorted(
|
||||
p.relative_to(candidate) for p in candidate.rglob("*") if p.suffix in [".npz", ".jpg"]
|
||||
)
|
||||
assert files == other, "Output inventory differs"
|
||||
failures = []
|
||||
arrays = 0
|
||||
equal_files = 0
|
||||
for rel in files:
|
||||
a, b = control / rel, candidate / rel
|
||||
if a.suffix == ".jpg":
|
||||
if a.read_bytes() != b.read_bytes():
|
||||
failures.append(dict(file=str(rel), reason="preview bytes differ"))
|
||||
continue
|
||||
identical = True
|
||||
with np.load(a) as x, np.load(b) as y:
|
||||
assert sorted(x.files) == sorted(y.files), "Class channels differ"
|
||||
for k in x.files:
|
||||
p, q = x[k], y[k]
|
||||
arrays += 1
|
||||
equal = (
|
||||
p.shape == q.shape
|
||||
and p.dtype == q.dtype
|
||||
and np.array_equal(p, q, equal_nan=True)
|
||||
)
|
||||
if not equal:
|
||||
identical = False
|
||||
failures.append(
|
||||
dict(
|
||||
file=str(rel),
|
||||
channel=k,
|
||||
max_error=float(np.nanmax(np.abs(p.astype(float) - q))),
|
||||
changed_pixels=int(np.sum(p != q)),
|
||||
)
|
||||
)
|
||||
equal_files += identical
|
||||
a = json.loads((control / "ortho/segmentation-report.json").read_text())
|
||||
b = json.loads((candidate / "ortho/segmentation-report.json").read_text())
|
||||
assert len(a) == len(b)
|
||||
for x, y in zip(a, b, strict=True):
|
||||
assert all(
|
||||
x[k] == y[k]
|
||||
for k in ["tile", "windows", "skipped", "road_pixels", "side_pixels", "source_hashes"]
|
||||
)
|
||||
a = json.loads((control / "layers/evidence/report.json").read_text())
|
||||
b = json.loads((candidate / "layers/evidence/report.json").read_text())
|
||||
assert a["model"] == b["model"] and len(a["records"]) == len(b["records"])
|
||||
for x, y in zip(a["records"], b["records"], strict=True):
|
||||
assert all(x[k] == y[k] for k in ["tile", "windows", "inputs", "pixels"])
|
||||
schedule = json.loads((candidate / "ortho/semantic-survey.json").read_text())
|
||||
result = dict(
|
||||
passed=not failures,
|
||||
tiles=len(schedule["records"]),
|
||||
arrays_compared=arrays,
|
||||
npz_files_equal=equal_files,
|
||||
files_compared=len(files),
|
||||
failures=failures,
|
||||
image_encodings=schedule["image_encodings"],
|
||||
separate_image_encodings=schedule["separate_image_encodings"],
|
||||
prompt_decodes=schedule["prompt_decodes"],
|
||||
coverage_equal=True,
|
||||
model_equal=True,
|
||||
final_geometry_recomputed=False,
|
||||
new_object_recovery_measured=False,
|
||||
)
|
||||
Path("/out/comparison.json").write_text(json.dumps(result, indent=2))
|
||||
assert not failures, "Semantic arrays differ; do not promote"
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Replay the unchanged first all-class map consumer on both semantic outputs."""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def run(stage, root, runtime, release, profile, config):
|
||||
from infrastructure_sources import checksum
|
||||
from local_state import write_json
|
||||
|
||||
spec = config["consumer_comparison"]
|
||||
original = Path(spec["original_job"])
|
||||
qualified = Path(spec["semantic_comparison"])
|
||||
proof = json.loads((qualified / "comparison/comparison.json").read_text())
|
||||
assert proof["passed"] and proof["tiles"] == spec["tiles"]
|
||||
source = json.loads((original / "request.json").read_text())["source"]
|
||||
package = runtime / "state/infrastructure-sources" / source["adapter_key"]
|
||||
assert checksum(package / source["ply"]) == source["sha256"]
|
||||
manifest = json.loads((original / "source-manifest.json").read_text())
|
||||
consumer = original / "modules" / manifest["snapshot"] / "full_plan"
|
||||
definition = json.loads(
|
||||
(release / "simulation/urban-plan-research/pipeline/definition.json").read_text()
|
||||
)
|
||||
group = next(g for g in definition["groups"] if g["group"] == "full_plan")
|
||||
# Execute frozen installed scientific code, never a copied accepted map.
|
||||
hashes = {}
|
||||
for alias, relative in group["files"].items():
|
||||
expected = manifest["files"][relative]
|
||||
assert checksum(consumer / alias) == expected, alias
|
||||
hashes[alias] = expected
|
||||
before_base = checksum(original / "geometry/whole-map.json")
|
||||
observations = original / "ortho"
|
||||
shared = root / "consumer-replay"
|
||||
shared.mkdir()
|
||||
write_json(
|
||||
shared / "input-manifest.json",
|
||||
dict(
|
||||
source=source,
|
||||
base_map_sha256=before_base,
|
||||
semantic_comparison_sha256=checksum(qualified / "comparison/comparison.json"),
|
||||
consumer_files=hashes,
|
||||
reused_prefix="immutable Gaussian renders, terrain, multiview and geometric baseline",
|
||||
fresh_scope="unchanged full_plan assemble_layers on new semantic evidence",
|
||||
),
|
||||
)
|
||||
for variant in ["control", "candidate"]:
|
||||
out = shared / variant
|
||||
out.mkdir()
|
||||
input_copy = out / "input-ortho"
|
||||
copies = []
|
||||
try:
|
||||
shutil.copytree(observations, input_copy)
|
||||
for p in observations.rglob("*"):
|
||||
if p.is_file():
|
||||
relative = p.relative_to(observations)
|
||||
digest = checksum(p)
|
||||
assert checksum(input_copy / relative) == digest
|
||||
copies.append(dict(path=str(p), sha256=digest))
|
||||
# Replace only the derived masks with this run's frozen semantic outputs.
|
||||
shutil.copytree(
|
||||
qualified / variant / "ortho/evidence", input_copy / "evidence", dirs_exist_ok=True
|
||||
)
|
||||
shutil.copytree(qualified / variant / "layers/evidence", out / "evidence")
|
||||
mounts = [
|
||||
(consumer, "/consumer", True),
|
||||
(input_copy, "/ortho", True),
|
||||
(input_copy / "survey", "/survey", True),
|
||||
(original / "geometry", "/base", True),
|
||||
(original / "multiview", "/multiview", True),
|
||||
(package, "/input", True),
|
||||
]
|
||||
stage(
|
||||
"consumer-" + variant,
|
||||
"import sys,runpy;sys.path[:0]=['/consumer','/consumer/mapping'];"
|
||||
"runpy.run_path('/consumer/assemble_layers.py',run_name='__main__')",
|
||||
out,
|
||||
mounts,
|
||||
)
|
||||
for row in copies:
|
||||
assert checksum(Path(row["path"])) == row["sha256"], "Source changed"
|
||||
finally:
|
||||
if input_copy.exists():
|
||||
shutil.rmtree(input_copy)
|
||||
write_json(
|
||||
out / "temporary-input-receipt.json",
|
||||
dict(source_files_verified=len(copies), removed_own_copy=True),
|
||||
)
|
||||
a = json.loads((shared / "control/full-map.json").read_text())
|
||||
b = json.loads((shared / "candidate/full-map.json").read_text())
|
||||
aa = {f["id"]: f for f in a["features"]}
|
||||
bb = {f["id"]: f for f in b["features"]}
|
||||
assert len(aa) == len(a["features"]) and len(bb) == len(b["features"]), (
|
||||
"Duplicate feature identities"
|
||||
)
|
||||
changed = [key for key in sorted(aa.keys() | bb.keys()) if aa.get(key) != bb.get(key)]
|
||||
assert checksum(original / "geometry/whole-map.json") == before_base
|
||||
assert checksum(package / source["ply"]) == source["sha256"]
|
||||
report = dict(
|
||||
passed=not changed,
|
||||
features_control=len(aa),
|
||||
features_candidate=len(bb),
|
||||
classes_control=dict(Counter(f["properties"]["class"] for f in aa.values())),
|
||||
classes_candidate=dict(Counter(f["properties"]["class"] for f in bb.values())),
|
||||
changed_ids=changed,
|
||||
exact_feature_properties_and_geometry_equal=not changed,
|
||||
source_unchanged=True,
|
||||
reused_road_geometry=True,
|
||||
final_refinement_chain_replayed=False,
|
||||
published=False,
|
||||
)
|
||||
write_json(shared / "comparison.json", report)
|
||||
print("CONSUMER_COMPARISON", json.dumps(report), flush=True)
|
||||
assert not changed, "Real geometry consumer changed; do not promote"
|
||||
@@ -0,0 +1,153 @@
|
||||
"""One image embedding per exact survey window, shared across class requests.
|
||||
|
||||
A source view, crop, resize, opacity gate and threshold define a request. Only
|
||||
identical requests share inference. Consumers retain their own raster assembly.
|
||||
No final map, fitted object or scene identity participates in this schedule.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from ortho_windows import merge_instances, windows
|
||||
from PIL import Image
|
||||
|
||||
|
||||
@dataclass
|
||||
class Request:
|
||||
kind: str
|
||||
raster_box: tuple
|
||||
image_box: tuple
|
||||
prompts: list = field(default_factory=list)
|
||||
consumers: list = field(default_factory=list)
|
||||
|
||||
|
||||
def schedule(method, alphas, sizes):
|
||||
"""Union exact legacy schedules without equating different scale policies."""
|
||||
jobs = [
|
||||
("coarse", "context", 60, 60, method["prompts"]),
|
||||
(
|
||||
"medium",
|
||||
"context",
|
||||
method["context_width_m"],
|
||||
method["context_step_m"],
|
||||
method["prompts"],
|
||||
),
|
||||
("detail", "ground", method["detail_width_m"], method["detail_step_m"], method["prompts"]),
|
||||
("building", "context", 30, 20, ["building"]),
|
||||
("markings", "ground", 15, 10, ["road marking", "crosswalk"]),
|
||||
]
|
||||
requests = {}
|
||||
counts = {}
|
||||
for consumer, kind, width, step, prompts in jobs:
|
||||
counts[consumer] = dict(accepted=0, skipped=0)
|
||||
alpha = alphas[kind]
|
||||
if alpha.shape != (1200, 1200):
|
||||
raise ValueError("Expected calibrated 1200-pixel opacity")
|
||||
for x, y, w, h in windows(60, width, step):
|
||||
box = tuple(np.rint(np.array([x, y, x + w, y + h]) * 20).astype(int))
|
||||
x0, y0, x1, y1 = box
|
||||
if (alpha[y0:y1, x0:x1] > 0.7).mean() < 0.04:
|
||||
counts[consumer]["skipped"] += 1
|
||||
continue
|
||||
counts[consumer]["accepted"] += 1
|
||||
image_box = tuple(
|
||||
np.rint(np.array([x, y, x + w, y + h]) * sizes[kind] / 60).astype(int)
|
||||
)
|
||||
key = (kind, box, image_box)
|
||||
req = requests.setdefault(key, Request(kind, box, image_box))
|
||||
req.consumers.append((consumer, tuple(prompts)))
|
||||
for prompt in prompts:
|
||||
if prompt not in req.prompts:
|
||||
req.prompts.append(prompt)
|
||||
return list(requests.values()), counts
|
||||
|
||||
|
||||
def predict_planes(processor, image, prompts):
|
||||
"""Image backbone runs once; each prompt retains its ordinary decoder call."""
|
||||
import torch
|
||||
|
||||
result = {}
|
||||
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
state = processor.set_image(image)
|
||||
for prompt in prompts:
|
||||
state = processor.set_text_prompt(prompt, state)
|
||||
masks = state["masks"].reshape(-1, image.height, image.width).cpu().numpy()
|
||||
scores = state["scores"].float().cpu().numpy().reshape(-1)
|
||||
plane = np.zeros((image.height, image.width), np.float32)
|
||||
for mask, score in zip(masks, scores, strict=True):
|
||||
np.maximum(plane, np.where(mask, score, 0), out=plane)
|
||||
result[prompt] = plane
|
||||
return result
|
||||
|
||||
|
||||
def infer_tile(method, images, alphas, predict):
|
||||
if method["prompts"] != ["road", "sidewalk", "vehicle"] or method["model_threshold"] != 0.3:
|
||||
raise ValueError("Joint survey requires the qualified common prompt/threshold contract")
|
||||
if any(im.width != im.height for im in images.values()):
|
||||
raise ValueError("Expected square orthographic observation")
|
||||
requests, counts = schedule(method, alphas, {k: im.width for k, im in images.items()})
|
||||
canvases = {}
|
||||
for req in requests:
|
||||
x0, y0, x1, y1 = req.raster_box
|
||||
with images[req.kind].crop(req.image_box) as crop:
|
||||
crop.thumbnail((1024, 1024), Image.Resampling.LANCZOS)
|
||||
planes = predict(crop, req.prompts)
|
||||
scaled = {
|
||||
p: cv2.resize(planes[p], (x1 - x0, y1 - y0), interpolation=cv2.INTER_AREA)
|
||||
for p in req.prompts
|
||||
}
|
||||
for consumer, prompts in req.consumers:
|
||||
canvas = canvases.setdefault(consumer, {})
|
||||
for prompt in prompts:
|
||||
if prompt not in canvas:
|
||||
canvas[prompt] = np.zeros((1200, 1200), np.float32)
|
||||
target = canvas[prompt]
|
||||
merge_instances(target, scaled[prompt], x0, y0)
|
||||
|
||||
# Empty/unknown input is an all-zero observation, not a fabricated class.
|
||||
def plane(consumer, prompt):
|
||||
value = canvases.get(consumer, {}).get(prompt)
|
||||
return np.zeros((1200, 1200), np.float32) if value is None else value
|
||||
|
||||
context = np.asarray([plane("coarse", p) for p in method["prompts"]])
|
||||
medium = np.asarray([plane("medium", p) for p in method["prompts"]])
|
||||
detail = np.asarray([plane("detail", p) for p in method["prompts"]])
|
||||
normal = np.maximum(context, medium)
|
||||
combined = np.maximum(normal, detail)
|
||||
combined[2] = normal[2]
|
||||
combined[:, ~(np.maximum(alphas["context"], alphas["ground"]) > 0.5)] = 0
|
||||
road, sidewalk, vehicle = combined
|
||||
normal_out = {
|
||||
"roadway": road,
|
||||
"sidewalk": sidewalk,
|
||||
"vehicle": vehicle,
|
||||
"road marking": np.zeros_like(road),
|
||||
"crosswalk": np.zeros_like(road),
|
||||
}
|
||||
ground_out = {
|
||||
**normal_out,
|
||||
"roadway": detail[0],
|
||||
"sidewalk": detail[1],
|
||||
"vehicle": np.zeros_like(road),
|
||||
}
|
||||
layers = {}
|
||||
for consumer, kind, prompts in [
|
||||
("building", "context", ["building"]),
|
||||
("markings", "ground", ["road marking", "crosswalk"]),
|
||||
]:
|
||||
for prompt in prompts:
|
||||
value = plane(consumer, prompt)
|
||||
value[alphas[kind] < 0.5] = 0
|
||||
layers[prompt] = value.astype("float16")
|
||||
return (
|
||||
normal_out,
|
||||
ground_out,
|
||||
layers,
|
||||
{
|
||||
"consumers": counts,
|
||||
"image_encodings": len(requests),
|
||||
"separate_image_encodings": sum(x["accepted"] for x in counts.values()),
|
||||
"prompt_decodes": sum(len(r.prompts) for r in requests),
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Shared first-pass surface/paint/building evidence; no map mutation."""
|
||||
|
||||
import gc
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from semantic_survey import infer_tile, predict_planes
|
||||
|
||||
|
||||
def run():
|
||||
sys.path.insert(0, "/release/simulation/ai-polygon/sam3-research")
|
||||
import sam3.model_builder as builder
|
||||
from qualify import load_exact, sha
|
||||
from sam3.model.sam3_image_processor import Sam3Processor
|
||||
|
||||
survey, evidence, run_root = Path("/survey"), Path("/evidence"), Path("/run")
|
||||
inputs_root = Path(os.environ.get("SURVEY_EVIDENCE_INPUT", "/evidence"))
|
||||
layer_root = Path("/layers/evidence")
|
||||
layer_root.mkdir(exist_ok=True, parents=True)
|
||||
(evidence / "road-prompt").mkdir(exist_ok=True)
|
||||
config = json.loads((run_root / "config.json").read_text())
|
||||
method = config["method"]
|
||||
if method["prompts"] != ["road", "sidewalk", "vehicle"] or method["model_threshold"] != 0.3:
|
||||
raise ValueError("Unqualified common inference threshold/prompts")
|
||||
model_spec = json.loads(
|
||||
Path("/release/simulation/ai-polygon/sam3-research/large-model.json").read_text()
|
||||
)
|
||||
assets = Path("/assets")
|
||||
for name, expected in model_spec["files"].items():
|
||||
assert sha(assets / name) == expected, "Semantic model digest changed"
|
||||
builder._load_checkpoint = load_exact
|
||||
torch.set_num_threads(3)
|
||||
cv2.setNumThreads(3)
|
||||
model = builder.build_sam3_image_model(
|
||||
bpe_path="/source/assets/bpe_simple_vocab_16e6.txt.gz",
|
||||
checkpoint_path=str(assets / next(iter(model_spec["files"]))),
|
||||
load_from_HF=False,
|
||||
enable_segmentation=True,
|
||||
enable_inst_interactivity=False,
|
||||
compile=False,
|
||||
text_encoder_type=model_spec["text_encoder"],
|
||||
text_encoder_context_length=16,
|
||||
device="cuda",
|
||||
)
|
||||
processor = Sam3Processor(model, device="cuda", confidence_threshold=0.3)
|
||||
started = time.monotonic()
|
||||
records, layer_records, schedules = [], [], []
|
||||
index = json.loads((survey / "tile-index.json").read_text())
|
||||
tiles = [t for t in index["tiles"] if t["status"] == "surveyed"]
|
||||
(run_root / "semantic-survey.json").write_text(json.dumps({"complete": False}))
|
||||
for tile in tiles:
|
||||
name = tile["id"]
|
||||
begin = time.monotonic()
|
||||
with np.load(survey / name / "top.geometry.npz") as g:
|
||||
context_alpha = g["alpha"]
|
||||
with np.load(inputs_root / (name + ".ground-dc.geometry.npz")) as g:
|
||||
ground_alpha = g["alpha"]
|
||||
with (
|
||||
Image.open(inputs_root / (name + ".context.png")) as a,
|
||||
Image.open(inputs_root / (name + ".ground.png")) as b,
|
||||
):
|
||||
images = {"context": a.convert("RGB"), "ground": b.convert("RGB")}
|
||||
try:
|
||||
normal, ground, layers, schedule = infer_tile(
|
||||
method,
|
||||
images,
|
||||
{"context": context_alpha, "ground": ground_alpha},
|
||||
lambda image, prompts: predict_planes(processor, image, prompts),
|
||||
)
|
||||
np.savez_compressed(evidence / (name + ".normal.npz"), **normal)
|
||||
np.savez_compressed(evidence / (name + ".ground.npz"), **ground)
|
||||
np.savez_compressed(
|
||||
evidence / "road-prompt" / (name + ".normal.npz"), road=normal["roadway"]
|
||||
)
|
||||
np.savez_compressed(
|
||||
evidence / "road-prompt" / (name + ".ground.npz"), road=ground["roadway"]
|
||||
)
|
||||
np.savez_compressed(layer_root / (name + ".npz"), **layers)
|
||||
road_area = (normal["roadway"] > 0.35) & (normal["sidewalk"] <= normal["roadway"])
|
||||
side_area = (normal["sidewalk"] > 0.4) & (normal["sidewalk"] > normal["roadway"])
|
||||
preview = np.asarray(images["context"].resize((1200, 1200)), dtype=np.float32).copy()
|
||||
preview[road_area] = 0.55 * preview[road_area] + 0.45 * np.array([65, 130, 225])
|
||||
preview[side_area] = 0.55 * preview[side_area] + 0.45 * np.array([25, 220, 145])
|
||||
Image.fromarray(np.uint8(preview)).save(evidence / (name + ".semantic.jpg"), quality=94)
|
||||
finally:
|
||||
for image in images.values():
|
||||
image.close()
|
||||
inputs = {
|
||||
kind: sha(inputs_root / (name + "." + kind + ".png")) for kind in ["context", "ground"]
|
||||
}
|
||||
seconds = time.monotonic() - begin
|
||||
counts = schedule["consumers"]
|
||||
records.append(
|
||||
dict(
|
||||
tile=name,
|
||||
windows=[counts[k]["accepted"] for k in ["coarse", "medium", "detail"]],
|
||||
skipped=[counts[k]["skipped"] for k in ["coarse", "medium", "detail"]],
|
||||
road_pixels=int(road_area.sum()),
|
||||
side_pixels=int(side_area.sum()),
|
||||
seconds=seconds,
|
||||
source_hashes=list(inputs.values()),
|
||||
joint_timing=True,
|
||||
)
|
||||
)
|
||||
layer_records.append(
|
||||
dict(
|
||||
tile=name,
|
||||
windows=sum(counts[k]["accepted"] for k in ["building", "markings"]),
|
||||
seconds=seconds,
|
||||
joint_timing=True,
|
||||
inputs=inputs,
|
||||
sha256=sha(layer_root / (name + ".npz")),
|
||||
pixels={p: int((x > 0.3).sum()) for p, x in layers.items()},
|
||||
)
|
||||
)
|
||||
schedules.append(dict(tile=name, **schedule))
|
||||
(run_root / "segmentation-report.json").write_text(json.dumps(records, indent=2))
|
||||
(layer_root / "report.json").write_text(
|
||||
json.dumps(
|
||||
dict(
|
||||
model=model_spec,
|
||||
records=layer_records,
|
||||
manual_rois=[],
|
||||
shared_policy=True,
|
||||
seconds=time.monotonic() - started,
|
||||
joint_timing=True,
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
print(
|
||||
"SHARED_SEMANTICS",
|
||||
len(records),
|
||||
"/",
|
||||
len(tiles),
|
||||
name,
|
||||
schedule["separate_image_encodings"],
|
||||
"->",
|
||||
schedule["image_encodings"],
|
||||
round(seconds, 2),
|
||||
flush=True,
|
||||
)
|
||||
gc.collect()
|
||||
(run_root / "segmentation-summary.json").write_text(
|
||||
json.dumps(
|
||||
dict(
|
||||
scene=os.environ["ORTHO_SCENE"],
|
||||
method=method,
|
||||
model=model_spec,
|
||||
tiles=len(records),
|
||||
windows=sum(sum(r["windows"]) for r in records),
|
||||
seconds=time.monotonic() - started,
|
||||
manual_rois=[],
|
||||
joint_timing=True,
|
||||
score_interpretation="model scores, not calibrated probabilities",
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
(run_root / "semantic-survey.json").write_text(
|
||||
json.dumps(
|
||||
dict(
|
||||
schema="missioncore.shared-semantic-survey/v1",
|
||||
complete=True,
|
||||
records=schedules,
|
||||
source_index_sha256=sha(survey / "tile-index.json"),
|
||||
config_sha256=sha(run_root / "config.json"),
|
||||
model=model_spec,
|
||||
seconds=time.monotonic() - started,
|
||||
image_encodings=sum(x["image_encodings"] for x in schedules),
|
||||
separate_image_encodings=sum(x["separate_image_encodings"] for x in schedules),
|
||||
prompt_decodes=sum(x["prompt_decodes"] for x in schedules),
|
||||
map_input=False,
|
||||
new_renders=0,
|
||||
repeated_detection=False,
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Compare shared requests against the existing independent surface pass."""
|
||||
|
||||
import ast
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from ortho_windows import merge_instances, windows
|
||||
from PIL import Image
|
||||
from semantic_survey import infer_tile, schedule
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
METHOD = dict(
|
||||
prompts=["road", "sidewalk", "vehicle"],
|
||||
model_threshold=0.3,
|
||||
context_width_m=30,
|
||||
context_step_m=20,
|
||||
detail_width_m=15,
|
||||
detail_step_m=10,
|
||||
)
|
||||
|
||||
|
||||
def picture():
|
||||
rng = np.random.default_rng(15)
|
||||
return Image.fromarray(rng.integers(0, 256, (128, 128, 3), dtype=np.uint8))
|
||||
|
||||
|
||||
def predict(image, prompts):
|
||||
# Pixel and prompt dependent, so crop/resize/order mistakes change the result.
|
||||
data = np.asarray(image).astype(np.float32) / 255
|
||||
all_prompts = ["road", "sidewalk", "vehicle", "building", "road marking", "crosswalk"]
|
||||
return {
|
||||
p: data[:, :, all_prompts.index(p) % 3] * ((all_prompts.index(p) + 1) / 7) for p in prompts
|
||||
}
|
||||
|
||||
|
||||
def original_surface_pass(images, alphas, method):
|
||||
# Execute the actual old function, not another version of the new scheduler.
|
||||
source = ROOT / "orthophoto/ortho_segment.py"
|
||||
if not source.is_file():
|
||||
source = Path(__file__).with_name("legacy_ortho_segment.py")
|
||||
fn = next(
|
||||
n
|
||||
for n in ast.parse(source.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "pass_scale"
|
||||
)
|
||||
import cv2
|
||||
|
||||
ns = dict(
|
||||
np=np,
|
||||
cv2=cv2,
|
||||
Image=Image,
|
||||
windows=windows,
|
||||
merge_instances=merge_instances,
|
||||
prompts=method["prompts"],
|
||||
predict=lambda im: predict(im, method["prompts"]),
|
||||
)
|
||||
exec(compile(ast.Module(body=[fn], type_ignores=[]), str(source), "exec"), ns)
|
||||
f = ns["pass_scale"]
|
||||
context, _, _ = f(images["context"], alphas["context"], 60, 60)
|
||||
medium, _, _ = f(
|
||||
images["context"], alphas["context"], method["context_width_m"], method["context_step_m"]
|
||||
)
|
||||
detail, _, _ = f(
|
||||
images["ground"], alphas["ground"], method["detail_width_m"], method["detail_step_m"]
|
||||
)
|
||||
normal = np.maximum(context, medium)
|
||||
combined = np.maximum(normal, detail)
|
||||
combined[2] = normal[2]
|
||||
valid = np.maximum(alphas["context"], alphas["ground"]) > 0.5
|
||||
combined[:, ~valid] = 0
|
||||
return combined, detail
|
||||
|
||||
|
||||
def test_shared_windows_are_exact_and_scale_policies_remain_distinct():
|
||||
alphas = {k: np.ones((1200, 1200), np.float32) for k in ["context", "ground"]}
|
||||
req, counts = schedule(METHOD, alphas, {"context": 4096, "ground": 4096})
|
||||
assert len(req) == 46
|
||||
assert sum(x["accepted"] for x in counts.values()) == 91
|
||||
assert sum(len(x.prompts) for x in req) == 219
|
||||
# Different surface schedule cannot silently reuse a paint crop at that scale.
|
||||
changed = {**METHOD, "detail_width_m": 20, "detail_step_m": 10}
|
||||
req, _ = schedule(changed, alphas, {"context": 4096, "ground": 4096})
|
||||
assert len(req) == 71
|
||||
|
||||
|
||||
def surface_outputs_equal_unchanged_legacy_function(partial):
|
||||
images = {"context": picture(), "ground": picture()}
|
||||
alphas = {k: np.ones((1200, 1200), np.float32) for k in images}
|
||||
if partial:
|
||||
alphas["context"][:700, :800] = 0
|
||||
alphas["ground"][600:, :] = 0
|
||||
alphas["context"][120:130, 1100:] = np.nan
|
||||
alphas["ground"][120:130, 1100:] = np.nan
|
||||
normal, ground, layers, stats = infer_tile(METHOD, images, alphas, predict)
|
||||
expected, detail = original_surface_pass(images, alphas, METHOD)
|
||||
for i, k in enumerate(["roadway", "sidewalk", "vehicle"]):
|
||||
np.testing.assert_array_equal(normal[k], expected[i])
|
||||
np.testing.assert_array_equal(ground["roadway"], detail[0])
|
||||
np.testing.assert_array_equal(ground["sidewalk"], detail[1])
|
||||
assert not ground["vehicle"].any()
|
||||
assert set(layers) == {"building", "road marking", "crosswalk"}
|
||||
assert all(v.dtype == np.float16 for v in layers.values())
|
||||
assert stats["image_encodings"] < stats["separate_image_encodings"]
|
||||
for im in images.values():
|
||||
im.close()
|
||||
|
||||
|
||||
def test_empty_evidence_never_invokes_model():
|
||||
images = {"context": picture(), "ground": picture()}
|
||||
alphas = {k: np.zeros((1200, 1200), np.float32) for k in images}
|
||||
|
||||
def forbidden(*_):
|
||||
raise AssertionError("No inference without observed support")
|
||||
|
||||
normal, ground, layers, stats = infer_tile(METHOD, images, alphas, forbidden)
|
||||
assert stats["image_encodings"] == 0
|
||||
assert all(not p.any() for d in [normal, ground, layers] for p in d.values())
|
||||
for im in images.values():
|
||||
im.close()
|
||||
|
||||
|
||||
def test_unqualified_threshold_is_not_silently_shared():
|
||||
with unittest.TestCase().assertRaisesRegex(ValueError, "threshold"):
|
||||
infer_tile({**METHOD, "model_threshold": 0.4}, {}, {}, predict)
|
||||
|
||||
|
||||
class SharedSurveyTests(unittest.TestCase):
|
||||
def test_shared_windows(self):
|
||||
test_shared_windows_are_exact_and_scale_policies_remain_distinct()
|
||||
|
||||
def test_surface_equivalence(self):
|
||||
for partial in [False, True]:
|
||||
with self.subTest(partial=partial):
|
||||
surface_outputs_equal_unchanged_legacy_function(partial)
|
||||
|
||||
def test_empty(self):
|
||||
test_empty_evidence_never_invokes_model()
|
||||
|
||||
def test_threshold(self):
|
||||
test_unqualified_threshold_is_not_silently_shared()
|
||||
Reference in New Issue
Block a user