feat(semantics): add portable annotation, learning and review contracts

Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 69dc566665
commit 25dc0a1b44
128 changed files with 23742 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
# Семантика отдельной сканированной сцены
Решение владельца от 26.10.2026, включая уточнение о функциональной роли зебр. Основная архитектура: [MISSIONCOR-50](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50); продукт: [MISSIONCOR-88](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-88); исполнение агентом: [MISSIONCOR-93](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-93).
## Сценарий и единица работы
Оператор удалённо подключается к роверу со сканером, проезжает произвольную ранее неизвестную зону и получает запись сцены. Это может быть 100 метров одной стороны улицы или маршрут длиной 5 километров в безымянной местности. Область полученного скана — целевая локация дальнейшей работы ровера. Наличие названия, адреса, GPS или объекта на публичной карте не требуется.
Каждый скан обрабатывается как отдельная сцена в собственной локальной системе координат. Система не ищет соседние сканы, не сопоставляет их геометрию, не объединяет маршруты и не восстанавливает общую географию по умолчанию. Сравнение, совмещение или объединение разных сканов — только отдельная явно заказанная задача. Технические размеры тайлов и лимиты памяти не должны становиться предположением о конкретной улице или её длине.
## Источники и назначение слоёв
- Исходное облако точек, записанное сенсором в реальном времени: первичные пространственные измерения и материал для локализации ровера в уже записанной сцене. Не подменять его облаком, мешем или другим представлением, восстановленным из Gaussian. Различие определяется происхождением данных, а не расширением LAS/PLY или названием папки.
- Gaussian-представление той же сцены: визуальный источник для просмотра, распознавания окружения и текущих экспериментов семантики. Не считать его доступным в реальном времени только потому, что исходное облако записывается в реальном времени.
- Семантический слой: дополнительные сведения о наблюдаемом окружении — дорожные и пешеходные области, бордюры и границы, фасады, переходы, дорожная разметка и другие поддержанные объекты. Результат остаётся привязанным к локальным координатам своей сцены и доступным для проверки и исправления.
Связь представлений внутри одной съёмки задаётся её реальными позами, координатными преобразованиями и калибровкой, когда они доступны. Это локальная связь собственных данных, не географическая привязка и не автоматическое сопоставление разных сканов. Формат raw-потока, синхронизацию и готовность локализации подтверждают соответствующие реализации/испытания; данный документ фиксирует цель, а не объявляет весь тракт уже работающим.
## Зачем извлекаем всю разметку
Зебры и пешеходные переходы — функционально важная часть семантики окружения для задач ровера. Их нельзя списывать на демонстрацию или исключать из продуктовой цели.
Полный набор наблюдаемой дорожной разметки также остаётся целью: линии, штрихи, стоп-линии, стрелки, обозначения, надписи, островки и другие классы по мере подтверждения данных и качества. Он делает интерфейс понятнее и выразительнее, полезен для демонстрации и продажи продукта и проверяет способность системы решать сложную задачу распознавания. Пилот на полосах перехода не сокращает эту цель до зебр.
Ровер не становится автомобильным автопилотом, следующим дорожным линиям. Разметка — один из семантических источников контекста; локализация и другие задачи ровера не должны зависеть от наличия краски на поверхности. Сцена без разметки — нормальный вход. Заявление о распознанной зебре само по себе не является готовой политикой пересечения дороги.
## Основной путь обработки
Запись одной сцены → сохранение исходных данных и их происхождения → подготовка локальных представлений и наблюдений → распознавание → объекты семантики в координатах этой сцены → визуальная проверка и редактор → версионированные проверенные примеры для обучения и оценки моделей.
Для отдельного скана алгоритм использует только данные этой сцены и зафиксированные общие веса/настройки. Адрес, номер улицы, публичная карта или содержимое других сканов не являются обязательными входами, признаками модели или условиями запуска. Внешние карты/вывески не используются для дорисовки или подтверждения дорожной краски. Общие правила формы помогают интерпретировать наблюдения, но не создают факт наличия объекта. Слабая наблюдаемость сохраняется как unknown.
## Обучение и оценка без географического процесса
Модель может обучаться на множестве отдельно обработанных сцен. Это не требует их совмещения или общего пространства координат. Train/development/evaluation задаются явным списком source IDs и версий; производные одного исходника не расходятся между обучением и контролем. Уже объявленные в данных связи происхождения сохраняются, но поиск географических пересечений между сканами не запускается.
Сравнение модели с эталонной разметкой выполняется внутри каждого выбранного скана; агрегирование метрик эксперимента не является сопоставлением геометрии сканов. Новый source ID сам по себе не доказывает физическую или статистическую независимость: при отсутствии отдельно заказанной проверки результаты называются оценкой на перечисленных отложенных сканах, без усиленного заявления о географическом переносе. Отсутствие GPS или доказательства непересечения не блокирует подготовку, распознавание или ограниченный эксперимент.
Сохраняются контроль утечки эталонов, неизменность входов, отдельный review, unknown, полнота объектов в пределах действительно проверенного материала и отсутствие подгонки порогов по тестовому ответу. Переименование файла не создаёт новый исходник. Если предсказания использованы для изменения рецепта, набор становится development.
## Действующая граница и продолжение
Географический поиск и address-check-v1 остаются историческими инженерными материалами. Они не являются обязательным этапом архитектуры, разрешением на продолжение поиска или доказательством качества детектора. Принятые маски и связи с собственными источниками сохраняются.
Следующее сравнение G12 / RGB SegFormer B0 проводится на зафиксированных сканах и исходной области проверенных меток. Сначала необходимы входы, код оценки, версии весов/среды и разрешение вычислений. Четыре локальных окна не дают полного покрытия всех классов разметки. Критерии качества не ослабляются, старые результаты и критерии опытов не переписываются задним числом. Готовность локализации, обучения и производственного исполнения отражается отдельными фактическими приёмками.
+517
View File
@@ -0,0 +1,517 @@
# Root-reviewed semantic agent cycle
Owner scope clarification, 2026-10-26: read
[SCENE_SEMANTICS_PRODUCT_CONCEPT.md](SCENE_SEMANTICS_PRODUCT_CONCEPT.md).
Each scan is one standalone local scene. Crosswalks are functional semantics;
all observed road markings remain a product/interface and hard-task target.
No GPS/address/public-map requirement or automatic cross-scan geographic
comparison, overlap search, registration or merging. Such work needs a separate
explicit owner request. Dataset splits use declared source identity/lineage;
uncertainty and held-out target isolation remain required.
## Current operating contract — 2026-10-26
[MISSIONCOR-93](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-93) and
`docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md` govern new urban annotation work.
New plans use `missioncore.semantic-agent-cycle/v2` (`SCHEMA_V2`); literal v1
remains supported for historical compatibility. Existing v1 plans/results are
not migrated or given new acceptance criteria retroactively. The original
implementation and dated experiments below retain their historical scope.
V2 adds a frozen `objective_contract` with `deliverable`, `min_admitted_units`,
and unique `required_checks`. At most two executors may be active. The planned
admission count must fit the units and require no more than half the dispatch
budget (one author plus one review per admitted unit). Scientific feasibility,
metric support and time estimates still require root preflight.
Root records actual delivery with `confirm_dispatch(token, root_actor,
executor_ref, evidence)` after sending the packet. An unconfirmed active or
interrupted handoff blocks another claim. Missing confirmation never frees a
reservation automatically. A fast fenced completion may precede confirmation;
the exact done token permits append-only receipt recovery even after closure.
This records trusted root evidence; it does not send messages or authenticate
an external executor.
Ready reviews precede new author claims. Each author completion already creates
its own ready review; there is no all-authors barrier. Status includes ordered
`ready_tasks`, `unconfirmed_handoffs` and `progress` counts.
V2 root decisions additionally contain `objective_outcome` (`achieved`,
`not_achieved`, `inconclusive`), exact boolean `objective_checks`,
`outcome_reason`, and `remaining_work` (a bounded list). Achievement requires the
frozen admission target and all required checks, with no remaining work. Partial
admission remains possible without claiming objective completion. Changing only
acceptance does not make unchanged substantive work a new experiment.
This objective concerns approved annotation evidence, not a published dataset
or accepted map. `agent_admission.publish()` follows a closed accepted cycle;
root must inspect the published target separately before completing the enclosing
work package. The controller cannot certify visual semantics or model utility.
49 focused local tests and Ruff passed. Coverage includes v1 compatibility,
source-bound admission, missed handoff, streamed review, partial outcomes,
feasible dispatch budgets and receipt recovery. No Worker rollout, training or
live-map mutation was performed. Full process speed/token benefit is still a
separate measurement, not inferred from these checks.
Implemented 2026-10-25 in `simulation/semantic-learning/agent_cycle.py`,
`region_coverage.py`, and `agent_admission.py`. This is a bounded annotation
workflow around the existing immutable corpus/admission contracts. It does not
consume the dataset builder's jobs, change a live map, launch training, or promote
a model. The source-only semantic-learning packager includes these modules.
## Execution boundary
The active Codex root session is the dispatcher and curator. It delegates bounded
annotation packets, then source review to a different actor. The Worker portable
store holds durable task state and data; no external model provider, paid API, new
daemon, or unattended scheduler has been introduced. Closing Codex preserves the
ledger but does not create a background LLM executor. Root can resume from it.
Use controller-assigned canonical actor IDs. Identity separation prevents
accidental self-review; it is not authentication or statistically independent
model judgement. A trusted dispatched executor may call `complete` only for its
assigned token/actor and immutable result. This records evidence and releases the
claim; it does not accept labels. Root retains dispatch, `reconcile`, `cancel_ready`, `decide`, and
publication responsibility. Agents cannot approve their own live writes or
training admission. Actor strings and a shared filesystem are an orchestration
boundary, not authentication or a security sandbox.
Completion is atomic and safe to retry with the same result after a lost reply or
process restart: it returns the original hash without another attempt or review
job. A changed result, wrong actor, unknown or superseded token is rejected.
Expiry is checked again after source/quota validation, immediately before writes.
Root settles and checks task state inside the decision transaction, so a concurrent
expiry cannot close a cycle around an unreconciled executor. Executors must report
an uncertain outcome and retry the same token/result; they must not claim a new
job, change the result, reconcile themselves, or bypass root admission.
For a validated result, the normal handoff is now direct executor completion in
its existing invocation, followed by the returned hash/receipt to root. Root
checks terminal evidence instead of copying and resending the same JSON. This
uses the same assigned token, actor, immutable result and admission boundaries.
A matched ready-result transport pilot on 2026-10-25 completed all eight steps
(four pairs) inside a frozen 20-minute budget. Median ready-to-ack latency was
38.494 seconds via root and 0.270 seconds direct; dispatch-to-ack medians were
65.918 and 18.734 seconds. All paired digests, closed ledger and accepted release
were unchanged. Each route used an identical already-completed `Cycle.complete`
replay plus a new durable benchmark receipt. This accepts the bounded handoff
choice only: first-result insertion, full annotation-cycle throughput, quality,
cost and model accuracy remain unmeasured by that comparison. One executor and
four purposeful payloads do not establish a general statistical speedup. Evidence:
`outputs/semantic-executor-completion-20261025/transport-comparison-1/REPORT.md`.
Send new executors a compact task packet and the specific source-view tools. Do
not fork the entire conversation by default. Reuse a bounded executor for a small
batch when its role and source isolation permit; do not create curator/researcher
agents merely to fill an architecture diagram. Root currently performs curation
and research decisions. An optional advisory product/methods scout now follows
`SEMANTIC_RESEARCH_SCOUT.md`; it feeds proposals to root and does not gate the
annotation critical path. At most two active tasks in the pilot, including any
concurrent scout; no GPU fitting.
## Contract and state
A frozen plan pins the baseline, objective, recipe, acceptance criteria, physical
TRAIN groups, selected native-pixel ROIs, source images/cameras and supervision
release. `validate_packet` resolves the actual corpus identity and split; declaring
`split: train` cannot make an evaluation source eligible.
The same Worker `queue.sqlite3` contains separate `agent_cycles`, `agent_tasks`,
and `agent_attempts` tables. Builder jobs and receipts remain unchanged. A single
`BEGIN IMMEDIATE` protects claims, dispatch counts and concurrent ownership.
1. `begin(plan)` freezes an iteration and its deadline.
2. `claim(identity, unit_id, stage, actor)` reserves one annotate/review job and
returns a fencing token. A review includes the exact proposal and its hash.
3. `complete(token, actor, result)` stores immutable bounded JSON evidence and
makes the next stage ready. Identical repeat completion is idempotent; a
different result for the same claim is rejected.
4. The iteration reaches `root_pending`. Expired claims remain resource
reservations until root verifies their executors have ended and calls
`reconcile`; expiry alone never starts a second copy.
5. `decide` records root's terminal verdict, inspected units, checks, tuning and
explicit `admitted_units`. Flagged tasks plus a deterministic sample must be
inspected. Rejected or unreviewed units cannot enter the admitted list.
6. Only then may `agent_admission.publish(store, id, destination)` produce a new
immutable supervision sidecar. It publishes only admitted units and preserves
every accepted old pixel, explicit unknown exclusion and other sample decision.
To abort a disrupted experiment, root may call `cancel_ready` with a recorded
reason. Only undispatched ready tasks become blocked; completed evidence and
active/interrupted reservations remain intact. Root must confirm stopped
executors, reconcile their claims, then close with a rejected/revise verdict.
No deadline, attempt count or frozen plan is rewritten. A clean successor records
the interruption and reuses any immutable prepared proposal explicitly; it does
not silently pretend the interrupted timing run succeeded.
A successor requires the previous root decision. Unchanged substantive work
(source hashes, region packet, baseline and recipe) is rejected even when the
unit IDs or parent change. Replication is a separately stated recipe, not a
technical retry. Retry limits do not reset on restart.
Limits are explicit parallelism, attempts per stage, total dispatches, iteration
wall time, lease time, 256 KiB per plan, 48 KiB per result, 32 KiB per root review, a bounded
2 MiB status/request envelope and 128 MiB of controller JSON evidence.
Quota exhaustion refuses new evidence; it does not delete historical data. This
version does not meter or enforce provider tokens/dollars, and a lease does not
kill a running LLM. Root must reconcile actual process/task status. The quota
error requires deliberate archival; no automatic destructive archival command is
provided.
CLI accepts bounded JSON request files:
```sh
python -B agent_cycle.py --store <worker-store> begin --request <plan-request.json>
python -B agent_cycle.py --store <worker-store> status --request <status-request.json>
```
The request contains keyword arguments to the action, for example
`{"identity":"<iteration-sha256>"}` for status. Other actions are `claim`,
`complete`, `reconcile`, `cancel_ready`, `decide`. The dispatcher controls actor arguments.
## Annotation and root review
An author sees raw RGB and bounded context, identifies visible paint polygons,
explicitly reviews the remaining ROI as background, and marks uncertain source
regions. Native-pixel margins around boundaries remain ignored. A missing polygon
outside the reviewed ROI never means background. Rules/context cannot fabricate
visible-paint labels. A protected unknown cannot overlap an accepted label.
Explicit source-uncertainty polygons are kept separate from automatic boundary
ignore margins. If explicit uncertainty intersects an earlier known paint or
background label, publication fails closed; preserving that old label would
silently contradict the new source review. Resolve it through a separately
reviewed, immutable baseline revision, never by silently changing the proposal
or relaxing the preservation gate. A final proof must show the published merged
target, not only the proposed polygons. Automatic edge margins alone do not
revoke existing accepted labels.
Uncertainty must concern the target class. Explain which visible evidence makes
observed road paint versus background undecidable. Unresolved surface material,
soft texture, shadow or blur alone does not decide either label. Clear source
boundaries and context can support background even when curb/gutter/material
identity is uncertain. A genuinely obscured surface, mixed paint boundary or
unresolved class ambiguity must remain unknown; absence of visible paint alone
is not background evidence. When useful, inspect a hash-bound native source crop
through the recorded resampling transform; another resolution of the same scan
is not independent evidence.
A separate 2026-10-25 adjudication retained all 218 disputed MI2-E background
pixels after independent and root source inspection. The new unknown region was
overbroad for those exact pixels. No baseline revision or wholesale proposal
admission followed; the failed 1/2 cycle stays closed. The source-specific verdict
must not become a blanket rule for shadows or blurred regions. Evidence:
`outputs/semantic-executor-completion-20261025/baseline-adjudication-1/REPORT.md`.
The deterministic validator checks explicit complete ROI coverage, source pins,
old-label conflicts and protected unknown. It cannot prove semantic correctness.
A separate reviewer inspects raw RGB and proposed masks, including gaps and
possible missed paint. Root reviews every flagged case and a small predetermined
sample of other cases; expand inspection only for concrete systematic concerns.
For a new workflow's first pilot, root may inspect all four small cases once.
Root's decision admits a subset rather than weakening quality thresholds for a
bad sample or repeating all successful work. Rejected regions keep their evidence
and reason. New supervised releases remain assistant-reviewed exposed TRAIN,
not independent gold. Training requires a separately frozen hypothesis, bounded
run recipe and physically disjoint evaluation policy.
## Full-cycle growth and baseline disagreements
The first direct-completion full-cycle pilot (2026-10-25) completed two author
and two separate-review tasks with first-result writes and no retries. Root
admitted one of two new TRAIN ROIs after exact merged-target inspection. The
fixed 2/2 hypothesis failed: one source-accepted proposal put 218 previously
accepted background pixels into explicit unknown. Its other numeric gates
passed, but it was excluded entirely. The old background is not presumed wrong;
the new unknown is not presumed authoritative. The accepted release added 55
paint and 9,403 background pixels and preserved all prior targets.
Treat this as a distinct baseline-adjudication task, not an ordinary growth retry.
Bind the old decision, new proposal, exact conflicting pixels and source view.
An independent review may affirm the old label, support a separately admitted
immutable baseline revision, or leave the disagreement unresolved. Do not clear
an uncertainty polygon to pass a preservation check, silently keep an old label
inside explicit unknown, or scale annotation merely because both reviewers
accepted source appearance. Root decides which evidence is admissible.
Full begin-to-published-proof time was 675.7 seconds; preparation and archival
are excluded. One small two-ROI trial without a control arm measures neither
model quality nor full-cycle comparative speedup. Evidence and exact next scope:
`outputs/semantic-executor-completion-20261025/full-cycle-1/REPORT.md`.
## Pilot and tuning
`outputs/semantic-agent-pilot-20261025` contains bounded local text and final proof
images. Raw media, ledger and supervision remain under the Worker portable store.
Four native ROIs were frozen across Maroseyka, Mira, Smolensk and Sretenka. Criteria:
complete ROI, at least 20 fresh paint and 20 fresh background pixels, at most 35%
unknown, unchanged prior labels, independent visual review. These thresholds are
pilot criteria, not a claim of universal road-marking ground truth.
The first integration check found a genuinely ambiguous source region above the
unknown limit. The workflow was tuned to explicitly quarantine units and publish
only root-admitted results; the numeric limits were not relaxed. Controller source
versions before and after this change are recorded in the pilot evidence.
The pilot measures successful source-reviewed regions, rejected reasons,
dispatch/attempt counts, executor wall times and root interventions. It cannot yet
claim a measured speedup over a single-agent baseline or a model accuracy gain.
Two compact final proof images are sufficient; do not retain unlimited crop
exports or media traces. Root's final result and next bounded hypothesis are in
the pilot report.
## 2026-10-25 — Cumulative supervision reaches a complete learning evaluation
`mixed_supervision.py` adds a generic, tested bridge from the last trained
supervision release to accepted mixed paint/background growth. It requires
source/view/group equality, exact reviewed withdrawal coordinates pinned by hash,
zero unknown weight, and conserved mass separately for each physical group and
class. Changed classes redistribute mass uniformly across supported frames and
pixels; this is not a location-dependent inference rule. Twenty-nine focused
tests cover source binding, forbidden class flips/withdrawals and mass handling.
The root session completed a separately frozen Worker experiment in
`outputs/semantic-executor-completion-20261025/roi-learning-1`: +8318 paint,
+87449 background and 244 authorized withdrawals; 24 main fits, 2 deterministic
repeats, 2 exact old-context replay fits, 585 TRAIN maps and 195 excluded-street
maps, with exact inference replay and root visual inspection of all 13 frames.
The four-case uncertainty instruction check separately passed 4/4 purposeful
exposed TRAIN cases; it is not general accuracy or independent gold.
TRAIN fitting improved strongly, but excluded-street mean balanced error rose
0.008812→0.010892; the new coarse-only control scored 0.008063. Six seed/street
pairs improved and six worsened. MI3 dashes separate when that street participates
in training but remain joined when it is excluded. The fixed transfer recipe is
rejected; annotations remain accepted, with no model promotion or live-map change.
The predeclared 2-percentage-point absolute median improvement gate was infeasible
at the measured baseline (maximum possible 0.773pp). It was not changed after the
run and is not used alone as evidence against the method; actual transfer metrics,
ablation and visual defects independently support rejection. See REPORT.md,
root-metric-audit.json, decision.json and the two final proof images. The model
cause is not isolated by this trial. No automatic expansion to 100 scans or
unattended model executor is claimed.
## 2026-10-26 — Exposed-control audit and bounded convex-head experiment
`transfer-control-1` audited the catalog and historical provenance before fitting.
All ten registered Moscow scans are development-exposed, including Mira 68–78;
three nature worlds are outside this task. Nine top-level dataset versions are
Maroseyka revisions, not nine independent streets. Two historically reserved
Novinskiy archives match their prior SHA-256 and remain unopened, one physical
candidate group. Footprint overlap/adjacency and complete exposure provenance
still need verification before independent testing. Exposure cannot be reset by
renaming a world or by a later stage reporting that it opened no images.
The new offline `linear_refinement.py` implements a 258-parameter residual linear
head with normalized full-known-pixel BCE, L2 on all coefficients including bias,
bounded L-BFGS and an explicit stationarity/technical-stop contract. Twenty-nine
focused Worker tests pass. Root completed 24 fits plus two exact repeats, 351 TRAIN
and 195 held predictions, 78 exact prior-MLP replays and 78 repeated linear maps.
All fits converged; source features and source labels remain pinned.
Mean development held BER fell from 0.008812 (old context MLP) and 0.010892
(latest ROI MLP) to 0.005854; coarse-only linear control scored 0.007203. However,
false paint increased on Maroseyka and Sretenka, and root inspection of all 13
frames plus a native MI3 crop confirmed filled dash gaps, symbol holes and a
manhole artifact. Existing TRAIN cohorts also regressed. Numeric and visual
admission failed; no model, live map or annotation release was promoted.
Capacity, optimizer and regularization changed jointly, so this does not isolate
a single cause or reject all linear models.
That report declared native-RGB detail guidance versus low-pass RGB as its next
hypothesis, keeping Novinskiy closed. The subsequent completed work is summarized
below. Exact source audit, decision and retirement evidence for the convex study
remain in `outputs/semantic-executor-completion-20261025/transfer-control-1/REPORT.md`.
## Current frozen-representation evidence and acceptance boundary
The source review and learning loop now runs across 26 accepted source windows,
with complete-symbol, crossing-gap and background supervision added through
separate author, reviewer and root decisions. The accepted composition is frozen
in `source-expansion-1/composition-release.json`; accepting these labels did not
accept a detector. Ambiguous borders and obscured paint remain unknown. Agent
agreement is not an independent gold standard, and repeated seeds or training
windows do not increase the number of independent observations.
Native-RGB guidance, wider source coverage and a lower-capacity head have each
received bounded Worker experiments. None has qualified for live-map promotion.
The recent comparisons keep all 26 targets, frozen coarse/fine features, native
RGB patches, class/family sampling, 1200 AdamW steps and threshold zero fixed.
They compare the 25,602-parameter nonlinear head (`complete-object-learning-1`),
a 333-parameter linear residual (`capacity-ablation-1`) and one fixed width8
nonlinear head with 2,754 parameters (`small-nonlinear-1`).
| Equal-image, then equal-seed held BER | Nonlinear | Linear | Width8 nonlinear |
|---|---:|---:|---:|
| Original cohort: 10 images with both known classes | 0.07506204 | 0.02733846 | 0.06178614 |
| Nine added source windows | 0.08573101 | 0.02170457 | 0.04761772 |
The linear head improves both supports in all three seeds. However, its false
paint increases in the Mira and Sretenka families and in each cohort aggregate. Actual visual review of
all 26 full frames confirms recovery of missing symbols together with narrowed
symbol holes and joined crossing gaps. These separate numerical and visual guards
reject the candidate despite better balanced error. This result changes both
capacity and nonlinear interactions; it does not identify either as the sole cause.
The smaller nonlinear head also fails the unchanged baseline guards and its
additional linear-control guards. Full visual review shows reduced paving
activation together with lost weak paint and entire yield triangles, plus a
filled manhole interruption. Its fixed width8 hypothesis is closed; no width
sweep follows. Known counts and qualitative changes in unknown areas remain
separate, with exact inference replay and two root-viewed proof JPEGs.
A separate CPU-only diagnostic exhaustively examines the saved linear scores.
There are 7,053 threshold masks satisfying the 12 monotone recall/FPR constraints,
but every one fails the older-control old13 BER guard; outside that interval at
least one monotone constraint fails. Exact integer counts and rational macro
metrics therefore rule out one common scalar threshold, shared across these
26 windows and three seeds, passing all original numerical guards. This is a
consumed-label diagnostic, not prospective calibration, topology qualification,
or a claim about every possible parent-specific calibrated system. No threshold
was applied. See `score-ranking-1/REPORT.md` and
`score-feasibility-1/supplemental-REPORT.md` in the same experiment base.
Any later nested calibration must exclude both the outer and inner physical
families from parent training, parent-dependent fine/coarse feature generation
and residual fitting. The existing outer fine features are fixed across these
arms, but are not label-independent pretrained features: their supervised parent
tail and normalization belong to the fold. Eighteen historical inner parents
have verified state/meta bytes and matching train/init lineage; that availability
alone does not qualify a calibration method or authorize an automatic retry.
Evaluation support is declared before fitting. BER/recall omit only images whose
accepted targets lack the required class denominator; FPR still includes known
background-only images. Unknown pixels never become background. For example,
old13 BER has 10 supported images while its FPR has all 13. Comparisons require
identical source/target identities and support, and retain all family-level
recall/FPR guards. Every outer fold excludes its entire physical family, including
Maroseyka/Pokrovka and Smolensk/Sadovaya-Karetnaya groupings. These remain repeatedly
consumed development folds, not a new independent geographic test.
Three native windows are 768px/12m; the other 23 are 512px/12m. Consequently a 5x5
native RGB patch has a different physical footprint. Frozen semantic features use
the same 128 grid over 12m, but grid spacing is not receptive-field size. This
recorded scale confound is not proof of the observed transfer failure: old and
new Mira, Sretenka and Smolensk windows share the same native scale.
Decisions are bound to immutable protocols, models, exact replay, byte-verified
result transport, source/target/prediction visual receipts and a root verdict.
Reports, two final proof images per experiment and content-addressed text archives
are retained; inventoried generated render PNGs are retired after all readers
finish. Active model/feature/prediction dependencies remain owned by their next
experiment. See `complete-object-learning-1/report.md` and
`capacity-ablation-1/REPORT.md` under
`outputs/semantic-executor-completion-20261025` for exact scopes and limitations.
## Resumable offline learning execution
`simulation/semantic-learning/learning_execution.py` supplies the missing bounded
execution ledger between an accepted release and a fixed recipe runner. It is
included by the existing source-only Worker packager. It does not dispatch LLM
agents, select a model, promote a release, or create a durable service.
The evidence root can be the read-only portable store, while a separate writable
state root owns only the experiment ledger. Plans can explicitly pin up to 1024
selected files within a 256KiB manifest; source references are never silently
substituted for actual payload identities. Worker qualification also proves that
changing an external input blocks completed-phase reuse.
A plan pins its declared inputs and Python runner/verifier sources, phase order,
output manifests, and separate run/verification subprocess deadlines. The caller
still owns the whole-phase wall deadline, isolated Worker runtime, GPU/CPU/RAM,
network and storage bounds. A verifier must validate the recipe's full source,
label, model and cache provenance, then return both the declared output roots and
all derived files they depend on. A complete manifest alone is insufficient:
checkpoint, metadata and prediction-array bytes belong to the recorded artifact
closure. Undeclared or external input dependencies remain the pinned recipe
validator's responsibility; the ledger does not recursively infer dependencies.
The SQLite transaction reserves a phase before launching it. A completed phase
is reused only while all declared inputs, preceding artifact closures and its own
closure remain byte-identical. Interrupted, failed and unacknowledged execution
remains reserved; elapsed time never retries training. Trusted root can reconcile
confirmed-stopped completed output through the same pinned verifier, or close an
archived failed phase while preserving its partial files. The root attestation is
an orchestration trust boundary, not an authentication service. Model-quality
rejection still produces a valid engineering artifact and never implies approval.
Thirty focused tests cover restart, two-controller competition, changed
source/target/model bytes, invalid verifiers, closure omission, unknown ownership,
archived failure and bounded subprocess execution. Worker qualification executes
a tiny real subprocess that writes synthetic weights and deliberately exits 19.
After controller restart, fit cannot rerun; root reconciliation recovers the
complete output, leaving the fit counter at 1. Payload corruption with an unchanged
manifest blocks the next phase. The verified original bytes then permit evaluation.
No real model is fitted in this qualification. Exact sources, limitations and the
root-verified content-addressed archive are recorded in
`outputs/semantic-executor-completion-20261025/execution-bridge-1/REPORT.md`
and the separate-state-root extension in `execution-bridge-1/state-root-REPORT.md`.
The latest canonical executor merges repeated preceding artifact paths within each
validation boundary, rejects conflicting pins before hashing, and still rehashes
all bytes at later pre/post/resume boundaries. A synthetic cumulative fixture
reduces 16 hash calls to 8; this is not a measured latency improvement. Equal hashes
at different paths remain separate checks. This refinement is for future cycles;
the completed parent-refresh plan retained its earlier qualified bridge bytes.
The parent-refresh experiment updated the supervised FPN on the accepted
26-window composition while retaining the original pretrained reset and historical
per-fold initializer/normalization, then fitted the unchanged linear residual. It
regenerated all parent-dependent features and validated actual parent/child/repeat
checkpoint tensors. This jointly changes parent supervision and class/family mass;
it does not isolate data quantity or remove historical initializer influence.
On 2026-10-26 the owner explicitly authorized temporary Worker images, code/tests,
and the bounded 27-fit experiment. The 129-test Worker suite passed without skips.
An initial no-fit preflight found a relative Torch module-path/cwd conflict; its
exact stopped attempt and sources were archived, and root closed the failed ledger
entry. The replacement entry restores the historical root cwd without relaxing
source checks; four new tests and five actual bridge/import checks cover the fix.
The reviewed replacement real preflight then passed all 12 fold contracts.
All 27 fits completed in 942.16 seconds of combined parent/child phases, below the
3600-second cap, with exact original-parent replay and new-parent/child repeats.
All models were frozen before scoring. TRAIN and held scoring each have 234 rows
(including immutable reference controls), and all 78 candidate held arrays replayed
exactly. An independent exact-count audit reproduced 11 failures among the 23
frozen comparisons. Against the unchanged linear-head G control, P worsened both
old10 and new9 balanced error in all three seeds. Actual visual review covered
all 26 full frames and seven overlapping object ROIs; root personally viewed
seven full frames and the two final M1/SK2 proofs. The M1 line-gap fill is a
visual rejection as well. These are exposed development families, not new
independent geography. P is rejected; the narrower 3x3 spatial-context S variant
was also rejected after complete numerical and visual review. Neither result
claims that all parent adaptation or all spatial context is ineffective.
Completed-phase reuse was exercised against the real P parent and child outputs:
the original receipts and tokens returned, all declared artifact bytes were
rechecked, and the raising runner was never called (zero additional fits).
No live map, accepted target or production model was changed. Compact evidence
and two final images per experiment are retained; exact disposable PNG retirement
is recorded separately after archive verification. The next experiment admission
is documented in `parent-refresh-1/NEXT_EXPERIMENT_ADMISSION.md`: versioned
supervision, confirmed geographic split, whole-object and hard-background
coverage, and bounded payload loading before scaling to many scans. More
training on the same consumed 26 windows is not an independent transfer test.
The original `parent-refresh-1/IMPLEMENTATION-CHECKPOINT.md` is historical; current
execution evidence is in its versioned controller receipts and
`autonomous-session-20261026.json` under the experiment base.
## Завершённый полный RGB-пилот · 26.10.2026
Владелец прямо поручил реализовать v4-план. Выполнен один полный RGB SegFormer MiT-B0 fit на current26:5000 шагов/seed11/558.378s; checkpoint закреплён. G12 восстановлен с побайтовым M4 replay tail/fine/coarse/logits. На четырёх заранее перечисленных окнах двух сканов без географического процесса получены native predictions, метрики только known support и точная локальная геометрия всех восьми масок.
Терминальное решение root и отдельного визуального критика — rejected_in_tested_recipe_and_support. FP5866→516 и gap-FP4719→121 улучшились, но FN724→1363; на source-1 FN50→1226 нарушает неизменный gate. Native review подтверждает исправление слияния полос N52-01 и новый разрыв полосы N51-07. Полные кадры показывают обширные срабатывания B0 на плитке/артефактах вне узких эталонов; это qualitative risk, не численная разметка unknown. Модель изолирована; live map не меняется. Архитектура целиком не отвергнута; повтор без новой проверяемой причины не запускается.
Реализован paint_comparison.py и19 целевых tests RGB/scorer; Ruff passed. Один root+один повторно используемый критик; broad research/sweep отсутствовали. Старый протокол и неудачные технические probes сохранены, включая исправление двух разных TF32-режимов historical extractor/decoder. Владелец разрешил этот ограниченный run; старые27 fit не использовались. Worker power/raw/live map/packages не изменялись.
Актуальные артефакты: outputs/semantic-rgb-comparison-20261026/{REPORT.md,root-decision.json,critic-review.json,comparison.json,resource-summary.json,next-step.json,closeout-receipt.json}. Тяжёлые файлы на одноимённом Worker experiment. Один checkpoint и два фиксированных probability массива N51-07 сохранены для следующей оценки; остальной явно перечисленный derived scratch удаляется после verified текстового архива, два итоговых листа остаются на Mac.
Следующий bounded-пакет: полная source-bound development-разметка одного N51-07, независимый review и оценка уже сохранённых predictions, без нового обучения/порогов. Проверить слепую зону узкого ROI и цену исправления полного окна. Эти четыре просмотренные окна использованы для выбора следующего направления; при дальнейшем тюне они development. Новое качество принимается на отдельно замороженных source IDs, без адресного/географического поиска. Этот результат заменяет прежний статус «сравнение не выполнено», но не закрывает всю автоматическую разметку.
+231
View File
@@ -0,0 +1,231 @@
# Urban semantic agent operating contract
Версия 2 · 26.10.2026. Канонические правила и текущая передача: [MISSIONCOR-93](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-93); продукт: [MISSIONCOR-88](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-88).
Ops хранит действующие решения владельца и текущий этап. Этот файл — переносимый вход в процедуру и описание локально реализованных ограничений. При возобновлении читать актуальную карточку; ограничения доступа из старого отчёта не заменяют последние указания владельца.
## Фундамент продукта и границы сцены
[SCENE_SEMANTICS_PRODUCT_CONCEPT.md](SCENE_SEMANTICS_PRODUCT_CONCEPT.md) — обязательный вход, согласованный владельцем 26.10.2026. Отдельный скан произвольной неизвестной зоны является целевой локальной сценой ровера. Исходное записанное сенсорное облако — основа пространственных измерений/локализации; Gaussian — визуальный источник текущей семантической работы; семантика — дополнительный контекст. Название улицы, GPS и публичная карта не требуются. Автоматическое сравнение, географический поиск, совмещение или объединение разных сканов запрещены без отдельной явно заказанной задачи.
Зебры функционально важны. Полный набор наблюдаемой дорожной разметки нужен также для интерфейса, промо и проверки сложного распознавания. Это не сводится ни к демонстрации, ни к одним зебрам. Основной путь: одна сцена → наблюдения → локальные семантические объекты → проверка/редактор → проверенные учебные данные. Готовность raw-локализации и runtime не объявляется этим документом.
## Постановка задачи и полезный результат цикла
Глобальный результат: семантический контекст отдельной произвольной сцены для задач ровера и интерфейса, включая зебры и весь наблюдаемый набор разметки. Учебный контур должен давать переносимое распознавание на заданных отложенных сканах и уменьшать ручное исправление; каждый запуск работает в координатах своей сцены без географических сервисов и связи с другими сканами.
Цикл обязан закончиться одним из содержательных результатов: принятый модуль/исправление с проверенной интеграцией; принятая версия полезных данных; конкретная гипотеза, закрытая достаточной проверкой в явно названных условиях. Нужны артефакт, сравнение с исходным состоянием, область применимости и следующее решение. Число тестов, отчётов, обучений и улучшение пиксельной метрики сами по себе пользой не считаются.
Незавершённый тест из-за срока/доступа/ошибки процедуры — inconclusive, а не отвергнутый метод. Закрытая гипотеза не означает невозможность всего подхода. Новые критические регрессии до приёмки исправляются в той же сессии либо изменение откатывается/изолируется; цикл не объявляется успешным с оставленной регрессией.
## Размер рабочего пакета — уточнение владельца 27.10.2026
Владелец просит существенно увеличить объём одного захода и не завершать его после отдельной внутренней проверки. Root заранее связывает несколько зависимых этапов в один полезный результат: проверка основания → реализация/данные → весь заранее ограниченный эксперимент → контроль регрессий и визуальный осмотр → исправление либо изоляция → интеграция и итог. Прохождение внутреннего gate не требует нового «го», если следующий шаг входит в поручение и лимиты. Краткие сообщения о ходе работы не являются остановкой или запросом разрешения.
Размер пакета определяется закрытым вопросом и проверенным артефактом, а не обещанием десятикратно увеличить число моделей, агентов или расход. После первого отрицательного результата выполняются оставшиеся заранее объявленные сравнения; новых произвольных sweep не добавляют. Если реальный блокер мешает этапу, root завершает независимые части и точно называет незавершённое. Обязательные проверки не заменяются планом следующего чата. Итог владельцу краткий: что теперь стало лучше, что отвергнуто и почему, что осталось нерешённым, где увидеть результат.
## Минимальный состав и ответственность root
Root держит цель, реестр проверенных подходов, критерии, бюджет, интеграцию и итоговое решение; сам реализует основную работу. Отвечает за фактическую передачу каждого задания, проверку принятого результата и продолжение до терминального исхода без выпрашивания следующего шага.
Критик — один переиспользуемый помощник: проверяет корректность эксперимента, переносимость, зависимости, регрессии, чистоту кода и отсутствие привязки к улице. При разметке выполняет отдельное review чужих предложений. Не требует полного переписывания из эстетических соображений.
Исследователь — один переиспользуемый помощник по запросу этапа: читает текущие результаты, проверяет готовые подходы по первоисточникам, приносит до трёх альтернатив с условиями применимости и маленькой различающей проверкой. Root принимает/отклоняет каждую рекомендацию с причиной. Он не браузит постоянно и не назначает сам обучение.
По умолчанию root + критик; максимум два одновременно работающих помощника вместе с временным исследователем. Без вложенного размножения агентов. Компактный бриф вместо полного чата; роли не требуют постоянно живых процессов. Вычисления и проверки форматов выполняет код.
## Порядок выбора пайплайна и граница R&D
Используем накопленный опыт, не начинаем перебор с нуля. Порядок: инвентаризация уже проверенного → требования к входу/выходу → сравнение совместимых готовых решений → дешёвые проверки представления и интеграции → ограниченное локальное сравнение → зафиксированный выбор → адресный тюнинг по измеренной причине.
Оценка кандидата: фактическая доступность нужных входов; сохранение отдельных штрихов/полос/отверстий символов; классы и отказ при неизвестном; связь с локальными координатами своей сцены; качество на заданных отложенных сканах; воспроизводимость и условия использования кода/весов; RAM/VRAM/время; труд интеграции и исправления оператором. Чужие benchmark не заменяют эту оценку.
Выбор означает лучший проверенный вариант в зафиксированном наборе кандидатов/условий, а не обещание глобального идеала. Глубокий кастомайзинг допускается после локализации ограничения готового решения. Повторный тюнинг на прежних контрольных кадрах не заменяет новый аргумент.
## Контракт одного ограниченного цикла
До старта root фиксирует: вопрос/гипотезу; прошлые результаты; точные исходники и версии; baseline; результат на выходе; измеримые проверки и их поддержку; критические регрессии; область переноса; исполнителей; время/число запусков/память/артефакты; причину прекращения и вариант отката. Критерии проверяются на математическую достижимость до вычислений.
Передача: резервирование → реальная отправка помощнику → запись ссылки/подтверждения. Неподтверждённая передача остаётся обязательством root, её нельзя считать работающим агентом или автоматически освобождать: отправка могла пройти без квитанции.
Проверка готовой единицы начинается сразу при свободном исполнителе; запрещён барьер «ждём все авторские предложения». Готовый review имеет приоритет перед новым авторским пакетом. После результата root проверяет фактический артефакт, а не только пересказ.
Принять часть качественных данных допустимо; это отдельно от достижения цели всего цикла. Завершение ledger, сохранение файла и успешный тест не равны завершению задачи. Новые планы должны фиксировать требуемые проверки и минимальный объём результата; старые frozen-протоколы не переписываются.
## Качество, переносимость и архитектурная чистота
Различать наблюдаемую краску, обоснованную геометрическую гипотезу и unknown; правило формы не создаёт факт наличия разметки. Нельзя склеивать штрихи/полосы ради pixel score или выдавать шаблон за измеренный контур.
Полный контроль выбранного окна включает пропущенные и ложные объекты, отдельные полосы/отверстия, геометрию, стыки тайлов и неопределённость. Изменение признано полезным после проверки через одинаковую сборку карты; для итоговой оценки — время исправления до одинаковой экспертной приемки. Произвольные 95% или 30% не считаются согласованными порогами.
Train/development/evaluation задаются явными source IDs и версиями; производные одного источника сохраняют partition, известные связи происхождения не теряются. Никакого автоматического сравнения геометрии разных сканов или доказательства географического непересечения как обязательного gate. Модель сравнивается с метками внутри каждого выбранного скана; метрики можно агрегировать. Физическую независимость не утверждать без отдельного основания, но её отсутствие не блокирует ограниченный эксперимент. Контроль переводится в development после использования его предсказаний для тюна; чтение исходника для независимой аннотации само по себе не равнозначно этому.
Критик проверяет отсутствие street ID/координатных веток, test-target leakage, размножения почти одинаковых стадий и скрытых зависимостей. Идентичный no-op сохраняет геометрию, происхождение и неизвестность. Использовать общие интерфейсы источника, наблюдений, модели, сборки и редактора.
## Бюджет, исследование и прекращение бесполезной работы
Одна исследовательская выдача: один явный вопрос, до трёх подходов, до шести первоисточников и восьми web-вызовов, ориентир до 20 минут. Это правила диспетчера, не автоматически измеренная провайдерская квота. Принимаются ноль полезных идей, если приведены основания. Не повторять обзор без новых данных/условий.
Первая сравнительная серия — не больше двух содержательно разных новых рецептов; не обязательны оба, если дешёвая проверка исключила один. Две проверки с одинаковыми по смыслу основаниями не порождают третью косметическую вариацию. Root фиксирует закрытие либо точное новое основание.
Учитывать полный wall time, минуты участия root/проверки, compute, объём данных и при доступности фактические provider tokens. Не подменять неизвестные токены оценкой по длине текста. Стоимость/время сравниваются с полученной принятой работой или ценностью закрытого решения. Проверки не повторяются без изменений, отказа или нового существенного риска.
Не создавать новые framework/daemon/дашборд для управления этим пакетом. Сначала использовать имеющиеся queue, admission, execution и редактор; локальное исправление инструмента должно устранять конкретный подтверждённый дефект.
## Передача между чатами и Codex
Новый root начинает с этой карточки и MISSIONCOR-88 через live Ops MCP; не восстанавливает цель только из последней фразы чата. Затем читает docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md, docs/SEMANTIC_AGENT_CYCLE.md, docs/SEMANTIC_RESEARCH_SCOUT.md, текущий отчёт и решение. Канонический репозиторий на этом Mac: /Users/dcconstructions/Downloads/mnt/NODEDC/NODEDC_MISSION_CORE. На другом компьютере найти этот же checkout/revision; абсолютный Mac-путь не является переносимым runtime-контрактом.
Бриф содержит карточку/версию, последний принятый результат, активную гипотезу и состояние, исходники/артефакты, известные дефекты, следующий конкретный шаг, лимиты и ограничения доступа. Полный чат и весь архив каждому помощнику не передаются. При продолжении сначала сверить фактический статус ledger/исполнителей в разрешённой области; не повторять completed-фазы.
По итогам содержательного этапа обновить текущие блоки и чекеры этой карточки, добавить короткую запись «решение → основание → эффект → следующий шаг». Полная история опытов остаётся по ссылкам; завершённые списки не копируются бесконечно. Для конфликтующих требований действует последнее прямое указание владельца.
## Что исполняется кодом
`simulation/semantic-learning/agent_cycle.py` поддерживает `missioncore.semantic-agent-cycle/v2`. Для новых циклов применять v2. Исторические планы v1 и их исходные решения остаются совместимы; они не получают новые критерии задним числом.
V2 фиксирует `objective_contract`: `deliverable`, `min_admitted_units` и уникальные `required_checks`. Это цель приёмки аннотационных свидетельств внутри Cycle, не приёмка опубликованного датасета, модели или всей карты. `agent_admission.publish()` выполняется после закрытого accepted-цикла; root отдельно проверяет фактическую публикацию. Общее завершение пакета учитывает этот следующий шаг.
До запуска проверяются достижимость количества единиц и минимум двух резервирований (author + review) на каждую целевую принятую единицу; параллельность v2 ограничена двумя исполнителями. Прочие научные критерии, диапазоны метрик и бюджет времени root проверяет до вычислений: код не решает этот вопрос автоматически.
После реальной передачи пакета root вызывает `confirm_dispatch(token, root_actor, executor_ref, evidence)` с ссылкой на действительного исполнителя и подтверждение. Пока активная/прерванная передача не подтверждена, новый claim запрещён. Квитанция не запускает агента и сама по себе не является аутентификацией. Срок не освобождает ресурс: остаётся обязательная сверка и reconcile. Быстрый результат до квитанции принимается по своему token; квитанция может быть добавлена позже, в том числе после закрытия для того же завершённого token, без изменения принятого результата.
Готовый review блокирует выдачу новой авторской задачи. Review создаётся при готовности отдельного предложения; ожидание всех авторов не требуется. `status()` показывает `ready_tasks` в нужном порядке, `unconfirmed_handoffs` и `progress` (план, предложения, проверки, допущенные единицы, блокировки и цель).
Решение v2 отдельно хранит обычный admission `verdict` и `objective_outcome`: `achieved`, `not_achieved` или `inconclusive`. Обязательны точные boolean `objective_checks`, причина `outcome_reason` и `remaining_work`. `achieved` требует целевого количества допущенных единиц, всех заранее названных проверок и пустого остатка. Частичное принятие хороших меток допустимо с недостигнутой общей целью; публикация не получает ложного статуса полного успеха. Причина/оставшаяся работа обязательны для остальных исходов.
Эти ограничения не доказывают качество геометрии или факт визуального просмотра. Root и критик проверяют эти свидетельства содержательно. Контроллер не выбирает модель, не выполняет web-поиск, не отправляет сообщения и не имеет собственного фонового LLM-процесса.
## Локальная проверка 26.10.2026
49 focused tests прошли: `test_agent_cycle.py`, `test_agent_completion.py`, `test_agent_source_binding.py`, `test_agent_outcomes.py`. Ruff для изменённого контроллера и новых тестов — чисто. Проверены потерянная передача, review до окончания других авторов, fast-completion/recovery, точные критерии, недостаточный dispatch budget, частичное принятие и сохранение v1. Отдельный критик нашёл два дефекта первой версии (восстановление квитанции после закрытия и недостаточный бюджет author+review); оба исправлены и покрыты регрессиями.
Это локальная проверка исходников на синтетических данных. Worker, установленные пакеты, реальные сканы, обучение и принятые карты в этом пакете не менялись. Реальное снижение времени/токенов ещё измеряется отдельным сравнением; наличие тестов не выдаётся за это измерение.
## Проверка геометрии и следующее действие · 26.10.2026
Завершён ограниченный offline gate: точная маска → отдельные полигоны с отверстиями → существующие операции/хранилища редактора на синтетике. Принят локальный адаптер paint_geometry; 98 целевых тестов прошли. Штатная SD-схема VMA отвергнута только как полная замена тел краски: ось/рамка/внешний контур теряют нужные детали. Архитектура VMA для других целей этим не исключена. Фактическое качество распознавания улиц не изменилось.
Подробный контракт, ограничения, исходники и решение: [SEMANTIC_PAINT_GEOMETRY.md](SEMANTIC_PAINT_GEOMETRY.md). Итоговые свидетельства: outputs/semantic-geometry-gate-20261026/. Следующий кандидат сравнения — полное обучение RGB SegFormer MiT-B0 против frozen G на одинаковой точной геометрии. Спецификация зафиксирована в next-experiment.json, но не является готовым к запуску выпуском: нужны immutable входы/явный список отложенных источников/проверенные объекты для заявленных метрик и актуальное разрешение Worker; географический gate отменён последующим решением владельца. Сохранены ограничения parent-refresh-1/NEXT_EXPERIMENT_ADMISSION.md. Не повторять завершённую проверку представления или F/G/H/S/P без нового основания. Актуальные разрешения Worker читать из последних ответов владельца и текущей передачи Ops; прежний запрет на доступ не отменяет последующий явный допуск чтения, а допуск чтения не разрешает обучение или управление питанием.
## Источники, исторические проверки и текущий план · 26.10.2026
После явных разрешений владельца проверены файлы urban-learning и два каталога Новинского 5.1/5.2. Пакет outputs/semantic-control-read-20261026/: 204 уникальных файла/33 464 191 байт совпали с pins, все 26 target bytearrays пересобраны точно, 12 model/state пар проверены по SHA. Root и критик просмотрели два учебных примера; частичные ROI не повышены до complete-object truth. Новинские архивы перечитаны по SHA, готовые фотографии просмотрены, локальные траектории прочитаны; географическая независимость ещё не установлена. Обе сцены остаются одной кандидатной семьёй.
После следующего прямого разрешения владельца подготовлен outputs/independent-control-novinskiy-20261026/: две конверсии, два обзора и 16 детальных ортовидов. Root просмотрел все окна, критик — пять ключевых. Выбраны четыре кандидата для локальной аннотации краски и четыре для ограниченного фона; восемь остались преимущественно unknown. Это проверенный источник, не готовая truth или улучшение распознавания. Общая независимая география ещё не доказана; одна семья novinskiy-bulvar, control_admitted=false. Полный manifest/камеры/хеши/geometry сохранены на Worker, собственные PLY и CUDA-кэш удалены после проверки. Питание, исходники и live map не менялись; fits=0, predictions=0, пакеты не устанавливались.
После следующего «го» выполнен annotations-v1: четыре локальные source-bound маски и 18 instance-наблюдений прошли отдельный визуальный review и сохранены на Worker с SHA/PNG/RLE readback. Шесть полос целиком в кадре, семь обрезаны, три имеют неопределённые границы, два наблюдения — фрагменты линии. Это ограниченные области (100 824 known pixels из четырёх контекстных кадров), не полная разметка кадров. Критик отклонил первый N52-08 за два ложных background-участка; исправлены 837 пикселей → unknown, повторный review принят. Plan, dispatch-ledger, rejected revision и root-decision сохранены. TRAIN-only controller/publisher не запускались; прямой source-only путь не выдаётся за проверку его runtime. На Mac два новых итоговых листа этого этапа; временные изображения убраны после проверки Worker.
Географическая проверка registration-v1 сначала завершилась inconclusive: широкое сопоставление верхних видов не дало подтверждённых ориентиров. Этот исторический результат сохранён; отсутствие совпадений никогда не считалось доказательством независимости. Автор затем уточнил происхождение: 5.1 — весь нечётный Новинский, 5.2 — весь чётный Новинский; 6.4 — чётный кусок Смоленского. Номера домов искать на углах в гауссах.
Историческое решение address-check-v1 (больше не основание обязательного gate): четыре уже принятых локальных пакета N51-04/N51-07/N52-01/N52-08 допущены как ОДНА географически отдельная семья для frozen-сравнения на их known support против точных current26/G12. В 14 существующих видах с уровня улицы найдены Senses (Пречистенка40/2стр1 по официальному сайту) и ипотечный центр с эмблемой Райффайзен (Смоленская-Сенная28 по релизу банка2011). Адресные таблички напрямую не прочитаны: это качественная локализация по двум source-bound ориентирам, контексту и свидетельству автора. Критик отдельно просмотрел шесть кадров и принял вывод. Все пять обучающих SM-окон привязаны к этому world21534482…; metadata всех12 pinned G-моделей содержат только current26; четыре контрольные маски точно связаны с двумя закреплёнными Novinskiy sources. Метрическое преобразование для этого ограничения не требуется: прежний избыточный gate явно изменён в control-admission.json до каких-либо предсказаний. GPS/точная дистанция не выдумывались.
Допуск ограничен 28 797 paint + 72 027 background pixels и исходной областью instance-review. Шесть целиком видимых полос не становятся точными полными контурами через unknown. Это не полная аннотация кадров, не оценка всей улицы, стрелок/символов с отверстиями, не подтверждение иных источников6.2/моделей. training_eligible=false; comparison_eligible_on_declared_support=true; global_comparison_execution_ready=false. После использования результатов для тюна этот контроль переводится в development. Исторические manifests не переписываются; address-check-v1/control-admission.json сохраняет прежнее решение. Текущую работу задают концепция отдельной сцены и next-experiment-v4, без географического gate.
Следующий шаг — подготовить ранее выбранное сравнение frozen G12 / полного RGB SegFormer B0: зафиксировать допустимую область метрик и unknown, проверить input/scorer, закрепить checkpoint/code/environment и получить текущий ограниченный допуск исполнения. Более широкий complete-object gate остаётся отдельным: он не закрывается малым контролем и не блокирует явно ограниченный пилот на имеющихся эталонах. Неподдержанные классы имеют статус not_assessed, а не passed. Не возвращаться к географическому поиску, сравнению или совмещению сканов без новой отдельной просьбы владельца, в том числе при добавлении новых сканов. Рецепт G: mean(sigmoid(native logits)), float64, threshold0.5, все12 frozen models для новой семьи; старые family-excluded оценки не подменять.
Материалы: outputs/independent-control-novinskiy-20261026/address-check-v1/{REPORT.md,root-decision.json,control-admission.json,source-binding-check.json,landmarks.json,critic-review.json,remote-readback.json,retirement-receipt.json}; Worker — одноимённый каталог в D:\NDC_MISSIONCORE\datasets\urban-learning\experiments. На Mac два итоговых адресных листа; исходные PNG остаются на Worker. Новых renders/conversions/fits/predictions/установок/power actions=0. Исходники и live map не менялись. Старый27-fit допуск не переносить, питание не трогать. Читать также annotations-v1 и актуальный MISSIONCOR-93.
## Текущая постановка после уточнения владельца · 26.10.2026
Географическая ветка остановлена как выход за нужный scope. Качественные находки прошлого address-check сохранены как история; они не являются необходимой предпосылкой алгоритма или обучения. Действующий протокол подготовки — outputs/scene-semantics-concept-20261026/next-experiment-v4.json; v3 не запускался и остаётся историей. Метки annotations-v1 и их unknown/scope сохранены, повторной аннотации ради новой постановки нет.
Для следующего bounded-сравнения фиксируются train/current26 и четыре evaluation-окна двух названных сканов. Проверять только исходники, утечку, поддержку метрик, код/веса/среду и реальный результат внутри каждой сцены. G12 остаётся историческим system comparator с прежним численным рецептом, не доказательством физической независимости и не причинным сравнением одной архитектуры. Уже заданные группы прошлых опытов не менять задним числом; новые сканы не связывать автоматически по адресу или близости. Full-marking цель сохраняется, малый опыт на полосах имеет только свой явно названный scope. В этой документальной коррекции Worker, обучение, live map и питание не затронуты.
## Завершённый полный RGB-пилот · 26.10.2026
Владелец прямо поручил реализовать v4-план. Выполнен один полный RGB SegFormer MiT-B0 fit на current26:5000 шагов/seed11/558.378s; checkpoint закреплён. G12 восстановлен с побайтовым M4 replay tail/fine/coarse/logits. На четырёх заранее перечисленных окнах двух сканов без географического процесса получены native predictions, метрики только known support и точная локальная геометрия всех восьми масок.
Терминальное решение root и отдельного визуального критика — rejected_in_tested_recipe_and_support. FP5866→516 и gap-FP4719→121 улучшились, но FN724→1363; на source-1 FN50→1226 нарушает неизменный gate. Native review подтверждает исправление слияния полос N52-01 и новый разрыв полосы N51-07. Полные кадры показывают обширные срабатывания B0 на плитке/артефактах вне узких эталонов; это qualitative risk, не численная разметка unknown. Модель изолирована; live map не меняется. Архитектура целиком не отвергнута; повтор без новой проверяемой причины не запускается.
Реализован paint_comparison.py и19 целевых tests RGB/scorer; Ruff passed. Один root+один повторно используемый критик; broad research/sweep отсутствовали. Старый протокол и неудачные технические probes сохранены, включая исправление двух разных TF32-режимов historical extractor/decoder. Владелец разрешил этот ограниченный run; старые27 fit не использовались. Worker power/raw/live map/packages не изменялись.
Актуальные артефакты: outputs/semantic-rgb-comparison-20261026/{REPORT.md,root-decision.json,critic-review.json,comparison.json,resource-summary.json,next-step.json,closeout-receipt.json}. Тяжёлые файлы на одноимённом Worker experiment. Один checkpoint и два фиксированных probability массива N51-07 сохранены для следующей оценки; остальной явно перечисленный derived scratch удаляется после verified текстового архива, два итоговых листа остаются на Mac.
Следующий bounded-пакет: полная source-bound development-разметка одного N51-07, независимый review и оценка уже сохранённых predictions, без нового обучения/порогов. Проверить слепую зону узкого ROI и цену исправления полного окна. Эти четыре просмотренные окна использованы для выбора следующего направления; при дальнейшем тюне они development. Новое качество принимается на отдельно замороженных source IDs, без адресного/географического поиска. Этот результат заменяет прежний статус «сравнение не выполнено», но не закрывает всю автоматическую разметку.
## Ночной пакет: расширенный фон и native-контекст · 26.10.2026
Выполнены расширение N51-07, независимый review, пересчёт фиксированных G12/B0 и один native512/stride256 B0 inference без нового обучения. Принято 397981 дополнительных фоновых и253 paint pixels; итог437435known/611141unknown. Это development, не полный эталон и не training release. Старую ROI сохраняем целиком, включая unknown. Ошибка r1, нарушавшая эту защиту, исправлена в общем label_extension.py и покрыта regression tests.
На расширенном фоне G12FP105/FN34; B0wholeFP69328/FN1013; B0slideFP92883/FN877. Старый узкий N51-07 ROI скрывал весь69328FP B0. Whole replay exact во всех4окнах. Slide увеличивает source2FP383→601 и gapFP0→10, разрыв полосы визуально сохраняется. Фиксированный рецепт отклонён, архитектура RGB целиком не отвергнута, G12 не продвинут в production. Unknown не превращён в negative и не вошёл в счётчик ошибок.
Приняты reusable экспериментальные label_extension/native_sliding с16целевыми тестами и Ruff; это не внедрение модельного рецепта в live map. Новые широкие модели/пороги/обучения/географические проверки не запускались. Новые данные нельзя автоматически включать в train: четыре просмотренных окна — development.
Следующий шаг определён в outputs/semantic-night-cycle-20261026/next-step.json: проверить фактически использованное покрытие/выборку train background против истории уже закрытых гипотез; новое обучение только при содержательном новом основании. Не повторять прежний fit или sweep по stride/threshold. Текущие решение/отчёт/критик/ресурсы/архив/closeout лежат в этом же каталоге на Mac и Worker. Старые заявления о следующем N51-07 rescore выше теперь исторические — этот rescore выполнен.
Последнее прямое поручение владельца: выключить Worker006 после всего ночного пакета. Оно заменяет прежнее «питание не трогать». Фактический power outcome записывается в shutdown-receipt.json и актуальном Ops; не считать намерение выключения подтверждённым состоянием. Следующий чат не должен автоматически включать Worker или повторять завершённые этапы.
## Проверка фактической B0-выборки · 27.10.2026
Завершён outputs/semantic-training-exposure-20261027. Все 26 target и 33 tile восстановлены точно; 5000×2 выбора sampler совпали с историческим SHA. Все tile выбирались; 1 152 178 фоновых пикселей, пять BG-only кадров получили 2568 выборов. Гипотеза пропущенного или исключённого фона отвергнута для B0 current26. Доля коэффициентов mean-CE для фона 88,5044% не является фактическим loss или вкладом в градиент.
Без нового обучения проверен прежний B0 checkpoint: 26 целых кадров и 33 обучающих tile в eval mode. Получены FN 7 / FP 8 на 134 645 paint / 1 152 178 BG. Для 23 одинаковых входов 512×512 совпали хеши вероятностей; BN buffers не менялись. Равенство сумм скрывает M3 FN 2→0 и M1 FN 0→2. Root и критик увидели посторонние ответы вне проверенных областей знакомых SK2/M4; unknown не считался количественным FP. Качество целого кадра и перенос не подтверждены.
Не повторять общую гипотезу «больше фона»: исторические hard-BG, context-BG и complete-object опыты уже есть. Следующий ограниченный замер — old/new support gap внутри SK2/M4: сначала проверить прежнюю разметку этих источников, при необходимости отдельно проверить сплошные области, затем оценить фиксированным checkpoint. Точный handoff — next-step.json. Новое обучение требует содержательного нового основания. Worker был доступен; питание этого продолжения не менялось. Предыдущая квитанция выключения остаётся историческим фактом, а не текущим статусом доступности.
## Измеренный разрыв на соседней плитке · 27.10.2026
Завершён outputs/semantic-support-gap-20261027. По source-review двух заранее закреплённых native ROI получены 48 076 новых фоновых пикселей; старые target и protected unknown не изменены. M4: old FP 0/5733, new FP 3140/13467 (23,32%). SK2: old FP 0/38191, new FP 4862/34609 (14,05%). Тот же B0 whole-native checkpoint, порог 0,5; probabilities exact предыдущему запуску, BN и old whole counts неизменны. Root и критик просмотрели source/annotation до scoring и два финальных листа. Это development-фон внутри знакомых кадров, не вся сцена/независимый перенос; качество модели не улучшено.
Историческое coverage M4 уже входило в old; SK2 target перенесён точно из исходной разметки. Новые runs сохраняются отдельно с provenance, в train не публикуются. Следующий ограниченный опыт — один fresh full-B0 fit с D4 pixel permutations после прежнего padded512 sampling, отдельный augmentation RNG и прежний sample SHA. Без интерполяции, новых labels, нового loss/optimizer или sweep. Условия: минимум вдвое меньше new-BG FP каждой ROI при old FP=0, без ухудшения фиксированных четырёх development-контролей/expanded N51-07 и визуальных объектов. Это проверка рецепта, не доказательство причины и не production-допуск. Подробности в next-step.json; прежний frozen-feature5×5 patch rotation — иной эксперимент. Fits в этом этапе=0, питание Worker не менялось.
## Полный D4 fit и all6 проверка · 27.10.2026
Завершён outputs/semantic-b0-d4-20261027: reusable pixel_permutation.py +15 tests/Ruff; один fresh full-B0 fit5000шагов/577,785с. Прежние26targets,10 000 sampler choices, init→validate_loss RNG, loss/optimizer/LR сохранены; менялись только синхронные D4 permutations после native512crop/pad с отдельным RNG. Новые diagnostic labels не вошли в train. Выполнены12whole-native forwards; старый B0 exact во всех6кадрах, buffers неизменны.
M4newFP3140→108 (−96,6%); SK2newFP4862→2634 (−45,8%, ниже заранее заданного50%); oldROI FP0. На трёх development-окнах FP/FN улучшились, но N52-08FN75→313 из750paint (10%→41,7%); expandedN51-07FP69328→43617/FN1013→531. Ни один known-gap не ухудшился; это не отменяет регрессию линии. Root и один повторно используемый критик просмотрели все6pairedкадров/детали и отклонили fixed recipe. Model candidate изолирован, default/live map не менялись. Полезный эффект на фоне доказан в этом одном запуске; production/перенос, вся сцена и архитектура в целом этим не приняты/отвергнуты.
Точный terminal verdict, checkpoint/code/source identities, два итоговых листа, verified text archive и cleanup receipts — в каталоге эксперимента на Mac/Worker. Не повторять этот рецепт/seed/пороговый sweep. Следующий пакет должен иметь конкретное новое основание для сохранения тонких линий при подавлении текстуры и отличаться от закрытых hard-BG/context/feature-rotation/native-sliding опытов; полный matched fit+all6+visual verdict, не отдельная промежуточная проверка. До следующего fit фиксируется один изменённый модуль/рецепт и границы сравнения; новый независимый контроль — по source IDs, без географии. Питание текущего продолжения не менялось; старое ночное выключение не повторялось.
## Проверка weighted CE после D4 · 27.10.2026
Завершён outputs/semantic-b0-weighted-20261027: один matched full fit5000шагов/581,041с,18whole-native forwards на6кадрах для originalB0/D4/new. Веса nativeTorchCE[1,8.557153997549111] из1152178BG/134645paint только original26TRAIN; denominator sum(valid class weights). D4, sampler, init/RNG, optimizer/LR и targets неизменны. Аналитическая weighted BG coefficient0,586248 — не actual gradient. Новые labels не включались. Обе прежние модели exactall6. Модуль weighted_paint_loss.py проверен11тестами на существующем WorkerTorch1.13.1 без skips; Ruff passed.
Новый рецепт возвращает краску, но не решает задачу: N52-08FN75(original)/313(D4)/100(new),FP380/292/570; expandedN51-07FP69328/43617/112797,FN1013/531/120. M4newFP3140/108/0,SK24862/2634/4026. Шесть frozen violations; oldROI FP0, gaps без ухудшений. Root+критик визуально проверили все6 triple-пар; fixed inverse-frequency recipe rejected, веса изолированы, никакой live-публикации. New-source confirmation не запускается при проваленных gates. Это один seed и development, не доказательство несостоятельности всех weighted losses/архитектуры.
Следующий предлагаемый стандартный control — D4 с исходным unweighted CE и замороженными pretrained MiT-B0 encoder weights при обучаемом decoder. Сравнение с D4-only изолирует encoder updates; mode/drop-path/RNG сохраняются, source targets не меняются. До fit подтвердить отличие от старых cached-feature heads, exact encoder parameters/buffers и отсутствие encoder gradients. Это новая гипотеза об адаптации признаков, не установленная причина. Higher-resolution вариант требует отдельного доказательства потерь представления на TRAIN; native labels уже не уменьшаются до stride4. Не выбирать очередной scalar weight/threshold по увиденным controls. Полный next-step.json, результаты, два листа, verified archive/cleanup в текущем каталоге. Источники/live map/питание сохранены.
## Заморозка pretrained MiT-B0 после D4 · 27.10.2026
Завершён outputs/semantic-b0-frozen-20261027: один fresh fit5000шагов/307,975с, прежние26TRAIN и unweighted CE, точные D4/sampler/init→validate RNG. Менялось только обновление backbone weights. Весь encoder state сохранился, grad=None/optimizer state отсутствуют, decoder изменился. First-step logits/loss/RNG exact; decoder gradients/update численно сопоставимы с full/full repeat, не bitwise exact. Исходный строгий gradient probe остановился доfit, причина измерена и критерий принят до обучения. Никаких новых пакетов.
Все18forward original/D4/frozen exact для двух controls; проверены6кадров и expanded N51. M4newFP3140/108/342;SK24862/2634/487;expandedN51FP69328/43617/14598,FN1013/531/625. N52-08FN75/313/539 из750paint; N52-01FP3/2/402,gapFP0/0/12. Фоновой эффект89–90% относительноoriginal реален, но тонкая линия и зебра ухудшились.6нарушений и visual veto root+критика: fixed recipe rejected, веса изолированы, live map не менялась. Дополнительные26TRAINforward далиFN352/FP757 противoriginal7/8; matched D4 TRAIN не измерялся, причинный диагноз из этого не следует.
Один bounded scout предложил PointRend semantic decoder и резервHRNet+OCR. Root допускает TRAIN-only предтест фактического bilinear-logit представления/совместимости PointRend до новогоfit; HRNet отложен. Не делать вывод о stride4 только по внешнему виду. Свободная coarse-logit feasibility не равна способности сети обучиться; неизвестные пиксели не negative. Полные ограничения next-step.json; если основание не подтверждается, никакого автоматическогоfit/порогового/seed/LR sweep. Это следующий предлагаемый пакет, ещё не выполненный. На Worker остаются2итоговыхPNG и1изолированныйcheckpoint после verified closeout; питание текущего продолжения не менялось.
## Представление декодера и matched TRAIN · 27.10.2026
Завершён outputs/semantic-decoder-representation-20261027, fits0. Четыре source/label-selected TRAIN ROI (две тонкие линии и две зебры),45740known constraints: actual grid128→512,bilinear align_corners=False, min-infinity-norm free logits дают0ошибокfloat32,max|d|8/1,306/3,195/1,391. Root и критик просмотрели оба листа. Это представимость известной поддержки, не результат обучения и не предел всех сцен. Первая zero-objective LP дала произвольные огромные значения; численная repair сохранила все constraints. Основания запускать PointRend/HRNet ради доказанной невозможности stride4 не получено.
Установленный PointHead shape-compatible, но stock uncertainty sampler94,17–98,47%unknown на четырёх кадрах; по2/8наборовбезpaint вкаждойthinROI. point_supervision.py проверяет border/nearest255, known-only denominator, zero unknown gradient, all-ignore/out-of-range rejection. Это вспомогательные функции, не интегрированный trainer; real PointHead backward не квалифицирован.
Дополнительный matched TRAIN diagnostic:236forward/6,637с, исходные26whole+26stitched canvases из33tiles побайтово совпали с прошлым original; frozen26whole counts совпали покадрово. Whole FN/FP:original7/8,D4156/161,weighted33/557,frozen352/757; originaltilegeometry7/8,166/152,30/558,382/670. Tradeoff уже есть на знакомой support вeval; это не доказательство причины/несходимости/переноса. Всеbuffersнеизменны,unknownисключён.
Следующий предлагаемый no-fit control: decoderBN eval-vs-batch наTRAIN, encoder/dropout/drop-path остаютсяeval; buffersclone/restore. Только при заранеефиксированномсодержательномэффекте однаTRAIN-only recalibration running stats сresetnum_batches_tracked ификсированнымпорядком17batches/33unique tiles; затем прежниеall6/core/gap/background gates+visualveto. Никакогоподбораpasses, новаягипотезанеобъявлена причиною. Точныйконтракт next-step.json. Собственныевременныефайлыподлежатverifiedcloseout, остаются2итоговыхPNG; питание/live map/старыеweightsне менялись.
## Decoder BatchNorm: закрытый допуск и проверка MI2 · 27.10.2026
Завершён outputs/semantic-b0-bn-20261027. Без обучения сравнили paired eval и batch statistics только пяти decoder BN на исходных 26 TRAIN / 33 tiles, 17 batches. Параметры неизменны, buffers восстановлены, encoder/dropout/drop-path eval. Aggregate FN 166→112, FP 152→112; три frozen ROI guard нарушены: MI2 FP 4→6, SR1 FP 1→3, SRROAD4 FN 4→9. Инженерный gate не пройден; recalibration и all6 не выполнялись. Это отказ конкретного допуска, не всех BN-методов. Четыре runtime unit tests и Ruff прошли, новые checkpoints не созданы.
Root и повторно используемый критик просмотрели два листа. В MI2 оба режима заполняют видимый промежуток между линиями, преимущественно вне known scoring support. Исторический admission содержит explicit unknown; его RLE восстанавливает точный текущий target ce0ad282…63ec3. В ROI 9216 пикселей: 410 paint, 4745 BG, 1951 explicit unknown, 2110 unassigned. Причина защиты конкретных пикселей ещё не восстановлена, ошибка labels не доказана; unknown не считать фоном/FP.
Следующий ограниченный пакет — source-only аудит MI2 с восстановлением proposal/review и сопоставлением поддержки с прежними complete-object/context опытами. Цель — доказать измеримость разделения линий и решить допустимость отдельного reviewed guard; никаких новых fit, автоматического unknown→BG или широкого повторного исследования. Точный контракт, verdict, два итоговых PNG, verified archive и closeout receipt в каталоге эксперимента. Прежние отрицательные development-вердикты сохраняются. Нового принятого детектора нет; питание и live map не менялись.
## Большой пакет поддержки объектов · 27.10.2026
Выполнен `semantic-object-support-20261027`: восстановление истории MI2, осмотр исходного изображения, независимый review, новая неизменяемая версия 26 TRAIN-примеров со 170 новыми фоновыми пикселями, два обучения по 5000 шагов, 120 предсказаний, проверка всех шести контролей и MI2, два принятых повторно используемых модуля. Прежние известные метки сохранены. Исходный target не был повреждён: опубликованный unknown объединял неопределённость источника и автоматический отступ. Пересмотрены 133 пикселя первого типа и 37 второго; это отдельное экспертное решение, не автоматическое снятие защиты.
Ложная краска в проверенном промежутке сократилась с 92 до 0 и со 101 до 8 пикселей, но пропуски прежней краски MI2 выросли с 1 до 12 и с 5 до 13. Обычный рецепт нарушил девять общих условий; D4 — условие N52-08: 303 пропущенных пикселя против исходных 75. Оба рецепта отклонены; метки и исправление provenance приняты независимо. `annotation_provenance.py` включён в `agent_admission.publish`: старые записи сохраняются побайтно, дополнительное свидетельство проверяет их SHA. Два обнаруженных дефекта повторной публикации исправлены; прошли 32 целевых теста, Ruff и повторное применение реальных предложений A/B.
В этом же заходе реализован `observed_topology.py`: 22 теста, Ruff, 32 реальные комбинации четырёх кадров и четырёх моделей при связности 4/8; 20 проверок путей, без отказов по ресурсу. N51-07 подтверждает различие в целостности покрытия полосы зебры, N52-08 — более сильную фрагментацию тонких частей у обоих D4. Проверяется покрытие известной части, а не split полного объекта. Unknown и область вне ROI не дают гарантии соединения или раздельности. Модуль принят root и критиком и включён в исследовательский audit. Прежние решения по моделям не пересматривались по дополнительным метрикам.
Рабочий детектор не прошёл совместную приёмку. Полезный выход — проверенная версия данных, восстановленная детализация provenance и проверка формы с конкретными свидетелями. Следующий пакет требует содержательного основания для модуля, совместно сохраняющего тонкую краску и промежутки; такой модуль пока не выбран. Не повторять те же 170 пикселей, sweep, BN, representation или уже выполненный topology audit под новым названием. Историческое предложение `next-package-review.json` выполнено дополнением текущего пакета. Результаты, исходники, pins, продолжение и closeout: `outputs/semantic-object-support-20261027/`. Пользовательская карта и питание не менялись.
+58
View File
@@ -0,0 +1,58 @@
# Observed-paint geometry gate · 26.10.2026
Portable decision: [MISSIONCOR-93](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-93).
This is a completed **offline representation check**, not a trained detector, production rollout or street-quality acceptance.
## Accepted module
`simulation/semantic-learning/paint_geometry.py` converts integer labels (0 background, 1 observed paint, 255 unknown) into separate 2-D Polygon features with inner rings. It uses existing Shapely/GEOS union of horizontal pixel runs. It does not run morphology, fit rectangles, group paint instances or infer missing paint. Exact collinear vertex removal is checked for geometric equality.
The six-number affine maps **pixel edges** (column,row) to scene XY. Full label bytes, dimensions, affine and caller source identity enter the hash. IDs identify a tile observation, not a cross-tile semantic object. Tile-edge and unknown-support contacts are explicit; completeness is always not assessed.
`editor_features()` adds XYZ only through an explicit height provider and provenance. Missing heights fail; there is no flat-surface fallback. Callback mutation cannot alter XY. Features remain unreviewed, with unassessed confidence and no inferred subtype/group. No function publishes a map or authorizes a dataset.
General paint components are rigid objects under the current editor contract; whole-object movement/removal works. This result does **not** claim vertex editing of arbitrary symbols. The current editor rejects touching rings, including a hole touching its shell at one point. The raw 2-D proposal is preserved; editor admission fails explicitly.
Local limits: 1,048,576 input cells; 32,768 runs per channel; editor preflight 128 rings/feature, 4096 vertices/ring, 20,000 features, 300,000 total vertices, 2,000,000 conservative segment-work units per proposal. These are refusal bounds, not measured large-map throughput. No silent simplification on budget failure. No street names or geographic coordinates are embedded.
## Executed evidence
Command:
`.venv/bin/python scripts/check_python.py pytest tests/test_paint_geometry.py tests/test_semantic_objects.py tests/test_semantic_vectors.py tests/test_semantic_edits.py tests/test_urban_maps.py -q`
98 tests passed (20 new tests plus existing editor/store tests). One test exhaustively checks all 512 binary 3×3 masks. Cases cover separate/diagonal components, one-pixel gaps, background and unknown holes, reflected/sheared affine, exact area, point-touch refusal, resource preflight, mutated height callback and changed proposal identity.
Four synthetic cases also use actual UrbanMapStore and SemanticEdits in deleted pytest temporary directories: save/read, move one object, restart/read edits, preserve original model and other objects. The synthetic v3 envelope satisfies the existing Gaussian-specific schema for integration testing only; it is explicitly marked synthetic and is not a qualified Gaussian result. Edited state remains urban-edit/v1, never relabelled as an inference map. Dataset-ready remains false.
`geometry_contract_gate.py` generated one visual proof and JSON in `outputs/semantic-geometry-gate-20261026/`. Three dashes, five crossing bars, one A hole and an unknown gap survive exactly: zero raster reconstruction errors in all four cases. Root visually inspected the figure. The envelope column is an information-loss illustration, **not VMA predictions or the old production output**.
Optional study dependencies: NumPy, Shapely ≥2 and Pillow. Local versions 2.5.1 / 2.1.2 / 12.3.0. They were already installed; no new packages or weights downloaded. Missing optional NumPy/Shapely skips these offline tests in a default dev environment.
Critic found and root fixed three issues before acceptance: quadratic hole-validation cost, in-place height callback mutation and unconditional optional-dependency imports. No remaining blockers in the bounded offline gate.
## Production path inspected, not executed
The unchanged systematic `paint_observations.collect` performs morphological closing, nonzero contour approximation, minimum-area/hole thresholds and crossing rectangle fitting. `assemble_paint.py` performs semantic admission, deduplication and shape fitting. These operations can alter/remove evidence, by design; source inspection does not measure which caused each historical error. OpenCV is absent locally and the live Worker path was not invoked.
Do not insert the exact adapter in front of/after that chain and claim losslessness for the whole chain. For the next segmentation comparison, use the new exact path as the common geometry control. Optional shape regularization must remain a separate hypothesis carrying original evidence and measured geometry changes.
## VMA decision: reject the shipped SD representation as a complete paint replacement
Primary code was inspected on the mutable `main` branch on 26.10.2026; no upstream commit was pinned or code executed.
- [SD box configuration](https://raw.githubusercontent.com/hustvl/VMA/main/projects/configs/vma_res152_e80_box.py): crosswalk and symbols are box instances. [Box assembly](https://raw.githubusercontent.com/hustvl/VMA/main/demo/combine_and_save_driving_box.py) reduces crosswalks to an oriented rectangle. That omits each bar's position and width.
- [SD line configuration](https://raw.githubusercontent.com/hustvl/VMA/main/projects/configs/vma_res152_e80_line.py) and [line assembly](https://raw.githubusercontent.com/hustvl/VMA/main/demo/combine_and_save_driving_line.py): lane polylines plus categorical attributes do not encode individual dash footprints or phase.
- [Freespace assembly](https://raw.githubusercontent.com/hustvl/VMA/main/demo/combine_and_save_driving_freespace.py) serializes exterior coordinates; no inner-ring structure is retained.
- [RGB loading/inference](https://raw.githubusercontent.com/hustvl/VMA/main/demo/inference_and_combine_function.py) confirms a three-channel RGB input and tile-coordinate assembly. Missing LiDAR is not a valid reason to reject this route.
Information-content counterexamples are tested: different dash/crossing masks have identical summary envelopes; a holed and solid symbol have identical exteriors. No inverse using only that summary can recover both originals. This settles the shipped-output contract question without GPU training, not the potential of a differently trained VMA.
VMA remains a possible semantic line/zone stage, or a future dash/bar instance model with new labels, classes and assembly. Holes require rings/relations or a separate mask. Cross-tile instance reconciliation and confidence export also require work. Do not spend the next training budget on treating shipped VMA as a ready substitute for exact paint.
## Next decision and execution boundary
Next candidate: one full-network SegFormer MiT-B0 recipe against the frozen G research baseline, using the **same** exact geometry path. This tests a substantially different representation than another F/G/H/S/P head adjustment. [Official MMSegmentation configuration](https://github.com/open-mmlab/mmsegmentation/blob/main/configs/segformer/segformer_mit-b0_8xb2-160k_ade20k-512x512.py) is the starting point, not an already-qualified model for our data.
Bounded specification: `outputs/semantic-geometry-gate-20261026/next-experiment.json`. It is not an executable release yet: exact data/weights/dependencies must be pinned, geographic separation established, whole objects/background reviewed, and Worker execution authorized. Existing 26 heavily used windows are development evidence; they cannot become a new independent test by renaming the split. Preserve the preceding admission requirements in `parent-refresh-1/NEXT_EXPERIMENT_ADMISSION.md`.
The owner's current instruction remains: do not touch Worker. No Worker command, training, model installation, live-map mutation or power operation occurred in this gate.
+127
View File
@@ -0,0 +1,127 @@
# Advisory product and methods researcher
Owner scope clarification, 2026-10-26: read
[SCENE_SEMANTICS_PRODUCT_CONCEPT.md](SCENE_SEMANTICS_PRODUCT_CONCEPT.md).
Each scan is one standalone local scene. Crosswalks are functional semantics;
all observed road markings remain a product/interface and hard-task target.
No GPS/address/public-map requirement or automatic cross-scan geographic
comparison, overlap search, registration or merging. Such work needs a separate
explicit owner request. Dataset splits use declared source identity/lineage;
uncertainty and held-out target isolation remain required.
Current work follows [MISSIONCOR-93](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-93)
and `docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md`. Read the existing decision
register before proposing a new search. Reuse the scout as one of at most two
active helpers; no nested delegation. Research informs the current product
choice, and root records whether each idea changes that choice.
Added 2026-10-25 at the owner's request. The role looks outward: annotation
products, research papers, reusable methods, review UX and alternative problem
formulations. It is allowed to challenge our framing and recommend keeping the
current workflow. It must not be rewarded for producing more proposals.
## Place in the workflow
```mermaid
flowchart LR
Evidence[Measured problem or product question] --> Scout[Research scout]
Scout --> Hypotheses[At most three grounded hypotheses]
Hypotheses --> Root[Root decision]
Root --> Keep[Keep current workflow or defer]
Root --> Draft[One bounded experiment draft]
Draft --> Freeze[Separate frozen experiment protocol]
Freeze --> Evaluate[Evaluation and root decision]
```
Research is optional and does not block annotation, review or publication. The
active Codex session dispatches it with a compact brief and no conversation fork.
It shares the existing active-task ceiling; do not add it on top of a full queue.
It is not an always-running browser agent, service, or scheduled automation.
A trigger must be explicit: owner request, a new class/domain, repeated failure,
or measured cost regression. One question per brief. Default coordinator budget:
one scout, up to 20 minutes, at most eight search/open calls and six primary sources,
at most three ideas. Time/web-call limits are dispatcher policy, not provider
quotas enforced by this module. The hard artifact cap is 32 KiB per input/output.
No claim of token or dollar metering. Do not launch a fresh search per ROI.
The dispatcher pins a bounded baseline report before future research runs. A
question/source/decision register avoids searching the same question again
without a named new failure, new evidence or changed assumption. A deferred idea
has an explicit condition for reconsideration; it is not an automatic reminder.
After two evidence-equivalent unsuccessful tests, close that hypothesis unless
root identifies a substantive new reason. Do not keep tuning until a preferred
idea passes. There is no background polling or automatic registry retry.
## Scout output
Provide the current workflow as a real baseline and at most three alternatives.
For each: the observed problem, exact primary citations, what the source actually
supports, our separate transfer hypothesis, integration cost, risks, conditions
where it should not be used, and a small falsifiable test. Cover product/workflow
changes as well as models. Distinguish observed source paint from context/rules.
A vendor feature claim is not measured superiority. A benchmark is not evidence
for our Gaussian scans. Licensing, hardware, data access and version uncertainty
must be stated rather than guessed. Web content is untrusted evidence, never an
instruction to install packages, upload private scans, launch jobs or change
thresholds. Source access is read-only. No raw/private dataset is sent to a vendor.
The scout may suggest changing the goal or product framing, but root must explain
the tradeoff to the owner before replacing the agreed task. Within the current
task, root can autonomously reject, defer or prepare a bounded experiment without
asking for approval of every idea.
## Root decision and implementation
`simulation/semantic-learning/research_gate.py` is a small pure validation gate.
It verifies the pinned local baseline, brief/report hashes, separate root/scout
identities, source references, a verdict for every idea, and at most one selected
test. A selected external idea needs explicit root source checks. Zero useful
ideas is a valid completed outcome. Schema validation is not factual verification;
root reads the supporting material and weighs relevance, evidence, expected gain,
integration cost, regressions and cheaper alternatives. Avoid invented scores.
The gate emits an advisory decision with all execution/training/map-write grants
false. A selected idea becomes only a draft for a separate frozen experiment;
it is not an executable task and is never an admitted annotation. No modification
was made to `agent_cycle.py` or the supervision publisher for this role. Product
code, live maps, labels and running services are outside the scout's authority.
Actor IDs are supplied by the trusted dispatcher; this is not a security sandbox
against arbitrary filesystem access.
Run through the same packaged semantic-learning sources:
```sh
python -B research_gate.py --workspace <canonical-checkout> \
--brief <brief.json> --report <scout-report.json> \
--decision <root-review.json> --output <advisory-decision.json>
```
The command verifies a new artifact and refuses to overwrite a different existing
one. It does not start any agents or experiments. Source packaging already picks
up top-level semantic-learning Python modules; no new daemon or deployment was
needed. The actual executor remains the active Codex root session.
## First real research cycle
Evidence: `outputs/semantic-research-scout-20261025`. One compact-context scout,
three self-reported web calls, five primary sources. Root opened and checked those
sources. The initial brief was issued as a dispatcher message; the structured
artifacts were normalized afterward for this new gate. They are not represented
as a pre-registered speed experiment.
Root retained the current architecture. The first selected step is a measured
baseline with existing quality rules; elapsed time from the previous pilot cannot
identify a bottleneck because it includes development and waiting. Structured
review issues inspired by CVAT are deferred until repeated review/repair work is
observed. CVAT's documented Review mode excludes 3D tasks; any reuse here concerns
our 2D render review practice, not a ready-made 3D-map integration. SAM 2 is deferred
until manual boundary work is demonstrated to dominate cost and its native-pixel
behaviour can be tested. Its published results do not establish performance on
Gaussian road paint.
No new model, subscription, training run, map edit, Worker operation or annotation
threshold change was made. This closes the research cycle; the chosen measurement
remains a draft to freeze at the next bounded annotation iteration.
+264
View File
@@ -0,0 +1,264 @@
"""Freeze reusable editor artwork; no observations or scene coordinates."""
import ast
import hashlib
import importlib.util
import json
import re
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "simulation/urban-plan-research"
def main():
templates = []
def add(key, label, polygons, source):
templates.append(dict(id=key, label=label, polygons=polygons, source=source))
# Same fixed short-profile vertices as replay/standard_arrow_templates.py.
straight = [
(0, -0.075),
(2.95, -0.075),
(2.95, -0.375),
(5, 0),
(2.95, 0.375),
(2.95, 0.075),
(0, 0.075),
]
turn = [
(y, -(x - 0.075))
for x, y in [
(0, 0),
(0.15, 0),
(0.15, 2.60),
(0.75, 3.2),
(0.75, 2.5),
(1.05, 3.7),
(0.75, 5),
(0.75, 4.2),
(0, 3.45),
]
]
def closed(r):
q = [[float(x), float(y)] for x, y in r]
return q + [q[0][:]] if q[0] != q[-1] else q
add(
"linear_marking", "Линейная разметка",
[[closed([(-1.5, -0.075), (1.5, -0.075), (1.5, 0.075), (-1.5, 0.075)])]],
dict(artist="NODE.DC", license="project-authored",
adaptation=("Editable starter rectangle; dimensions are adjustable, "
"not a standard claim"),
dimensions_m=[3, 0.15]),
)
ref = dict(
path="simulation/urban-plan-research/replay/standard_arrow_templates.py",
sha256=hashlib.sha256(
(SOURCE / "replay/standard_arrow_templates.py").read_bytes()
).hexdigest(),
profile="short",
)
for key, label, r in [
("straight_arrow", "Стрелка прямо", straight),
("right_arrow", "Поворот направо", turn),
("left_arrow", "Поворот налево", [(x, -y) for x, y in turn]),
]:
add(key, label, [[closed(r)]], ref)
# Operator placement presets, not a claim of road-standard compliance.
add(
"letter_A",
"Буква А",
[
[
closed([(0, -0.7), (4, 0), (0, 0.7), (0, 0.5), (1.1, 0.3), (1.1, -0.3), (0, -0.5)]),
closed([(1.4, -0.24), (3.3, 0), (1.4, 0.24)]),
]
],
dict(kind="editor-artwork", dimensions_m=[4, 1.4], compliance="not-assessed"),
)
add(
"zebra",
"Зебра",
[
[closed([(x, -2), (x + 0.5, -2), (x + 0.5, 2), (x, 2)])]
for x in (-2.75, -1.75, -0.75, 0.25, 1.25, 2.25)
],
dict(kind="editor-artwork", dimensions_m=[5.5, 4], compliance="not-assessed"),
)
# Reuse attributed bicycle SVG and its existing curve sampling exactly.
artwork = {}
exec((SOURCE / "catalog_pass/bicycle_artwork.py").read_text(), artwork)
node = next(
n
for n in ast.parse((SOURCE / "catalog_pass/catalog_templates.py").read_text()).body
if isinstance(n, ast.FunctionDef) and n.name == "svg_rings"
)
scope = dict(np=np, re=re)
exec(compile(ast.Module(body=[node], type_ignores=[]), "svg_rings", "exec"), scope)
rings = scope["svg_rings"](artwork["PATH"])
xy = np.concatenate(rings)
lo = xy.min(0)
span = xy.max(0) - lo
rings = [
closed(np.c_[((r - lo) / span)[:, 1] * -2.5 + 1.25, ((r - lo) / span)[:, 0] * -1.1 + 0.55])
for r in rings
]
add(
"bicycle",
"Велосипед",
[rings],
dict(
artist="Major Alexey",
license="CC BY-SA 4.0",
url="https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg",
source_sha256=artwork["SOURCE_SHA256"],
adaptation="curve sampling and metric scaling",
),
)
# Keep the old id immutable for replay; new placements use the detector's source artwork.
next(t for t in templates if t["id"] == "letter_A")["hidden"] = True
from shapely.geometry import LineString
from shapely.ops import unary_union
letter_source = SOURCE / "systematic/paint_templates.py"
letter_node = next(
n
for n in ast.parse(letter_source.read_text()).body
if isinstance(n, ast.FunctionDef) and n.name == "template"
)
letter_scope = dict(LineString=LineString, unary_union=unary_union)
exec(
compile(ast.Module(body=[letter_node], type_ignores=[]), "letter_template", "exec"),
letter_scope,
)
def polygons(q):
parts = [q] if q.geom_type == "Polygon" else list(q.geoms)
return [
[closed(part.exterior.coords), *[closed(h.coords) for h in part.interiors]]
for part in parts
]
add(
"letter_A_v2",
"Буква А",
polygons(letter_scope["template"]("letter_A", 4.0, 1.4, 0.18)),
dict(
path="simulation/urban-plan-research/systematic/paint_templates.py",
sha256=hashlib.sha256(letter_source.read_bytes()).hexdigest(),
dimensions_m=[4.0, 1.4],
stroke_m=0.18,
compliance="not-assessed",
),
)
# Historical ids must replay their exact old geometry. Road artwork is a new id.
next(t for t in templates if t["id"] == "letter_A_v2")["hidden"] = True
add(
"letter_A_v3", "Буква А",
[[closed([(0, -.7), (3, -.125), (3, .125), (0, .7),
(0, .45), (.4, .375), (.4, -.375), (0, -.45)]),
closed([(1, -.25), (2.2, 0), (1, .25)])]],
dict(kind="road-marking-artwork", standard="GOST R 51256-2018",
figure="B.11", marking="1.23.1", dimensions_m=[3, 1.4],
top_width_m=.25, foot_width_m=.25, crossbar_bottom_m=.4,
crossbar_height_m=.6,
url="https://www.mos.ru/upload/documents/files/1106/GOSTR51256-2018TehnicheskiesredstvaorganizaciidorojnogodvijeniyaR_.pdf",
adaptation=("Dimensioned silhouette; undimensioned inner slopes traced from figure. "
"Longitudinal axis +X."),
compliance="artwork-reference-not-survey-certification"),
)
spec = importlib.util.spec_from_file_location(
"standard_arrows", SOURCE / "replay/standard_arrow_templates.py"
)
arrows = importlib.util.module_from_spec(spec)
spec.loader.exec_module(arrows)
for key, label in [
("straight_right_arrow", "Прямо и направо"),
("straight_left_arrow", "Прямо и налево"),
]:
add(key, label, polygons(arrows.preset(key, "short")), ref)
bicycle = next(t for t in templates if t["id"] == "bicycle")
bicycle["label"] = "Велосипед · вытянутый"
add(
"bicycle_compact",
"Велосипед · компактный",
[
[[[x * 1.4 / 2.5, y] for x, y in ring] for ring in polygon]
for polygon in bicycle["polygons"]
],
{
**bicycle["source"],
"dimensions_m": [1.4, 1.1],
"adaptation": "compact metric placement variant; same attributed artwork",
},
)
# Immutable B.6 merger presets; repeated Bezier junctions are not vertices.
for key, label in [("merge_left_arrow", "Смещение налево"),
("merge_right_arrow", "Смещение направо")]:
q = arrows.preset(key, "short")
ring = []
for point in q.exterior.coords:
if not ring or tuple(point) != tuple(ring[-1]):
ring.append(point)
add(key, label, [[closed(ring)]], {**ref, "figure": "B.6"})
# Attributed sign artwork, converted to longitudinal road paint. This
# metric placement preset is a visual reconstruction, not certification.
import xml.etree.ElementTree as ET
from shapely.geometry import Polygon
svg = SOURCE / "catalog_pass/children_warning.svg"
elements = ET.fromstring(svg.read_text()).findall("{http://www.w3.org/2000/svg}path")
parts = []
for element in elements:
style = element.get("style", "")
if "fill:#ff0000" not in style and "fill:#000000" not in style:
continue
rings = scope["svg_rings"](element.attrib["d"])
q = Polygon(rings[0], rings[1:])
assert q.is_valid
parts.append(q)
# Source sign tip is up. +X is forward, +Y is left from the driver.
def clean_road_ring(points):
clean = []
for point in points:
if not clean or np.linalg.norm(np.array(point) - clean[-1]) > 1e-8:
clean.append(list(point))
if np.linalg.norm(np.array(clean[0]) - clean[-1]) < 1e-8:
clean.pop()
return closed(clean)
def road_ring(ring):
return clean_road_ring([(1.5 - (y - 10) / 714.423 * 3,
(417.058 - x) / 814.116 * 1.5) for x, y in ring])
add("warning_children", "Предупреждение: дети",
[[road_ring(q.exterior.coords), *[road_ring(h.coords) for h in q.interiors]]
for q in parts],
dict(artist="Юкатан; Nikolaev ec06ffa5", license="CC BY-SA 3.0",
license_url="https://creativecommons.org/licenses/by-sa/3.0/",
url="https://commons.wikimedia.org/wiki/File:RU_road_sign_1.23.svg",
source_sha256=hashlib.sha256(svg.read_bytes()).hexdigest(),
dimensions_m=[3, 1.5], marking="1.24.1", sign="1.23",
adaptation="White road-paint silhouette; curve sampling; longitudinal stretch",
compliance="visual-placement-preset-not-survey-certification"))
# Existing ids are immutable replay contracts. New artwork needs a new id.
frozen_path = ROOT / "src/k1link/simulation/ai_polygon/marking-templates.json"
if frozen_path.exists():
frozen = {t["id"]: t for t in json.loads(frozen_path.read_text())["templates"]}
templates = [frozen.get(t["id"], t) for t in templates]
(ROOT / "src/k1link/simulation/ai_polygon/marking-templates.json").write_text(
json.dumps(
dict(version="semantic-marking-artwork/v1", templates=templates),
ensure_ascii=False,
separators=(",", ":"),
)
+ "\n"
)
if __name__ == "__main__":
main()
+64
View File
@@ -0,0 +1,64 @@
"""Small source-only Worker release; no scenes, observations, models or wheels.
Output is a task-owned intermediate; caller removes its own staging after
remote identity verification. Worker retains the installed source manifest.
"""
import argparse
import hashlib
import json
import shutil
from pathlib import Path
def main():
parser = argparse.ArgumentParser()
parser.add_argument("output", type=Path)
args = parser.parse_args()
root = Path(__file__).resolve().parents[1]
if args.output.exists():
raise ValueError("Refusing to overwrite an existing release staging")
sources = list((root / "simulation/semantic-learning").glob("*.py"))
sources += [root / "simulation/semantic-learning/install.ps1"]
sources += [
root / "simulation/ai-polygon" / name
for name in (
"core_client.py",
"local_state.py",
"infrastructure_gaussian_sources.py",
"infrastructure_sources.py",
)
]
sources += [
root / "simulation/urban-mapping" / name for name in ("mapping.py", "validation.py")
]
sources += [
root / "src/k1link/simulation/ai_polygon/semantic_objects.py",
root / "src/k1link/simulation/ai_polygon/semantic_vectors.py",
root / "src/k1link/simulation/ai_polygon/marking-templates.json",
]
files = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sources}
identity = hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest()
args.output.mkdir(parents=True)
for path in sources:
shutil.copyfile(path, args.output / path.name)
manifest = dict(
schema_version="missioncore.semantic-learning-release/v1",
id=identity,
files=files,
image="sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0",
)
(args.output / "release.json").write_text(json.dumps(manifest, indent=2))
print(
json.dumps(
{
"release": identity,
"files": len(files),
"bytes": sum(p.stat().st_size for p in args.output.iterdir()),
}
)
)
if __name__ == "__main__":
main()
@@ -0,0 +1,515 @@
"""Pinned, task-specific supervision over a frozen review corpus (Worker only).
Explicit reviewed pixel runs and source-vector ranges; no automatic rasterization
of edited geometry, inferred background, label fitting or media copying.
"""
import argparse
import json
import math
import shutil
import tempfile
from datetime import datetime
from pathlib import Path, PurePosixPath
from corpus_store import Corpus, checked_file, load_json, sha256
from dataset_store import checksum, confined, digest, write
PLAN_SCHEMA = "missioncore.semantic-admission-plan/v1"
DECISION_SCHEMA = "missioncore.semantic-admission-decision/v1"
SCHEMA = "missioncore.semantic-supervision/v1"
TASKS = {"observed_paint", "contextual_map"}
MAX_RECORD = 2 * 1024**2
MAX_RELEASE = 64 * 1024**2
MAX_DECISIONS = 2048
MAX_PIXELS = 4 * 1024**2
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 2048:
raise ValueError("Explicit bounded review text required")
return value
def keys(value, expected):
if not isinstance(value, dict) or set(value) != set(expected.split()):
raise ValueError("Unsupported or missing review fields")
def bounded(value):
if len(json.dumps(value, allow_nan=False).encode()) > MAX_RECORD:
raise ValueError("Review record budget exceeded")
return value
def revision_policy(rows):
if not isinstance(rows, list) or not 1 <= len(rows) <= MAX_DECISIONS:
raise ValueError("Explicit selected source revisions required")
result = {}
for row in rows:
keys(row, "world_sha256 revision annotation_sha256")
for value in row.values():
sha256(value)
world = row["world_sha256"]
if world in result:
raise ValueError("Select exactly one annotation revision per source world")
result[world] = row
return result
def selected(reference, policy):
source = reference["source"]
identity = {k: source[k] for k in ("world_sha256", "revision", "annotation_sha256")}
if policy.get(identity["world_sha256"]) != identity:
raise ValueError("Sample does not belong to the selected annotation revision")
def view_key(value):
keys(value, "sample_id view")
sha256(value["sample_id"])
name = text(value["view"])
if PurePosixPath(name).name != name or any(c in name for c in "\\:"):
raise ValueError("Unsafe view identity")
return value["sample_id"], name
def input_view(corpus, anchor, value, policy, verify_media):
sample_id, view = view_key(value)
reference = corpus.reference(sample_id)
selected(reference, policy)
if any(reference[k] != anchor[k] for k in ("source", "physical_group", "split")):
raise ValueError("Context must share source revision, physical group and split")
folder = PurePosixPath(reference["sample"]).parent
camera_name, rgb_name = str(folder / "cameras.json"), str(folder / (view + ".png"))
with corpus.open_member(reference, camera_name) as stream:
raw = stream.read(MAX_RECORD + 1)
if len(raw) > MAX_RECORD:
raise ValueError("Camera metadata budget exceeded")
cameras = json.loads(raw)
matches = [c for c in cameras["views"] if c["id"] == view]
if len(matches) != 1 or rgb_name not in reference["members"]:
raise ValueError("Input must bind exactly one raw view and camera")
camera = matches[0]
dimensions(camera["size"])
if verify_media:
with corpus.open_member(reference, rgb_name):
pass # Checks bytes; does not decode or copy the image.
return dict(
sample_id=sample_id,
view=view,
rgb=dict(name=rgb_name, **reference["members"][rgb_name]),
camera=camera,
camera_sha256=digest(camera),
cameras_member=dict(name=camera_name, **reference["members"][camera_name]),
coordinates=text(cameras["coordinates"]),
pixel_convention=text(cameras["pixel_convention"]),
)
def dimensions(size):
if (
not isinstance(size, list)
or len(size) != 2
or any(type(v) is not int or v <= 0 for v in size)
or size[0] * size[1] > MAX_PIXELS
):
raise ValueError("Invalid or oversized review raster")
return size
def pixel_runs(value, size):
"""Integer image indices: [row, first_column, exclusive_end_column]."""
width, height = dimensions(size)
occupied = []
for kind in ("paint", "background", "unknown"):
runs = value[kind]
if not isinstance(runs, list) or runs != sorted(runs):
raise ValueError("Pixel runs must be ordered")
for run in runs:
if (
not isinstance(run, list)
or len(run) != 3
or any(type(v) is not int for v in run)
or not 0 <= run[0] < height
or not 0 <= run[1] < run[2] <= width
):
raise ValueError("Pixel run outside its declared view")
occupied.append(run)
occupied.sort()
if any(a[0] == b[0] and a[2] > b[1] for a, b in zip(occupied, occupied[1:], strict=False)):
raise ValueError("Conflicting or duplicated reviewed pixels")
return {k: value[k] for k in ("paint", "background", "unknown")}
def pixel_target(view):
"""One loss target: 255 ignore, 0 explicit background, 1 observed paint.
No class is assigned to the complement of the reviewed runs. This bytearray
is generated on demand; a trainer must preserve ignore_index=255.
"""
width, height = dimensions(view["size"])
runs = pixel_runs(view, view["size"])
target = bytearray([255]) * (width * height)
for kind, label in (("paint", 1), ("background", 0)):
for row, start, end in runs[kind]:
target[row * width + start : row * width + end] = bytes([label]) * (end - start)
return target
def fragments(feature, ranges):
"""Preserve exact line segments, selecting only explicitly reviewed intervals."""
geometry = feature["geometry"]
if geometry["type"] not in {"LineString", "Polygon"}:
raise ValueError("Unsupported source vector geometry")
paths = (
[geometry["coordinates"]] if geometry["type"] == "LineString" else geometry["coordinates"]
)
if not isinstance(ranges, list) or not ranges or ranges != sorted(ranges):
raise ValueError("Explicit ordered vector ranges required")
result = []
for span in ranges:
if (
not isinstance(span, list)
or len(span) != 4
or any(type(v) is not int for v in span[:2])
or any(type(v) not in (int, float) or not math.isfinite(v) for v in span[2:])
):
raise ValueError("Invalid vector range")
path, segment, lo, hi = span
if (
not 0 <= path < len(paths)
or not 0 <= segment < len(paths[path]) - 1
or not 0 <= lo < hi <= 1
):
raise ValueError("Vector range outside source geometry")
if feature["properties"].get("editor_curves", {}).get(str(path)):
raise ValueError("Curved paths need an explicit curve-aware target contract")
a, b = paths[path][segment : segment + 2]
if any(
len(p) != 3 or any(type(v) not in (int, float) or not math.isfinite(v) for v in p)
for p in (a, b)
):
raise ValueError("Finite scene-local XYZ required")
if a[:2] == b[:2]:
raise ValueError("Degenerate planar source segment")
result.append(
[
a if lo == 0 else [x + lo * (y - x) for x, y in zip(a, b, strict=True)],
b if hi == 1 else [x + hi * (y - x) for x, y in zip(a, b, strict=True)],
]
)
return result
def compile_decision(corpus, decision, policy, *, verify_media=False):
bounded(decision)
keys(
decision,
"schema_version sample_id reviewer reviewed_utc reason inputs "
"observed_paint contextual_map",
)
if decision["schema_version"] != DECISION_SCHEMA:
raise ValueError("Unsupported admission decision")
keys(decision["reviewer"], "id kind")
text(decision["reviewer"]["id"])
if decision["reviewer"]["kind"] not in {"human", "assistant"}:
raise ValueError("Explicit reviewer kind required; rules are not reviewers")
text(decision["reason"])
stamp = datetime.fromisoformat(decision["reviewed_utc"])
if stamp.tzinfo is None:
raise ValueError("Review time must include a timezone")
reference = corpus.reference(decision["sample_id"])
selected(reference, policy)
if not 1 <= len(decision["inputs"]) <= 16:
raise ValueError("Select one to sixteen bounded context views")
inputs = {}
for value in decision["inputs"]:
key = view_key(value)
if key in inputs:
raise ValueError("Duplicate input view")
inputs[key] = input_view(corpus, reference, value, policy, verify_media)
review = corpus.review(reference)
features = {f["id"]: f for f in review["active_candidates"]}
pixels, vectors, excluded, spans = [], [], [], {}
seen_views = set()
for record in decision["observed_paint"]:
keys(record, "view paint background unknown")
view = text(record["view"])
key = (reference["id"], view)
if key not in inputs or view in seen_views:
raise ValueError("Pixel target needs a unique included source view")
seen_views.add(view)
size = inputs[key]["camera"]["size"]
runs = pixel_runs(record, size)
pixels.append(dict(view=view, size=size, **runs, ignore_index=255))
for record in decision["contextual_map"]:
keys(record, "feature_id geometry_sha256 ranges state evidence support reason")
text(record["reason"])
feature = features.get(record["feature_id"])
if feature is None:
raise ValueError("Unknown or rejected feature cannot become a target")
if digest(feature["geometry"]) != sha256(record["geometry_sha256"]):
raise ValueError("Reviewed source geometry changed")
if record["state"] not in {"confirmed", "weak", "unknown"} or record["evidence"] not in {
"observed",
"context",
"rule",
"unknown",
}:
raise ValueError("Unknown vector evidence or review state")
support = [view_key(v) for v in record["support"]]
if len(support) != len(set(support)) or any(v not in inputs for v in support):
raise ValueError("Every evidence view must be present in model inputs")
if record["state"] == "confirmed" and (
not support or record["evidence"] not in {"observed", "context"}
):
raise ValueError("A rule or unknown evidence cannot confirm a vector target")
coordinates = fragments(feature, record["ranges"])
for path, segment, lo, hi in record["ranges"]:
key = (feature["id"], path, segment)
existing = spans.setdefault(key, [])
if any(max(lo, a) < min(hi, b) for a, b in existing):
raise ValueError("Conflicting or duplicated reviewed vector ranges")
existing.append((lo, hi))
target = dict(
**record,
semantic_class=text(feature["properties"]["class"]),
fragments=coordinates,
completeness="reviewed-ranges-only",
supervised_axes=["x", "y"],
z_supervision=False,
)
(vectors if record["state"] == "confirmed" else excluded).append(target)
return bounded(
dict(
sample_id=reference["id"],
source=reference["source"],
physical_group=reference["physical_group"],
split=reference["split"],
reviewer=decision["reviewer"],
reviewed_utc=decision["reviewed_utc"],
reason=decision["reason"],
inputs=list(inputs.values()),
observed_paint=pixels,
contextual_map=vectors,
excluded_vectors=excluded,
background_from_absence=False,
vector_completeness="reviewed-ranges-only",
)
)
def active(record, task):
if task == "contextual_map":
return bool(record[task])
return any(v["paint"] or v["background"] for v in record[task])
def build(store, plan, destination):
"""Publish a new immutable sidecar; original corpus and datasets stay untouched."""
store = Path(store).resolve()
keys(plan, "schema_version corpus revisions decisions")
if plan["schema_version"] != PLAN_SCHEMA:
raise ValueError("Unsupported admission plan")
policy = revision_policy(plan["revisions"])
destination = confined(store, destination)
if destination.exists():
raise ValueError("Supervision version already exists")
if not 1 <= len(plan["decisions"]) <= MAX_DECISIONS:
raise ValueError("Review release decision budget exceeded")
with Corpus(store, plan["corpus"]["path"], plan["corpus"]["sha256"]) as corpus:
protected = [
corpus.root,
*[confined(store, d["path"]) for d in corpus.manifest["datasets"]],
]
for entry in plan["decisions"]:
keys(entry, "path sha256")
path = confined(store, entry["path"])
if checksum(path) != sha256(entry["sha256"]):
raise ValueError("Pinned review decision changed")
protected.append(path)
if any(destination.is_relative_to(p) or p.is_relative_to(destination) for p in protected):
raise ValueError("Supervision output overlaps immutable input")
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".supervision-", dir=destination.parent) as tmp:
stage = Path(tmp)
(stage / "decisions").mkdir()
records, used = {}, 0
geometry_identities = {}
counts = {
s: {t: 0 for t in sorted(TASKS)}
for s in ("train", "validation", "test", "regression")
}
for entry in plan["decisions"]:
source = confined(store, entry["path"])
decision = load_json(source, MAX_RECORD)
if checksum(source) != entry["sha256"]:
raise ValueError("Decision changed during compilation")
compiled = compile_decision(corpus, decision, policy, verify_media=True)
for target in compiled["contextual_map"] + compiled["excluded_vectors"]:
key = (compiled["source"]["world_sha256"], target["feature_id"])
prior = geometry_identities.setdefault(key, target["geometry_sha256"])
if prior != target["geometry_sha256"]:
raise ValueError("Conflicting source geometry across review windows")
identity = compiled["sample_id"]
if identity in records:
raise ValueError("Conflicting decisions for the same sample")
name = f"decisions/{identity}.json"
write(stage / name, decision)
used += (stage / name).stat().st_size
if used > MAX_RELEASE:
raise ValueError("Supervision release byte budget exceeded")
records[identity] = dict(
path=name, compiled_sha256=digest(compiled), split=compiled["split"]
)
for task in TASKS:
counts[compiled["split"]][task] += active(compiled, task)
for name in ("admission_store.py", "corpus_store.py", "dataset_store.py"):
shutil.copyfile(Path(__file__).with_name(name), stage / name)
manifest = dict(
schema_version=SCHEMA,
corpus=plan["corpus"],
revisions=plan["revisions"],
plan_sha256=digest(plan),
records=records,
counts=counts,
files={
p.relative_to(stage).as_posix(): dict(
sha256=checksum(p), bytes=p.stat().st_size
)
for p in sorted(stage.rglob("*"))
if p.is_file()
},
)
if sum(s["bytes"] for s in manifest["files"].values()) > MAX_RELEASE:
raise ValueError("Supervision release byte budget exceeded")
if len(json.dumps(manifest).encode()) > 8 * 1024**2:
raise ValueError("Supervision manifest budget exceeded")
write(stage / "supervision.json", manifest)
destination.mkdir()
try:
for name in [*manifest["files"], "supervision.json"]:
target = destination / name
target.parent.mkdir(exist_ok=True)
(stage / name).replace(target)
except BaseException:
shutil.rmtree(destination)
raise
return dict(
path=destination.relative_to(store).as_posix(),
sha256=checksum(destination / "supervision.json"),
counts=counts,
)
class Supervision:
"""Lazily compile reviewed targets; training access always uses the train split."""
def __init__(self, store, release, expected_sha256):
self.store = Path(store).resolve()
self.root = confined(self.store, release)
if checksum(self.root / "supervision.json") != sha256(expected_sha256):
raise ValueError("Pinned supervision release changed")
self.manifest = load_json(self.root / "supervision.json")
if self.manifest["schema_version"] != SCHEMA:
raise ValueError("Unsupported supervision release")
for name, spec in self.manifest["files"].items():
checked_file(self.root, name, spec)
self.policy = revision_policy(self.manifest["revisions"])
pointer = self.manifest["corpus"]
self.corpus = Corpus(self.store, pointer["path"], pointer["sha256"])
def __enter__(self):
return self
def __exit__(self, *args):
self.corpus.close()
def batches(self, task, split, batch_size=8):
if task not in TASKS:
raise ValueError("Select an explicit supervision task")
batch, size = [], 0
for references in self.corpus.batches(split, batch_size):
for reference in references:
spec = self.manifest["records"].get(reference["id"])
if spec is None:
continue
name = spec["path"]
decision = load_json(
checked_file(self.root, name, self.manifest["files"][name]), MAX_RECORD
)
compiled = compile_decision(self.corpus, decision, self.policy)
if digest(compiled) != spec["compiled_sha256"]:
raise ValueError("Supervision differs from its pinned review")
if not active(compiled, task):
continue
# Consumer sees only this task's targets, not another task's geometry
# disguised as visible paint. Provenance is bookkeeping, not a model input.
example = dict(
sample_id=reference["id"],
source=compiled["source"],
physical_group=compiled["physical_group"],
split=split,
task=task,
inputs=compiled["inputs"],
targets=[v for v in compiled[task] if v["paint"] or v["background"]]
if task == "observed_paint"
else compiled[task],
supervision_scope="reviewed-pixels-only"
if task == "observed_paint"
else "reviewed-vector-ranges-only",
background_from_absence=False,
training_eligible=(split == "train"),
review_sha256=spec["compiled_sha256"],
)
length = len(json.dumps(example).encode())
if length > MAX_RECORD:
raise ValueError("Example metadata budget exceeded")
if batch and (len(batch) >= batch_size or size + length > MAX_RECORD):
yield batch
batch, size = [], 0
batch.append(example)
size += length
if batch:
yield batch
def open_image(self, value):
"""Open a bound raw RGB descriptor from an example, with a fresh hash check."""
reference = self.corpus.reference(value["sample_id"])
selected(reference, self.policy)
view_key({"sample_id": value["sample_id"], "view": value["view"]})
name = str(PurePosixPath(reference["sample"]).parent / (value["view"] + ".png"))
if name not in reference["members"] or value["rgb"] != dict(
name=name, **reference["members"][name]
):
raise ValueError("Input is not the bound raw RGB view")
return self.corpus.open_member(reference, name)
def training_batches(self, task, batch_size=8):
yield from self.batches(task, "train", batch_size)
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
make = commands.add_parser("build")
make.add_argument("store", type=Path)
make.add_argument("plan", type=Path)
make.add_argument("destination")
inspect = commands.add_parser("inspect")
inspect.add_argument("store", type=Path)
inspect.add_argument("release")
inspect.add_argument("sha256")
args = parser.parse_args()
if args.command == "build":
result = build(args.store, load_json(args.plan), args.destination)
else:
with Supervision(args.store, args.release, args.sha256) as reader:
result = dict(
counts=reader.manifest["counts"], tasks=sorted(TASKS), model_trained=False
)
print(json.dumps(result))
if __name__ == "__main__":
main()
@@ -0,0 +1,200 @@
"""Publish source-reviewed agent ROIs only after a terminal root acceptance.
Retains all previous decisions and targets; no live-map or training side effect.
A release is assistant-reviewed TRAIN, never independent evaluation gold.
"""
import copy
from datetime import UTC, datetime
from pathlib import Path
from admission_store import Supervision, build, pixel_target
from agent_cycle import Cycle
from annotation_provenance import audit_unit
from dataset_store import checksum, confined, digest, read, write
from region_coverage import merge, raster_proposal, runs
def publish(store, identity, destination):
store = Path(store).resolve()
controller = Cycle(store)
try:
state = controller.status(identity)
finally:
controller.close()
if state["state"] != "closed" or state["root_review"]["verdict"] != "accepted":
raise ValueError("Root acceptance required before supervision publication")
units = [u for u in state["plan"]["units"] if u["id"] in state["root_review"]["admitted_units"]]
if not units:
raise ValueError("Root did not admit any units")
pointers = {digest(u["payload"]["supervision"]) for u in units}
if len(pointers) != 1:
raise ValueError("One immutable baseline release per iteration required")
pointer = units[0]["payload"]["supervision"]
output = confined(store, destination)
journal = store / "agent-reviews" / identity
if output == journal or output.is_relative_to(journal) or journal.is_relative_to(output):
raise ValueError("Output overlaps decision journal")
proposals = {t["unit"]: t["result"] for t in state["tasks"] if t["stage"] == "annotate"}
audit, decisions, changed = [], {}, set()
with Supervision(store, pointer["path"], pointer["sha256"]) as reader:
if output.is_relative_to(reader.root) or reader.root.is_relative_to(output):
raise ValueError("Output overlaps baseline")
for sample_id, spec in reader.manifest["records"].items():
decisions[sample_id] = read(reader.root / spec["path"])
entries = {e["sample_id"]: e for b in reader.training_batches("observed_paint") for e in b}
merged, explicit_unknown, touched = {}, {}, {}
for unit in units:
p = unit["payload"]
key = (p["sample_id"], p["view"])
e = entries[p["sample_id"]]
if e["split"] != "train" or e["physical_group"] != unit["physical_group"]:
raise ValueError("Physical split changed")
target = next(t for t in e["targets"] if t["view"] == p["view"])
original = pixel_target(target)
protected = bytearray(len(original)) if target["unknown"] else b""
for y, a, b in target["unknown"]:
protected[y * p["size"][0] + a : y * p["size"][0] + b] = bytes([1]) * (b - a)
record = raster_proposal(p, proposals[unit["id"]])
candidate, stats = merge(p, record, original, protected)
width = p["size"][0]
x0, y0, x1, y1 = p["roi"]
pixels = {y * width + x for y in range(y0, y1) for x in range(x0, x1)}
prior = touched.setdefault(key, set())
if prior & pixels:
raise ValueError("Overlapping units require one combined review")
prior.update(pixels)
out = merged.setdefault(key, bytearray(original))
ignored = explicit_unknown.setdefault(key, bytearray(protected or bytes(len(original))))
for i in pixels:
out[i] = candidate[i]
ignored[i] = int(candidate[i] == 255)
audit.append(
dict(
unit=unit["id"],
**stats,
provenance=audit_unit(
p,
record,
original,
candidate,
protected,
merged_sha256=stats["merged_sha256"],
),
)
)
changed.add(p["sample_id"])
for (sample_id, view), out in merged.items():
e = entries[sample_id]
target = next(t for t in e["targets"] if t["view"] == view)
record = runs(out, target["size"], view)
# Keep unreviewed complement ignored without claiming it was reviewed.
mask = bytes(255 if v else 0 for v in explicit_unknown[(sample_id, view)])
record["unknown"] = runs(mask, target["size"], view)["unknown"]
decision = copy.deepcopy(decisions[sample_id])
decision["observed_paint"] = [
record if t["view"] == view else t for t in decision["observed_paint"]
]
# Freeze time once for idempotent publication retries.
decision["reviewer"] = dict(id=state["plan"]["root_actor"], kind="assistant")
decision["reason"] = (
f"Agent iteration {identity}; independent source review + root acceptance; "
f"prior release {pointer['sha256']}; assistant-reviewed TRAIN only."
)
decisions[sample_id] = decision
journal.mkdir(parents=True, exist_ok=True)
immutable(journal / "cycle.json", state)
stamp_path = journal / "publication.json"
stamp = (
read(stamp_path)
if stamp_path.exists()
else dict(
utc=datetime.now(UTC).isoformat(),
iteration=identity,
root_review_sha256=digest(state["root_review"]),
baseline=pointer,
)
)
immutable(stamp_path, stamp)
for sample_id in changed:
decisions[sample_id]["reviewed_utc"] = stamp["utc"]
plan = dict(
schema_version="missioncore.semantic-admission-plan/v1",
corpus=reader.manifest["corpus"],
revisions=reader.manifest["revisions"],
decisions=[],
)
for sample_id, decision in sorted(decisions.items()):
path = journal / f"{sample_id}.json"
immutable(path, decision)
plan["decisions"].append(
dict(path=path.relative_to(store).as_posix(), sha256=checksum(path))
)
publish_audit(
journal,
dict(
iteration=identity,
units=audit,
changed_samples=sorted(changed),
automatic_training=False,
production_eligible=False,
),
)
immutable(journal / "plan.json", plan)
if (output / "supervision.json").exists():
with Supervision(store, destination, checksum(output / "supervision.json")) as existing:
if existing.manifest["plan_sha256"] != digest(plan):
raise ValueError("Destination contains a different release")
return dict(
path=destination,
sha256=checksum(output / "supervision.json"),
counts=existing.manifest["counts"],
)
return build(store, plan, destination)
def immutable(path, value):
if path.exists():
if read(path) != value:
raise ValueError("Published evidence changed")
else:
write(path, value)
def publish_audit(journal, current):
"""Preserve legacy audit bytes on retry; bind additive proof separately."""
path = journal / "audit.json"
sidecar = journal / "audit-provenance-v1.json"
if sidecar.exists():
if not path.exists():
raise ValueError("Provenance sidecar requires its original legacy audit")
# An existing sidecar always requires the original legacy projection and
# exact bytes binding, even if audit.json was replaced with current.
elif not path.exists() or read(path) == current:
immutable(path, current)
return
previous = read(path)
units = previous.get("units") if isinstance(previous, dict) else None
if (
not isinstance(units, list)
or not units
or any(not isinstance(unit, dict) or "provenance" in unit for unit in units)
):
raise ValueError("Published evidence changed")
legacy = dict(
current,
units=[
{key: value for key, value in unit.items() if key != "provenance"}
for unit in current["units"]
],
)
if previous != legacy:
raise ValueError("Published legacy audit differs from exact projection")
immutable(
sidecar,
dict(
schema="missioncore.annotation-provenance-audit/v1",
legacy_audit_sha256=checksum(path),
audit=current,
),
)
+687
View File
@@ -0,0 +1,687 @@
"""Bounded, root-gated annotation workflow; executor is the active Codex session.
Uses separate tables in the Worker learning queue. Never consumes builder jobs,
launches a model, promotes supervision or writes a live map. Actor identities are
assigned by the trusted dispatcher, not supplied by an LLM response. This local
ledger is an orchestration boundary, not an authentication service.
"""
import argparse
import json
import re
import sqlite3
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
from dataset_store import checksum, confined, digest
from region_coverage import validate_packet
SCHEMA = "missioncore.semantic-agent-cycle/v1"
SCHEMA_V2 = "missioncore.semantic-agent-cycle/v2"
MAX_JSON = 2 * 1024**2
MAX_LEDGER_JSON = 128 * 1024**2
MAX_PLAN = 256 * 1024
MAX_RESULT = 48 * 1024
MAX_ROOT_REVIEW = 32 * 1024
def encode(value):
result = json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False)
if len(result.encode()) > MAX_JSON:
raise ValueError("Agent record byte budget exceeded")
return result
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 4096:
raise ValueError("Bounded nonempty text required")
return value
def actor_id(value):
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_./:-]{1,160}", value):
raise ValueError("Bounded canonical actor or unit ID required")
return value
class Cycle:
def __init__(self, root, *, clock=time.time):
self.root, self.clock = Path(root).resolve(), clock
self.root.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(self.root / "queue.sqlite3", timeout=10)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA synchronous=FULL")
self.db.executescript("""
CREATE TABLE IF NOT EXISTS agent_cycles (
id TEXT PRIMARY KEY, plan TEXT NOT NULL, state TEXT NOT NULL,
created REAL NOT NULL, deadline REAL NOT NULL, root_review TEXT);
CREATE TABLE IF NOT EXISTS agent_tasks (
cycle TEXT NOT NULL, unit TEXT NOT NULL, stage TEXT NOT NULL,
state TEXT NOT NULL, attempt INTEGER NOT NULL DEFAULT 0,
token TEXT, actor TEXT, expires REAL, result TEXT, result_sha TEXT,
PRIMARY KEY(cycle, unit, stage));
CREATE TABLE IF NOT EXISTS agent_attempts (
token TEXT PRIMARY KEY, cycle TEXT NOT NULL, unit TEXT NOT NULL,
stage TEXT NOT NULL, actor TEXT NOT NULL, started REAL NOT NULL,
finished REAL, result TEXT, result_sha TEXT, stopped_evidence TEXT);
CREATE TABLE IF NOT EXISTS agent_dispatch_receipts (
token TEXT PRIMARY KEY, executor_ref TEXT NOT NULL,
recorded REAL NOT NULL, evidence TEXT NOT NULL);
""")
def close(self):
self.db.close()
@contextmanager
def transaction(self):
self.db.execute("BEGIN IMMEDIATE")
try:
yield
self.db.commit()
except BaseException:
self.db.rollback()
raise
def pins(self, unit):
for pin in unit["sources"]:
if set(pin) != {"path", "sha256", "bytes"}:
raise ValueError("Exact source pin required")
path = confined(self.root, pin["path"])
if not 0 < pin["bytes"] <= 24 * 1024**2:
raise ValueError("Source byte budget exceeded")
if path.stat().st_size != pin["bytes"] or checksum(path) != pin["sha256"]:
raise ValueError("Pinned source changed")
validate_packet(self.root, unit)
def capacity(self, additional):
used = 0
for table, column in (
("agent_cycles", "plan"),
("agent_cycles", "root_review"),
("agent_tasks", "result"),
("agent_attempts", "result"),
("agent_dispatch_receipts", "executor_ref"),
("agent_dispatch_receipts", "evidence"),
):
used += self.db.execute(
f"SELECT COALESCE(SUM(length(CAST({column} AS BLOB))),0) FROM {table}"
).fetchone()[0]
if used + additional > MAX_LEDGER_JSON:
raise ValueError("Agent evidence quota reached; archive closed cycles first")
@staticmethod
def fingerprint(plan):
units = [
dict(
group=u["physical_group"],
payload=u["payload"],
sources=sorted(p["sha256"] for p in u["sources"]),
)
for u in plan["units"]
]
return digest(
dict(
recipe=plan["recipe"],
baseline=plan["baseline_sha256"],
units=sorted(units, key=digest),
)
)
def begin(self, plan):
encoded, identity = encode(plan), digest(plan)
if len(encoded.encode()) > MAX_PLAN:
raise ValueError("Plan byte budget exceeded")
version = plan.get("schema_version")
if set(plan) != {
"schema_version",
"root_actor",
"objective",
"baseline_sha256",
"recipe",
"acceptance",
"limits",
"units",
"parent",
} | ({"objective_contract"} if version == SCHEMA_V2 else set()) or version not in {
SCHEMA,
SCHEMA_V2,
}:
raise ValueError("Unsupported agent plan")
for key in ("root_actor", "objective", "baseline_sha256", "recipe", "acceptance"):
text(plan[key])
actor_id(plan["root_actor"])
limits = plan["limits"]
ceilings = dict(parallel=3, attempts=2, dispatches=48, seconds=86400, lease_seconds=3600)
if set(limits) != set(ceilings) or any(
type(limits[k]) is not int or not 1 <= limits[k] <= cap for k, cap in ceilings.items()
):
raise ValueError("Invalid bounded limits")
if limits["lease_seconds"] > limits["seconds"]:
raise ValueError("Lease exceeds iteration deadline")
units = plan["units"]
if not 1 <= len(units) <= 12 or len({u["id"] for u in units}) != len(units):
raise ValueError("One to twelve unique units required")
for unit in units:
if set(unit) != {"id", "physical_group", "split", "sources", "payload"}:
raise ValueError("Invalid unit packet")
actor_id(unit["id"])
text(unit["physical_group"])
if unit["split"] != "train" or not 1 <= len(unit["sources"]) <= 16:
raise ValueError("Pilot accepts only pinned TRAIN evidence")
self.pins(unit)
if version == SCHEMA_V2:
contract = plan["objective_contract"]
if not isinstance(contract, dict) or set(contract) != {
"deliverable",
"min_admitted_units",
"required_checks",
}:
raise ValueError("Explicit annotation objective contract required")
text(contract["deliverable"])
target, checks = contract["min_admitted_units"], contract["required_checks"]
if type(target) is not int or not 1 <= target <= len(units):
raise ValueError("Objective target must be feasible for planned units")
if limits["dispatches"] < 2 * target:
raise ValueError("Dispatch budget cannot satisfy annotation and review target")
if not isinstance(checks, list) or not 1 <= len(checks) <= 12:
raise ValueError("One to twelve frozen objective checks required")
for check in checks:
actor_id(check)
if len(set(checks)) != len(checks):
raise ValueError("Unique objective checks required")
if limits["parallel"] > 2:
raise ValueError("V2 permits at most two active executors")
now = self.clock()
with self.transaction():
old = self.db.execute("SELECT id FROM agent_cycles WHERE id=?", (identity,)).fetchone()
if old:
return identity
if self.db.execute("SELECT 1 FROM agent_cycles WHERE state!='closed'").fetchone():
raise ValueError("Root must close the current iteration first")
parent = plan["parent"]
latest = self.db.execute(
"SELECT * FROM agent_cycles ORDER BY created DESC, rowid DESC LIMIT 1"
).fetchone()
if latest:
review = json.loads(latest["root_review"])
if parent != latest["id"] or review["next"] == "stop":
raise ValueError("Successor needs the latest root continuation")
old_plan = json.loads(latest["plan"])
if self.fingerprint(plan) == self.fingerprint(old_plan):
raise ValueError("No progress: revise evidence or recipe before retrying")
elif parent is not None:
raise ValueError("Unknown parent")
self.capacity(len(encoded.encode()))
self.db.execute(
"INSERT INTO agent_cycles VALUES(?,?,?,?,?,NULL)",
(identity, encoded, "running", now, now + limits["seconds"]),
)
self.db.executemany(
"INSERT INTO agent_tasks(cycle,unit,stage,state) VALUES(?,?,?,?)",
[(identity, u["id"], "annotate", "ready") for u in units],
)
return identity
def _cycle(self, identity):
row = self.db.execute("SELECT * FROM agent_cycles WHERE id=?", (identity,)).fetchone()
if row is None:
raise ValueError("Unknown iteration")
return row, json.loads(row["plan"])
def _settle(self, identity):
row, plan = self._cycle(identity)
if row["state"] == "closed":
return
now = self.clock()
self.db.execute(
"UPDATE agent_tasks SET state='interrupted' "
"WHERE cycle=? AND state='active' AND expires<=?",
(identity, now),
)
dispatched = self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
).fetchone()[0]
if now >= row["deadline"] or dispatched >= plan["limits"]["dispatches"]:
self.db.execute(
"UPDATE agent_tasks SET state='blocked' WHERE cycle=? AND state='ready'",
(identity,),
)
if now >= row["deadline"]:
self.db.execute(
"UPDATE agent_tasks SET state='interrupted' WHERE cycle=? AND state='active'",
(identity,),
)
pending = self.db.execute(
"SELECT 1 FROM agent_tasks WHERE cycle=? AND state IN ('ready','active')", (identity,)
).fetchone()
self.db.execute(
"UPDATE agent_cycles SET state=? WHERE id=?",
("running" if pending else "root_pending", identity),
)
def claim(self, identity, unit_id, stage, actor):
actor_id(actor)
with self.transaction():
self._settle(identity)
now = self.clock()
row, plan = self._cycle(identity)
if row["state"] != "running":
raise ValueError("Iteration is waiting for root")
task = self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? AND unit=? AND stage=?",
(identity, unit_id, stage),
).fetchone()
if task is None or task["state"] != "ready":
raise ValueError("Task is not claimable")
if plan["schema_version"] == SCHEMA_V2:
if self._unconfirmed_handoffs(identity):
raise ValueError("Confirm outstanding handoff or reconcile it before claiming")
if (
stage == "annotate"
and self.db.execute(
"SELECT 1 FROM agent_tasks WHERE cycle=? "
"AND stage='review' AND state='ready'",
(identity,),
).fetchone()
):
raise ValueError("Ready reviews must be dispatched before another author")
active = self.db.execute(
"SELECT COUNT(*) FROM agent_tasks WHERE state IN ('active','interrupted')"
).fetchone()[0]
if active >= plan["limits"]["parallel"]:
raise ValueError("Global agent concurrency exhausted")
if stage == "review":
author = self.db.execute(
"SELECT actor FROM agent_tasks WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()[0]
if actor == author:
raise ValueError("Author cannot review their own proposal")
unit = next(u for u in plan["units"] if u["id"] == unit_id)
self.pins(unit)
now = self.clock()
if now >= row["deadline"]:
raise ValueError("Iteration deadline passed during input verification")
token = uuid.uuid4().hex
expires = min(now + plan["limits"]["lease_seconds"], row["deadline"])
self.db.execute(
"UPDATE agent_tasks SET state='active',attempt=attempt+1,token=?,actor=?,expires=? "
"WHERE cycle=? AND unit=? AND stage=?",
(token, actor, expires, identity, unit_id, stage),
)
self.db.execute(
"INSERT INTO agent_attempts(token,cycle,unit,stage,actor,started) "
"VALUES(?,?,?,?,?,?)",
(token, identity, unit_id, stage, actor, now),
)
packet = dict(
cycle=identity, unit=unit, stage=stage, token=token, actor=actor, expires=expires
)
if stage == "review":
proposal = self.db.execute(
"SELECT result,result_sha FROM agent_tasks "
"WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()
packet.update(proposal=json.loads(proposal[0]), proposal_sha256=proposal[1])
return packet
def _unconfirmed_handoffs(self, identity):
return [
dict(row)
for row in self.db.execute(
"SELECT t.token,t.unit,t.stage,t.actor,t.expires FROM agent_tasks t "
"LEFT JOIN agent_dispatch_receipts d ON d.token=t.token "
"WHERE t.cycle=? AND t.state IN ('active','interrupted') AND d.token IS NULL "
"ORDER BY t.unit,t.stage",
(identity,),
)
]
def confirm_dispatch(self, token, root_actor, executor_ref, evidence):
"""Record a real handoff after sending; absence never proves no executor exists."""
actor_id(executor_ref)
text(evidence)
with self.transaction():
attempt = self.db.execute(
"SELECT * FROM agent_attempts WHERE token=?", (token,)
).fetchone()
if attempt is None:
raise ValueError("Unknown claim")
row, plan = self._cycle(attempt["cycle"])
if root_actor != plan["root_actor"] or plan["schema_version"] != SCHEMA_V2:
raise ValueError("V2 root dispatch confirmation required")
previous = self.db.execute(
"SELECT * FROM agent_dispatch_receipts WHERE token=?", (token,)
).fetchone()
if previous:
if (previous["executor_ref"], previous["evidence"]) != (executor_ref, evidence):
raise ValueError("Conflicting dispatch receipt")
return dict(previous)
task = self.db.execute("SELECT * FROM agent_tasks WHERE token=?", (token,)).fetchone()
if (
task is None
or task["state"] not in {"active", "interrupted", "done"}
or (row["state"] == "closed" and task["state"] != "done")
):
raise ValueError("Cannot confirm a closed or superseded handoff")
self.capacity(len(executor_ref.encode()) + len(evidence.encode()))
recorded = self.clock()
self.db.execute(
"INSERT INTO agent_dispatch_receipts VALUES(?,?,?,?)",
(token, executor_ref, recorded, evidence),
)
return dict(
token=token, executor_ref=executor_ref, recorded=recorded, evidence=evidence
)
def complete(self, token, actor, result):
encoded, sha = encode(result), digest(result)
if len(encoded.encode()) > MAX_RESULT:
raise ValueError("Result byte budget exceeded")
with self.transaction():
attempt = self.db.execute(
"SELECT * FROM agent_attempts WHERE token=?", (token,)
).fetchone()
if attempt is None or attempt["actor"] != actor:
raise ValueError("Claim ownership mismatch")
if attempt["result"] is not None:
if attempt["result_sha"] != sha:
raise ValueError("Changed duplicate completion")
return sha
identity, unit_id, stage = (attempt[k] for k in ("cycle", "unit", "stage"))
row, plan = self._cycle(identity)
task = self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? AND unit=? AND stage=?",
(identity, unit_id, stage),
).fetchone()
if (
row["state"] == "closed"
or task["token"] != token
or task["state"] != "active"
or self.clock() >= min(task["expires"], row["deadline"])
):
raise ValueError("Expired or superseded claim; root must reconcile executor")
self.pins(next(u for u in plan["units"] if u["id"] == unit_id))
text(result.get("reason"))
if stage == "review":
proposal = self.db.execute(
"SELECT result_sha FROM agent_tasks "
"WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()[0]
if result.get("proposal_sha256") != proposal or result.get("verdict") not in {
"accept",
"reject",
}:
raise ValueError("Review must bind the exact proposal")
self.capacity(2 * len(encoded.encode()))
now = self.clock()
if now >= min(task["expires"], row["deadline"]):
raise ValueError(
"Claim expired during result validation; root must reconcile executor"
)
self.db.execute(
"UPDATE agent_attempts SET finished=?,result=?,result_sha=? WHERE token=?",
(now, encoded, sha, token),
)
self.db.execute(
"UPDATE agent_tasks SET state='done',result=?,result_sha=? WHERE token=?",
(encoded, sha, token),
)
if stage == "annotate":
self.db.execute(
"INSERT INTO agent_tasks(cycle,unit,stage,state) VALUES(?,?,'review','ready')",
(identity, unit_id),
)
self._settle(identity)
return sha
def reconcile(self, token, root_actor, stopped_evidence, *, retry=False):
"""Trusted root verifies executor termination BEFORE releasing reservation."""
text(stopped_evidence)
with self.transaction():
task = self.db.execute("SELECT * FROM agent_tasks WHERE token=?", (token,)).fetchone()
if task is None:
raise ValueError("Unknown claim")
row, plan = self._cycle(task["cycle"])
if root_actor != plan["root_actor"] or row["state"] == "closed":
raise ValueError("Root reconciliation required")
if task["state"] not in {"active", "interrupted"}:
raise ValueError("Only unfinished executor may be reconciled")
count = self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (task["cycle"],)
).fetchone()[0]
allowed = (
task["attempt"] < plan["limits"]["attempts"]
and count < plan["limits"]["dispatches"]
and self.clock() < row["deadline"]
)
if retry and not allowed:
raise ValueError("Retry budget exhausted")
self.db.execute(
"UPDATE agent_attempts SET finished=?,stopped_evidence=? WHERE token=?",
(self.clock(), stopped_evidence, token),
)
self.db.execute(
"UPDATE agent_tasks SET state=?,token=NULL WHERE token=?",
("ready" if retry else "blocked", token),
)
self._settle(task["cycle"])
def cancel_ready(self, identity, root_actor, reason):
"""Root cancels undispatched work without releasing executor reservations."""
text(reason)
result = dict(reason=reason, disposition="cancelled_by_root")
encoded, sha = encode(result), digest(result)
with self.transaction():
row, plan = self._cycle(identity)
if root_actor != plan["root_actor"] or row["state"] == "closed":
raise ValueError("Root cancellation requires an open iteration")
count = self.db.execute(
"SELECT COUNT(*) FROM agent_tasks WHERE cycle=? AND state='ready'",
(identity,),
).fetchone()[0]
if count:
self.capacity(count * len(encoded.encode()))
self.db.execute(
"UPDATE agent_tasks SET state='blocked',result=?,result_sha=? "
"WHERE cycle=? AND state='ready'",
(encoded, sha, identity),
)
self._settle(identity)
return dict(cancelled=count)
def status(self, identity):
with self.transaction():
return self._status(identity)
def _status(self, identity):
"""Read settled state while the caller holds the transaction."""
self._settle(identity)
row, plan = self._cycle(identity)
tasks = [
dict(r)
for r in self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? ORDER BY unit,stage", (identity,)
)
]
for task in tasks:
if task["result"]:
task["result"] = json.loads(task["result"])
sample = min((u["id"] for u in plan["units"]), key=lambda u: digest([identity, u]))
flagged = sorted(
{
t["unit"]
for t in tasks
if t["state"] != "done"
or (t["stage"] == "review" and t["result"]["verdict"] == "reject")
}
)
snapshot = dict(
id=identity,
state=row["state"],
plan=plan,
tasks=tasks,
root_required_units=sorted({sample, *flagged}),
dispatches=self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
).fetchone()[0],
root_review=json.loads(row["root_review"]) if row["root_review"] else None,
)
if plan["schema_version"] == SCHEMA_V2:
review = snapshot["root_review"] or {}
snapshot.update(
unconfirmed_handoffs=self._unconfirmed_handoffs(identity),
ready_tasks=[
dict(unit=t["unit"], stage=t["stage"])
for t in sorted(
(t for t in tasks if t["state"] == "ready"),
key=lambda t: (t["stage"] != "review", t["unit"]),
)
],
progress=dict(
planned=len(plan["units"]),
proposed=sum(t["stage"] == "annotate" and t["state"] == "done" for t in tasks),
reviewed=sum(t["stage"] == "review" and t["state"] == "done" for t in tasks),
review_accepted=sum(
t["stage"] == "review"
and t["state"] == "done"
and t["result"]["verdict"] == "accept"
for t in tasks
),
admitted=len(review.get("admitted_units", [])),
blocked=sum(t["state"] == "blocked" for t in tasks),
unreconciled=sum(t["state"] == "interrupted" for t in tasks),
target=plan["objective_contract"]["min_admitted_units"],
objective_outcome=review.get("objective_outcome"),
),
)
return snapshot
def decide(self, identity, actor, review):
encoded = encode(review)
if len(encoded.encode()) > MAX_ROOT_REVIEW:
raise ValueError("Root review byte budget exceeded")
with self.transaction():
snapshot = self._status(identity)
plan = snapshot["plan"]
if actor != plan["root_actor"] or snapshot["state"] != "root_pending":
raise ValueError("Root decision only at terminal iteration")
if any(t["state"] == "interrupted" for t in snapshot["tasks"]):
raise ValueError("Unconfirmed executors still reserve resources")
if (
set(review)
!= {
"verdict",
"next",
"reason",
"inspected_units",
"admitted_units",
"checks",
"tuning",
}
| (
{"objective_outcome", "objective_checks", "outcome_reason", "remaining_work"}
if plan["schema_version"] == SCHEMA_V2
else set()
)
or review["verdict"] not in {"accepted", "rejected"}
or review["next"] not in {"continue", "revise", "stop"}
):
raise ValueError("Explicit root verdict and next action required")
text(review["reason"])
text(review["tuning"])
if plan["schema_version"] == SCHEMA_V2:
contract, checks = plan["objective_contract"], review["objective_checks"]
outcome = review["objective_outcome"]
if (
outcome not in {"achieved", "not_achieved", "inconclusive"}
or not isinstance(checks, dict)
or set(checks) != set(contract["required_checks"])
or any(type(v) is not bool for v in checks.values())
):
raise ValueError("Exact frozen objective checks and outcome required")
text(review["outcome_reason"])
remaining = review["remaining_work"]
if not isinstance(remaining, list) or len(remaining) > 12:
raise ValueError("Bounded remaining work required")
for item in remaining:
text(item)
if outcome == "achieved":
if (
review["verdict"] != "accepted"
or not all(checks.values())
or len(review["admitted_units"]) < contract["min_admitted_units"]
or remaining
):
raise ValueError("Objective target/checks not achieved")
elif not remaining:
raise ValueError("Unmet objective needs remaining work or blocker")
if not set(snapshot["root_required_units"]).issubset(review["inspected_units"]):
raise ValueError("Inspect flagged and preselected units")
admitted = review["admitted_units"]
if not isinstance(admitted, list) or len(set(admitted)) != len(admitted):
raise ValueError("Unique admitted unit list required")
approved = {
t["unit"]
for t in snapshot["tasks"]
if t["stage"] == "review"
and t["state"] == "done"
and t["result"]["verdict"] == "accept"
}
if review["verdict"] == "accepted":
if (
not admitted
or not set(admitted).issubset(approved)
or not review["checks"]
or any(v is not True for v in review["checks"].values())
):
raise ValueError("Cannot accept failed or incomplete evidence")
for unit in plan["units"]:
self.pins(unit)
elif admitted or review["next"] == "continue":
raise ValueError("Rejected iteration cannot admit units or continue unchanged")
self.capacity(len(encoded.encode()))
self.db.execute(
"UPDATE agent_cycles SET state='closed',root_review=? WHERE id=?",
(encoded, identity),
)
return digest(review)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--store", required=True)
parser.add_argument(
"action",
choices=[
"begin",
"status",
"claim",
"confirm_dispatch",
"complete",
"reconcile",
"cancel_ready",
"decide",
],
)
parser.add_argument(
"--request", required=True, help="Bounded JSON arguments; actor assigned by dispatcher"
)
args = parser.parse_args()
path = Path(args.request)
if path.stat().st_size > MAX_JSON:
raise ValueError("Request too large")
request = json.loads(path.read_text(encoding="utf-8"))
cycle = Cycle(args.store)
try:
print(encode(getattr(cycle, args.action)(**request)))
finally:
cycle.close()
if __name__ == "__main__":
main()
@@ -0,0 +1,83 @@
"""Pinned source-reviewed label withdrawal; no class inference or model input."""
import hashlib
import math
import numpy as np
from PIL import Image, ImageDraw
def withdraw_labels(sample, review, target):
if (
review["name"] != sample["name"]
or review["input_sha256"] != sample["input"]["rgb"]["sha256"]
):
raise ValueError("Pinned raw input required")
if (
target.dtype != np.uint8
or target.ndim != 2
or list(target.shape[::-1]) != sample["size"]
or not np.isin(target, [0, 1, 255]).all()
):
raise ValueError("Aligned uint8 target required")
actual = hashlib.sha256(target.tobytes()).hexdigest()
if actual != sample["target_sha256"] or review["target_sha256"] != actual:
raise ValueError("Pinned target changed")
expected = {c["id"]: c["sha256"] for c in sample["components"]}
if review["reviewed_components"] != expected or not review["raw_first"]:
raise ValueError("Complete raw-first component review required")
if not isinstance(review["reason"], str) or not review["reason"].strip():
raise ValueError("Explicit visual evidence required")
zones = review["withdrawals"]
if not isinstance(zones, list) or len(zones) > 64:
raise ValueError("Bounded explicit withdrawal zones required")
changed = np.zeros(target.shape, dtype=bool)
ids, counts = set(), []
width, height = sample["size"]
for zone in zones:
if (
not isinstance(zone["id"], str)
or not zone["id"]
or zone["id"] in ids
or type(zone["label"]) is not int
or zone["label"] not in (0, 1)
or not isinstance(zone["reason"], str)
or not zone["reason"].strip()
):
raise ValueError("Unique zone, old class and visual reason required")
ids.add(zone["id"])
polygon = zone["polygon"]
if not isinstance(polygon, list) or not 3 <= len(polygon) <= 16:
raise ValueError("Explicit bounded native-pixel polygon required")
for point in polygon:
if (
not isinstance(point, list)
or len(point) != 2
or any(type(v) not in (int, float) or not math.isfinite(v) for v in point)
or not 0 <= point[0] < width
or not 0 <= point[1] < height
):
raise ValueError("Polygon outside native image")
canvas = Image.new("1", (width, height))
ImageDraw.Draw(canvas).polygon([tuple(p) for p in polygon], fill=1)
part = np.asarray(canvas, dtype=bool) & (target == zone["label"])
if not part.any():
raise ValueError("Withdrawal must touch explicit known labels")
counts.append(
dict(
id=zone["id"],
label=zone["label"],
selected=int(part.sum()),
newly_withdrawn=int((part & ~changed).sum()),
)
)
changed |= part
revised = target.copy()
revised[changed] = 255
return revised, dict(
zones=counts,
removed_paint=int((changed & (target == 1)).sum()),
removed_background=int((changed & (target == 0)).sum()),
target_sha256=actual,
revised_sha256=hashlib.sha256(revised.tobytes()).hexdigest(),
)
@@ -0,0 +1,147 @@
"""Read-only provenance proof for a reviewed ROI; never infer legacy subtypes.
The sidecar describes annotation mechanics, not semantic truth. A zero source-
unknown count is meaningful only when source_subtypes_known is true.
"""
import hashlib
from admission_store import pixel_runs
from dataset_store import digest
from region_coverage import roi_bounds
def sha(value):
return hashlib.sha256(value).hexdigest()
def _mask(spans, width, count):
mask = bytearray(count)
for y, a, b in spans:
mask[y * width + a : y * width + b] = bytes([1]) * (b - a)
return mask
def _difference(spans, mask, width):
result = []
for y, a, b in spans:
start = None
for x in range(a, b):
keep = not mask[y * width + x]
if keep and start is None:
start = x
if not keep and start is not None:
result.append([y, start, x])
start = None
if start is not None:
result.append([y, start, b])
return result
def audit_unit(packet, record, original, merged, protected=b"", *, merged_sha256):
"""Validate exact source->merged mechanics and return additive JSON evidence.
Prior protected RLE has no trustworthy subtype; it stays explicitly untyped.
Missing source_unknown likewise makes this record's unknown untyped. Outside
this ROI, original 255 without prior protection is unassigned to this review.
The caller still owns source/media binding and independent semantic review.
"""
size = packet["size"]
x0, y0, x1, y1 = roi_bounds(size, packet["roi"])
width, height = size
count = width * height
if any(not isinstance(v, (bytes, bytearray)) for v in (original, merged, protected)):
raise ValueError("Native byte targets and protected mask required")
if any(len(v) != count or set(v) - {0, 1, 255} for v in (original, merged)):
raise ValueError("Aligned ternary native targets required")
if sha(original) != packet["target_sha256"] or sha(merged) != merged_sha256:
raise ValueError("Target SHA mismatch")
if protected and (len(protected) != count or set(protected) - {0, 1}):
raise ValueError("Aligned binary protected mask required")
if sha(protected) != packet["protected_sha256"]:
raise ValueError("Protected SHA mismatch")
if record["view"] != packet["view"]:
raise ValueError("Source view mismatch")
checked = pixel_runs(record, size)
labels = bytearray([3]) * count # 3 = not reviewed; never a class or ignore.
for kind, value in (("background", 0), ("paint", 1), ("unknown", 255)):
for y, a, b in checked[kind]:
if not y0 <= y < y1 or not x0 <= a < b <= x1:
raise ValueError("Reviewed spans outside ROI")
labels[y * width + a : y * width + b] = bytes([value]) * (b - a)
if sum(v != 3 for v in labels) != (x1 - x0) * (y1 - y0):
raise ValueError("Incomplete ROI; unassigned is not reviewed unknown")
typed = "source_unknown" in record
source = pixel_runs(
dict(paint=[], background=[], unknown=record.get("source_unknown", [])), size
)["unknown"]
source_mask = _mask(source, width, count)
if any(mark and labels[i] != 255 for i, mark in enumerate(source_mask)):
raise ValueError("Source unknown must be within reviewed unknown")
automatic = _difference(checked["unknown"], source_mask, width) if typed else []
untyped = [] if typed else checked["unknown"]
categories = dict(source_unknown=source, automatic_margin=automatic, untyped_unknown=untyped)
# Check the disjoint union independently with the normal RLE validator.
union = sorted(span for spans in categories.values() for span in spans)
pixel_runs(dict(paint=[], background=[], unknown=union), size)
if _mask(union, width, count) != _mask(checked["unknown"], width, count):
raise ValueError("Unknown provenance union differs")
prior = protected or bytes(count)
outside = dict(pixels=0, prior_known=0, prior_protected_untyped=0, unassigned_unknown=0)
prior_counts = dict(pixels=0, inside_roi=0, outside_roi=0, remaining_unknown=0)
for i, (old, new, value) in enumerate(zip(original, merged, labels, strict=True)):
if prior[i]:
if old != 255 or new != 255:
raise ValueError("Prior protected unknown changed")
prior_counts["pixels"] += 1
prior_counts["inside_roi" if value != 3 else "outside_roi"] += 1
prior_counts["remaining_unknown"] += 1
if source_mask[i] and (old != 255 or new != 255):
raise ValueError("Source unknown conflicts with accepted labels")
if old != 255 and new != old:
raise ValueError("Accepted known label changed")
expected = value if value in (0, 1) else old
if new != expected:
raise ValueError("Merged target differs from source-to-merge contract")
if value == 3:
outside["pixels"] += 1
key = (
"prior_known"
if old != 255
else "prior_protected_untyped"
if prior[i]
else "unassigned_unknown"
)
outside[key] += 1
proof = {}
for kind, spans in categories.items():
mask = _mask(spans, width, count)
counts = dict(
pixels=0, remaining_unknown=0, retained_old_paint=0, retained_old_background=0
)
for i, mark in enumerate(mask):
if mark:
counts["pixels"] += 1
key = {
255: "remaining_unknown",
1: "retained_old_paint",
0: "retained_old_background",
}[merged[i]]
counts[key] += 1
proof[kind] = dict(runs=spans, mask_sha256=sha(mask), **counts)
return dict(
schema="missioncore.annotation-provenance/v1",
view=record["view"],
size=list(size),
roi=list(packet["roi"]),
original_sha256=sha(original),
merged_sha256=sha(merged),
protected_sha256=sha(protected),
record_sha256=digest(record),
source_subtypes_known=typed,
categories=proof,
prior_protected_untyped=prior_counts,
outside_roi=outside,
reviewed_pixels=(x1 - x0) * (y1 - y0),
labels_changed_by_audit=0,
)
@@ -0,0 +1,44 @@
"""Apply reviewed known-to-unknown withdrawals to TRAIN-only paired targets."""
import numpy as np
def training_view(record, revised):
if record["split"] != "train":
raise ValueError("TRAIN records only")
old, base = record["target"], record["base_target"]
arrays = [old, base, revised]
if any(
a.dtype != np.uint8
or a.ndim != 2
or a.shape != old.shape
or not np.isin(a, [0, 1, 255]).all()
for a in arrays
):
raise ValueError("Aligned uint8 targets required")
if not np.array_equal(old[base != 255], base[base != 255]):
raise ValueError("Parent base labels conflict")
if not np.array_equal(old == 0, base == 0):
raise ValueError("Parent comparison admits paint only")
changed = old != revised
if np.any(changed & ((old == 255) | (revised != 255))):
raise ValueError("Known-to-unknown withdrawal only")
for name in ["weak", "clear", "added"]:
mask = record[name]
if mask.dtype != bool or mask.shape != old.shape or np.any(mask & (old != 1)):
raise ValueError("Pinned condition masks must select parent paint")
if not np.array_equal(record["added"], (base == 255) & (old == 1)):
raise ValueError("Added cohort differs from parent labels")
if np.any(changed & (record["weak"] | record["added"])):
raise ValueError("This fixed comparison preserves all weak and added paint")
target = revised.copy()
original = base.copy()
original[changed] = 255
return dict(
record,
target=target,
base_target=original,
weak=record["weak"].copy(),
added=record["added"].copy(),
clear=record["clear"] & (target == 1),
)
@@ -0,0 +1,106 @@
"""Pinned TRAIN-only background admission with fixed existing window mass."""
import hashlib
import numpy as np
from condition_inventory import raster
from PIL import Image, ImageFilter
def add_background(sample, review, target, protected):
if sample["split"] != "train" or review["name"] != sample["name"]:
raise ValueError("Pinned TRAIN sample required")
if (
target.dtype != np.uint8
or target.ndim != 2
or list(target.shape[::-1]) != sample["size"]
or not np.isin(target, [0, 1, 255]).all()
or protected.dtype != bool
or protected.shape != target.shape
or np.any(protected & (target != 255))
):
raise ValueError("Aligned labels and unknown-only protected mask required")
for key, actual in [
("target_sha256", hashlib.sha256(target.tobytes()).hexdigest()),
("protected_sha256", hashlib.sha256(protected.tobytes()).hexdigest()),
("rgb_sha256", sample["rgb_sha256"]),
]:
if review[key] != actual or sample[key] != actual:
raise ValueError("Pinned source or target changed")
if review["boundary_ignore_px"] != 2 or not isinstance(review["regions"], list):
raise ValueError("Explicit two-native-pixel uncertainty margin required")
if len(review["regions"]) > 32:
raise ValueError("Bounded reviewed regions required")
added = np.zeros(target.shape, dtype=bool)
audit, seen = [], set()
for region in review["regions"]:
if not region["reason"].strip() or not region["id"] or region["id"] in seen:
raise ValueError("Unique region identity and visible-source reason required")
seen.add(region["id"])
mask = raster(region["polygon"], sample["size"])
core = (
np.asarray(Image.fromarray(mask.astype("uint8") * 255).filter(ImageFilter.MinFilter(5)))
> 0
)
if np.any(core & (target == 1)):
raise ValueError("Reviewed background conflicts with accepted paint")
fresh = core & (target == 255) & ~protected
if np.any(fresh & added):
raise ValueError("Overlapping added-background interiors")
added |= fresh
audit.append(
dict(
id=region["id"],
new_pixels=int(fresh.sum()),
known_background=int((core & (target == 0)).sum()),
protected_excluded=int((core & protected).sum()),
)
)
out = target.copy()
out[added] = 0
return out, added, audit
def prepare_background(records, weights):
"""Keep positive weights exact; redistribute each window's existing BG mass.
New negatives may enter only windows already containing reviewed background.
Empty additions are an exact identity, including dtype and sample order.
"""
if not records or set(weights) != {r["name"] for r in records}:
raise ValueError("Matching nonempty records and weights required")
output, result, seen = [], {}, set()
for r in records:
name = r["name"]
if r["split"] != "train" or name in seen:
raise ValueError("Unique TRAIN records required")
seen.add(name)
target, added, w = r["target"], r["added_background"], weights[name]
if (
target.dtype != np.uint8
or target.ndim != 2
or not np.isin(target, [0, 1, 255]).all()
or added.dtype != bool
or added.shape != target.shape
or w.shape != target.shape
or w.dtype.kind != "f"
or not np.isfinite(w).all()
or np.any(w < 0)
or np.any(w[target == 255] != 0)
or np.any(added & (target != 255))
):
raise ValueError("Invalid labels, admitted background or weights")
t, ww = target.copy(), w.copy()
nadd = int(added.sum())
if nadd:
existing = target == 0
nold = int(existing.sum())
if not nold or np.any(w[existing] <= 0):
raise ValueError("Existing positive background mass required in each added window")
mass = float(w[existing].sum(dtype=np.float64))
ww[existing] *= nold / (nold + nadd)
ww[added] = mass / (nold + nadd)
t[added] = 0
output.append(dict(r, target=t))
result[name] = ww
return output, result
@@ -0,0 +1,87 @@
"""Worker-only rendering of the previously frozen six control windows."""
import hashlib
import json
import time
from pathlib import Path
from mapping import prepare_crops, render
from PIL import Image, ImageDraw
root = Path("/experiment")
control = json.loads((root / "control.json").read_text())
source = json.loads((root / "control-source-receipt.json").read_text())["source"]
out = root / "control-observations"
out.mkdir(exist_ok=False)
start = time.monotonic()
jobs = []
for w in control["windows"]:
x, y, z = w["center"]
views = [
dict(
id="top",
projection="ortho",
size=[768, 768],
width_m=12,
eye=[x, y, z + 25],
target=[x, y, z],
up=[0, 1, 0],
),
dict(
id="oblique",
projection="pinhole",
size=[768, 768],
fov_degrees=65,
eye=[x, y - 7, z + 9],
target=[x, y, z],
up=[0, 0, 1],
),
]
jobs.append(
dict(
source=source,
bounds_xy=[[x - 6, y - 6], [x + 6, y + 6]],
halo_m=15,
views=views,
)
)
for start_index in range(0, len(jobs), 3):
batch = jobs[start_index : start_index + 3]
for i, (job, rows) in enumerate(zip(batch, prepare_crops(batch), strict=True)):
w = control["windows"][start_index + i]
folder = out / w["id"]
folder.mkdir()
(folder / "cameras.json").write_text(json.dumps(job, allow_nan=False))
render(job, folder, prepared_rows=rows)
del rows
sheet = Image.new("RGB", (1536, 800), "#161616")
for n, view in enumerate(["top", "oblique"]):
sheet.paste(Image.open(folder / (view + ".png")), (n * 768, 32))
ImageDraw.Draw(sheet).text(
(12, 10),
w["id"] + " | RAW TOP / RAW OBLIQUE | no algorithm overlay",
fill="white",
)
sheet.save(folder / "raw-review.jpg", quality=94)
print("complete " + w["id"], flush=True)
files = {
p.relative_to(out).as_posix(): dict(
bytes=p.stat().st_size, sha256=hashlib.sha256(p.read_bytes()).hexdigest()
)
for p in out.rglob("*")
if p.is_file()
}
manifest = dict(
schema_version="missioncore.boundary-control-observations/v1",
control_sha256=hashlib.sha256((root / "control.json").read_bytes()).hexdigest(),
source=source,
files=files,
seconds=time.monotonic() - start,
training_eligible=False,
)
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, allow_nan=False))
print(
json.dumps(
dict(seconds=manifest["seconds"], bytes=sum(f["bytes"] for f in files.values()))
)
)
@@ -0,0 +1,354 @@
"""Offline RGB/depth ranking probe. Never substitutes production admission.
Uses the existing four physical evidence terms, without learned masks or
occluder fields (absent from the reviewed image pack). Consequently its fixed
score is a diagnostic reference, NOT the production algorithm's full score.
"""
import argparse
import hashlib
import json
import time
from pathlib import Path
import numpy as np
from boundary_anchors import PhysicalFields, resample, sample
from boundary_review import clipped_range, verify_pack
from PIL import Image, ImageDraw
from scipy.optimize import minimize
PRIOR = np.array([0.65, 0.65, 0.25, 0.20], dtype=np.float64)
TERMS = ["persistent_contrast_edge", "height_step", "oriented_edge", "side_texture"]
def components(fields, uv, normal):
"""Same float32 arrays, interpolation and constants as PhysicalFields.measure."""
n = np.broadcast_to(normal, uv.shape)
plus = uv + n * fields.policy.cross_section_m / fields.cell
minus = uv - n * fields.policy.cross_section_m / fields.cell
near = sample(fields.gray, plus) - sample(fields.gray, minus)
far = sample(fields.gray, uv + n * 0.8 / fields.cell) - sample(
fields.gray, uv - n * 0.8 / fields.cell
)
contrast = np.clip(np.minimum(abs(near), abs(far)) / 18, 0, 1) * (near * far > 0)
edge = np.clip(
abs(sample(fields.gx, uv) * n[..., 0] + sample(fields.gy, uv) * n[..., 1]) / 55,
0,
1,
)
dz = sample(fields.z, plus) - sample(fields.z, minus)
step = np.exp(-(((dz - 0.12) / 0.12) ** 2)) * (dz > 0.025) * (dz < 0.35)
texture = np.clip(
(sample(fields.texture, plus) - sample(fields.texture, minus)) / 20, 0, 1
)
score, reliable = fields.measure(uv, normal)
# The retained fixed score comes from production code, not a reordered sum.
return np.stack([contrast * edge, step, edge, texture], axis=-1) * reliable[
..., None
], score * reliable
def fields_for(folder):
rgb = np.array(Image.open(folder / "top.png").convert("RGB"))
g = np.load(folder / "top.geometry.npz")
z = g["view"][2, 3] - g["depth"]
zero = np.zeros(z.shape, np.float32)
cell = 1 / float(g["intrinsics"][0, 0])
return PhysicalFields(rgb, z, g["alpha"], zero, zero, zero, cell), g
def project(points, g):
xyz = np.asarray(points, dtype=np.float64)
view, k = g["view"], g["intrinsics"]
camera = xyz @ view[:3, :3].T + view[:3, 3]
return camera[:, :2] * np.diag(k)[:2] + k[:2, 2] - 0.5
def describe(fields, path, rect, sidewalk_direction):
chunks = []
lengths = []
baseline = []
sidewalk = np.asarray(sidewalk_direction, dtype=float)
if (
sidewalk.shape != (2,)
or not np.isfinite(sidewalk).all()
or np.linalg.norm(sidewalk) == 0
):
raise ValueError("Explicit review orientation required")
for a, b in zip(path, path[1:], strict=False):
clip = clipped_range(a, b, rect)
if clip is None:
continue
a, b = np.asarray(a), np.asarray(b)
ends = np.array([a + t * (b - a) for t in clip])
length = float(np.linalg.norm(ends[1] - ends[0]) * fields.cell)
if length < 1e-8:
continue
# Measurements only: never store these samples as replacement geometry.
points = resample(ends * fields.cell, 0.20) / fields.cell
tangent = (b - a) / np.linalg.norm(b - a)
n = np.array([-tangent[1], tangent[0]])
if n @ sidewalk < 0:
n = -n
feature, score = components(fields, points, n)
chunks.append(feature.mean(0))
baseline.append(float(score.mean()))
lengths.append(length)
if not chunks:
raise ValueError("Candidate has no reviewed extent")
return np.average(chunks, axis=0, weights=lengths), float(
np.average(baseline, weights=lengths)
)
def fit(differences, prior=PRIOR):
d = np.asarray(differences, dtype=np.float64)
if d.ndim != 2 or d.shape[1] != 4 or len(d) < 2 or not np.isfinite(d).all():
raise ValueError("Finite, reviewed candidate pairs required")
# Fixed before held-out evaluation. No hyperparameter search on control.
def objective(w):
return np.logaddexp(0, -d @ w).mean() + 0.1 * np.square(w - prior).sum()
result = minimize(
objective,
prior,
method="L-BFGS-B",
bounds=[(0, 2)] * 4,
options={"maxiter": 100, "ftol": 1e-12, "gtol": 1e-8},
)
if not result.success or not np.isfinite(result.x).all():
raise ValueError("Ranking fit did not converge")
return result.x
def train(root, pack_name="expanded-pack", run_name="rank-probe"):
start = time.monotonic()
pack = root / pack_name
verification = verify_pack(pack)
review = json.loads((root / "control-review.json").read_text())
control = json.loads((root / "control.json").read_text())
train_world = json.loads((pack / "pack.json").read_text())["source"]["world_sha256"]
if (
review["training_eligible"] is not False
or not review["reviewed_before_fit"]
or review["control_sha256"]
!= hashlib.sha256((root / "control.json").read_bytes()).hexdigest()
or control["world_sha256"] == train_world
):
raise ValueError("Frozen independent visual control required before fit")
records = json.loads((pack / "records.json").read_text())
orientation = json.loads((root / "training-orientation.json").read_text())
rows = []
for r in records:
if not r["ranking_trial_eligible"]:
continue
folder = pack / "observations" / Path(r["sample"]).parent
labels = json.loads((folder / "labels.json").read_text())
fields, g = fields_for(folder)
def candidate(key, labels=labels, r=r, fields=fields, g=g):
f = next(f for f in labels[key] if f["id"] == r["feature_id"])
return describe(
fields,
project(f["geometry"]["coordinates"], g),
r["rect_px"],
orientation[r["id"]],
)
positive, pb = candidate("proposed_element")
negative, nb = candidate("original_element")
rows.append(
dict(
id=r["id"],
feature_id=r["feature_id"],
sample=r["sample"],
positive=positive.tolist(),
negative=negative.tolist(),
fixed_margin=pb - nb,
)
)
preparation = time.monotonic() - start
d = np.array([np.array(r["positive"]) - r["negative"] for r in rows])
training = time.monotonic()
w = fit(d)
training = time.monotonic() - training
# Leave entire source feature out, including distant windows on that feature.
loo = []
for fid in sorted({r["feature_id"] for r in rows}):
hold = np.array([r["feature_id"] == fid for r in rows])
lw = fit(d[~hold])
loo.extend(
dict(id=rows[i]["id"], margin=float(d[i] @ lw))
for i in np.flatnonzero(hold)
)
for r, margin in zip(rows, d @ w, strict=True):
r["learned_margin"] = float(margin)
model = dict(
schema_version="missioncore.boundary-rank-probe/v1",
terms=TERMS,
weights=w.tolist(),
prior=PRIOR.tolist(),
training_pack_sha256=verification["sha256"],
training_world_sha256=json.loads((pack / "pack.json").read_text())["source"][
"world_sha256"
],
control_sha256=hashlib.sha256((root / "control.json").read_bytes()).hexdigest(),
acceptance_changed=False,
production_eligible=False,
missing_production_fields=["semantic_context", "occluder"],
l2_to_prior=0.1,
weight_bounds=[0, 2],
sample_m=0.2,
review_orientation=True,
source_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
physical_fields_sha256=hashlib.sha256(
(root / "boundary_anchors.py").read_bytes()
).hexdigest(),
)
model["control_review_sha256"] = hashlib.sha256(
(root / "control-review.json").read_bytes()
).hexdigest()
target = root / run_name
target.mkdir(exist_ok=False)
(target / "model.json").write_text(json.dumps(model, indent=2, allow_nan=False))
report = dict(
rows=rows,
leave_feature_out=loo,
preparation_seconds=preparation,
training_seconds=training,
pairs=len(rows),
independent_source_features=len(set(r["feature_id"] for r in rows)),
fixed_correct=sum(r["fixed_margin"] > 0 for r in rows),
fit_correct=sum(r["learned_margin"] > 0 for r in rows),
leave_feature_out_correct=sum(r["margin"] > 0 for r in loo),
full_chain_run=False,
)
(target / "training-report.json").write_text(
json.dumps(report, indent=2, allow_nan=False)
)
print(json.dumps(report, allow_nan=False))
def evaluate(root, run_name="rank-probe"):
start = time.monotonic()
target = root / run_name
model = json.loads((target / "model.json").read_text())
review = json.loads((root / "control-review.json").read_text())
if (
model["control_review_sha256"]
!= hashlib.sha256((root / "control-review.json").read_bytes()).hexdigest()
):
raise ValueError("Control review changed after fitting")
if (
model["source_sha256"]
!= hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
):
raise ValueError("Probe implementation changed after fitting")
observations = root / "control-observations"
if (
review["observations_sha256"]
!= hashlib.sha256((observations / "manifest.json").read_bytes()).hexdigest()
):
raise ValueError("Control observation identity changed")
manifest = json.loads((observations / "manifest.json").read_text())
for name, spec in manifest["files"].items():
p = (observations / name).resolve()
if (
not p.is_relative_to(observations.resolve())
or hashlib.sha256(p.read_bytes()).hexdigest() != spec["sha256"]
):
raise ValueError("Control observation member changed")
rows = []
for r in review["records"]:
if not r["eligible"]:
rows.append(dict(id=r["id"], status="unscored-unknown", reason=r["reason"]))
continue
folder = observations / r["id"]
fields, g = fields_for(folder)
path = np.array(r["path_px"], dtype=float)
direction = np.array(r["sidewalk_direction"], dtype=float)
direction /= np.linalg.norm(direction)
choices = []
for offset in review["candidate_offsets_m"]:
candidate = path + offset / fields.cell * direction
feature, fixed = describe(fields, candidate, r["rect_px"], direction)
choices.append(
dict(
offset_m=offset,
fixed_score=fixed,
learned_score=float(feature @ model["weights"]),
)
)
fixed = max(choices, key=lambda x: x["fixed_score"])
learned = max(choices, key=lambda x: x["learned_score"])
row = dict(
id=r["id"],
status="diagnostic-only",
fixed_offset_m=fixed["offset_m"],
learned_offset_m=learned["offset_m"],
fixed_abs_offset_m=abs(fixed["offset_m"]),
learned_abs_offset_m=abs(learned["offset_m"]),
choices=choices,
)
rows.append(row)
raw = Image.open(folder / "top.png").convert("RGB")
over = raw.copy()
draw = ImageDraw.Draw(over)
for offset, color in [
(fixed["offset_m"], "#ff9750"),
(learned["offset_m"], "#c77dff"),
(0, "#55ff8b"),
]:
p = path + offset / fields.cell * direction
draw.line([tuple(x) for x in p], fill=color, width=3)
sheet = Image.new("RGB", (1536, 800), "#161616")
sheet.paste(raw, (0, 32))
sheet.paste(over, (768, 32))
ImageDraw.Draw(sheet).text(
(12, 10),
r["id"]
+ " | raw / green: visual reference; orange: fixed physical score; purple: learned",
fill="white",
)
sheet.save(target / (r["id"] + "-evaluation.jpg"), quality=94)
report = dict(
rows=rows,
seconds=time.monotonic() - start,
model_sha256=hashlib.sha256((target / "model.json").read_bytes()).hexdigest(),
scored_windows=sum(r["eligible"] for r in review["records"]),
unknown_windows=sum(not r["eligible"] for r in review["records"]),
full_chain_run=False,
production_eligible=False,
acceptance_changed=False,
limitation=("Two locally visible control segments. RGB/depth feature probe lacks "
"production semantic context and occluder fields; approximate visual "
"references. No deployment or general accuracy claim."),
)
p = target / "evaluation.json"
if p.exists():
raise ValueError("Do not overwrite frozen evaluation")
p.write_text(json.dumps(report, indent=2, allow_nan=False))
print(
json.dumps(
{
**report,
"rows": [{k: v for k, v in r.items() if k != "choices"} for r in rows],
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["train", "evaluate"])
parser.add_argument("--root", type=Path, default=Path("/experiment"))
parser.add_argument("--pack", default="expanded-pack")
parser.add_argument("--run", default="rank-probe")
args = parser.parse_args()
if any(Path(s).name != s or s in {".", ".."} for s in (args.pack, args.run)):
parser.error("Pack/run must be direct child directory names")
if args.action == "evaluate":
evaluate(args.root, args.run)
else:
train(args.root, args.pack, args.run)
@@ -0,0 +1,238 @@
"""Portable, explicitly reviewed boundary evidence; no implicit pixel/background truth.
Run on Worker. A reviewer selects a rectangle in an existing orthographic image.
The target is a range on the original stored polyline, never a refitted curve.
Only an explicit relative preference is eligible for the first ranking trial.
"""
import argparse
import math
import shutil
from pathlib import Path
from dataset_store import checksum, confined, digest, read, review_samples, write
SCHEMA = "missioncore.boundary-review-pack/v1"
LIMIT = 96 * 1024**2
def clipped_range(a, b, rect):
"""Liang–Barsky parameters on the unchanged source segment (pixel centres)."""
lo, hi = 0.0, 1.0
for axis in (0, 1):
delta = b[axis] - a[axis]
if delta == 0:
if not rect[axis] <= a[axis] <= rect[axis + 2]:
return None
else:
x, y = sorted(((rect[axis] - a[axis]) / delta, (rect[axis + 2] - a[axis]) / delta))
lo, hi = max(lo, x), min(hi, y)
return [lo, hi] if hi > lo else None
def compile_record(labels, cameras, decision):
if decision["evidence"] not in {"visible", "context", "uncertain"}:
raise ValueError("Unknown evidence category")
if not decision.get("reviewer") or not decision.get("reason"):
raise ValueError("Explicit reviewer and reason required")
feature = next(f for f in labels["proposed_element"] if f["id"] == decision["feature_id"])
if (
feature["properties"]["class"] != "road_boundary"
or feature["properties"].get("review_status") == "rejected"
or feature["geometry"]["type"] != "LineString"
):
raise ValueError("Expected an active road boundary LineString")
camera = next(c for c in cameras["views"] if c["id"] == decision["view"])
if camera["projection"] != "ortho":
raise ValueError("Review ranges currently require orthographic projection")
rect = decision["rect_px"]
if (
len(rect) != 4
or not all(math.isfinite(x) for x in rect)
or not 0 <= rect[0] < rect[2] < camera["size"][0]
or not 0 <= rect[1] < rect[3] < camera["size"][1]
):
raise ValueError("Review rectangle outside image")
projections = [
p for p in labels["projections"][decision["view"]] if p["feature_id"] == feature["id"]
]
if len(projections) != 1:
raise ValueError("Ambiguous source path")
projection = projections[0]
points = feature["geometry"]["coordinates"]
uv = projection["uv"]
if len(points) != len(uv) or len(points) != len(projection["in_front"]):
raise ValueError("Projection/path identity mismatch")
ranges = []
for i, (a, b) in enumerate(zip(uv, uv[1:], strict=False)):
if not all(math.isfinite(v) for v in (*a, *b, *points[i], *points[i + 1])):
raise ValueError("Non-finite observation")
span = clipped_range(a, b, rect)
if span and projection["in_front"][i] and projection["in_front"][i + 1]:
ranges.append(dict(segment=i, t=span))
if not ranges:
raise ValueError("Review rectangle contains no source segment")
original = next((f for f in labels["original_element"] if f["id"] == feature["id"]), None)
preference = decision.get("preference")
if preference not in {None, "edited-better-than-original"}:
raise ValueError("Unknown ranking preference")
eligible = preference is not None and decision["evidence"] == "visible"
if preference and (
not eligible or original is None or original["geometry"] == feature["geometry"]
):
raise ValueError("Preference requires visible evidence and distinct source candidates")
return dict(
**decision,
geometry_sha256=digest(feature["geometry"]),
original_geometry_sha256=digest(original["geometry"]) if original else None,
camera_sha256=digest(camera),
path=0,
segment_ranges=ranges,
ranking_trial_eligible=eligible,
metric_ground_truth=False,
dense_segmentation_eligible=False,
background_targets=[],
complete_regions=[],
human_approved=False,
)
def check_control(control, train_world):
if (
control.get("schema_version") != "missioncore.boundary-control/v1"
or control.get("role") != "held-out-scene"
or control.get("world_sha256") == train_world
or control.get("training_eligible") is not False
or not control.get("windows")
or not control.get("frozen_utc")
):
raise ValueError("A distinct frozen control scene is required")
for key in ("world_sha256", "model_sha256"):
value = control.get(key, "")
if len(value) != 64 or any(c not in "0123456789abcdef" for c in value):
raise ValueError("Control source identity required")
def verify_pack(root):
root = Path(root)
manifest = read(root / "pack.json")
if manifest["schema_version"] != SCHEMA:
raise ValueError("Unsupported boundary pack")
actual = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}
if actual != set(manifest["files"]) | {"pack.json"}:
raise ValueError("Unexpected pack member")
total = 0
for name, spec in manifest["files"].items():
path = confined(root, name)
total += path.stat().st_size
if path.stat().st_size != spec["bytes"] or checksum(path) != spec["sha256"]:
raise ValueError("Pack member changed: " + name)
if total > LIMIT:
raise ValueError("Boundary pack exceeds bounded size")
decisions = read(root / "decisions.json")
check_control(read(root / "control.json"), manifest["source"]["world_sha256"])
records = []
for decision in decisions["records"]:
folder = Path("observations") / Path(decision["sample"]).parent
labels = read(confined(root, (folder / "labels.json").as_posix()))
cameras = read(confined(root, (folder / "cameras.json").as_posix()))
records.append(compile_record(labels, cameras, decision))
if records != read(root / "records.json"):
raise ValueError("Admission differs from reviewed evidence")
return dict(
sha256=checksum(root / "pack.json"),
bytes=total,
records=len(records),
ranking_pairs=sum(r["ranking_trial_eligible"] for r in records),
)
def build_pack(source, decisions, control, destination):
source, destination = Path(source), Path(destination)
if destination.exists() or destination.resolve().is_relative_to(source.resolve()):
raise ValueError("Use a new destination outside the immutable source dataset")
if checksum(source / "dataset.json") != decisions["dataset_sha256"]:
raise ValueError("Reviewed collection changed")
if not 1 <= len(decisions["records"]) <= 12:
raise ValueError("First review pack is bounded to twelve decisions")
if len({r["id"] for r in decisions["records"]}) != len(decisions["records"]):
raise ValueError("Duplicate review identity")
wanted = {d["sample"] for d in decisions["records"]}
# This verifies the complete immutable collection before selecting a small subset.
rows = {row["sample"]: row for row in review_samples(source) if row["sample"] in wanted}
if set(rows) != wanted:
raise ValueError("Unknown reviewed sample")
identity = next(iter(rows.values()))["source"]
if any(r["source"] != identity for r in rows.values()):
raise ValueError("Mixed source revisions")
check_control(control, identity["world_sha256"])
files = {"provenance/collection.json": source / "dataset.json"}
records = []
for d in decisions["records"]:
sample = confined(source, d["sample"])
folder = sample.parent
labels, cameras = read(folder / "labels.json"), read(folder / "cameras.json")
records.append(compile_record(labels, cameras, d))
shard = read(folder.parent / "dataset.json")
part = folder.parent.name
files[f"provenance/{part}.json"] = folder.parent / "dataset.json"
files["provenance/annotation.json"] = folder.parent / "annotation.json"
for name in read(sample)["members"] + [folder.name + "/sample.json"]:
member = confined(folder.parent, name)
if name not in shard["files"]:
raise ValueError("Unbound observation")
files[f"observations/{part}/{name}"] = member
if sum(p.stat().st_size for p in files.values()) > LIMIT - 1024**2:
raise ValueError("Selected observations exceed size budget")
destination.parent.mkdir(parents=True, exist_ok=True)
if shutil.disk_usage(destination.parent).free < 12 * 1024**3 + LIMIT:
raise ValueError("Worker disk reserve would be exceeded")
staging = destination.with_name(destination.name + ".partial")
staging.mkdir() # No overwrite of another attempt.
for name, origin in files.items():
target = staging / name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(origin, target)
if checksum(target) != checksum(origin):
raise ValueError("Observation copy changed")
for name, value in (
("decisions.json", decisions),
("control.json", control),
("records.json", records),
):
write(staging / name, value)
# A standalone stdlib reader travels with the pack.
for script in (Path(__file__), Path(__file__).with_name("dataset_store.py")):
shutil.copyfile(script, staging / script.name)
write(
staging / "pack.json",
dict(
schema_version=SCHEMA,
source=identity,
source_collection_sha256=decisions["dataset_sha256"],
usage="local-boundary-ranking-trial",
dense_segmentation_eligible=False,
files={
p.relative_to(staging).as_posix(): dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in sorted(staging.rglob("*"))
if p.is_file()
},
),
)
result = verify_pack(staging)
staging.rename(destination)
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", type=Path)
parser.add_argument("--decisions", type=Path)
parser.add_argument("--control", type=Path)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.output:
result = build_pack(args.root, read(args.decisions), read(args.control), args.output)
else:
result = verify_pack(args.root)
print(result)
@@ -0,0 +1,347 @@
"""GPU sample builder. Executed only inside the Worker renderer container."""
import time
from pathlib import Path
import numpy as np
from dataset_store import SCHEMA, checksum, read, write
from mapping import camera, prepare_crops, render
from PIL import Image
def contexts(package):
import copy
import math
from semantic_objects import members, object_operation, pivot
from semantic_vectors import knots, vector_operation
features = copy.deepcopy(package["model"]["features"])
def replay(op, origin="human-edit"):
nonlocal features
f = next((f for f in features if f["id"] == op.get("feature_id")), None)
curved = f and f["properties"].get("editor_curves", {}).get(str(op.get("path")))
if op["kind"] in ("place", "transform", "remove", "retemplate"):
features = object_operation(features, op, origin=origin)
elif (
op["kind"]
in (
"curve",
"delete_vertices",
"region",
"translate",
"translate_vertices",
"duplicate_vertex",
"duplicate_marking",
)
or curved
):
features = vector_operation(features, op, origin=origin)
else:
apply(f, op)
for row in package["revisions"][:-1]:
for op in row["operations"]:
replay(op, row.get("origin", "human-edit"))
before = copy.deepcopy(features)
affected = []
for op in package["revisions"][-1]["operations"]:
kind = op["kind"]
fid = op.get("feature_id")
anchors = []
if kind in ("delete_vertices", "translate", "translate_vertices") and op["vertices"]:
for v in op["vertices"]:
f = next(f for f in features if f["id"] == v["feature_id"])
anchors.append((f["id"], knots(f, v["path"])[v["index"]]["point"]))
elif kind == "region":
for a, b in zip(op["brush"], op["brush"][1:], strict=False):
count = max(1, math.ceil(math.dist(a[:2], b[:2]) / 6))
if count > 32:
raise ValueError("Region exceeds bounded observation windows")
anchors.extend(
(fid, [a[k] + j / count * (b[k] - a[k]) for k in range(3)])
for j in range(count)
)
elif kind == "place":
anchors = [(fid, op["position"])]
elif kind in ("transform", "remove", "translate", "duplicate_marking", "retemplate"):
anchors = [(fid, pivot(members(features, fid)))]
else:
f = next(f for f in features if f["id"] == fid)
anchors = [(fid, knots(f, op["path"])[op["index"]]["point"])]
replay(op, package["revisions"][-1].get("origin", "human-edit"))
for fid, old in anchors:
point = (
[v + op["delta"][k] for k, v in enumerate(old)]
if kind
in ("translate", "translate_vertices", "duplicate_vertex", "duplicate_marking")
else op.get("position", old)
)
if kind == "transform":
point = pivot(members(features, fid))
if math.dist(point, old) > 8:
raise ValueError("Edit displacement exceeds bounded observation window")
centre = [(a + b) / 2 for a, b in zip(old, point, strict=True)]
if kind == "duplicate_marking":
fid = op["new_feature_id"]
selected = next(f for f in features if f["id"] == fid)
group = selected["properties"].get("semantic_element_id", fid)
if not any(
previous == group and math.dist(c[:2], centre[:2]) < 3 for previous, c in affected
):
affected.append((group, centre))
if not 1 <= len(affected) <= 16:
raise ValueError("Split edits into at most 16 local observation windows")
return before, features, affected
def centres(package):
return contexts(package)[2]
def apply(feature, op):
g = feature["geometry"]
points = g["coordinates"][op["path"]] if g["type"] == "Polygon" else g["coordinates"]
i = op["index"]
if op["kind"] == "move":
points[i] = op["position"][:]
elif op["kind"] == "insert":
a, b = points[i : i + 2]
points.insert(i + 1, [a[k] + op["t"] * (b[k] - a[k]) for k in range(3)])
else:
points.pop(i)
if g["type"] == "Polygon":
points[-1] = points[0][:]
def build():
start = time.monotonic()
batch = read("/job/batch.json") if Path("/job/batch.json").exists() else None
out = Path("/output") / batch["name"] if batch else Path("/output")
out.mkdir(exist_ok=True)
envelope = read("/job/envelope.json")
source = read("/job/source.json")
package = envelope["annotation"]["package"]
from semantic_objects import members
if batch:
from final_snapshot import plan
snapshot = plan(package, batch["classes"])
if snapshot != read("/job/plan.json"):
raise ValueError("Snapshot plan changed")
windows = snapshot["windows"][batch["start"] : batch["stop"]]
if not 1 <= len(windows) <= 4:
raise ValueError("Invalid bounded shard")
previous = package["model"]["features"]
replayed = package["edited"]["features"]
affected = [(w["features"][0], w["center"]) for w in windows]
else:
previous, replayed, affected = contexts(package)
proposed = package["edited"]["features"]
if {f["id"]: f["geometry"] for f in replayed} != {f["id"]: f["geometry"] for f in proposed}:
raise ValueError("Replayed geometry differs from the admitted edit")
after = {f["id"]: f for f in proposed}
before = {f["id"]: f for f in previous}
samples = []
crop_jobs = [
dict(
source=source, bounds_xy=[[xyz[0] - 6, xyz[1] - 6], [xyz[0] + 6, xyz[1] + 6]], halo_m=15
)
for _, xyz in affected
]
crops = prepare_crops(crop_jobs) if batch else None
for i, (fid, xyz) in enumerate(affected):
name = windows[i]["id"] if batch else f"sample-{i:03d}"
folder = out / name
folder.mkdir(exist_ok=True)
x, y, z = xyz
specs = [
dict(
id="top",
projection="ortho",
size=[768, 768],
width_m=12,
eye=[x, y, z + 25],
target=[x, y, z],
up=[0, 1, 0],
),
dict(
id="oblique",
projection="pinhole",
size=[768, 768],
fov_degrees=65,
eye=[x, y - 7, z + 9],
target=[x, y, z],
up=[0, 0, 1],
),
]
job = dict(
source=source, bounds_xy=[[x - 6, y - 6], [x + 6, y + 6]], halo_m=15, views=specs
)
write(
folder / "cameras.json",
dict(
**job,
coordinates="scene-local XYZ, metres, Z up",
pixel_convention="OpenCV: pixel centres (column + 0.5, row + 0.5)",
depth_semantics="Gaussian expected centre depth; approximate, not LiDAR terrain",
height_source=(
"existing Z retained; new placements use unverified Gaussian visual pick"
),
),
)
if crops is None:
render(job, folder)
else:
crop = next(crops)
render(job, folder, prepared_rows=crop)
del crop
selected_ids = set(windows[i]["features"]) if batch else None
projections = {}
for spec in specs:
view, k = camera(spec)
g = np.load(folder / (spec["id"] + ".geometry.npz"))
observed = np.isfinite(g["depth"]) & (g["depth"] > 0) & (g["alpha"] >= 0.95)
Image.fromarray(observed.astype(np.uint8) * 255).save(
folder / (spec["id"] + ".observed.png")
)
# Unknown/unreviewed is ignored, never rasterized as background.
Image.fromarray(np.zeros((768, 768), np.uint8)).save(
folder / (spec["id"] + ".supervision.png")
)
group = after.get(fid, before.get(fid))["properties"].get("semantic_element_id")
elements = [
f
for f in proposed
if (selected_ids is not None and f["id"] in selected_ids)
or f["id"] == fid
or (group and f["properties"].get("semantic_element_id") == group)
or f["properties"].get("region_origin_id") == fid
]
paths = []
path_features = []
for element in elements:
geometry = element["geometry"]
rings = (
geometry["coordinates"]
if geometry["type"] == "Polygon"
else [geometry["coordinates"]]
)
paths.extend(rings)
path_features.extend([element["id"]] * len(rings))
pixels = []
for path, path_feature in zip(paths, path_features, strict=True):
local = np.asarray(path, dtype=np.float64) @ view[:3, :3].T + view[:3, 3]
uv = local[:, :2].copy()
if spec["projection"] == "pinhole":
uv /= np.maximum(local[:, 2, None], 1e-12)
uv = uv * np.diag(k)[:2] + k[:2, 2] - 0.5
pixels.append(
{
"feature_id": path_feature,
"uv": uv.tolist(),
"in_front": (local[:, 2] > 0).tolist(),
"inside": ((uv >= 0) & (uv < 768)).all(axis=1).tolist(),
}
)
projections[spec["id"]] = pixels
write(
folder / "labels.json",
dict(
original=before.get(fid),
original_element=[f for f in previous if f["id"] in selected_ids]
if batch
else members(previous, fid)
if fid in before
else [],
proposed_element=[f for f in proposed if f["id"] in selected_ids]
if batch
else [
f
for f in proposed
if f["id"] == fid
or f["properties"].get("semantic_element_id")
== after[fid]["properties"].get("semantic_element_id", fid)
or f["properties"].get("region_origin_id") == fid
],
proposed=after.get(fid),
projections=projections,
label_scope="final class geometry; no complete region or negative labels"
if batch
else "selected object only; no complete region or negative labels",
classes=batch["classes"] if batch else None,
window=windows[i] if batch else None,
origin=package["revisions"][-1].get("origin", "human-edit"),
review="unreviewed",
operations=package["revisions"][-1]["operations"],
),
)
member_files = [
p.relative_to(out).as_posix() for p in sorted(folder.iterdir()) if p.is_file()
]
write(
folder / "sample.json",
dict(
feature_id=fid,
members=member_files,
training_eligible=False,
complete_regions=[],
split_group=package["world_sha256"],
revision=package["revision"],
),
)
samples.append(name + "/sample.json")
write(out / "annotation.json", envelope["annotation"])
(out / "dataset_reader.py").write_bytes(
Path(__file__).with_name("dataset_store.py").read_bytes()
)
(out / "DATASET.md").write_text(
"""# Mission Core semantic correction observations
Portable review dataset, not approved training ground truth. RGB is rendered
from the pinned Gaussian source without annotation overlays. Vectors retain
original coordinates/height; cameras and pixel projections are explicit.
Use dataset_reader.review_samples(root) for review: active_candidates and
rejected_history are separate; approved_targets and background_targets remain
empty. proposed_element retains history and must never be used as a positive
label list. Even editor review_status=accepted is not per-view training approval.
The algorithm baseline and proposed edits remain separate. No unreviewed
object/region is negative background. Supervision masks are all zero (ignore).
Observed masks describe opaque Gaussian pixels, not semantic label validity.
Human approval and geometric surface-support review are still required before
supervised training. Adjacent views/revisions of one world share split_group.
No paths or URLs to Core are needed to read these samples. This does not bundle
the multi-GB source scene or claim survey-grade depth or a trained model.
""",
encoding="utf-8",
)
files = {
p.relative_to(out).as_posix(): dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in sorted(out.rglob("*"))
if p.is_file() and p.name != "dataset.json"
}
write(
out / "dataset.json",
dict(
schema_version=SCHEMA,
files=files,
samples=samples,
training_eligible=False,
review="unreviewed",
source=source,
world_sha256=package["world_sha256"],
model_sha256=package["model_sha256"],
annotation_sha256=envelope["annotation"]["sha256"],
revision=package["revision"],
renderer_image=envelope["renderer_image"],
builder_sha256=checksum(__file__),
split_group=package["world_sha256"],
seconds=time.monotonic() - start,
),
)
if __name__ == "__main__":
build()
@@ -0,0 +1,334 @@
"""Uniform quarter-turn feature pooling; offline admission only, never publishes maps."""
import json
import sys
from pathlib import Path
import cv2
import numpy as np
from grouped_selection_study import objective, select, transfer_gate
from object_assembly_study import measured
from object_proposal_study import masks, save_new, sha, timestamp
from paint_hypothesis_study import probability
from PIL import Image
from shapely.geometry import shape
from visual_admission_study import (
check_inputs,
evaluation,
fit_head,
fractional_weights,
predict,
rank,
)
VARIANTS = ["single512", "c4_512", "c4_fused"]
def c4_mean(orbit):
"""Uniform finite-group average; no label, score, or angle-based selection."""
if orbit.ndim != 3 or orbit.shape[0] != 4 or not np.isfinite(orbit).all():
raise ValueError("Expected four finite descriptor arrays")
return orbit.astype(np.float64).mean(axis=0).astype(np.float32)
def supports(candidates):
inside = [masks(shape(c["geometry"])) for c in candidates]
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (23, 23))
rings = [(cv2.dilate(m.astype(np.uint8), kernel) > 0) & ~m for m in inside]
return inside + rings
def descriptor_orbit(rgb, support, model, processor):
import torch
if not support:
return np.empty((4, 0, 512), dtype=np.float32)
n = len(support) // 2
result = []
for k in range(4):
tensors = processor(
images=Image.fromarray(np.rot90(rgb, k).copy()),
return_tensors="pt",
size={"height": 512, "width": 512},
).to("cuda")
assert tuple(tensors["pixel_values"].shape[-2:]) == (512, 512)
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
output = model(**tensors, output_hidden_states=True)
feat = torch.rot90(output.pixel_decoder_last_hidden_state[0].float(), -k, [-2, -1])
assert tuple(feat.shape) == (256, 128, 128), feat.shape
weights = np.asarray([fractional_weights(m, feat.shape[-2:]).ravel() for m in support])
pooled = (torch.as_tensor(weights, device="cuda") @ feat.flatten(1).T).cpu().numpy()
result.append(np.concatenate([pooled[:n], pooled[n:]], axis=1))
del output, tensors, feat
return np.asarray(result)
def extract(root):
import torch
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
torch.set_num_threads(3)
cv2.setNumThreads(3)
check_inputs(root)
for name, h in json.loads((root / "model-inventory.json").read_text())["files"].items():
assert sha(Path("/model") / name) == h, name
processor = AutoImageProcessor.from_pretrained("/model", local_files_only=True)
model = (
Mask2FormerForUniversalSegmentation.from_pretrained("/model", local_files_only=True)
.eval()
.cuda()
)
for p in model.parameters():
p.requires_grad_(False)
records = json.loads((root / "candidates.json").read_text())["records"]
folder = root / "features"
folder.mkdir(exist_ok=False)
receipts = []
for i, rec in enumerate(records):
rgb_path = root / "data" / (rec["id"] + ".png")
rgb = np.asarray(Image.open(rgb_path).convert("RGB"))
cs = rec["variants"]["retained"]
support = supports(cs)
orbit = descriptor_orbit(rgb, support, model, processor)
mean = c4_mean(orbit)
checks = []
# Predeclared regression cases: actual independent rotated-input inference,
# beyond merely permuting already computed descriptors.
if rec["id"] in ["pokrovka-2", "pokrovka-visual-2"]:
for turn in [1, 2, 3]:
rotated = descriptor_orbit(
np.rot90(rgb, turn).copy(),
[np.rot90(m, turn).copy() for m in support],
model,
processor,
)
checks.append(c4_mean(rotated))
path = folder / (rec["id"] + ".npz")
np.savez_compressed(
path,
orbit=orbit,
pooled=mean,
rotated=np.asarray(checks),
ids=np.asarray([c["id"] for c in cs]),
)
receipts.append(
dict(id=rec["id"], sha256=sha(path), rgb_sha256=sha(rgb_path), candidates=len(cs))
)
print(json.dumps(dict(completed=i + 1, total=len(records))), flush=True)
save_new(
root / "features.json",
dict(
**timestamp(),
source_sha256=sha(Path(__file__)),
candidates_sha256=sha(root / "candidates.json"),
records=receipts,
max_gpu_bytes=torch.cuda.max_memory_allocated(),
),
)
def loaded(root):
records = json.loads((root / "candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
receipt = json.loads((root / "features.json").read_text())
assert receipt["source_sha256"] == sha(Path(__file__))
assert receipt["candidates_sha256"] == sha(root / "candidates.json")
data = {}
for rec in records:
rid = rec["id"]
path = root / "features" / (rid + ".npz")
assert sha(path) == next(a["sha256"] for a in receipt["records"] if a["id"] == rid)
z = np.load(path)
cs = rec["variants"]["retained"]
assert z["ids"].tolist() == [c["id"] for c in cs]
hand = np.asarray([c["features"][:14] for c in cs]).reshape(-1, 14)
assert np.array_equal(c4_mean(z["orbit"]), z["pooled"])
data[rid] = dict(
handcrafted14=hand,
single512=z["orbit"][0],
c4_512=z["pooled"],
c4_fused=np.concatenate([hand, z["pooled"]], axis=1),
)
return records, review, data
def train(root):
check_inputs(root)
records, review, data = loaded(root)
dev = [r for r in records if r["split"] == "development"]
assert not ({r["street"] for r in dev} & {"pokrovka", "sadovaya-karetnaya"})
protocol = json.loads((root / "protocol.json").read_text())
ceiling = {r["id"]: measured(r["variants"]["retained"], review[r["id"]]) for r in dev}
variants = {}
for variant in VARIANTS:
experiments = []
for l2 in protocol["regularization"]:
scores, folds = {}, {}
for street in sorted({r["street"] for r in dev}):
training = [r for r in dev if r["street"] != street]
validation = [r for r in dev if r["street"] == street]
model = fit_head(training, review, data, variant, l2)
scores.update(predict(validation, data, variant, model))
folds[street] = dict(
training_streets=sorted({r["street"] for r in training}), model=model
)
sweep = []
for threshold in protocol["thresholds"]:
result = evaluation(dev, review, scores, threshold)
sweep.append(
dict(
threshold=threshold,
**result["summary"],
**objective(result["rows"], ceiling),
)
)
selected = select(sweep)
experiments.append(dict(l2=l2, selected=selected, folds=folds, sweep=sweep))
feasible = [e for e in experiments if e["selected"] is not None]
best = max(feasible, key=lambda e: (*rank(e["selected"]), e["l2"])) if feasible else None
model = fit_head(dev, review, data, variant, best["l2"]) if best else None
variants[variant] = dict(
selected=best["selected"] if best else None,
l2=best["l2"] if best else None,
model=model,
experiments=experiments,
)
print(
json.dumps(
dict(
variant=variant,
selected=variants[variant]["selected"],
l2=variants[variant]["l2"],
)
),
flush=True,
)
choices = [v for v in VARIANTS if variants[v]["selected"] is not None]
chosen = (
max(choices, key=lambda v: (*rank(variants[v]["selected"]), -VARIANTS.index(v)))
if choices
else None
)
save_new(
root / "models-frozen.json",
dict(
**timestamp(),
chosen=chosen,
variants=variants,
source_sha256=sha(Path(__file__)),
hashes={
n: sha(root / n)
for n in [
"protocol.json",
"review-frozen.json",
"inputs.json",
"input-hashes.json",
"candidates.json",
"features.json",
"model-inventory.json",
]
},
),
)
print("chosen", chosen)
def evaluate(root):
check_inputs(root)
records, review, data = loaded(root)
frozen = json.loads((root / "models-frozen.json").read_text())
assert frozen["source_sha256"] == sha(Path(__file__))
for n, h in frozen["hashes"].items():
assert sha(root / n) == h, n
old = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]["model"]
results = {}
for cohort in ["regression", "heldout"]:
rows = [a for a in records if a["split"] == cohort]
baseline = evaluation(rows, review, predict(rows, data, "handcrafted14", old), 0.15)
variants = {}
for variant, arm in frozen["variants"].items():
if arm["selected"] is None:
continue
out = evaluation(
rows,
review,
predict(rows, data, variant, arm["model"]),
arm["selected"]["threshold"],
)
variants[variant] = dict(**out, gate_vs_frozen=transfer_gate(baseline, out))
for out in variants.values():
out["gate_vs_single"] = (
transfer_gate(variants["single512"], out) if "single512" in variants else None
)
ceiling = evaluation(
rows, review, {a["id"]: [1.0] * len(a["variants"]["retained"]) for a in rows}, 0.0
)
results[cohort] = dict(baseline=baseline, variants=variants, ceiling=ceiling)
checks = []
for rec in records:
z = np.load(root / "features" / (rec["id"] + ".npz"))
assert all(
np.array_equal(c4_mean(np.roll(z["orbit"], k, axis=0)), z["pooled"]) for k in range(4)
)
for turn, rotated in enumerate(z["rotated"], 1):
for variant in ["c4_512", "c4_fused"]:
arm = frozen["variants"][variant]
if arm["selected"] is None:
continue
x = (
rotated
if variant == "c4_512"
else np.concatenate([data[rec["id"]]["handcrafted14"], rotated], axis=1)
)
a = probability(data[rec["id"]][variant], arm["model"])
b = probability(x, arm["model"])
threshold = arm["selected"]["threshold"]
error = float(np.max(np.abs(a - b))) if len(a) else 0.0
checks.append(
dict(
id=rec["id"],
turn=turn,
variant=variant,
descriptor_max_error=float(np.max(np.abs(rotated - z["pooled"]))),
score_max_error=error,
accepted_identical=bool(np.array_equal(a >= threshold, b >= threshold)),
passed=error <= 1e-5
and bool(np.array_equal(a >= threshold, b >= threshold)),
)
)
save_new(
root / "results.json",
dict(
**timestamp(),
chosen=frozen["chosen"],
models_sha256=sha(root / "models-frozen.json"),
cohorts=results,
invariance=dict(
cyclic_permutations_bitexact=len(records),
independently_recomputed=checks,
passed=all(x["passed"] for x in checks),
),
),
)
print(
json.dumps(
{
k: dict(
baseline=v["baseline"]["summary"],
variants={
n: dict(**a["summary"], gate=a["gate_vs_frozen"])
for n, a in v["variants"].items()
},
ceiling=v["ceiling"]["summary"],
)
for k, v in results.items()
}
)
)
print("invariance", checks)
if __name__ == "__main__":
{"extract": extract, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
@@ -0,0 +1,172 @@
"""TRAIN-only visual condition sidecars over immutable observed-paint targets.
Tags describe raw evidence quality, not annotation age or an inference rule.
Region masks only select already reviewed class-compatible pixels. Unreviewed
candidate windows remain unsupervised; no target is inferred from a tag.
"""
import hashlib
import math
import numpy as np
from PIL import Image, ImageDraw
SCHEMA = "missioncore.semantic-condition-review/v1"
TAGS = {
"paint_clear": 1,
"paint_weak_visible": 1,
"background_asphalt": 0,
"background_paving": 0,
"background_utility_cover": 0,
"background_curb": 0,
}
FAMILIES = {"line", "crossing", "symbol", "hatching", "surface"}
def raster(polygon, size):
"""Convex review polygon in the explicit 512-square review coordinate frame."""
if not isinstance(polygon, list) or not 3 <= len(polygon) <= 32:
raise ValueError("Bounded convex polygon required")
if any(
not isinstance(p, list)
or len(p) != 2
or any(type(v) not in (int, float) or not math.isfinite(v) or not 0 <= v <= 512 for v in p)
for p in polygon
):
raise ValueError("Invalid review coordinates")
# Convex, consistently wound polygons have no ambiguous self-intersections.
signs = []
for i, a in enumerate(polygon):
b, c = polygon[(i + 1) % len(polygon)], polygon[(i + 2) % len(polygon)]
cross = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
if cross:
signs.append(cross > 0)
area = sum(
a[0] * b[1] - b[0] * a[1] for a, b in zip(polygon, polygon[1:] + polygon[:1], strict=True)
)
if (
not signs
or len(set(signs)) != 1
or not area
or len(set(map(tuple, polygon))) != len(polygon)
):
raise ValueError("Degenerate or nonconvex review polygon")
# Also require every vertex to be on the same side of every edge: rejects stars.
for a, b in zip(polygon, polygon[1:] + polygon[:1], strict=True):
side = [(b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) for c in polygon]
if min(side) < 0 < max(side):
raise ValueError("Self-intersecting review polygon")
out = Image.new("1", tuple(size))
points = [(math.floor(x * size[0] / 512), math.floor(y * size[1] / 512)) for x, y in polygon]
ImageDraw.Draw(out).polygon(points, fill=1)
return np.asarray(out, dtype=bool)
def compile_record(sample, review, target):
if sample["split"] != "train" or review["name"] != sample["name"]:
raise ValueError("Conditions may only annotate the pinned TRAIN sample")
if target.dtype != np.uint8 or target.ndim != 2 or target.size > 4 * 1024**2:
raise ValueError("Bounded uint8 target required")
if list(target.shape[::-1]) != sample["size"] or not np.isin(target, [0, 1, 255]).all():
raise ValueError("Invalid target shape/classes")
expected = sample.get("target_sha256")
if sample["kind"] not in {"existing", "candidate"}:
raise ValueError("Unsupported sample kind")
if sample["kind"] == "existing" and (
not isinstance(expected, str)
or len(expected) != 64
or any(c not in "0123456789abcdef" for c in expected)
):
raise ValueError("Existing targets require an explicit SHA-256 pin")
actual = hashlib.sha256(target.tobytes()).hexdigest()
if expected is not None and actual != expected:
raise ValueError("Pinned target changed")
if sample["kind"] == "candidate" and (expected is not None or np.any(target != 255)):
raise ValueError("Unadmitted candidates cannot acquire targets from conditions")
if review["target_sha256"] != expected or review["input_sha256"] != sample["rgb_sha256"]:
raise ValueError("Review input/target identity mismatch")
regions = review["regions"]
if not isinstance(regions, list) or len(regions) > 64:
raise ValueError("Region budget exceeded")
occupied = np.zeros(target.shape, dtype=bool)
counts, masks, ids = [], {}, set()
for r in regions:
if not isinstance(r["id"], str) or not r["id"] or r["id"] in ids:
raise ValueError("Unique region identities required")
ids.add(r["id"])
if r["tag"] not in TAGS or r["family"] not in FAMILIES or not r.get("reason", "").strip():
raise ValueError("Explicit supported condition and review reason required")
if (r["family"] == "surface") != (TAGS[r["tag"]] == 0):
raise ValueError("Condition class/family mismatch")
roi = raster(r["polygon"], sample["size"])
mask = roi & (target == TAGS[r["tag"]])
if np.any(mask & occupied):
raise ValueError("Overlapping reviewed condition pixels")
occupied |= mask
masks[r["id"]] = mask
counts.append(
dict(
id=r["id"],
tag=r["tag"],
family=r["family"],
reviewed_pixels=int(mask.sum()),
region_pixels=int(roi.sum()),
unknown_region_pixels=int((roi & (target == 255)).sum()),
)
)
return dict(
name=sample["name"],
group=sample["group"],
kind=sample["kind"],
regions=counts,
untagged_paint=int(((target == 1) & ~occupied).sum()),
untagged_background=int(((target == 0) & ~occupied).sum()),
target_sha256=actual,
targets_changed=False,
), masks
def footprint(camera):
"""Axis-aligned top-view footprint in its source-local physical coordinate frame."""
if camera["projection"] != "ortho":
raise ValueError("Orthographic footprint required")
w, h = camera["size"]
if "view_matrix" not in camera:
eye, target = camera["eye"], camera["target"]
if eye[:2] != target[:2] or camera["up"] != [0, 1, 0] or eye[2] <= target[2]:
raise ValueError("Unsupported top camera")
half = camera["width_m"] / 2
return [
target[0] - half,
target[1] - half * h / w,
target[0] + half,
target[1] + half * h / w,
]
v, k = np.asarray(camera["view_matrix"], float), np.asarray(camera["intrinsics"], float)
if (
v.shape != (4, 4)
or k.shape != (3, 3)
or not np.isfinite(v).all()
or not np.isfinite(k).all()
):
raise ValueError("Invalid camera matrices")
if not np.allclose(v[:2, 2], 0) or not np.allclose([v[0, 1], v[1, 0], k[0, 1], k[1, 0]], 0):
raise ValueError("Only axis-aligned top cameras supported")
if min(k[0, 0], k[1, 1]) <= 0 or min(abs(v[0, 0]), abs(v[1, 1])) == 0:
raise ValueError("Degenerate camera")
xy = [
np.linalg.solve(v[:2, :2], (np.array([u, t]) - k[:2, 2]) / np.diag(k)[:2] - v[:2, 3])
for u, t in [(0, 0), (w, h)]
]
return [float(min(a)) for a in zip(*xy, strict=True)] + [
float(max(a)) for a in zip(*xy, strict=True)
]
def overlap_fraction(a, b):
intersection = max(0, min(a[2], b[2]) - max(a[0], b[0])) * max(
0, min(a[3], b[3]) - max(a[1], b[1])
)
if intersection < 1e-8:
return 0.0
return intersection / min((a[2] - a[0]) * (a[3] - a[1]), (b[2] - b[0]) * (b[3] - b[1]))
@@ -0,0 +1,71 @@
"""Admit reviewed context negatives while preserving per-street class mass."""
import numpy as np
def prepare_context(records, weights, additions):
names = [r["name"] for r in records]
if (
not names
or len(set(names)) != len(names)
or set(names) != set(weights)
or set(names) != set(additions)
):
raise ValueError("Matching unique TRAIN records, weights and additions required")
out, result = [], {}
for r in records:
name = r["name"]
t, w, a = r["target"], weights[name], additions[name]
if (
r["split"] != "train"
or t.dtype != np.uint8
or t.ndim != 2
or not np.isin(t, [0, 1, 255]).all()
or w.shape != t.shape
or w.dtype.kind != "f"
or not np.isfinite(w).all()
or np.any(w < 0)
or np.any(w[t == 255] != 0)
or a.dtype != bool
or a.shape != t.shape
or np.any(a & (t != 255))
):
raise ValueError("Only unknown pixels may become reviewed TRAIN background")
target = t.copy()
target[a] = 0
out.append(dict(r, target=target, context_added=a.copy()))
result[name] = w.copy()
for group in sorted({r["group"] for r in records}):
before = [r for r in records if r["group"] == group]
after = [r for r in out if r["group"] == group]
if not any(additions[r["name"]].any() for r in before):
continue
mass = sum(
float(weights[r["name"]][r["target"] == 0].sum(dtype=np.float64)) for r in before
)
present = [r for r in after if np.any(r["target"] == 0)]
if mass <= 0 or not present:
raise ValueError("Existing reviewed street background mass required")
for r in present:
mask = r["target"] == 0
result[r["name"]][mask] = mass / len(present) / int(mask.sum())
actual = sum(
float(result[r["name"]][r["target"] == 0].sum(dtype=np.float64)) for r in after
)
if not np.isclose(actual, mass, atol=1e-8, rtol=1e-6):
raise ValueError("Street background mass changed")
return out, result
def context_gate(old, new, control):
"""Frozen coverage screen; no thresholds or model selection after fitting."""
checks = {
"halve_context_fp": new["context_fp"] <= 0.5 * old["context_fp"],
"reduce_bce": new["bce"] < old["bce"],
"beat_control_bce": new["bce"] < control["bce"],
}
for key in ["original_fp", "prior_added_fp", "weak_fn", "clear_fn"]:
checks["retain_" + key] = new[key] <= old[key]
for key in ["background_fp", "weak_fn", "clear_fn"]:
checks["control_" + key] = new[key] <= control[key]
return {"passed": all(checks.values()), "checks": checks}
@@ -0,0 +1,381 @@
"""Frozen Worker corpus index over existing portable semantic review datasets.
Only metadata is indexed. Samples keep all views, cameras and labels together;
no image copy, model fitting or automatic training admission occurs here.
Groups are explicit experiment/source-lineage assignments; one unnamed scan
may have its own group. This reader performs no geographic or cross-scan
matching and requires no GPS/overlap proof. Group IDs do not prove independence.
"""
import argparse
import hashlib
import json
import shutil
import sqlite3
import tempfile
from contextlib import contextmanager
from pathlib import Path
from dataset_store import checksum, confined, digest, review_labels, sample_records
SCHEMA = "missioncore.semantic-corpus/v1"
PLAN_SCHEMA = "missioncore.semantic-corpus-plan/v1"
SPLITS = {"train", "validation", "test", "regression"}
MAX_METADATA = 8 * 1024**2
MAX_SAMPLE_METADATA = 24 * 1024**2
MAX_DATASETS = 2048
MAX_REFERENCE = 256 * 1024
MAX_BATCH_BYTES = 2 * 1024**2
MAX_INDEX_BYTES = 256 * 1024**2
def load_json(path, limit=MAX_METADATA):
with Path(path).open("rb") as stream:
raw = stream.read(limit + 1)
if len(raw) > limit:
raise ValueError("Corpus metadata budget exceeded")
return json.loads(raw)
def sha256(value):
if (
not isinstance(value, str)
or len(value) != 64
or any(c not in "0123456789abcdef" for c in value)
):
raise ValueError("Invalid SHA-256 identity")
return value
def assignments(plan):
if plan.get("schema_version") != PLAN_SCHEMA:
raise ValueError("Unsupported corpus plan")
result, groups = {}, set()
for group in plan["groups"]:
name, split = group["id"], group["split"]
if (
not isinstance(name, str)
or not name
or len(name) > 128
or name in groups
or split not in SPLITS
):
raise ValueError("Invalid or duplicate physical group")
groups.add(name)
if not group["worlds"]:
raise ValueError("Empty physical group")
for world in group["worlds"]:
sha256(world)
if world in result:
raise ValueError("One source world assigned to multiple physical groups")
result[world] = dict(physical_group=name, split=split)
if not 1 <= len(result) <= MAX_DATASETS:
raise ValueError("Corpus source-group budget exceeded")
return dict(sorted(result.items()))
def checked_file(root, name, spec):
path = confined(Path(root), name)
if path.stat().st_size != spec["bytes"] or checksum(path) != spec["sha256"]:
raise ValueError("Pinned corpus member changed: " + name)
return path
def build(store, plan, destination):
"""Build beside datasets; publish corpus.json last as the completion marker."""
store = Path(store).resolve()
destination = confined(store, destination)
if destination.exists():
raise ValueError("Corpus version already exists")
policy = assignments(plan)
datasets = sorted(plan["datasets"], key=lambda d: d["path"])
if not 1 <= len(datasets) <= MAX_DATASETS:
raise ValueError("Corpus dataset budget exceeded")
identities, paths = set(), set()
for entry in datasets:
sha256(entry["sha256"])
path = confined(store, entry["path"])
if path in paths or entry["sha256"] in identities:
raise ValueError("Duplicate corpus dataset")
paths.add(path)
identities.add(entry["sha256"])
if destination.is_relative_to(path) or path.is_relative_to(destination):
raise ValueError("Corpus output overlaps immutable input")
if checksum(path / "dataset.json") != entry["sha256"]:
raise ValueError("Pinned dataset manifest changed")
parent = plan.get("parent")
if parent:
with Corpus(store, parent["path"], parent["sha256"]) as prior:
if any(policy.get(w) != a for w, a in prior.manifest["assignments"].items()):
raise ValueError("Growth cannot change prior physical splits")
previous = {(d["path"], d["sha256"]) for d in prior.manifest["datasets"]}
if not previous <= {(d["path"], d["sha256"]) for d in datasets}:
raise ValueError("Growth cannot silently discard prior datasets")
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".corpus-", dir=destination.parent) as temporary:
staging = Path(temporary) / "published"
staging.mkdir()
db = sqlite3.connect(staging / "index.sqlite3")
try:
page_size = db.execute("PRAGMA page_size").fetchone()[0]
db.execute(f"PRAGMA max_page_count={max(1, MAX_INDEX_BYTES // page_size)}")
db.executescript("""
CREATE TABLE samples (
id TEXT PRIMARY KEY, dataset TEXT NOT NULL, physical_group TEXT NOT NULL,
split TEXT NOT NULL, reference TEXT NOT NULL
);
CREATE INDEX by_split ON samples(split, physical_group, id);
""")
split_groups = {}
for entry in datasets:
root = confined(store, entry["path"])
count = 0
for row in sample_records(root):
source = row["source"]
assignment = policy.get(source["world_sha256"])
if assignment is None:
raise ValueError("Missing physical-area assignment for source")
# Preserve explicitly declared producer lineage without inferring
# geographic relationships between different scans.
previous = split_groups.setdefault(source["split_group"], assignment)
if previous != assignment:
raise ValueError("Related source split_group crosses physical groups")
identity = digest([entry["sha256"], row["sample"]])
reference = dict(
id=identity,
dataset=entry["path"],
dataset_sha256=entry["sha256"],
**assignment,
**row,
training_eligible=False,
)
encoded = json.dumps(reference, sort_keys=True, allow_nan=False)
if len(encoded.encode()) > MAX_REFERENCE:
raise ValueError("Sample reference budget exceeded")
db.execute(
"INSERT INTO samples VALUES (?,?,?,?,?)",
(
identity,
entry["path"],
assignment["physical_group"],
assignment["split"],
encoded,
),
)
count += 1
if not count:
raise ValueError("Empty corpus dataset")
if checksum(root / "dataset.json") != entry["sha256"]:
raise ValueError("Dataset changed during indexing")
db.commit()
counts = {
s: n for s, n in db.execute("SELECT split,count(*) FROM samples GROUP BY split")
}
except sqlite3.OperationalError as exc:
if exc.sqlite_errorcode == sqlite3.SQLITE_FULL:
raise ValueError("Corpus index or disk capacity exhausted") from exc
raise
finally:
db.close()
for name in ("corpus_store.py", "dataset_store.py"):
shutil.copyfile(Path(__file__).with_name(name), staging / name)
manifest = dict(
schema_version=SCHEMA,
plan_sha256=digest(plan),
assignments=policy,
datasets=datasets,
parent=parent,
sample_counts=counts,
training_eligible=False,
files={
p.name: dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in sorted(staging.iterdir())
},
)
encoded = json.dumps(manifest, sort_keys=True, indent=2, allow_nan=False)
if len(encoded.encode()) > MAX_METADATA:
raise ValueError("Corpus manifest budget exceeded")
(staging / "corpus.json").write_text(encoded)
# Never overwrite a published corpus, including an empty existing folder.
destination.mkdir()
try:
for name in manifest["files"]:
(staging / name).replace(destination / name)
(staging / "corpus.json").replace(destination / "corpus.json")
except BaseException:
shutil.rmtree(destination)
raise
return dict(
path=destination.relative_to(store).as_posix(),
sha256=checksum(destination / "corpus.json"),
sample_counts=counts,
)
class Corpus:
"""Read-only, pinned index with bounded metadata batches and explicit media reads."""
def __init__(self, store, corpus, expected_sha256):
self.store = Path(store).resolve()
self.root = confined(self.store, corpus)
if checksum(self.root / "corpus.json") != sha256(expected_sha256):
raise ValueError("Pinned corpus manifest changed")
self.sha256 = expected_sha256
self.manifest = load_json(self.root / "corpus.json")
if (
self.manifest.get("schema_version") != SCHEMA
or self.manifest.get("training_eligible") is not False
):
raise ValueError("Unsupported corpus review policy")
for name, spec in self.manifest["files"].items():
checked_file(self.root, name, spec)
index = confined(self.root, "index.sqlite3")
if "index.sqlite3" not in self.manifest["files"]:
raise ValueError("Unbound corpus index")
self.db = sqlite3.connect(index.as_uri() + "?mode=ro&immutable=1", uri=True)
self.db.execute("PRAGMA query_only=ON")
self.db.execute("PRAGMA cache_size=-1024")
self.db.execute("PRAGMA temp_store=FILE")
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
self.db.close()
def batches(self, split, batch_size=8, *, physical_group=None):
"""Yield metadata only; caller explicitly opens the current sample's media.
This is deterministic traversal, not a class-balanced training sampler.
Batch size limits references in this reader, not objects retained by a caller.
"""
if split not in SPLITS or type(batch_size) is not int or not 1 <= batch_size <= 128:
raise ValueError("Invalid corpus split or batch size")
sql = "SELECT reference FROM samples WHERE split=?"
params = [split]
if physical_group is not None:
sql += " AND physical_group=?"
params.append(physical_group)
sql += " ORDER BY physical_group,id"
cursor = self.db.execute(sql, params)
try:
batch, size = [], 0
for (encoded,) in cursor:
length = len(encoded.encode())
if length > min(MAX_REFERENCE, MAX_BATCH_BYTES):
raise ValueError("Sample reference budget exceeded")
if batch and (len(batch) >= batch_size or size + length > MAX_BATCH_BYTES):
yield batch
batch, size = [], 0
batch.append(json.loads(encoded))
size += length
if batch:
yield batch
finally:
cursor.close()
def reference(self, sample_id):
"""Resolve one bound sample without enumerating other samples or media."""
row = self.db.execute(
"SELECT reference FROM samples WHERE id=?", (sha256(sample_id),)
).fetchone()
if row is None:
raise ValueError("Unknown corpus sample")
return json.loads(row[0])
def _reference(self, reference):
row = self.db.execute(
"SELECT reference FROM samples WHERE id=?", (reference["id"],)
).fetchone()
if row is None or json.loads(row[0]) != reference:
raise ValueError("Reference does not belong to this pinned corpus")
root = confined(self.store, reference["dataset"])
if checksum(root / "dataset.json") != reference["dataset_sha256"]:
raise ValueError("Pinned dataset manifest changed")
return root
def review(self, reference):
"""Load one sample's metadata/labels; no automatic training targets."""
root = self._reference(reference)
sample = load_json(
checked_file(root, reference["sample"], reference["sample_spec"]), MAX_SAMPLE_METADATA
)
labels = load_json(
checked_file(root, reference["labels"], reference["members"][reference["labels"]]),
MAX_SAMPLE_METADATA,
)
return dict(reference=reference, context=sample, **review_labels(labels))
@contextmanager
def open_member(self, reference, name):
"""Verify and stream one declared view/camera/mask; never scan the corpus."""
root = self._reference(reference)
if name not in reference["members"]:
raise ValueError("Unbound sample member")
path = confined(root, name)
spec = reference["members"][name]
with path.open("rb") as stream:
length = stream.seek(0, 2)
stream.seek(0)
actual = hashlib.file_digest(stream, "sha256").hexdigest()
if length != spec["bytes"] or actual != spec["sha256"]:
raise ValueError("Pinned corpus member changed: " + name)
stream.seek(0)
yield stream
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
make = commands.add_parser(
"build", help="Freeze an explicit multi-area review corpus on Worker"
)
make.add_argument("store", type=Path)
make.add_argument("plan", type=Path)
make.add_argument("destination", help="New corpus path relative to the portable store")
inspect = commands.add_parser("inspect", help="Read bounded metadata from a pinned corpus")
inspect.add_argument("store", type=Path)
inspect.add_argument("corpus")
inspect.add_argument("sha256")
inspect.add_argument("--split", choices=sorted(SPLITS), required=True)
inspect.add_argument("--limit", type=int, default=8)
args = parser.parse_args()
if args.command == "build":
print(json.dumps(build(args.store, load_json(args.plan), args.destination)))
else:
if not 1 <= args.limit <= 128:
raise ValueError("Inspection limit must be from 1 to 128")
with Corpus(args.store, args.corpus, args.sha256) as corpus:
batches = corpus.batches(args.split, batch_size=args.limit)
try:
rows = next(batches, [])
finally:
batches.close()
print(
json.dumps(
dict(
samples=[
{
k: r[k]
for k in (
"id",
"dataset",
"sample",
"physical_group",
"split",
"training_eligible",
)
}
for r in rows
],
total=corpus.manifest["sample_counts"].get(args.split, 0),
)
)
)
if __name__ == "__main__":
main()
@@ -0,0 +1,345 @@
"""Controlled label-coverage experiment. Offline; no production map writes."""
import json
import sys
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np
from c4_admission_study import loaded
from grouped_selection_study import objective, select, transfer_gate
from object_assembly_study import measured
from object_proposal_study import labels, overlap, save_new, sha, timestamp
from paint_hypothesis_study import fit_classifier
from shapely.geometry import shape
from shapely.ops import unary_union
from visual_admission_study import check_inputs, evaluation, fit_head, predict, rank
def expanded_labels(candidates, reviewed):
result = labels(candidates, reviewed)
background = unary_union([shape(g) for g in reviewed.get("complete_background", [])])
for i, c in enumerate(candidates):
p = shape(c["geometry"])
if (
result[i] < 0
and not background.is_empty
and p.area > 0
and p.intersection(background).area / p.area >= 0.9
):
result[i] = 0
return result
def training_records(records, arm):
return [
r
for r in records
if r["split"] == "development" and (arm == "expanded" or "-coverage-" not in r["id"])
]
def fit(records, review, data, l2, expanded):
if not expanded:
return fit_head(records, review, data, "c4_512", l2)
x, y = [], []
for r in records:
ls = expanded_labels(r["variants"]["retained"], review[r["id"]])
x.append(data[r["id"]]["c4_512"][ls >= 0])
y.append(ls[ls >= 0])
xx, yy = np.concatenate(x), np.concatenate(y)
if min(np.sum(yy == 0), np.sum(yy == 1)) < 2:
raise ValueError("Insufficient reviewed classes")
model = fit_classifier(xx, yy, l2, 500)
model.update(positive=int(sum(yy == 1)), negative=int(sum(yy == 0)))
return model
def partial_gate(baseline, candidate):
found = {
o["id"]
for r in candidate["rows"]
for o in r["clipped_components"]["objects"]
if o["matched"]
}
return [
o["id"]
for r in baseline["rows"]
for o in r["clipped_components"]["objects"]
if o["matched"] and o["id"] not in found
]
def freeze(root):
protocol = dict(
**timestamp(),
session="coverage-admission-20261022",
hypothesis=(
"Does corrected and expanded raw-reviewed supervision improve unchanged "
"C4 candidate admission?"
),
scope=(
"Offline linear paint/background coverage. No map publication, topology "
"completion or full pipeline claim."
),
arms=["old104", "expanded"],
regularization=[0.01, 0.1, 1.0],
thresholds=[i / 20 for i in range(1, 20)],
development=(
"17 previous +12 new windows, same6 development streets; controls "
"excluded from every fit."
),
controls=(
"31 exposed regression +6 new raw-only windows >=18m from prior "
"same-street centers.2 control streets never fit."
),
annotations=(
"18 new windows inspected raw and overlay before fitting.54 full or "
"clipped objects.9 old negative region corrections; ambiguous scan "
"patches unknown.Original104 labels preserved for comparator.Explicit "
"background used only expanded training and both-arm evaluation."
),
representation=(
"Immutable installed Mask2FormerMapillary65; unchanged uniform C4 mean "
"of512 inside/ring descriptors. No backbone fine-tuning."
),
training=(
"Same balanced logistic500L-BFGS, training-fold normalization,6-fold "
"leave-street-out. No street IDs as features."
),
selection=(
"Zero reviewed OOF false positives; maximize worst street complete "
"matchable recall, macrofamily, found; lower median tied threshold; "
"regularization ties strongerL2. Exactly same selection in both arms."
),
acceptance=(
"Expanded must preserve every matched whole identity of old14 and old104 "
"C4 in BOTH cohorts; no extra reviewedFP on each street; strict gain in "
"each cohort; no lost clipped matched identity. Report failures without "
"tuning on controls."
),
limitations=(
"Single reviewer, sparse/unknown boundaries, few control streets; "
"geometric labels approximate, objects may duplicate proposals. New full "
"and clipped linear positives should cover>=3development streets; "
"otherwise coverage hypothesis is unqualified."
),
visual=(
"Inspect new18 annotations, all37 controls with acceptance overlays after "
"frozen evaluation. Keep2proofs."
),
resources=(
"Worker006 only, fixed installedimage, no network,3CPU8GiBGPU batch1,12GiBfree reserve."
),
retention=(
"Content-addressed verified textarchive, inventoried removal of "
"derivedmedia/arrays,2proofimages only; raw/models/acceptedmaps "
"preserved."
),
)
save_new(root / "protocol.json", protocol)
save_new(
root / "review-original.json",
json.loads(Path("/c4study/review-audit-corrected.json").read_text()),
)
save_new(root / "review-frozen.json", json.loads((root / "review-draft.json").read_text()))
names = [
"protocol.json",
"review-original.json",
"review-frozen.json",
"inputs.json",
"model-inventory.json",
]
names += [p.name for p in root.glob("*.py")]
names += [str(p.relative_to(root)) for p in (root / "data").iterdir()]
save_new(root / "input-hashes.json", {n: sha(root / n) for n in sorted(names)})
print("frozen", len(names))
def audit(root):
check_inputs(root)
records = json.loads((root / "candidates.json").read_text())["records"]
old = {a["id"]: a for a in json.loads(Path("/c4study/candidates.json").read_text())["records"]}
original = json.loads((root / "review-original.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
changes = []
counts = defaultdict(Counter)
families = defaultdict(lambda: defaultdict(Counter))
compared = 0
for r in records:
cs = r["variants"]["retained"]
rid = r["id"]
if rid in old:
assert cs == old[rid]["variants"]["retained"], rid
compared += 1
if r["split"] != "development":
continue
new = expanded_labels(cs, review[rid])
for c, y in zip(cs, new, strict=True):
counts["expanded"][str(y)] += 1
if y == 1:
targets = review[rid]["objects"]
match = max(
targets, key=lambda o: overlap(shape(o["geometry"]), shape(c["geometry"]))
)
families["expanded"][match["family"]][r["street"]] += 1
if rid in original:
ls = labels(cs, original[rid])
for c, a, b in zip(cs, ls, new, strict=True):
counts["old104"][str(a)] += 1
if a != b:
changes.append(dict(window=rid, candidate=c["id"], old=int(a), new=int(b)))
assert counts["old104"]["1"] == 36 and counts["old104"]["0"] == 68, counts
assert compared == 48, compared
result = dict(
**timestamp(),
labels=counts,
families=families,
changes=changes,
old_candidate_windows_bitexact=compared,
)
save_new(root / "label-audit.json", result)
print(json.dumps(result))
def train(root):
check_inputs(root)
records, review, data = loaded(root)
original = json.loads((root / "review-original.json").read_text())["records"]
protocol = json.loads((root / "protocol.json").read_text())
arms = {}
for arm in protocol["arms"]:
dev = training_records(records, arm)
rr = review if arm == "expanded" else original
assert not ({r["street"] for r in dev} & {"pokrovka", "sadovaya-karetnaya"})
ceiling = {r["id"]: measured(r["variants"]["retained"], rr[r["id"]]) for r in dev}
experiments = []
for l2 in protocol["regularization"]:
scores = {}
folds = {}
for street in sorted({r["street"] for r in dev}):
tr = [r for r in dev if r["street"] != street]
va = [r for r in dev if r["street"] == street]
model = fit(tr, rr, data, l2, arm == "expanded")
scores.update(predict(va, data, "c4_512", model))
folds[street] = dict(training_ids=[r["id"] for r in tr], model=model)
sweep = []
for threshold in protocol["thresholds"]:
result = evaluation(dev, rr, scores, threshold)
sweep.append(
dict(
threshold=threshold,
**result["summary"],
**objective(result["rows"], ceiling),
)
)
experiments.append(dict(l2=l2, selected=select(sweep), folds=folds, sweep=sweep))
feasible = [e for e in experiments if e["selected"] is not None]
best = max(feasible, key=lambda e: (*rank(e["selected"]), e["l2"])) if feasible else None
arms[arm] = dict(
selected=best["selected"] if best else None,
l2=best["l2"] if best else None,
model=fit(dev, rr, data, best["l2"], arm == "expanded") if best else None,
experiments=experiments,
)
print(
json.dumps(dict(arm=arm, l2=arms[arm]["l2"], selected=arms[arm]["selected"])),
flush=True,
)
save_new(
root / "models-frozen.json",
dict(
**timestamp(),
arms=arms,
hashes={
n: sha(root / n)
for n in [
"protocol.json",
"review-frozen.json",
"review-original.json",
"input-hashes.json",
"candidates.json",
"features.json",
"coverage_admission_study.py",
]
},
),
)
def evaluate(root):
check_inputs(root)
records, review, data = loaded(root)
frozen = json.loads((root / "models-frozen.json").read_text())
for n, h in frozen["hashes"].items():
assert sha(root / n) == h, n
ref = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]
prior = json.loads(Path("/c4study/models-frozen.json").read_text())["variants"]["c4_512"]
# Exact reproduction must precede interpretation of the new arm.
old = frozen["arms"]["old104"]
assert (
old["l2"] == prior["l2"] and old["selected"]["threshold"] == prior["selected"]["threshold"]
)
old_scores = predict(records, data, "c4_512", old["model"])
prior_scores = predict(records, data, "c4_512", prior["model"])
error = max(
[
abs(a - b)
for rid in old_scores
for a, b in zip(old_scores[rid], prior_scores[rid], strict=True)
],
default=0,
)
assert error < 1e-8, error
results = {}
gates = {}
for split in ["regression", "heldout"]:
subset = [r for r in records if r["split"] == split]
result = {}
result["old14"] = evaluation(
subset,
review,
predict(subset, data, "handcrafted14", ref["model"]),
ref["selected"]["threshold"],
)
for arm, info in frozen["arms"].items():
ps = (
predict(subset, data, "c4_512", info["model"])
if info["model"]
else {r["id"]: [0] * len(r["variants"]["retained"]) for r in subset}
)
result[arm] = evaluation(
subset, review, ps, info["selected"]["threshold"] if info["selected"] else 1
)
gates[split] = {}
for comparator in ["old14", "old104"]:
gate = transfer_gate(result[comparator], result["expanded"])
lost = partial_gate(result[comparator], result["expanded"])
gate.update(lost_clipped_objects=lost, passed=gate["passed"] and not lost)
gates[split][comparator] = gate
results[split] = result
out = dict(
**timestamp(),
results=results,
gates=gates,
passed=all(g["passed"] for split in gates.values() for g in split.values()),
old104_reproduction_max_score_error=error,
)
save_new(root / "results.json", out)
print(
json.dumps(
dict(
passed=out["passed"],
gates=gates,
summaries={
s: {a: v["summary"] for a, v in rr.items()} for s, rr in results.items()
},
)
)
)
if __name__ == "__main__":
globals()[sys.argv[1]](Path(sys.argv[2]) if len(sys.argv) > 2 else Path("/experiment"))
@@ -0,0 +1,114 @@
"""Training-label factorial with common held-out targets and non-compensating gates.
Offline diagnostic: exposed controls never select recipes; no production publication.
"""
import copy
import math
from transfer_gates import component_regressions
def learning_view(records, coverage):
"""Swap only training supervision, preserving the common evaluation records."""
if coverage not in ("old", "new") or any(r["split"] != "train" for r in records):
raise ValueError("Training records and registered coverage only")
key = "old_target" if coverage == "old" else "target"
return [dict(r, target=r[key]) for r in records]
def relabel_parent(rows, session):
result = copy.deepcopy(rows)
for r in result:
if r["arm"].startswith(("head-", "decoder-")):
r["arm"] = "new-" + r["arm"]
r["origin"] = session
return result
def assess(rows, seeds):
if not seeds or len(set(seeds)) != len(seeds):
raise ValueError("Unique preregistered seeds required")
expected = {"old-linear", "new-linear"} | {
f"{c}-{f}-{s}" for c in ("old", "new") for f in ("head", "decoder") for s in seeds
}
if not rows or any(r["phase"] != "development" for r in rows):
raise ValueError("Development only")
if {r["arm"] for r in rows} != expected:
raise ValueError("Incomplete factorial")
groups = {r["held_out"] for r in rows}
if len(groups) != 4:
raise ValueError("Four physical groups required")
summaries = {}
for arm in sorted(expected):
rr = [r for r in rows if r["arm"] == arm]
if len(rr) != 4 or {r["held_out"] for r in rr} != groups:
raise ValueError("Incomplete/duplicate group")
if any(not r["completed"] or r["held_out"] in r["fitted_groups"] for r in rr):
raise ValueError("Incomplete or leaked fit")
errors = []
for r in rr:
m = r["metrics"]
if any(
m[k] is None or not math.isfinite(m[k]) or not 0 <= m[k] <= 1
for k in ("recall", "fpr")
):
raise ValueError("Both reviewed classes required")
errors.append((1 - m["recall"] + m["fpr"]) / 2)
summaries[arm] = dict(mean=sum(errors) / 4, worst=max(errors))
audits = []
eligible = []
for coverage in ("old", "new"):
for family in ("head", "decoder"):
failures = []
for seed in seeds:
arm = f"{coverage}-{family}-{seed}"
refs = {"old-linear", f"{coverage}-linear"}
if family == "decoder":
refs.add(f"{coverage}-head-{seed}")
for ref in sorted(refs):
a, b = summaries[arm], summaries[ref]
cc = component_regressions(rows, ref, [arm])
composite = a["mean"] < b["mean"] - 1e-12 and a["worst"] <= b["worst"] + 1e-12
check = dict(arm=arm, composite_pass=composite, **cc)
audits.append(check)
if not composite or not cc["all_components_non_regressing"]:
failures.append(check)
if not failures:
eligible.append(f"{coverage}-{family}")
return dict(
eligible_families=eligible,
summaries=summaries,
audits=audits,
all_seeds_required=True,
production_eligible=False,
control_selection=False,
)
def effects(rows, seeds):
"""Paired effects in metric fractions; descriptive, no pixel-independence CI."""
assess(rows, seeds)
by_key = {(r["held_out"], r["arm"]): r["metrics"] for r in rows}
result = []
for group in sorted({r["held_out"] for r in rows}):
for seed in seeds:
for metric in ("recall", "fpr"):
def val(coverage, family, group=group, seed=seed, metric=metric):
return by_key[(group, f"{coverage}-{family}-{seed}")][metric]
old_gain = val("old", "decoder") - val("old", "head")
new_gain = val("new", "decoder") - val("new", "head")
result.append(
dict(
group=group,
seed=seed,
metric=metric,
old_decoder_minus_head=old_gain,
new_decoder_minus_head=new_gain,
interaction=new_gain - old_gain,
new_minus_old_decoder=val("new", "decoder") - val("old", "decoder"),
)
)
return result
@@ -0,0 +1,80 @@
"""TRAIN-only coverage/mass controls with sample-stable augmentation.
No coordinates or per-street exceptions. Existing pixel labels are immutable.
"""
import hashlib
import json
import numpy as np
from spatial_decoder_probe import dense_weights
POLICIES = {"base", "equal_window", "mass"}
def prepare(records, policy):
if policy not in POLICIES or not records:
raise ValueError("Known policy and nonempty TRAIN records required")
ids, names = set(), set()
for r in records:
sid, name = r["sample_id"], r["name"]
if r["split"] != "train" or not sid or sid in ids or name in names:
raise ValueError("Unique TRAIN samples required")
ids.add(sid)
names.add(name)
t, old = r["target"], r["base_target"]
if (
t.dtype != np.uint8
or old.dtype != np.uint8
or t.ndim != 2
or t.shape != old.shape
or not np.isin(t, [0, 1, 255]).all()
or not np.isin(old, [0, 1, 255]).all()
):
raise ValueError("Aligned uint8 targets required")
if not np.array_equal(t[old != 255], old[old != 255]):
raise ValueError("Existing labels are immutable")
if not np.array_equal(t == 0, old == 0):
raise ValueError("This comparison admits paint only")
ordered = sorted(records, key=lambda r: r["sample_id"])
base = [dict(r, target=r["base_target"]) for r in ordered]
original = dense_weights(base)
if policy == "base":
return base, original
if policy == "equal_window":
return ordered, dense_weights(ordered)
weights = {name: w.copy() for name, w in original.items()}
for group in sorted({r["group"] for r in ordered}):
rr = [r for r in ordered if r["group"] == group]
old_count = sum(int((r["base_target"] == 1).sum()) for r in rr)
new_count = sum(int(((r["base_target"] == 255) & (r["target"] == 1)).sum()) for r in rr)
if not old_count:
raise ValueError("Every street needs original positive support")
if not new_count:
continue
mass = sum(
float(original[r["name"]][r["base_target"] == 1].sum(dtype=np.float64)) for r in rr
)
factor = old_count / (old_count + new_count)
for r in rr:
weights[r["name"]][r["base_target"] == 1] *= factor
added = (r["base_target"] == 255) & (r["target"] == 1)
weights[r["name"]][added] = mass / (old_count + new_count)
return ordered, weights
def rotation(seed, step, sample_id):
if not isinstance(seed, int) or not isinstance(step, int) or step < 0 or not sample_id:
raise ValueError("Integer seed/update and sample identity required")
payload = json.dumps(
["coverage-rotation-v1", seed, step, sample_id], separators=(",", ":")
).encode()
return hashlib.sha256(payload).digest()[0] % 4
def schedule_digest(records, seed, steps):
rows = [
(r["sample_id"], [rotation(seed, step, r["sample_id"]) for step in range(steps)])
for r in sorted(records, key=lambda r: r["sample_id"])
]
return hashlib.sha256(json.dumps(rows, separators=(",", ":")).encode()).hexdigest()
@@ -0,0 +1,195 @@
"""Bounded train-only sample-growth experiment with frozen exposed controls."""
import argparse
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, counts, fit, resize_plane
from scipy.special import expit
from supervision_density_probe import check_pair, load_examples, samples
def check_expansion(old, new, before, after):
if not set(old) < set(new):
raise ValueError("Expected a strict sample expansion")
groups = {e["physical_group"] for e in old.values() if e["split"] == "train"}
seen_images = {i["rgb"]["sha256"] for e in old.values() for i in e["inputs"]}
for sid, e in old.items():
check_pair(e, new[sid], before[sid], after[sid])
if not np.array_equal(before[sid], after[sid]):
raise ValueError("Existing training targets changed")
for sid in set(new) - set(old):
e = new[sid]
if e["split"] != "train" or e["physical_group"] not in groups:
raise ValueError("Addition must belong to an existing training physical group")
if not {0, 1} <= set(np.unique(after[sid])):
raise ValueError("New crossing requires both paint and gap background")
for i in e["inputs"]:
if i["rgb"]["sha256"] in seen_images:
raise ValueError("Duplicate observation in added windows")
seen_images.add(i["rgb"]["sha256"])
def qualify(metrics, audit, reproduced):
failures = []
if not reproduced:
failures.append("baseline reproduction failed")
for group, variants in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
a, b = variants["baseline"][metric], variants["expanded"][metric]
if a is not None and b is not None and sign * (b - a) < -1e-12:
failures.append(group + ": " + metric)
if audit["expanded"]["recall"] < audit["baseline"]["recall"]:
failures.append("diagnostic paint recall")
if audit["expanded"]["fpr"] >= audit["baseline"]["fpr"]:
failures.append("diagnostic gap false positives not strictly reduced")
return dict(accepted=not failures, failures=failures)
def run(root, store):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
torch.set_num_threads(3)
start = time.monotonic()
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
protocol = read(root / "protocol.json")
frozen = read(root / "review-frozen.json")
manifest = read(root / "feature-manifest.json")
parent = store / "experiments" / protocol["parent"]
assert frozen["source_sha256"] == checksum(Path(__file__))
assert (
manifest["protocol_sha256"] == frozen["protocol_sha256"] == checksum(root / "protocol.json")
)
for key, name in [
("audit_sha256", "p1-audit-runs-final.json"),
("pixel_runs_sha256", "pixel-runs-final.json"),
("regions_sha256", "regions-final.json"),
]:
assert frozen[key] == checksum(root / name)
assert checksum(root / "model-inventory.json") == checksum(parent / "model-inventory.json")
params = protocol["fit"]
assert params == read(parent / "protocol.json")["fit"]
old_receipt = read(parent / "supervision-receipt.json")
assert old_receipt["sha256"] == protocol["parent_release_sha256"]
old, before = load_examples(store, old_receipt)
new, after = load_examples(store, read(root / "supervision-receipt.json"))
check_expansion(old, new, before, after)
assert set(new) == {r["sample_id"] for r in manifest["records"]}
assert {r["name"] for r in manifest["records"] if r["sample_id"] not in old} == set(
protocol["added_training_windows"]
)
units = {"baseline": [], "expanded": []}
for r in manifest["records"]:
sid = r["sample_id"]
assert checksum(root / r["cache"]) == r["sha256"]
with np.load(root / r["cache"]) as z:
assert np.array_equal(z["target"], after[sid])
if r["split"] == "train":
unit = samples(z["features"].astype("float32"), after[sid], r, params)
units["expanded"].append(unit)
if sid in old:
units["baseline"].append(unit)
models = {arm: fit(us, params["l2"], params["max_iterations"]) for arm, us in units.items()}
fit_seconds = time.monotonic() - start
write(
root / "models-frozen.json",
dict(
models=models,
threshold=params["threshold"],
protocol_sha256=checksum(root / "protocol.json"),
review_sha256=checksum(root / "review-frozen.json"),
features_sha256=checksum(root / "feature-manifest.json"),
source_sha256=checksum(Path(__file__)),
frozen_before_evaluation=True,
),
)
rows, train_rows, diagnostic = [], [], None
old_rows = {r["name"]: r for r in read(parent / "result.json")["rows"]}
for r in manifest["records"]:
# Training diagnostics are reported separately, never scored as transfer.
with np.load(root / r["cache"]) as z:
features, target = z["features"].astype("float32"), z["target"]
predictions = {}
for arm, m in models.items():
coef = np.array(m["coefficients"])
scaled = coef[1:] / np.array(m["scale"])
bias = coef[0] - np.array(m["mean"]) @ scaled
logits = np.einsum("chw,c->hw", features, scaled) + bias
predictions[arm] = (
expit(resize_plane(logits[None], target.shape)[0]) >= params["threshold"]
)
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
row = dict(
name=r["name"],
group=r["group"],
variants={arm: counts(p, target) for arm, p in predictions.items()},
)
(rows if r["split"] == "regression" else train_rows).append(row)
if r["name"] == "P1":
t = read(root / "p1-audit-runs-final.json")
audit_target = np.frombuffer(
pixel_target(dict(t, size=[512, 512])), dtype="uint8"
).reshape(512, 512)
diagnostic = {
arm: aggregate([counts(p, audit_target)]) for arm, p in predictions.items()
}
assert diagnostic is not None
metrics = {
g: {arm: aggregate([r["variants"][arm] for r in rows if r["group"] == g]) for arm in models}
for g in sorted({r["group"] for r in rows})
}
reproduced_counts = all(
r["variants"]["baseline"] == old_rows[r["name"]]["variants"]["dense"] for r in rows
)
prior_model = read(parent / "models-frozen.json")["models"]["dense"]
delta = max(
float(np.max(np.abs(np.array(models["baseline"][k]) - np.array(prior_model[k]))))
for k in ["mean", "scale", "coefficients"]
)
outcome = qualify(metrics, diagnostic, reproduced_counts and delta == 0.0)
result = dict(
**outcome,
metrics=metrics,
rows=rows,
train_rows=train_rows,
diagnostic=diagnostic,
baseline_reproduced=reproduced_counts and delta == 0.0,
baseline_max_parameter_delta=delta,
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
fit_and_load_seconds=fit_seconds,
total_seconds=time.monotonic() - start,
evaluated_utc=__import__("datetime")
.datetime.now(__import__("datetime").timezone.utc)
.isoformat(),
production_eligible=False,
blind_generalization_claim=False,
)
write(root / "result.json", result)
print(
__import__("json").dumps(
{
k: result[k]
for k in [
"accepted",
"failures",
"metrics",
"diagnostic",
"baseline_reproduced",
"baseline_max_parameter_delta",
]
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("root", type=Path)
parser.add_argument("--store", type=Path, default=Path("/store"))
args = parser.parse_args()
run(args.root, args.store)
@@ -0,0 +1,430 @@
"""Worker-only bounded inbox and portable, hash-verified sample manifests (stdlib)."""
import hashlib
import json
import os
import shutil
import sqlite3
from pathlib import Path, PurePosixPath
SCHEMA = "missioncore.semantic-dataset/v1"
MAX_JOB = 24 * 1024**2
MAX_DATASET = 512 * 1024**2
def digest(value):
return hashlib.sha256(
json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
).hexdigest()
def checksum(path):
with Path(path).open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def write(path, value):
path = Path(path)
raw = json.dumps(value, ensure_ascii=False, allow_nan=False).encode()
tmp = path.with_suffix(".tmp")
with tmp.open("wb") as stream:
stream.write(raw)
stream.flush()
os.fsync(stream.fileno())
os.replace(tmp, path)
def read(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def confined(root, name):
rel = PurePosixPath(name)
if (
not rel.parts
or rel.is_absolute()
or ".." in rel.parts
or "\\" in name
or ":" in name
or rel.as_posix() != name
):
raise ValueError("Unsafe dataset member")
path = root.joinpath(*rel.parts)
if path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
raise ValueError("Dataset member escaped root")
return path
def verify(root):
root = Path(root)
manifest = read(root / "dataset.json")
if manifest["schema_version"] == "missioncore.semantic-collection/v1":
if (
manifest.get("training_eligible") is not False
or not 1 <= len(manifest["shards"]) <= 256
):
raise ValueError("Invalid collection review policy")
total = count = 0
expected = {"dataset.json", *manifest["files"]}
for name, spec in manifest["files"].items():
p = confined(root, name)
if p.stat().st_size != spec["bytes"] or checksum(p) != spec["sha256"]:
raise ValueError("Collection file changed")
total += spec["bytes"]
for name, spec in manifest["shards"].items():
child = confined(root, name)
if read(child / "dataset.json")["schema_version"] != SCHEMA:
raise ValueError("Nested collections forbidden")
result = verify(child)
if result != spec:
raise ValueError("Collection shard changed")
count += result["sample_count"]
total += result["bytes"]
expected.update(p.relative_to(root).as_posix() for p in child.rglob("*") if p.is_file())
if (
total > 4 * 1024**3
or {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()} != expected
):
raise ValueError("Collection size or membership changed")
return dict(
sha256=checksum(root / "dataset.json"),
sample_count=count,
bytes=total,
training_eligible=False,
)
if manifest["schema_version"] != SCHEMA or manifest["training_eligible"] is not False:
raise ValueError("Unsupported dataset review policy")
total = 0
for name, spec in manifest["files"].items():
path = confined(root, name)
total += spec["bytes"]
if (
total > MAX_DATASET
or path.stat().st_size != spec["bytes"]
or checksum(path) != spec["sha256"]
):
raise ValueError("Dataset integrity check failed: " + name)
actual = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}
if actual != set(manifest["files"]) | {"dataset.json"}:
raise ValueError("Unmanifested dataset contents")
for sample in manifest["samples"]:
row = read(confined(root, sample))
for name in row["members"]:
if name not in manifest["files"]:
raise ValueError("Unbound sample member")
if row["training_eligible"] or row["complete_regions"]:
raise ValueError("Unreviewed edit cannot provide training ground truth")
return {
"sha256": checksum(root / "dataset.json"),
"sample_count": len(manifest["samples"]),
"bytes": total,
"training_eligible": False,
}
def review_labels(labels):
"""Separate retained history from current candidates. Neither is training truth.
Editor 'accepted' is a map review status, not per-view training admission.
Projection flags/opaque pixels likewise do not prove visual evidence.
"""
features = labels["proposed_element"]
by_id = {f["id"]: f for f in features}
if len(by_id) != len(features):
raise ValueError("Duplicate feature identity in review sample")
active, rejected = [], []
for f in features:
status = f["properties"].get("review_status", "unreviewed")
if status not in {"unreviewed", "accepted", "rejected"}:
raise ValueError("Unknown map review status")
(rejected if status == "rejected" else active).append(f)
active_ids = {f["id"] for f in active}
views = {}
for name, projections in labels["projections"].items():
if any(p["feature_id"] not in by_id for p in projections):
raise ValueError("Projection references an unknown feature")
views[name] = dict(
candidate_projections=[p for p in projections if p["feature_id"] in active_ids],
rejected_projections=[p for p in projections if p["feature_id"] not in active_ids],
evidence="unreviewed",
approved_targets=[],
complete_regions=[],
training_eligible=False,
)
return dict(
original=labels["original_element"],
active_candidates=active,
rejected_history=rejected,
approved_targets=[],
background_targets=[],
views=views,
training_eligible=False,
)
def sample_records(root):
"""Yield bound context/member references; never decode or collect image arrays."""
root = Path(root)
verify(root)
manifest = read(root / "dataset.json")
children = (
[(name, confined(root, name)) for name in manifest["shards"]]
if manifest["schema_version"] == "missioncore.semantic-collection/v1"
else [("", root)]
)
annotation = manifest.get("annotation_sha256")
for prefix, child in children:
shard = read(child / "dataset.json")
for key in ("world_sha256", "revision", "split_group"):
if not shard.get(key) or shard[key] != manifest.get(key):
raise ValueError("Review shard source identity mismatch: " + key)
annotation = annotation or shard.get("annotation_sha256")
if not annotation or annotation != shard.get("annotation_sha256"):
raise ValueError("Review shard annotation identity mismatch")
source = {
k: shard[k] for k in ("world_sha256", "revision", "annotation_sha256", "split_group")
}
for name in shard["samples"]:
sample = read(confined(child, name))
label_name = str(PurePosixPath(name).with_name("labels.json"))
if label_name not in sample["members"]:
raise ValueError("Sample has no bound labels")
if (
sample["revision"] != shard["revision"]
or sample["split_group"] != shard["split_group"]
):
raise ValueError("Sample source identity mismatch")
yield dict(
source=source,
sample=str(PurePosixPath(prefix) / name),
labels=str(PurePosixPath(prefix) / label_name),
sample_spec=shard["files"][name],
members={
str(PurePosixPath(prefix) / member): shard["files"][member]
for member in sample["members"]
},
)
def review_samples(root):
"""Read verified portable observations without merging history into targets."""
root = Path(root)
for row in sample_records(root):
yield dict(
source=row["source"],
sample=row["sample"],
labels=row["labels"],
**review_labels(read(confined(root, row["labels"]))),
)
def review_index(root):
"""Small relative-path index. Existing datasets remain immutable; no RGB copy."""
root = Path(root)
source = None
samples, active, rejected, identities = [], set(), set(), {}
for row in review_samples(root):
source = row["source"]
partitions = {}
for key, ids in (("active_candidates", active), ("rejected_history", rejected)):
partitions[key] = [f["id"] for f in row[key]]
for f in row[key]:
identity = digest(f)
if f["id"] in identities and identities[f["id"]] != identity:
raise ValueError("Feature changed between review windows")
identities[f["id"]] = identity
ids.add(f["id"])
samples.append(
dict(
sample=row["sample"],
labels=row["labels"],
**partitions,
views={
name: dict(
evidence="unreviewed",
approved_targets=[],
complete_regions=[],
training_eligible=False,
)
for name in row["views"]
},
approved_targets=[],
background_targets=[],
training_eligible=False,
)
)
if source is None:
raise ValueError("Empty review dataset")
if active & rejected:
raise ValueError("Conflicting feature lifecycle between windows")
return dict(
schema_version="missioncore.semantic-review-index/v1",
dataset_sha256=checksum(root / "dataset.json"),
reader_sha256=checksum(__file__),
source=source,
samples=samples,
active_candidate_ids=sorted(active),
rejected_history_ids=sorted(rejected),
approved_targets=[],
background_targets=[],
training_eligible=False,
)
class Store:
def __init__(self, root, *, quota=20 * 1024**3, reserve=12 * 1024**3):
self.root, self.quota, self.reserve = Path(root), quota, reserve
self.root.mkdir(parents=True, exist_ok=True)
for folder in ("inbox", "datasets", "work", "sources", "logs"):
(self.root / folder).mkdir(exist_ok=True)
self.db = sqlite3.connect(self.root / "queue.sqlite3")
self.db.execute("PRAGMA synchronous=FULL")
self.db.execute("""CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY, identity TEXT NOT NULL, state TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
receipt TEXT NOT NULL, error TEXT, acknowledged TEXT)""")
self.db.commit()
def capacity(self, additional):
used = sum(p.stat().st_size for p in self.root.rglob("*") if p.is_file())
if (
used + additional > self.quota
or shutil.disk_usage(self.root).free < self.reserve + additional
):
raise RuntimeError("Worker learning storage quota/reserve reached")
def accept(self, envelope):
exported = envelope["annotation"]
package = exported["package"]
identity = exported["sha256"]
if identity != digest(package):
raise ValueError("Annotation checksum mismatch")
revision = package["revision"]
if len(revision) != 64 or any(c not in "0123456789abcdef" for c in revision):
raise ValueError("Invalid revision identity")
if (
package["world_sha256"] != envelope["world"]["sha256"]
or package["world_sha256"] != envelope["source"]["world_sha256"]
):
raise ValueError("Source does not belong to annotation world")
parent = None
for row in package["revisions"]:
if (
row["parent"] != parent
or digest({k: v for k, v in row.items() if k != "revision"}) != row["revision"]
):
raise ValueError("Annotation history changed")
parent = row["revision"]
if parent != revision or digest(package["model"]) != package["model_sha256"]:
raise ValueError("Annotation baseline changed")
previous = self.db.execute("SELECT identity FROM jobs WHERE id=?", (revision,)).fetchone()
if previous:
if previous[0] != identity:
raise ValueError("Conflicting annotation identity")
return revision
raw_size = len(json.dumps(envelope).encode())
if raw_size > MAX_JOB:
raise ValueError("Annotation exceeds inbox limit")
if (
self.db.execute(
"SELECT count(*) FROM jobs WHERE state NOT IN ('draft-ready','failed')"
).fetchone()[0]
>= 20
):
raise RuntimeError("Worker learning queue is full")
self.capacity(raw_size + 1024**2)
path = self.root / "inbox" / (revision + ".json")
if path.exists() and read(path) != envelope:
raise ValueError("Conflicting recovered inbox item")
write(path, envelope) # Durable file first; a crash before SQL is safe to replay.
receipt = dict(
state="received", package_sha256=identity, dataset_sha256=None, sample_count=0
)
with self.db:
self.db.execute(
"INSERT INTO jobs(id,identity,state,receipt) VALUES(?,?,?,?)",
(revision, identity, "received", json.dumps(receipt)),
)
return revision
def update(self, key, state, result=None, error=None):
identity = self.db.execute("SELECT identity FROM jobs WHERE id=?", (key,)).fetchone()[0]
receipt = dict(
state=state,
package_sha256=identity,
dataset_sha256=result["sha256"] if result else None,
sample_count=result["sample_count"] if result else 0,
)
with self.db:
self.db.execute(
"UPDATE jobs SET state=?,receipt=?,error=? WHERE id=?",
(state, json.dumps(receipt), error, key),
)
return receipt
def next(self):
row = self.db.execute(
"SELECT id,attempts FROM jobs WHERE state IN ('received','building') "
"ORDER BY rowid LIMIT 1"
).fetchone()
if not row:
return None
key, attempts = row
destination = self.root / "datasets" / key
if destination.exists():
try:
result = verify(destination)
except (ValueError, OSError, KeyError) as exc:
self.update(key, "failed", error="Published integrity failure: " + str(exc)[:1000])
else:
self.update(key, "draft-ready", result)
return None
if attempts >= 3:
self.update(key, "failed", error="Interrupted three times; explicit repair required")
return None
with self.db:
self.db.execute("UPDATE jobs SET attempts=attempts+1 WHERE id=?", (key,))
self.update(key, "building")
return key
def publish(self, key, staging):
result = verify(staging)
destination = self.root / "datasets" / key
if destination.exists():
if verify(destination) != result:
raise ValueError("Published dataset is immutable")
else:
os.replace(staging, destination)
self.update(key, "draft-ready", result)
return result
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Verify a portable semantic review dataset")
parser.add_argument("dataset", type=Path)
parser.add_argument(
"--review-index", type=Path, help="Write a separate review index, never training labels"
)
args = parser.parse_args()
if args.review_index:
destination = args.review_index.resolve()
if destination.is_relative_to(args.dataset.resolve()) or destination.exists():
raise ValueError("Review index must be new and outside the immutable dataset")
index = review_index(args.dataset)
write(destination, index)
print(
json.dumps(
dict(
samples=len(index["samples"]),
active=len(index["active_candidate_ids"]),
rejected=len(index["rejected_history_ids"]),
approved=0,
dataset_sha256=index["dataset_sha256"],
training_eligible=False,
)
)
)
else:
print(json.dumps(verify(args.dataset)))
@@ -0,0 +1,531 @@
"""Offline adaptation of installed Mask2Former high-resolution FPN tail.
Whole physical-street folds, fixed recipe, paired optimizer control; no deployment.
The backbone, lateral fusion and deformable-attention encoder remain frozen.
"""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, counts
from spatial_decoder_probe import dense_weights, linear, linear_prediction, prepare_torch
from street_holdout_probe import folds
def choose(rows, seeds):
if any(r["phase"] != "development" for r in rows):
raise ValueError("Development only")
groups = {r["held_out"] for r in rows}
if len(groups) != 4:
raise ValueError("Four physical streets required")
expected = {"old-linear", "new-linear"} | {
f"{f}-{s}" for f in ["head", "decoder"] for s in seeds
}
if {r["arm"] for r in rows} != expected:
raise ValueError("Incomplete arms")
summary = {}
for arm in sorted(expected):
rr = [r for r in rows if r["arm"] == arm]
if len(rr) != 4 or {r["held_out"] for r in rr} != groups:
raise ValueError("Incomplete folds")
if any(r["held_out"] in r["fitted_groups"] for r in rr):
raise ValueError("Physical-street leakage")
errors = [(1 - r["metrics"]["recall"] + r["metrics"]["fpr"]) / 2 for r in rr]
summary[arm] = dict(
mean=float(np.mean(errors)),
worst=max(errors),
completed=all(r["completed"] for r in rr),
)
def better(a, b):
return (
summary[a]["completed"]
and summary[a]["mean"] < summary[b]["mean"] - 1e-12
and summary[a]["worst"] <= summary[b]["worst"] + 1e-12
)
eligible = []
for family in ["head", "decoder"]:
if all(
better(f"{family}-{s}", "new-linear")
and (family != "decoder" or better(f"decoder-{s}", f"head-{s}"))
for s in seeds
):
eligible.append(family)
selected = (
min(
eligible,
key=lambda f: (
max(summary[f"{f}-{s}"]["mean"] for s in seeds),
max(summary[f"{f}-{s}"]["worst"] for s in seeds),
f,
),
)
if eligible
else "new-linear"
)
return dict(
selected_family=selected,
selected_arms=[f"{selected}-{s}" for s in seeds] if eligible else ["new-linear"],
eligible_families=eligible,
summaries=summary,
all_seeds_required=True,
frozen_before_controls=True,
)
def network(base, state, family):
import torch
from torch import nn
if family not in ["head", "decoder"]:
raise ValueError("Unsupported adaptation family")
class Tail(nn.Module):
def __init__(self):
super().__init__()
self.layer = nn.Sequential(
nn.Conv2d(256, 256, 3, padding=1, bias=False), nn.GroupNorm(32, 256), nn.ReLU()
)
self.projection = nn.Conv2d(256, 256, 1)
self.load_state_dict(state)
for p in self.parameters():
p.requires_grad_(family == "decoder")
self.head = nn.Conv2d(256, 1, 1)
with torch.no_grad():
self.head.weight.copy_(torch.tensor(base["coefficients"][1:])[:, None, None][None])
self.head.bias.fill_(base["coefficients"][0])
self.register_buffer(
"mean", torch.tensor(base["mean"], dtype=torch.float32)[None, :, None, None]
)
self.register_buffer(
"scale", torch.tensor(base["scale"], dtype=torch.float32)[None, :, None, None]
)
def features(self, x):
with torch.autocast("cuda", dtype=torch.bfloat16):
return self.projection(self.layer(x)).float()
def classify(self, f):
return self.head((f - self.mean) / self.scale)
return Tail()
def prediction(record, net):
import torch
with torch.inference_mode():
fs = []
for k in range(4):
f = net.features(
torch.from_numpy(record["tail_input"][k : k + 1]).cuda().view(torch.bfloat16)
)
fs.append(torch.rot90(f, -k, [-2, -1]))
f = torch.stack(fs).mean(0).half().float()
logits = net.classify(f)
logits = torch.nn.functional.interpolate(
logits, size=record["target"].shape, mode="bilinear", align_corners=False
)
return (logits[0, 0] >= 0).cpu().numpy()
def fit_tail(
records,
base,
family,
seed,
root,
tag,
protocol,
*,
weight_policy="uniform",
control_policy=None,
background_policy=None,
):
import torch
from dataset_store import checksum, write
start = time.monotonic()
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
state = torch.load(root / "pretrained-tail.pt", map_location="cpu", weights_only=True)
net = network(base, state, family).cuda().eval()
if control_policy is not None:
from coverage_mass_control import prepare, rotation, schedule_digest
records, weights = prepare(records, control_policy)
if set(base["training_groups"]) != {r["group"] for r in records}:
raise ValueError("Control records differ from initialization groups")
elif weight_policy == "uniform":
weights = dense_weights(records)
elif weight_policy == "release_balanced":
from supervision_balance import release_balanced_weights
weights = release_balanced_weights(records)
else:
raise ValueError("Unsupported loss-weight policy")
if background_policy is not None:
if background_policy != "frozen_window_mass" or control_policy is None:
raise ValueError("Background admission requires the paired control recipe")
from background_admission import prepare_background
records, weights = prepare_background(records, weights)
batch = []
for r in records:
known = r["target"] != 255
batch.append(
(
torch.from_numpy(r["tail_input"]).cuda().view(torch.bfloat16),
r["target"].shape,
torch.from_numpy(known).cuda(),
torch.from_numpy(r["target"][known].astype("float32")).cuda(),
torch.from_numpy(weights[r["name"]][known]).cuda(),
)
)
params = [dict(params=net.head.parameters(), lr=protocol["lr_head"])]
if family == "decoder":
params.append(
dict(
params=list(net.layer.parameters()) + list(net.projection.parameters()),
lr=protocol["lr_tail"],
)
)
optimizer = torch.optim.AdamW(params, weight_decay=protocol["weight_decay"])
first = None
last = []
for step in range(protocol["steps"]):
optimizer.zero_grad(set_to_none=True)
value = 0.0
order = range(len(batch)) if control_policy is not None else rng.permutation(len(batch))
for index in order:
xx, size, mask, yy, ww = batch[index]
if control_policy is not None and not bool(mask.any()):
continue
k = (
rotation(seed, step, records[index]["sample_id"])
if control_policy is not None
else int(rng.integers(4))
)
f = torch.rot90(net.features(xx[k : k + 1]), -k, [-2, -1]).half().float()
out = torch.nn.functional.interpolate(
net.classify(f), size=size, mode="bilinear", align_corners=False
)[0, 0][mask]
loss = (
torch.nn.functional.binary_cross_entropy_with_logits(out, yy, reduction="none") * ww
).sum()
if not torch.isfinite(loss):
raise ValueError("Nonfinite loss")
loss.backward()
value += float(loss.detach())
grad = torch.nn.utils.clip_grad_norm_(
net.parameters(), protocol["clip_grad_norm"], error_if_nonfinite=True
)
optimizer.step()
if first is None:
first = value
last = (last + [value])[-20:]
if step % 10 == 0 or step + 1 == protocol["steps"]:
write(
root / "fit-progress.json",
dict(
tag=tag,
step=step + 1,
total=protocol["steps"],
loss=value,
gradient_norm=float(grad),
seconds=time.monotonic() - start,
),
)
if time.monotonic() - start > protocol["resources"]["max_neural_fit_seconds"]:
raise TimeoutError("Fixed fit budget exceeded")
delta = {
k: float(torch.linalg.vector_norm(net.state_dict()[k].cpu() - v)) for k, v in state.items()
}
assert (
any(v > 0 for v in delta.values())
if family == "decoder"
else all(v == 0 for v in delta.values())
)
path = root / "models" / (tag + ".pt")
torch.save({k: v.detach().cpu() for k, v in net.state_dict().items()}, path)
meta = dict(
kind="tail",
family=family,
seed=seed,
base=base,
state=path.relative_to(root).as_posix(),
state_sha256=checksum(path),
steps=protocol["steps"],
completed=True,
first_loss=first,
last_loss=last[-1],
last20=last,
pretrained_parameter_delta_l2=delta,
loss_weight_policy=weight_policy,
trained_parameters=sum(p.numel() for p in net.parameters() if p.requires_grad),
training_groups=base["training_groups"],
seconds=time.monotonic() - start,
convergence_claim=False,
)
if control_policy is not None:
meta.update(
control_policy=control_policy,
schedule_sha256=schedule_digest(records, seed, protocol["steps"]),
accumulation_order=[r["sample_id"] for r in records],
)
if background_policy is not None:
meta["background_policy"] = background_policy
return net, meta
def load(root):
from dataset_store import checksum, read
protocol = read(root / "protocol.json")
frozen = read(root / "run-frozen.json")
manifest = read(root / "decoder-cache.json")
assert checksum(Path(__file__)) == frozen["source_sha256"]
assert (
checksum(root / "protocol.json") == frozen["protocol_sha256"] == manifest["protocol_sha256"]
)
assert checksum(root / "pretrained-tail.pt") == manifest["pretrained_tail_sha256"]
assert checksum(root / "decoder-cache.json") == frozen["cache_manifest_sha256"]
data = []
for r in manifest["records"]:
assert checksum(root / r["cache"]) == r["sha256"]
with np.load(root / r["cache"]) as z:
data.append(
dict(
r,
**{
k: z[k].astype("float32") if k == "features" else z[k].copy()
for k in ["tail_input", "features", "target", "old_target"]
},
)
)
return protocol, data
def development(root):
import torch
from dataset_store import checksum, read, write
prepare_torch()
p, data = load(root)
start = time.monotonic()
rows = []
(root / "models").mkdir(exist_ok=False)
parent = read(Path("/store/experiments") / "semantic-spatial-20261023/development-result.json")
predictions = {r["name"]: {} for r in data if r["split"] == "train"}
for fi, (group, train, held) in enumerate(folds(data)):
old = linear(train, "old_target", p["fit"])
new = linear(train, "target", p["fit"])
arms = ["old-linear", "new-linear"] + [
f"{f}-{s}" for s in p["seeds"] for f in ["head", "decoder"]
]
for arm in arms:
tag = f"fold{fi}-{arm}"
net = None
if arm in ["old-linear", "new-linear"]:
meta = dict(
kind="linear",
base=old if arm == "old-linear" else new,
completed=True,
training_groups=new["training_groups"],
)
else:
family, seed = arm.split("-")
net, meta = fit_tail(train, new, family, int(seed), root, tag, p)
path = root / "models" / (tag + ".json")
write(path, meta)
windows = []
for r in held:
pred = linear_prediction(r, meta["base"]) if net is None else prediction(r, net)
windows.append(dict(name=r["name"], **counts(pred, r["target"])))
predictions[r["name"]][arm] = pred
row = dict(
phase="development",
arm=arm,
held_out=group,
completed=True,
metrics=aggregate(windows),
windows=windows,
model=path.relative_to(root).as_posix(),
model_sha256=checksum(path),
fitted_groups=meta["training_groups"],
)
if net is None:
before = next(
x for x in parent["rows"] if x["arm"] == arm and x["held_out"] == group
)
assert row["metrics"] == before["metrics"] and row["windows"] == before["windows"]
rows.append(row)
write(
root / "development-progress.json",
dict(completed=len(rows), total=32, last=row, seconds=time.monotonic() - start),
)
print(tag + " done", flush=True)
del net
torch.cuda.empty_cache()
if time.monotonic() - start > p["resources"]["max_development_seconds"]:
raise TimeoutError("Development budget exceeded")
for name, preds in predictions.items():
np.savez_compressed(root / "cache" / (name + "-dev-predictions.npz"), **preds)
selection = choose(rows, p["seeds"])
write(
root / "development-result.json",
dict(
rows=rows,
selection=selection,
seconds=time.monotonic() - start,
protocol_sha256=checksum(root / "protocol.json"),
),
)
write(
root / "selection-frozen.json",
dict(
**selection,
development_sha256=checksum(root / "development-result.json"),
protocol_sha256=checksum(root / "protocol.json"),
),
)
print(json.dumps(selection))
def final_fit(root):
from dataset_store import checksum, read, write
prepare_torch()
p, data = load(root)
choice = read(root / "selection-frozen.json")
assert choice["development_sha256"] == checksum(root / "development-result.json")
train = [r for r in data if r["split"] == "train"]
old = linear(train, "old_target", p["fit"])
new = linear(train, "target", p["fit"])
previous = read(Path("/store/experiments") / "semantic-spatial-20261023/models-frozen.json")
models = {}
for a, b in [("old-linear", old), ("new-linear", new)]:
for k in ["coefficients", "mean", "scale"]:
assert previous["models"][a]["base"][k] == b[k]
for arm in sorted(set(["old-linear", "new-linear"] + choice["selected_arms"])):
if arm in ["old-linear", "new-linear"]:
meta = dict(kind="linear", base=old if arm == "old-linear" else new, completed=True)
else:
family, seed = arm.split("-")
net, meta = fit_tail(train, new, family, int(seed), root, "final-" + arm, p)
del net
models[arm] = meta
write(
root / "models-frozen.json",
dict(
models=models,
selection_sha256=checksum(root / "selection-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
production_eligible=False,
),
)
print(json.dumps(dict(final_models=list(models))))
def evaluate(root):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
prepare_torch()
p, data = load(root)
models = read(root / "models-frozen.json")
choice = read(root / "selection-frozen.json")
assert (
models["selection_sha256"] == checksum(root / "selection-frozen.json")
and not (root / "result.json").exists()
)
rows = []
audit = {}
nets = {}
pretrained = torch.load(root / "pretrained-tail.pt", map_location="cpu", weights_only=True)
for arm, m in models["models"].items():
if m["kind"] == "tail":
net = network(m["base"], pretrained, m["family"]).cuda().eval()
assert checksum(root / m["state"]) == m["state_sha256"]
net.load_state_dict(
torch.load(root / m["state"], map_location="cuda", weights_only=True)
)
nets[arm] = net
for r in data:
if r["split"] != "regression":
continue
preds = {}
for a, m in models["models"].items():
pred = (
linear_prediction(r, m["base"]) if m["kind"] == "linear" else prediction(r, nets[a])
)
preds[a] = pred
rows.append(dict(name=r["name"], group=r["group"], arm=a, **counts(pred, r["target"])))
if r["name"] == "P1":
target = np.frombuffer(
pixel_target(dict(read(root / "p1-audit-runs-final.json"), size=[512, 512])),
dtype="uint8",
).reshape(512, 512)
audit[a] = aggregate([counts(pred, target)])
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **preds)
metrics = {
g: {
a: aggregate([r for r in rows if r["group"] == g and r["arm"] == a])
for a in models["models"]
}
for g in sorted({r["group"] for r in rows})
}
previous = read(Path("/store/experiments") / "semantic-spatial-20261023/result.json")
for a in ["old-linear", "new-linear"]:
assert audit[a] == previous["diagnostic"][a]
for g in metrics:
assert metrics[g][a] == previous["metrics"][g][a]
failures = []
if choice["selected_family"] == "new-linear":
failures.append("No development improvement selected")
for a in choice["selected_arms"]:
for g, mm in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
if (
mm[a][metric] is not None
and sign * (mm[a][metric] - mm["old-linear"][metric]) < -1e-12
):
failures.append(a + ": " + g + " " + metric)
if (
audit[a]["recall"] < audit["old-linear"]["recall"]
or audit[a]["fpr"] >= audit["old-linear"]["fpr"]
):
failures.append(a + ": P1gap")
result = dict(
rows=rows,
metrics=metrics,
diagnostic=audit,
selection=choice,
accepted=not failures,
failures=failures,
production_eligible=False,
baseline_exact=True,
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
)
write(root / "result.json", result)
print(
json.dumps(
dict(accepted=result["accepted"], failures=failures, metrics=metrics, diagnostic=audit)
)
)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("phase", choices=["development", "fit", "evaluate"])
ap.add_argument("--root", type=Path, default=Path("/experiment"))
args = ap.parse_args()
{"development": development, "fit": final_fit, "evaluate": evaluate}[args.phase](args.root)
@@ -0,0 +1,89 @@
"""Bounded native-detail residual probe; no coordinates or location-specific rules."""
def network(seed):
import torch
from torch import nn
torch.manual_seed(seed)
net = nn.Sequential(
nn.Conv2d(4, 16, 3, padding=1),
nn.ReLU(),
nn.Conv2d(16, 16, 3, padding=1),
nn.ReLU(),
nn.Conv2d(16, 1, 1),
)
nn.init.zeros_(net[-1].weight)
nn.init.zeros_(net[-1].bias)
return net
def inputs(coarse, rgb, arm):
import torch
if arm not in {"coarse_only", "native_rgb"}:
raise ValueError("Unknown refinement arm")
if (
coarse.ndim != 4
or coarse.shape[1] != 1
or rgb.shape != (coarse.shape[0], 3, *coarse.shape[-2:])
or coarse.dtype != torch.float32
or rgb.dtype != torch.uint8
or coarse.requires_grad
or coarse.device != rgb.device
or not torch.isfinite(coarse).all()
):
raise ValueError("Aligned detached float32 scores and native uint8 RGB required")
fine = (
rgb.float().div(127.5).sub(1)
if arm == "native_rgb"
else torch.zeros_like(rgb, dtype=torch.float32)
)
return torch.cat((coarse, fine), dim=1)
def residual(net, x, tile=None):
"""Two 3x3 layers require a two-pixel halo. No resize or boundary averaging."""
if tile is None:
return net(x)
if not isinstance(tile, int) or isinstance(tile, bool) or tile < 1:
raise ValueError("Positive integer tile size required")
import torch
h, w = x.shape[-2:]
out = torch.empty((x.shape[0], 1, h, w), dtype=x.dtype, device=x.device)
for y in range(0, h, tile):
for xx in range(0, w, tile):
y1, x1 = min(y + tile, h), min(xx + tile, w)
sy, sx, ey, ex = max(0, y - 2), max(0, xx - 2), min(h, y1 + 2), min(w, x1 + 2)
patch = net(x[..., sy:ey, sx:ex])
out[..., y:y1, xx:x1] = patch[..., y - sy : y1 - sy, xx - sx : x1 - sx]
return out
def prediction(net, coarse, x, tile=None):
"""Add once after C4 residual averaging, preserving exact zero identity."""
import torch
correction = torch.stack(
[
torch.rot90(residual(net, torch.rot90(x, k, [-2, -1]), tile), -k, [-2, -1])
for k in range(4)
]
).mean(0)
return coarse + correction
def validate_groups(records, held, groups, parent_groups):
expected = set(groups) - {held}
if held not in groups or len(set(groups)) != len(groups) or set(parent_groups) != expected:
raise ValueError("Parent must exclude the whole held street")
ids = [r["sample_id"] for r in records]
if (
not records
or len(set(ids)) != len(ids)
or not all(ids)
or any(r["split"] != "train" or r["group"] == held for r in records)
or {r["group"] for r in records} != expected
):
raise ValueError("Unique TRAIN records from exactly the allowed streets required")
@@ -0,0 +1,186 @@
"""Fixed class/family/frame/pixel mass and deterministic point budgets.
The caller supplies the complete source-group to exclusion-family mapping,
filters the held family and validates source/target admission before this helper.
Original group and split metadata are preserved. A mapping must cover all study
families, even when one arm contains no frames from some of its source groups.
"""
from collections.abc import Mapping
import numpy as np
def _identity(value):
return isinstance(value, str) and bool(value)
def prepare(records, held_family, family_by_group):
"""Return sample-sorted record copies, float64 weights and JSON mass audit.
Each class receives .5 total mass, divided equally among allowed families,
then among frames supporting that class, then among its pixels. Every
allowed family must support both classes, but a frame may support only one.
Unknown-only frames cannot receive positive sampling quotas and are rejected.
Record dicts and targets are copied; unrelated payloads are shared untouched.
"""
if (
not _identity(held_family)
or not isinstance(family_by_group, Mapping)
or not family_by_group
or any(not _identity(g) or not _identity(f) for g, f in family_by_group.items())
):
raise ValueError("Explicit nonempty source-group/family mapping required")
families = set(family_by_group.values())
if held_family not in families:
raise ValueError("Held family must be present in the study mapping")
allowed = sorted(families - {held_family})
records = list(records)
if not records or not allowed:
raise ValueError("Nonempty records and allowed families required")
names, samples, observed = set(), set(), set()
for record in records:
if not isinstance(record, Mapping) or any(
not _identity(record.get(key)) for key in ("name", "sample_id", "group")
):
raise ValueError("Record name, sample_id and source group required")
name, sid, group = (record[k] for k in ("name", "sample_id", "group"))
if name in names or sid in samples:
raise ValueError("Duplicate frame name or sample_id")
names.add(name)
samples.add(sid)
if group not in family_by_group:
raise ValueError("Source group missing from explicit family mapping")
family = family_by_group[group]
if family == held_family:
raise ValueError("Held family must never be admitted; caller must filter it")
observed.add(family)
target = record.get("target")
if (
not isinstance(target, np.ndarray)
or target.dtype != np.uint8
or target.ndim != 2
or not target.size
or not np.isin(target, (0, 1, 255)).all()
):
raise ValueError("Nonempty 2D uint8 targets with labels 0, 1, 255 required")
if not np.any(target != 255):
raise ValueError("Every frame needs known class support")
if observed != set(allowed):
raise ValueError("Every allowed family must be represented in both study arms")
out = [
dict(r, target=r["target"].copy())
for r in sorted(records, key=lambda r: r["sample_id"])
]
weights = {r["name"]: np.zeros(r["target"].shape, dtype=np.float64) for r in out}
support = {
r["name"]: {label: int((r["target"] == label).sum()) for label in (0, 1)}
for r in out
}
family_classes = []
family_mass = 0.5 / len(allowed)
for family in allowed:
rows = [r for r in out if family_by_group[r["group"]] == family]
for label in (0, 1):
present = [r for r in rows if support[r["name"]][label]]
if not present:
raise ValueError("Every allowed family must support both classes")
frame_mass = family_mass / len(present)
for row in present:
mask = row["target"] == label
weights[row["name"]][mask] = frame_mass / support[row["name"]][label]
actual = sum(
float(weights[r["name"]][r["target"] == label].sum()) for r in present
)
if not np.isclose(actual, family_mass, rtol=1e-12, atol=1e-12):
raise ValueError("Family/class mass accounting failed")
family_classes.append(
dict(
family=family,
label=label,
supported_frames=len(present),
pixels=sum(support[r["name"]][label] for r in present),
expected_mass=family_mass,
mass=actual,
)
)
frames = []
for row in out:
target, weight = row["target"], weights[row["name"]]
if (
not np.isfinite(weight).all()
or np.any(weight[target != 255] <= 0)
or np.any(weight[target == 255] != 0)
):
raise ValueError("Finite positive known weights and zero unknown weights required")
frames.append(
dict(
name=row["name"],
sample_id=row["sample_id"],
group=row["group"],
family=family_by_group[row["group"]],
unknown_pixels=int((target == 255).sum()),
mass=float(weight.sum()),
classes=[
dict(
label=label,
pixels=support[row["name"]][label],
mass=float(weight[target == label].sum()),
)
for label in (0, 1)
],
)
)
classes = []
for label in (0, 1):
actual = sum(f["classes"][label]["mass"] for f in frames)
if not np.isclose(actual, 0.5, rtol=1e-12, atol=1e-12):
raise ValueError("Global class mass accounting failed")
classes.append(
dict(
label=label,
expected_mass=0.5,
mass=actual,
pixels=sum(support[r["name"]][label] for r in out),
)
)
total = sum(f["mass"] for f in frames)
if not np.isclose(total, 1.0, rtol=1e-12, atol=1e-12):
raise ValueError("Total mass accounting failed")
return out, weights, dict(
schema="missioncore.diversity-mass/v1",
held_family=held_family,
allowed_families=allowed,
total_mass=total,
classes=classes,
family_classes=family_classes,
frames=frames,
)
def quotas(total_points, frames, step):
"""Allocate positive int64 quotas in frame order; rotate remainder by step.
Sum is total_points; over any complete frames-step cycle every frame receives
exactly total_points draws. The caller aligns this vector with sorted records.
"""
values = (total_points, frames, step)
if any(
not isinstance(v, (int, np.integer)) or isinstance(v, (bool, np.bool_)) for v in values
):
raise ValueError("Integer point budget, frame count and step required")
total_points, frames, step = (int(v) for v in values)
if (
frames <= 0
or total_points < frames
or total_points > np.iinfo(np.int64).max
or step < 0
):
raise ValueError("Positive per-frame budget and nonnegative step required")
base, remainder = divmod(total_points, frames)
result = np.full(frames, base, dtype=np.int64)
start = step % frames
stop = start + remainder
result[start:min(stop, frames)] += 1
result[:max(0, stop - frames)] += 1
return result
@@ -0,0 +1,97 @@
"""Point-wise frozen-scene feature refinement; offline, no location inputs."""
def network(seed, channels=256, width=256):
import torch
from torch import nn
if channels < 1 or width < 1:
raise ValueError("Positive channel counts required")
class Head(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.ModuleList(
[nn.Linear(channels + 1, width)] + [nn.Linear(width + 1, width) for _ in range(2)]
)
self.output = nn.Linear(width + 1, 1)
for layer in self.layers:
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
nn.init.zeros_(layer.bias)
nn.init.zeros_(self.output.weight)
nn.init.zeros_(self.output.bias)
def forward(self, fine, coarse, arm):
if arm not in {"coarse_only", "scene_features"}:
raise ValueError("Unknown feature arm")
if fine.ndim != 2 or coarse.shape != (len(fine), 1):
raise ValueError("Expected points by channels and points by one")
if fine.shape[1] != channels:
raise ValueError("Feature channel mismatch")
x = fine if arm == "scene_features" else torch.zeros_like(fine)
for layer in self.layers:
x = torch.relu(layer(torch.cat((x, coarse), dim=1)))
return coarse + self.output(torch.cat((x, coarse), dim=1))
with torch.random.fork_rng(devices=[]):
torch.manual_seed(seed)
return Head()
def sample_native(fine, shape, indices):
"""Bilinear sample at native pixel centres, align_corners=False, border pad."""
import torch
from torch.nn import functional as F
h, w = shape
if fine.ndim != 4 or fine.shape[0] != 1 or min(h, w) < 1:
raise ValueError("Expected one feature image and positive native shape")
if indices.ndim != 1 or indices.dtype != torch.long:
raise ValueError("Expected flat int64 indices")
if len(indices) and (indices.min() < 0 or indices.max() >= h * w):
raise ValueError("Point outside native image")
y = torch.div(indices, w, rounding_mode="floor").to(fine.dtype)
x = (indices % w).to(fine.dtype)
grid = torch.stack(((x + 0.5) * (2.0 / w) - 1, (y + 0.5) * (2.0 / h) - 1), -1)
return F.grid_sample(
fine, grid[None, None], mode="bilinear", padding_mode="border", align_corners=False
)[0, :, 0].T.contiguous()
def predict(net, fine, coarse, arm, chunk=8192):
import torch
if chunk < 1 or coarse.ndim != 2:
raise ValueError("Expected positive chunk and 2D coarse scores")
out = []
flat = coarse.reshape(-1, 1)
with torch.inference_mode():
for start in range(0, flat.shape[0], chunk):
ids = torch.arange(start, min(start + chunk, len(flat)), device=fine.device)
out.append(net(sample_native(fine, coarse.shape, ids), flat[ids], arm)[:, 0])
return torch.cat(out).reshape(coarse.shape)
def capacity_screen(before, after, control):
"""Frozen TRAIN screen: geometry/error gains without losing known paint."""
import math
required = {"bce", "weak_fn", "clear_fn", "background_fp"}
for row in (before, after, control):
if set(row) != required:
raise ValueError("Incomplete capacity metrics")
if not all(math.isfinite(v) and v >= 0 for v in row.values()):
raise ValueError("Invalid capacity metrics")
if any(type(row[k]) is not int for k in required - {"bce"}):
raise ValueError("Pixel counts must be integers")
checks = {
"half_parent_bce": after["bce"] <= before["bce"] * 0.5,
"half_parent_bg_fp": after["background_fp"] <= before["background_fp"] * 0.5,
"retain_parent_weak": after["weak_fn"] <= before["weak_fn"],
"retain_parent_clear": after["clear_fn"] <= before["clear_fn"],
"beat_control_bce": after["bce"] < control["bce"],
"no_control_bg_regression": after["background_fp"] <= control["background_fp"],
"no_control_weak_regression": after["weak_fn"] <= control["weak_fn"],
"no_control_clear_regression": after["clear_fn"] <= control["clear_fn"],
}
return dict(passed=all(checks.values()), checks=checks, production_eligible=False)
@@ -0,0 +1,120 @@
"""Deterministic review windows over final geometry, independent of mouse history."""
import copy
import math
from dataset_store import digest
from semantic_objects import object_operation, paths
from semantic_vectors import vector_operation
VECTOR = {
"curve",
"delete_vertices",
"region",
"translate",
"translate_vertices",
"duplicate_vertex",
"duplicate_marking",
}
def replay(package):
features = copy.deepcopy(package["model"]["features"])
for row in package["revisions"]:
for op in row["operations"]:
kind = op["kind"]
origin = row.get("origin", "human-edit")
f = next((f for f in features if f["id"] == op.get("feature_id")), None)
if kind in {"place", "transform", "remove", "retemplate"}:
features = object_operation(features, op, origin)
elif (
kind in VECTOR
or f
and f["properties"].get("editor_curves", {}).get(str(op.get("path")))
):
features = vector_operation(features, op, origin)
else:
if not f:
raise ValueError("Unknown feature in annotation history")
points = paths(f)[op["path"]]
i = op["index"]
if kind == "move":
points[i] = op["position"][:]
elif kind == "insert":
a, b = points[i : i + 2]
points.insert(i + 1, [a[k] + op["t"] * (b[k] - a[k]) for k in range(3)])
elif kind == "delete":
points.pop(i)
else:
raise ValueError("Unknown annotation operation")
if f["geometry"]["type"] == "Polygon":
points[-1] = points[0][:]
if {f["id"]: f["geometry"] for f in features} != {
f["id"]: f["geometry"] for f in package["edited"]["features"]
}:
raise ValueError("Replayed geometry differs from admitted edit")
return features
def segment_cells(a, b, step=10):
"""Exact segment/grid intersections: long edges need no inserted label vertices."""
cuts = {0.0, 1.0}
for k in (0, 1):
if a[k] == b[k]:
continue
lo, hi = sorted((a[k], b[k]))
for n in range(math.floor(lo / step) + 1, math.ceil(hi / step)):
cuts.add((n * step - a[k]) / (b[k] - a[k]))
ts = sorted(cuts)
for left, right in zip(ts, ts[1:], strict=False):
t = (left + right) / 2
cell = tuple(math.floor((a[k] + t * (b[k] - a[k])) / step) for k in (0, 1))
yield cell, a[2] + left * (b[2] - a[2])
yield cell, a[2] + right * (b[2] - a[2])
def plan(package, classes=None):
replay(package)
before = package["model"]["features"]
after = package["edited"]["features"]
originals = {f["id"]: f for f in before}
if classes is None:
classes = sorted({f["properties"]["class"] for f in after if originals.get(f["id"]) != f})
if not classes or any(
c not in {f["properties"]["class"] for f in before + after} for c in classes
):
raise ValueError("Unknown/empty review scope")
cells = {}
for _source, features in (("model", before), ("edited", after)):
for f in features:
if f["properties"]["class"] not in classes:
continue
# Rejected geometry remains review evidence, never positive supervision.
for ring in paths(f):
for a, b in zip(ring, ring[1:], strict=False):
for cell, z in segment_cells(a, b):
item = cells.setdefault(cell, {"features": set(), "low": z, "high": z})
item["features"].add(f["id"])
item["low"] = min(z, item["low"])
item["high"] = max(z, item["high"])
windows = [
dict(
id=f"tile-{x}-{y}",
center=[(x + 0.5) * 10, (y + 0.5) * 10, (v["low"] + v["high"]) / 2],
features=sorted(v["features"]),
)
for (x, y), v in sorted(cells.items())
]
if not windows or len(windows) > 1024:
raise ValueError("Review scope exceeds bounded snapshot budget")
return dict(
schema_version="missioncore.semantic-snapshot-plan/v1",
revision=package["revision"],
world_sha256=package["world_sha256"],
classes=sorted(classes),
stride_m=10,
width_m=12,
windows=windows,
geometry_sha256=digest([f for f in after if f["properties"]["class"] in classes]),
training_eligible=False,
)
@@ -0,0 +1,35 @@
"""Predeclared TRAIN-only capacity screen; never a deployment acceptance gate."""
import math
def capacity_screen(before, after):
"""Require halved BCE/weak misses/background errors and no clear-paint loss."""
for row in (before, after):
if set(row) != {"bce", "weak_fn", "background_fp", "clear_fn"}:
raise ValueError("Exact fixed support metrics required")
if (
isinstance(row["bce"], bool)
or not isinstance(row["bce"], (int, float))
or not math.isfinite(row["bce"])
or row["bce"] < 0
):
raise ValueError("Finite nonnegative objective required")
for key in ("weak_fn", "background_fp", "clear_fn"):
if type(row[key]) is not int or row[key] < 0:
raise ValueError("Nonnegative integer error counts required")
limits = {
"bce": before["bce"] * 0.5,
"weak_fn": before["weak_fn"] * 0.5,
"background_fp": before["background_fp"] * 0.5,
"clear_fn": before["clear_fn"],
}
failures = [key for key, limit in limits.items() if after[key] > limit]
return {
"passed": not failures,
"failures": failures,
"limits": limits,
"before": dict(before),
"after": dict(after),
"production_eligible": False,
}
@@ -0,0 +1,101 @@
"""CPU-only representation gate; synthetic contracts, NOT street/model quality."""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from paint_geometry import editor_features, vectorize
from PIL import Image, ImageDraw
from shapely import contains_xy
from shapely.geometry import Polygon, shape
from shapely.ops import unary_union
def fixtures():
dash = np.zeros((64, 96), np.uint8)
for a, b in [(6, 23), (28, 43), (57, 88)]:
dash[29:35, a:b] = 1
zebra = np.zeros_like(dash)
for a in [10, 28, 46, 64, 82]:
zebra[8:56, a:a + 7] = 1
# Raster A is deliberately synthetic, with a small but explicit hole.
yy, xx = np.indices(dash.shape)
outer = Polygon([(20, 56), (43, 7), (53, 7), (77, 56),
(63, 56), (57, 43), (39, 43), (33, 56)])
hole = Polygon([(44, 31), (48, 20), (52, 31)])
letter = contains_xy(outer.difference(hole), xx + .5, yy + .5).astype(np.uint8)
clipped = np.zeros_like(dash)
clipped[27:36, :90] = 1
clipped[:, 43:50] = 255
return {"separate_dashes": dash, "zebra_bars": zebra,
"letter_hole": letter, "unknown_gap_and_edge": clipped}
def rasterize(features, shape_hw, matrix):
yy, xx = np.indices(shape_hw)
a, b, d, e, xoff, yoff = matrix
x, y = a * (xx + .5) + b * (yy + .5) + xoff, d * (xx + .5) + e * (yy + .5) + yoff
return contains_xy(unary_union([shape(f["geometry"]) for f in features]), x, y)
def run(destination):
destination = Path(destination)
destination.mkdir(parents=True, exist_ok=False)
start = time.monotonic()
matrix = [.1, 0, 0, -.1, 10, 20]
report = dict(
scope="Synthetic discrete geometry contract; no model inference or live map",
frame="pixel edges; supplied synthetic height plane only",
upstream_vma_executed=False, production_heuristic_executed=False, cases=[],
)
canvas = Image.new("RGB", (980, 670), "#111820")
draw = ImageDraw.Draw(canvas)
draw.text((16, 12), "SYNTHETIC CONTRACT CHECK - not street predictions", fill="white")
for x, label in [(16, "Input (purple = unknown)"),
(340, "Exact cells -> editor features"),
(664, "Envelope only (lossy illustration)")]:
draw.text((x, 38), label, fill="white")
for index, (name, labels) in enumerate(fixtures().items()):
proposal = vectorize(labels, pixel_to_scene=matrix, source_id="synthetic/" + name)
features = editor_features(
proposal, height_at=lambda xy: 2 + xy[:, 0] * .01,
height_source="synthetic-known-plane",
)
recovered = rasterize(features, labels.shape, matrix)
truth = labels == 1
assert np.array_equal(recovered, truth)
exact = unary_union([shape(f["geometry"]) for f in features])
# Structural illustration only, not an execution/emulation of VMA.
envelope = exact.envelope
simplified = rasterize([dict(geometry=envelope.__geo_interface__)], labels.shape, matrix)
row = dict(
case=name, foreground_pixels=int(truth.sum()), exact_pixel_errors=0,
features=len(features),
holes=sum(len(shape(f["geometry"]).interiors) for f in features),
support_boundary=[f["properties"]["support_boundary"] for f in features],
envelope_pixel_errors=int(np.count_nonzero(simplified != truth)),
proposal_sha256=proposal["proposal_sha256"],
)
report["cases"].append(row)
y = 66 + index * 146
draw.text((16, y), name, fill="white")
for x, mask in [(16, truth), (340, recovered), (664, simplified)]:
rgb = np.zeros((*labels.shape, 3), np.uint8)
rgb[:] = [28, 38, 49]
rgb[mask] = [246, 215, 100]
if x == 16:
rgb[labels == 255] = [136, 91, 185]
# 96x64 to 288x112 display; dimensions are shared across columns.
im = Image.fromarray(rgb).resize((288, 112), Image.Resampling.NEAREST)
canvas.paste(im, (x, y + 18))
report["seconds"] = time.monotonic() - start
(destination / "gate.json").write_text(json.dumps(report, indent=2) + "\n")
canvas.save(destination / "geometry-proof.png")
return report
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("destination", type=Path)
print(json.dumps(run(parser.parse_args().destination), indent=2))
@@ -0,0 +1,238 @@
"""Offline street-grouped threshold experiment; no publication or map writes."""
import json
import sys
from collections import defaultdict
from pathlib import Path
import numpy as np
from object_assembly_study import measured
from object_proposal_study import aggregate, labels, save_new, sha, timestamp
from paint_hypothesis_study import fit_classifier, probability
def development(records, streets):
"""Explicit allowlist prevents previous controls entering a development fold."""
return [r for r in records if r["street"] in streets]
def fit(records, review):
x, y = [], []
for r in records:
cs = r["variants"]["retained_off"]
for c, label in zip(cs, labels(cs, review[r["id"]]), strict=True):
if label >= 0:
x.append(c["features"][:14])
y.append(int(label))
if min(y.count(0), y.count(1)) < 2:
raise ValueError("Insufficient positive or negative development examples")
return fit_classifier(np.asarray(x), np.asarray(y), 0.01, 500)
def probabilities(records, model):
return {
r["id"]: probability(
np.asarray([c["features"][:14] for c in r["variants"]["retained_off"]]), model
).tolist()
if r["variants"]["retained_off"]
else []
for r in records
}
def evaluated(records, review, probs, threshold):
rows = []
for r in records:
accepted = [
c
for c, p in zip(r["variants"]["retained_off"], probs[r["id"]], strict=True)
if p >= threshold
]
rows.append(
dict(
id=r["id"],
street=r["street"],
accepted_ids=[c["id"] for c in accepted],
**measured(accepted, review[r["id"]]),
)
)
return dict(
rows=rows,
summary=aggregate(rows),
streets={
st: aggregate([a for a in rows if a["street"] == st])
for st in sorted({r["street"] for r in rows})
},
)
def objective(rows, ceiling):
"""Score recall of complete matchable objects, balancing streets and families."""
streets, families = defaultdict(lambda: [0, 0]), defaultdict(lambda: [0, 0])
for r in rows:
eligible = {o["id"] for o in ceiling[r["id"]]["objects"] if o["matched"]}
for obj in r["objects"]:
if obj["id"] in eligible:
for group, key in [(streets, r["street"]), (families, obj["family"])]:
group[key][0] += int(obj["matched"])
group[key][1] += 1
return dict(
worst_street=min((n / d for n, d in streets.values()), default=0),
macro_family=float(np.mean([n / d for n, d in families.values()])) if families else 0,
street_matchable=dict(streets),
family_matchable=dict(families),
)
def select(rows):
feasible = [r for r in rows if r["unsupported"] == 0]
if not feasible:
return None
def key(r):
return r["worst_street"], r["macro_family"], r["found"]
best = max(key(r) for r in feasible)
tied = sorted([r for r in feasible if key(r) == best], key=lambda r: r["threshold"])
return tied[(len(tied) - 1) // 2]
def transfer_gate(baseline, candidate):
lost = []
by_id = {r["id"]: r for r in candidate["rows"]}
for row in baseline["rows"]:
found = {o["id"] for o in by_id[row["id"]]["objects"] if o["matched"]}
lost.extend(o["id"] for o in row["objects"] if o["matched"] and o["id"] not in found)
no_extra_fp = all(
candidate["streets"][st]["unsupported"] <= b["unsupported"]
for st, b in baseline["streets"].items()
)
b, c = baseline["summary"], candidate["summary"]
gain = c["found"] > b["found"] or c["unsupported"] < b["unsupported"]
return dict(
lost_objects=lost,
no_extra_reviewed_fp=no_extra_fp,
strict_gain=gain,
passed=not lost and no_extra_fp and gain,
)
def train(root):
protocol = json.loads((root / "protocol.json").read_text())
source = Path("/assemblystudy")
records = development(
json.loads((source / "assembled-candidates.json").read_text())["records"],
protocol["development_streets"],
)
review = json.loads((source / "review-frozen.json").read_text())["records"]
folds, out = {}, {}
for street in sorted({r["street"] for r in records}):
training = [r for r in records if r["street"] != street]
validation = [r for r in records if r["street"] == street]
model = fit(training, review)
out.update(probabilities(validation, model))
folds[street] = dict(
training_streets=sorted({r["street"] for r in training}),
validation_ids=[r["id"] for r in validation],
model=model,
)
ceiling = {r["id"]: measured(r["variants"]["retained_off"], review[r["id"]]) for r in records}
sweep = []
for t in protocol["thresholds"]:
result = evaluated(records, review, out, t)
sweep.append(
dict(
threshold=t,
**result["summary"],
**objective(result["rows"], ceiling),
merged=sum(r["merged"] for r in result["rows"]),
)
)
chosen = select(sweep)
save_new(
root / "models-frozen.json",
dict(
**timestamp(),
protocol_sha256=sha(root / "protocol.json"),
source_sha256=sha(Path(__file__)),
input_sha256={
str(source / n): sha(source / n)
for n in ["assembled-candidates.json", "review-frozen.json"]
},
selected=chosen,
sweep=sweep,
folds=folds,
out_of_fold=out,
final_model=fit(records, review),
),
)
print(json.dumps(dict(selected=chosen, folds=len(folds), windows=len(records))))
def evaluate(root):
frozen = json.loads((root / "models-frozen.json").read_text())
if frozen["selected"] is None:
raise ValueError("No feasible out-of-fold threshold; hypothesis rejected")
assert frozen["protocol_sha256"] == sha(root / "protocol.json")
assert frozen["source_sha256"] == sha(Path(__file__))
for path, digest in frozen["input_sha256"].items():
assert sha(Path(path)) == digest
old = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]
results = {}
for cohort in ["known_regression", "fresh_control"]:
if cohort == "known_regression":
records = [
r
for r in json.loads(Path("/assemblystudy/assembled-candidates.json").read_text())[
"records"
]
if r["street"] in ["pokrovka", "sadovaya-karetnaya"]
]
review = json.loads(Path("/assemblystudy/review-frozen.json").read_text())["records"]
else:
records = json.loads((root / "candidates.json").read_text())["records"]
records = [
dict(r, variants={"retained_off": r["variants"]["retained"]}) for r in records
]
review = json.loads((root / "review-frozen.json").read_text())["records"]
base = evaluated(records, review, probabilities(records, old["model"]), 0.15)
new = evaluated(
records,
review,
probabilities(records, frozen["final_model"]),
frozen["selected"]["threshold"],
)
ceiling = evaluated(
records,
review,
{r["id"]: [1.0] * len(r["variants"]["retained_off"]) for r in records},
0.0,
)
results[cohort] = dict(
baseline=base, grouped=new, proposal_ceiling=ceiling, gate=transfer_gate(base, new)
)
save_new(
root / "results.json",
dict(
**timestamp(),
frozen_sha256=sha(root / "models-frozen.json"),
fresh_inputs={
n: sha(root / n) for n in ["inputs.json", "review-frozen.json", "candidates.json"]
},
cohorts=results,
),
)
print(
json.dumps(
{
k: {n: v[n]["summary"] for n in ["baseline", "grouped", "proposal_ceiling"]}
| {"gate": v["gate"]}
for k, v in results.items()
}
)
)
if __name__ == "__main__":
{"train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
+28
View File
@@ -0,0 +1,28 @@
param([Parameter(Mandatory=$true)][string]$Release,[switch]$Apply)
$ErrorActionPreference='Stop'
$root='D:\NDC_MISSIONCORE\datasets\urban-learning'
$runtime='D:\NDC_MISSIONCORE\runtime\simulation'
$python="$runtime\isaac-sim-6.1.0\kit\python\python.exe"
$manifest=Get-Content "$Release\release.json" -Raw | ConvertFrom-Json
foreach($f in $manifest.files.psobject.Properties){
$path=Join-Path $Release $f.Name
if((Get-FileHash $path -Algorithm SHA256).Hash.ToLower() -ne $f.Value){throw "Release identity mismatch: $($f.Name)"}
}
if(-not (Test-Path $python)){throw 'Worker Python unavailable'}
$image=& docker image inspect $manifest.image --format '{{.Id}}'
if($LASTEXITCODE -ne 0 -or $image -ne $manifest.image){throw 'Pinned renderer unavailable'}
$arguments="-B -u `"$Release\worker.py`" --root `"$root`" --state `"$runtime\state`" --token-file `"$runtime\private\worker.token`""
if(-not $Apply){Write-Output $arguments;exit}
New-Item -ItemType Directory -Force -Path $root | Out-Null
$old=Get-ScheduledTask -TaskName 'ndc-semantic-learning-worker' -ErrorAction SilentlyContinue
if($old){
if($old.State -eq 'Running'){throw 'Stop the owned learning worker only after checking its active job'}
Export-ScheduledTask -TaskName 'ndc-semantic-learning-worker' | Set-Content "$root\previous-task.xml"
}
$action=New-ScheduledTaskAction -Execute $python -Argument $arguments -WorkingDirectory $Release
$principal=New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited
$trigger=New-ScheduledTaskTrigger -AtLogOn -User $principal.UserId
$settings=New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName 'ndc-semantic-learning-worker' -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Force | Out-Null
Start-ScheduledTask -TaskName 'ndc-semantic-learning-worker'
Write-Output 'Installed ndc-semantic-learning-worker; data root is separate from runtime and release'
@@ -0,0 +1,16 @@
"""Extend reviewed labels without silently overriding known or locked unknown."""
import numpy as np
def extend_reviewed_target(base, proposal, protected):
if (not isinstance(base, np.ndarray) or base.ndim != 2 or base.dtype != np.uint8
or not isinstance(proposal, np.ndarray) or proposal.shape != base.shape
or proposal.dtype != np.uint8 or not isinstance(protected, np.ndarray)
or protected.shape != base.shape or protected.dtype != np.bool_
or not np.isin(base, [0, 1, 255]).all()
or not np.isin(proposal, [0, 1, 255]).all()):
raise ValueError("Aligned uint8 labels and explicit bool protection required")
preserve = protected | (base != 255)
result = proposal.copy()
result[preserve] = base[preserve]
return result
@@ -0,0 +1,465 @@
"""Pinned, resumable phase ledger for trusted offline learning runners.
This is not a scheduler, an authentication boundary or a model acceptance gate.
The input root may be a read-only portable store with a separate writable
state_root for this run's ledger. Plans declare the actual file dependency closure;
metadata references are not recursively inferred. The caller supplies the bounded
Worker/container runtime and whole-phase wall
budget. Run and verification subprocesses have separate explicit deadlines. A completed phase is
reused only while its input and output bytes still match. Any interrupted or
failed attempt reserves its phase until trusted root reconciliation; time alone
never authorizes a retry. Verifiers validate artifacts, not model quality.
"""
import argparse
import json
import re
import sqlite3
import subprocess
import sys
import threading
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
from dataset_store import checksum, confined, digest
SCHEMA = "missioncore.learning-execution/v1"
MAX_JSON = 262144
MAX_LOG = 1048576
def encoded(value):
data = json.dumps(value, sort_keys=True, ensure_ascii=True, allow_nan=False)
if len(data.encode()) > MAX_JSON:
raise ValueError("Execution record too large")
return data
def pin(root, name):
path = confined(root, name)
if not path.is_file():
raise ValueError("Missing regular artifact: " + name)
return dict(sha256=checksum(path), bytes=path.stat().st_size)
def check_pins(root, pins):
for name, expected in pins.items():
if pin(root, name) != expected:
raise ValueError("Artifact changed: " + name)
def invoke(root, argv, timeout):
"""No shell; deadline and in-memory output cap, no unbounded log file."""
process = subprocess.Popen(
[sys.executable, "-B", str(confined(root, argv[0])), *argv[1:]],
cwd=root,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
output = bytearray()
overflow = threading.Event()
def collect():
while chunk := process.stdout.read(65536):
if len(output) + len(chunk) > MAX_LOG:
overflow.set()
process.kill()
return
output.extend(chunk)
reader = threading.Thread(target=collect, daemon=True)
reader.start()
try:
process.wait(timeout=timeout)
except BaseException:
process.kill()
process.wait(timeout=5)
raise
finally:
reader.join(timeout=2)
if not reader.is_alive():
process.stdout.close()
if reader.is_alive():
raise ValueError("Runner left an unconfirmed output producer")
if overflow.is_set():
raise ValueError("Runner diagnostic output exceeded limit")
text = output.decode("utf-8", errors="strict")
if process.returncode:
raise ValueError(f"Runner returned {process.returncode}: {text[-4000:]}")
return text
class Execution:
def __init__(self, root, *, state_root=None, clock=time.time, runner=invoke):
self.root = Path(root).resolve()
if state_root is None:
self.root.mkdir(parents=True, exist_ok=True)
self.state_root = self.root
else:
if not self.root.is_dir():
raise ValueError("Pinned input root must already exist")
self.state_root = Path(state_root).resolve()
self.state_root.mkdir(parents=True, exist_ok=True)
self.clock, self.runner = clock, runner
self.db = sqlite3.connect(self.state_root / "learning-execution.sqlite3", timeout=10)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA synchronous=FULL")
self.db.executescript("""
CREATE TABLE IF NOT EXISTS learning_runs (
id TEXT PRIMARY KEY, plan TEXT NOT NULL, created REAL NOT NULL);
CREATE TABLE IF NOT EXISTS learning_phases (
run TEXT NOT NULL, position INTEGER NOT NULL, name TEXT NOT NULL,
state TEXT NOT NULL, token TEXT, started REAL, finished REAL,
receipt TEXT, incident TEXT, reconciliation TEXT,
PRIMARY KEY(run,name));
""")
def close(self):
self.db.close()
@contextmanager
def transaction(self):
self.db.execute("BEGIN IMMEDIATE")
try:
yield
self.db.commit()
except BaseException:
self.db.rollback()
raise
def register(self, plan):
raw = encoded(plan)
if set(plan) != {"schema", "objective", "inputs", "phases"} or plan["schema"] != SCHEMA:
raise ValueError("Unsupported execution plan")
if not isinstance(plan["objective"], str) or not 1 <= len(plan["objective"]) <= 4096:
raise ValueError("Objective required")
if not isinstance(plan["inputs"], dict) or not 1 <= len(plan["inputs"]) <= 1024:
raise ValueError("Bounded pinned inputs required")
for name, value in plan["inputs"].items():
if (
set(value) != {"sha256", "bytes"}
or not re.fullmatch(r"[0-9a-f]{64}", value["sha256"])
or type(value["bytes"]) is not int
or value["bytes"] < 0
):
raise ValueError("Exact input pin required")
confined(self.root, name)
phases = plan["phases"]
if not isinstance(phases, list) or not 1 <= len(phases) <= 12:
raise ValueError("One to twelve phases required")
names, outputs = set(), set()
for phase in phases:
if set(phase) != {
"name",
"run",
"verify",
"outputs",
"run_timeout_seconds",
"verify_timeout_seconds",
}:
raise ValueError("Exact phase contract required")
name = phase["name"]
if (
not isinstance(name, str)
or not re.fullmatch(r"[a-z][a-z0-9_-]{0,47}", name)
or name in names
):
raise ValueError("Unique phase name required")
names.add(name)
for action in ("run", "verify"):
argv = phase[action]
if (
not isinstance(argv, list)
or not 1 <= len(argv) <= 16
or any(not isinstance(x, str) or len(x) > 4096 or "\x00" in x for x in argv)
or argv[0] not in plan["inputs"]
or not argv[0].endswith(".py")
):
raise ValueError("Pinned Python command required")
members = phase["outputs"]
if not isinstance(members, list) or not 1 <= len(members) <= 32:
raise ValueError("Declared phase outputs required")
for member in members:
confined(self.root, member)
if member in outputs or member in plan["inputs"]:
raise ValueError("Output aliases another output or input")
outputs.add(member)
for field, limit in (("run_timeout_seconds", 7200), ("verify_timeout_seconds", 300)):
if type(phase[field]) is not int or not 1 <= phase[field] <= limit:
raise ValueError("Bounded per-process deadline required")
check_pins(self.root, plan["inputs"])
identity = digest(plan)
with self.transaction():
if self.db.execute("SELECT 1 FROM learning_runs WHERE id=?", (identity,)).fetchone():
return identity
if self.db.execute(
"SELECT 1 FROM learning_phases WHERE state IN ('running','unknown')"
).fetchone():
raise ValueError("An unfinished executor still owns resources")
total = self.db.execute(
"SELECT COALESCE(SUM(length(CAST(plan AS BLOB))),0) FROM learning_runs"
).fetchone()[0]
count = self.db.execute("SELECT COUNT(*) FROM learning_runs").fetchone()[0]
if total + len(raw.encode()) > 16 * 1024**2 or count >= 512:
raise ValueError("Execution ledger quota reached; archive closed runs")
for name in outputs:
if confined(self.root, name).exists():
raise ValueError("Unowned output already exists: " + name)
self.db.execute(
"INSERT INTO learning_runs VALUES(?,?,?)", (identity, raw, self.clock())
)
self.db.executemany(
"INSERT INTO learning_phases(run,position,name,state) VALUES(?,?,?,'pending')",
[(identity, i, p["name"]) for i, p in enumerate(phases)],
)
return identity
def status(self, identity):
run = self.db.execute("SELECT * FROM learning_runs WHERE id=?", (identity,)).fetchone()
if run is None:
raise ValueError("Unknown execution")
phases = []
for row in self.db.execute(
"SELECT * FROM learning_phases WHERE run=? ORDER BY position", (identity,)
):
receipt = json.loads(row["receipt"]) if row["receipt"] else None
phases.append(
dict(
name=row["name"],
state=row["state"],
token=row["token"],
started=row["started"],
finished=row["finished"],
receipt_sha256=digest(receipt) if receipt else None,
output_count=len(receipt["outputs"]) if receipt else 0,
artifact_count=len(receipt["artifacts"]) if receipt else 0,
incident=row["incident"],
reconciled=row["reconciliation"] is not None,
)
)
return dict(id=identity, phases=phases)
def _context(self, identity, name):
row = self.db.execute("SELECT plan FROM learning_runs WHERE id=?", (identity,)).fetchone()
if row is None:
raise ValueError("Unknown execution")
plan = json.loads(row["plan"])
phase = next((p for p in plan["phases"] if p["name"] == name), None)
if phase is None:
raise ValueError("Unknown phase")
previous_artifacts = {}
for previous in plan["phases"]:
if previous["name"] == name:
break
row = self.db.execute(
"SELECT state,receipt FROM learning_phases WHERE run=? AND name=?",
(identity, previous["name"]),
).fetchone()
if row["state"] != "complete":
raise ValueError("Previous phase is not complete")
for member, expected in json.loads(row["receipt"])["artifacts"].items():
if member in previous_artifacts and previous_artifacts[member] != expected:
raise ValueError("Conflicting previous artifact pins: " + member)
previous_artifacts[member] = expected
# Merge only within this boundary. Every later pre/post/resume call hashes again.
# Validate conflicts before reading payloads; never let a later receipt replace a pin.
check_pins(self.root, plan["inputs"])
check_pins(self.root, previous_artifacts)
return plan, phase
def _verify(self, identity, phase, token):
before = {name: pin(self.root, name) for name in phase["outputs"]}
raw = self.runner(self.root, phase["verify"], phase["verify_timeout_seconds"])
if len(raw.encode()) > MAX_JSON:
raise ValueError("Verifier receipt too large")
verdict = json.loads(raw)
if (
set(verdict) != {"valid", "outputs", "artifacts"}
or verdict["valid"] is not True
or verdict["outputs"] != before
):
raise ValueError("Verifier did not validate exact declared outputs")
artifacts = verdict["artifacts"]
if (
not isinstance(artifacts, dict)
or not 1 <= len(artifacts) <= 1024
or any(artifacts.get(name) != expected for name, expected in before.items())
):
raise ValueError("Verifier artifact closure must contain exact declared outputs")
for expected in artifacts.values():
if (
not isinstance(expected, dict)
or set(expected) != {"sha256", "bytes"}
or not isinstance(expected["sha256"], str)
or not re.fullmatch(r"[0-9a-f]{64}", expected["sha256"])
or type(expected["bytes"]) is not int
or expected["bytes"] < 0
):
raise ValueError("Exact artifact closure pins required")
check_pins(self.root, artifacts)
self._context(identity, phase["name"])
return dict(
schema=SCHEMA,
run=identity,
phase=phase["name"],
token=token,
outputs=before,
artifacts=artifacts,
artifact_validation=True,
model_acceptance=False,
)
def execute(self, identity, name):
with self.transaction():
_, phase = self._context(identity, name)
row = self.db.execute(
"SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name)
).fetchone()
if row["state"] == "complete":
receipt = json.loads(row["receipt"])
check_pins(self.root, receipt["artifacts"])
return receipt
if (
row["state"] != "pending"
or self.db.execute(
"SELECT 1 FROM learning_phases WHERE state IN ('running','unknown')"
).fetchone()
):
raise ValueError("Unfinished executor requires root reconciliation")
if any(confined(self.root, x).exists() for x in phase["outputs"]):
raise ValueError("Unowned phase output exists")
used = self.db.execute(
"SELECT COALESCE(SUM(COALESCE(length(CAST(receipt AS BLOB)),0) + "
"COALESCE(length(CAST(reconciliation AS BLOB)),0)),0) FROM learning_phases"
).fetchone()[0]
if used + MAX_JSON + 8192 > 32 * 1024**2:
raise ValueError("Execution receipt quota reached; archive closed runs")
token = uuid.uuid4().hex
self.db.execute(
"UPDATE learning_phases SET state='running',token=?,started=? "
"WHERE run=? AND name=?",
(token, self.clock(), identity, name),
)
try:
self.runner(self.root, phase["run"], phase["run_timeout_seconds"])
receipt = self._verify(identity, phase, token)
with self.transaction():
self._finish(identity, name, token, receipt)
return receipt
except BaseException as error:
with self.transaction():
self.db.execute(
"UPDATE learning_phases SET state='unknown',incident=? "
"WHERE run=? AND name=? AND token=? AND state='running'",
(str(error)[:4096], identity, name, token),
)
raise
def _finish(self, identity, name, token, receipt):
changed = self.db.execute(
"UPDATE learning_phases SET state='complete',receipt=?,finished=? "
"WHERE run=? AND name=? AND token=? AND state IN ('running','unknown')",
(encoded(receipt), self.clock(), identity, name, token),
).rowcount
if changed != 1:
raise ValueError("Executor token is stale")
def reconcile(self, identity, name, token, stopped_evidence):
"""Trusted root attests process termination. Never launches/retries fit.
A lost acknowledgement can be recovered only by the same pinned verifier.
Incomplete/invalid outputs retain ownership; caller must archive and close
the failed experiment explicitly, rather than rerun into partial output.
"""
if not isinstance(stopped_evidence, str) or not 1 <= len(stopped_evidence) <= 4096:
raise ValueError("Root termination evidence required")
_, phase = self._context(identity, name)
row = self.db.execute(
"SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name)
).fetchone()
if row["state"] not in ("running", "unknown") or row["token"] != token:
raise ValueError("No matching unfinished executor")
receipt = self._verify(identity, phase, token)
with self.transaction():
self._finish(identity, name, token, receipt)
self.db.execute(
"UPDATE learning_phases SET reconciliation=? WHERE run=? AND name=?",
(stopped_evidence, identity, name),
)
return receipt
def close_failed(self, identity, name, token, stopped_evidence, archive):
"""Trusted root closes a stopped, archived failure; outputs are preserved."""
if not isinstance(stopped_evidence, str) or not 1 <= len(stopped_evidence) <= 4096:
raise ValueError("Root termination evidence required")
if not isinstance(archive, dict) or len(archive) != 1:
raise ValueError("One verified failure archive required")
check_pins(self.root, archive)
with self.transaction():
row = self.db.execute(
"SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name)
).fetchone()
if row is None or row["state"] not in ("running", "unknown") or row["token"] != token:
raise ValueError("No matching unfinished executor")
receipt = dict(
stopped_evidence=stopped_evidence,
archive=archive,
outputs_preserved=True,
retry_authorized=False,
)
self.db.execute(
"UPDATE learning_phases SET state='failed',finished=?,reconciliation=? "
"WHERE run=? AND name=?",
(self.clock(), encoded(receipt), identity, name),
)
return receipt
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", type=Path)
parser.add_argument("--state-root", type=Path)
sub = parser.add_subparsers(dest="action", required=True)
register = sub.add_parser("register")
register.add_argument("manifest", type=Path)
for action in ("status", "execute", "reconcile", "close-failed"):
command = sub.add_parser(action)
command.add_argument("identity")
if action != "status":
command.add_argument("phase")
if action in ("reconcile", "close-failed"):
command.add_argument("token")
command.add_argument("stopped_evidence")
if action == "close-failed":
command.add_argument("archive")
args = parser.parse_args()
run = Execution(args.root, state_root=args.state_root)
try:
if args.action == "register":
data = args.manifest.read_bytes()
if len(data) > MAX_JSON:
raise ValueError("Manifest too large")
result = run.register(json.loads(data))
elif args.action == "status":
result = run.status(args.identity)
elif args.action == "execute":
result = run.execute(args.identity, args.phase)
elif args.action == "reconcile":
result = run.reconcile(args.identity, args.phase, args.token, args.stopped_evidence)
else:
result = run.close_failed(
args.identity,
args.phase,
args.token,
args.stopped_evidence,
{args.archive: pin(run.root, args.archive)},
)
print(encoded(result))
finally:
run.close()
if __name__ == "__main__":
main()
@@ -0,0 +1,241 @@
"""Bounded linear capacity/optimizer control over frozen features, offline only.
This changes both capacity and optimizer relative to the MLP control; it does not
isolate either cause or qualify transfer. Inputs contain only known binary labels.
Timeouts are cooperative between tensor operations; an external process deadline
must bound a stalled kernel. No torch import or fitting occurs at module import.
"""
import math
import time
L2 = 0.01
MAX_ITER = 300
MAX_EVAL = 400
TOLERANCE_GRAD = 1e-5
TOLERANCE_CHANGE = 1e-10
STATIONARITY_LIMIT = 1e-4
FIT_TIMEOUT_SECONDS = 120.0
EVALUATION_TIMEOUT_SECONDS = 120.0
ARMS = frozenset({"coarse_only", "scene_features"})
def network(seed=0, channels=256):
"""Return a zero-initialized head compatible with feature_refinement.predict.
``seed`` is accepted for the existing factory interface but cannot affect the
zero initialization. Creating this head does not consume the torch RNG.
"""
import torch
from torch import nn
if type(channels) is not int or channels < 1:
raise ValueError("Positive integer feature channel count required")
class Head(nn.Module):
def __init__(self):
super().__init__()
self.weight = nn.Parameter(torch.zeros(1, channels + 1))
self.bias = nn.Parameter(torch.zeros(1))
def forward(self, fine, coarse, arm):
if arm not in ARMS:
raise ValueError("Unknown feature arm")
if fine.ndim != 2 or fine.shape[1] != channels:
raise ValueError("Expected points by feature channels")
if coarse.shape != (len(fine), 1):
raise ValueError("Expected points by one coarse logits")
for value in (fine, coarse):
if value.dtype != self.weight.dtype or value.device != self.weight.device:
raise ValueError("Head and features must have the same dtype and device")
x = fine if arm == "scene_features" else torch.zeros_like(fine)
return coarse + nn.functional.linear(
torch.cat((x, coarse), dim=1), self.weight, self.bias
)
return Head()
def _validate(Xfine, coarse, target, weights, arm, chunk):
import torch
if arm not in ARMS:
raise ValueError("Unknown feature arm")
if type(chunk) is not int or chunk < 1:
raise ValueError("Positive integer chunk required")
values = (Xfine, coarse, target, weights)
if not all(isinstance(value, torch.Tensor) for value in values):
raise ValueError("All inputs must be torch tensors")
if Xfine.ndim != 2 or min(Xfine.shape) < 1:
raise ValueError("Expected nonempty points by feature channels")
n = len(Xfine)
if coarse.shape != (n, 1):
raise ValueError("Expected points by one coarse logits")
if target.shape not in {(n,), (n, 1)} or weights.shape not in {(n,), (n, 1)}:
raise ValueError("Expected one target and weight per point")
if Xfine.dtype not in {torch.float32, torch.float64}:
raise ValueError("Features must be float32 or float64")
if coarse.dtype != Xfine.dtype or weights.dtype != Xfine.dtype:
raise ValueError("Features, coarse logits and weights must share a floating dtype")
if target.is_complex() or target.dtype not in {
torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32,
torch.int64, torch.float32, torch.float64,
}:
raise ValueError("Targets must have a real binary dtype")
if any(value.device != Xfine.device for value in values):
raise ValueError("All inputs must share a device")
if any(value.requires_grad for value in values):
raise ValueError("Inputs must be frozen, without input gradients")
if not all(bool(torch.isfinite(value).all()) for value in values):
raise ValueError("Inputs must be finite")
if not bool(((target == 0) | (target == 1)).all()):
raise ValueError("Only binary known targets 0/1 allowed, including at zero weight")
if not bool((weights >= 0).all()):
raise ValueError("Weights must be nonnegative")
weight_sum = weights.sum(dtype=torch.float64)
if not bool(torch.isfinite(weight_sum)) or float(weight_sum) <= 0:
raise ValueError("Weights must have a finite positive sum")
return target.reshape(-1, 1).to(Xfine.dtype), weights.reshape(-1, 1) / weight_sum
class _TechnicalStop(RuntimeError):
pass
def fit(Xfine, coarse, target, weights, arm="scene_features", *, chunk=8192):
"""Fit all supplied known pixels and return ``(head, diagnostics)``.
Objective: sum(w * BCE) / sum(w) + .5 * .01 * sum(residual_params**2).
Bias and inactive fine coefficients are penalized as well, making the finite
dimensional objective strongly convex. Weight scale and pixel duplication do
not alter its definition. Chunking bounds activation memory, not sample count.
All hyperparameters are frozen constants. At most 400 objective/gradient
evaluations include a reserved final evaluation at the optimizer's returned
parameters. A technical stop returns the last fully evaluated parameters, if
any, and cannot be interpreted as a negative learning result.
"""
import torch
from torch.nn import functional as F
started = time.monotonic()
y, normalized_weights = _validate(Xfine, coarse, target, weights, arm, chunk)
head = network(channels=Xfine.shape[1]).to(Xfine)
parameters = list(head.parameters())
optimizer = torch.optim.LBFGS(
parameters, lr=1.0, max_iter=MAX_ITER, max_eval=MAX_EVAL,
tolerance_grad=TOLERANCE_GRAD, tolerance_change=TOLERANCE_CHANGE,
history_size=100, line_search_fn="strong_wolfe",
)
evaluations = 0
completed_evaluations = 0
last_values = None
last_parameters = [p.detach().clone() for p in parameters]
stop_reason = None
runtime_error = None
def check_time(evaluation_started):
now = time.monotonic()
if now - started >= FIT_TIMEOUT_SECONDS:
raise _TechnicalStop("fit_timeout")
if now - evaluation_started >= EVALUATION_TIMEOUT_SECONDS:
raise _TechnicalStop("evaluation_timeout")
def evaluate(*, final=False):
nonlocal evaluations, completed_evaluations, last_values, last_parameters
# LBFGS line searches can otherwise exceed the nominal max_eval budget.
if evaluations >= MAX_EVAL - (0 if final else 1):
raise _TechnicalStop("evaluation_limit")
evaluation_started = time.monotonic()
check_time(evaluation_started)
evaluations += 1
optimizer.zero_grad(set_to_none=True)
data_loss = Xfine.new_zeros(())
for start in range(0, len(Xfine), chunk):
check_time(evaluation_started)
end = min(start + chunk, len(Xfine))
logits = head(Xfine[start:end], coarse[start:end], arm)
term = (
F.binary_cross_entropy_with_logits(logits, y[start:end], reduction="none")
* normalized_weights[start:end]
).sum()
if not bool(torch.isfinite(term)):
raise _TechnicalStop("nonfinite_objective")
term.backward()
data_loss += term.detach()
check_time(evaluation_started)
l2_loss = 0.5 * L2 * sum(p.square().sum() for p in parameters)
if not bool(torch.isfinite(l2_loss)):
raise _TechnicalStop("nonfinite_objective")
l2_loss.backward()
gradients = torch.cat([p.grad.reshape(-1) for p in parameters])
if not bool(torch.isfinite(gradients).all()):
raise _TechnicalStop("nonfinite_gradient")
objective = data_loss + l2_loss.detach()
if not bool(torch.isfinite(objective)):
raise _TechnicalStop("nonfinite_objective")
values = {
"loss": float(objective), "data_loss": float(data_loss),
"l2_loss": float(l2_loss.detach()),
"gradient_inf_norm": float(gradients.abs().max()),
}
check_time(evaluation_started)
last_values = values
last_parameters = [p.detach().clone() for p in parameters]
completed_evaluations += 1
return objective
try:
optimizer.step(evaluate)
evaluate(final=True)
except _TechnicalStop as exc:
stop_reason = str(exc)
except RuntimeError as exc:
stop_reason = "optimizer_runtime_error"
runtime_error = str(exc)
if stop_reason is not None:
with torch.no_grad():
for parameter, saved in zip(parameters, last_parameters, strict=True):
parameter.copy_(saved)
values = last_values or dict(
loss=None, data_loss=None, l2_loss=None, gradient_inf_norm=None,
)
stationarity = (
values["gradient_inf_norm"] is not None
and math.isfinite(values["gradient_inf_norm"])
and values["gradient_inf_norm"] <= STATIONARITY_LIMIT
)
if stop_reason is None and not stationarity:
stop_reason = "stationarity_not_met"
# A timeout remains a technical stop even if the last iterate was stationary.
converged = stop_reason is None and stationarity
head.zero_grad(set_to_none=True)
head.eval()
diagnostics = {
"status": "converged" if converged else "technical_stop",
"converged": converged, "stop_reason": stop_reason,
**values,
"stationarity": {"passed": stationarity, "limit": STATIONARITY_LIMIT},
"arm": arm, "points": len(Xfine),
"parameter_count": sum(p.numel() for p in parameters),
"parameters": {
"weight": head.weight.detach().cpu().tolist(),
"bias": head.bias.detach().cpu().tolist(),
},
"evaluations": evaluations, "completed_evaluations": completed_evaluations,
"iterations": optimizer.state.get(parameters[0], {}).get("n_iter", 0),
"seconds": time.monotonic() - started,
"configuration": {
"l2": L2, "max_iter": MAX_ITER, "max_eval": MAX_EVAL,
"tolerance_grad": TOLERANCE_GRAD, "tolerance_change": TOLERANCE_CHANGE,
"line_search_fn": "strong_wolfe", "chunk": chunk,
"fit_timeout_seconds": FIT_TIMEOUT_SECONDS,
"evaluation_timeout_seconds": EVALUATION_TIMEOUT_SECONDS,
},
"limitation": "Capacity and optimizer both differ from the MLP control.",
"production_eligible": False,
}
if runtime_error is not None:
diagnostics["runtime_error"] = runtime_error
return head, diagnostics
@@ -0,0 +1,219 @@
"""Validated mixed TRAIN labels with conserved physical-group class masses.
Inputs come from hash-verified ``Supervision.training_batches('observed_paint')``.
This adapter does not admit reviews or authenticate their author. The caller pins
an independently reviewed withdrawal manifest's exact UTF-8 bytes and SHA-256:
{"schema": "missioncore.mixed-withdrawals/v1", "evidence": [
{"path": "archive/member.json", "sha256": "<reviewed evidence hash>"}],
"records": {"<sample_id>": {"source": <entry source>, "input": <input>,
"old_target_sha256": "<old uint8 target bytes hash>",
"runs": [[row, inclusive_start, exclusive_end]]}}}
The manifest may cover a full release while records select a whole-street fold.
Every selected withdrawal must match exactly. Audit the complete release once
before splitting; no pixel count or location is an authorization. Evidence files
must be verified by the caller before pinning this manifest. Class/cohort masks
in existing records are historical; score them intersected with the final target.
"""
import hashlib
import json
import numpy as np
from admission_store import pixel_target
def _sha(value):
return hashlib.sha256(value).hexdigest()
def _hash(value):
return (
isinstance(value, str) and len(value) == 64 and all(c in "0123456789abcdef" for c in value)
)
def _withdrawals(payload, expected):
if payload is None and expected is None:
return {}
if not isinstance(payload, bytes) or not _hash(expected) or _sha(payload) != expected:
raise ValueError("Withdrawal manifest bytes differ from their frozen hash")
doc = json.loads(payload)
if (
doc.get("schema") != "missioncore.mixed-withdrawals/v1"
or not isinstance(doc.get("records"), dict)
or not isinstance(doc.get("evidence"), list)
or not doc["evidence"]
or any(
not isinstance(e, dict)
or not isinstance(e.get("path"), str)
or not e["path"]
or not _hash(e.get("sha256"))
for e in doc["evidence"]
)
):
raise ValueError("Pinned reviewed withdrawal evidence required")
return doc["records"]
def _target(entry, selected):
matches = [v for v in entry["targets"] if v["view"] == selected["view"]]
if len(matches) != 1:
raise ValueError("Exactly one target for the selected input view required")
view = matches[0]
if view["size"] != selected["camera"]["size"]:
raise ValueError("Target and selected image dimensions differ")
return np.frombuffer(pixel_target(view), dtype=np.uint8).reshape(tuple(view["size"][::-1]))
def _removals(proof, record, entry, before):
mask = np.zeros(before.shape, dtype=bool)
if proof is None:
return mask
if (
proof.get("source") != entry["source"]
or proof.get("input") != record["input"]
or proof.get("old_target_sha256") != _sha(before.tobytes())
or not isinstance(proof.get("runs"), list)
or not proof["runs"]
):
raise ValueError("Withdrawal evidence does not bind this source, view and old target")
height, width = before.shape
for run in proof["runs"]:
if (
not isinstance(run, list)
or len(run) != 3
or any(type(v) is not int for v in run)
or not 0 <= run[0] < height
or not 0 <= run[1] < run[2] <= width
):
raise ValueError("Withdrawal run outside selected native image")
row, start, end = run
if mask[row, start:end].any():
raise ValueError("Duplicate withdrawal pixels")
mask[row, start:end] = True
return mask
def prepare_mixed(
records, weights, old_entries, new_entries, *, withdrawal_bytes=None, withdrawal_sha256=None
):
"""Return copied records, name-keyed weights and JSON-serializable audit.
Only selected TRAIN sample IDs may appear in the entry mappings. Group/class
mass is conserved independently, never pooled across streets or classes.
A changed class shares its baseline mass equally across final supported
frames, then uniformly over that frame's class pixels. An unchanged class
retains its exact weights. Unknown always has zero mass. Added support with
no prior group/class mass, or withdrawal of all its support, fails closed.
"""
names = [r["name"] for r in records]
ids = [r["sample_id"] for r in records]
if (
not records
or len(set(names)) != len(names)
or len(set(ids)) != len(ids)
or set(names) != set(weights)
or set(ids) != set(old_entries)
or set(ids) != set(new_entries)
):
raise ValueError("Unique matching TRAIN records, weights and release entries required")
proofs = _withdrawals(withdrawal_bytes, withdrawal_sha256)
out, result, audit = [], {}, []
for record in records:
sid, name = record["sample_id"], record["name"]
old, new = old_entries[sid], new_entries[sid]
fields = ("sample_id", "source", "physical_group", "split", "task", "inputs")
if (
any(old[k] != new[k] for k in fields)
or old["sample_id"] != sid
or old["split"] != "train"
or record["split"] != "train"
or old["task"] != "observed_paint"
or old["physical_group"] != record["group"]
or not old["source"]
or old["inputs"].count(record["input"]) != 1
or record["input"]["sample_id"] != sid
or ("source" in record and record["source"] != old["source"])
):
raise ValueError("TRAIN source, sample, physical group or image binding changed")
before, after = _target(old, record["input"]), _target(new, record["input"])
target, weight = record["target"], weights[name]
if (
target.dtype != np.uint8
or target.shape != before.shape
or not np.array_equal(target, before)
or weight.shape != before.shape
or weight.dtype.kind != "f"
or not np.isfinite(weight).all()
or np.any(weight[before != 255] <= 0)
or np.any(weight[before == 255] != 0)
):
raise ValueError("Cached old target or known/unknown weight support differs")
removed = (before != 255) & (after == 255)
if np.any((before != 255) & (after != 255) & (before != after)):
raise ValueError("Known class flips are not mixed-supervision growth")
allowed = _removals(proofs.get(sid), record, old, before)
if not np.array_equal(removed, allowed):
raise ValueError("Withdrawals differ from the exact reviewed pixels")
paint, background = (before == 255) & (after == 1), (before == 255) & (after == 0)
out.append(
dict(
record,
target=after.copy(),
mixed_added_paint=paint,
mixed_added_background=background,
mixed_withdrawn=removed,
)
)
result[name] = weight.copy()
result[name][after == 255] = 0
audit.append(
dict(
name=name,
sample_id=sid,
group=record["group"],
old_target_sha256=_sha(before.tobytes()),
new_target_sha256=_sha(after.tobytes()),
added_paint=int(paint.sum()),
added_background=int(background.sum()),
withdrawn_paint=int((removed & (before == 1)).sum()),
withdrawn_background=int((removed & (before == 0)).sum()),
)
)
mass_audit = []
for group in sorted({r["group"] for r in records}):
paired = [(r, n) for r, n in zip(records, out, strict=True) if r["group"] == group]
for label in (0, 1):
mass = sum(
float(weights[r["name"]][r["target"] == label].sum(dtype=np.float64))
for r, _ in paired
)
changed = any(
not np.array_equal(r["target"] == label, n["target"] == label) for r, n in paired
)
present = [n for _, n in paired if np.any(n["target"] == label)]
if changed:
if mass <= 0 or not present:
raise ValueError("Changed group/class needs baseline mass and final support")
for n in present:
mask = n["target"] == label
result[n["name"]][mask] = mass / len(present) / int(mask.sum())
actual = sum(
float(result[n["name"]][n["target"] == label].sum(dtype=np.float64))
for _, n in paired
)
if not np.isclose(actual, mass, atol=1e-8, rtol=1e-6):
raise ValueError("Physical-group class mass changed")
mass_audit.append(
dict(
group=group,
label=label,
before=mass,
after=actual,
redistributed=changed,
supported_frames=len(present),
)
)
return out, result, dict(records=audit, masses=mass_audit, withdrawal_sha256=withdrawal_sha256)
@@ -0,0 +1,33 @@
"""Windows-owned conversion descendants die with the learning coordinator."""
import ctypes
from ctypes import wintypes
class NativeChildren:
def __init__(self):
self.kernel = ctypes.WinDLL("kernel32", use_last_error=True)
self.kernel.CreateJobObjectW.restype = wintypes.HANDLE
self.kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
self.kernel.SetInformationJobObject.argtypes = [
wintypes.HANDLE,
ctypes.c_int,
ctypes.c_void_p,
wintypes.DWORD,
]
self.kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
self.kernel.CloseHandle.argtypes = [wintypes.HANDLE]
self.handle = self.kernel.CreateJobObjectW(None, None)
limits = ctypes.create_string_buffer(144)
ctypes.c_uint32.from_buffer(limits, 16).value = 0x2000
if not self.handle or not self.kernel.SetInformationJobObject(self.handle, 9, limits, 144):
raise ctypes.WinError(ctypes.get_last_error())
def assign(self, process):
if not self.kernel.AssignProcessToJobObject(self.handle, int(process._handle)):
process.kill()
process.wait(timeout=30)
raise ctypes.WinError(ctypes.get_last_error())
def close(self):
self.kernel.CloseHandle(self.handle)
@@ -0,0 +1,255 @@
"""Shared native/low-pass RGB residual point head; offline, no fitting or IDs.
Native guidance is compared with area-downsampled/bilinear-upsampled guidance.
This changes spatial detail and local color mixing together. It does not prove
the cause of a prior model's boundary errors. Input fine/coarse maps are already
frozen and C4-averaged; only RGB patches receive the additional C4 operation here.
"""
from feature_refinement import sample_native
ARMS = frozenset({"native_rgb", "lowpass_rgb"})
PATCH_SIZE = 5
PATCH_CHANNELS = 3 * PATCH_SIZE * PATCH_SIZE
def _floating(value, name):
import torch
if not isinstance(value, torch.Tensor) or value.dtype not in {torch.float32, torch.float64}:
raise ValueError(f"{name} must be a float32/float64 tensor")
if value.requires_grad:
raise ValueError(f"{name} must be frozen without input gradients")
if not bool(torch.isfinite(value).all()):
raise ValueError(f"{name} must be finite")
def _rgb(rgb, *, centered):
_floating(rgb, "RGB")
if rgb.ndim != 4 or rgb.shape[:2] != (1, 3) or min(rgb.shape[-2:]) < 1:
raise ValueError("Expected nonempty RGB with shape (1, 3, H, W)")
lower = -1 if centered else 0
if not bool(((rgb >= lower) & (rgb <= 1)).all()):
raise ValueError(f"RGB must be in [{lower}, 1]")
def _shape(shape):
if (
not isinstance(shape, (tuple, list))
or len(shape) != 2
or any(type(size) is not int or size < 1 for size in shape)
):
raise ValueError("Feature shape must contain two positive integer dimensions")
return tuple(shape)
def _maps(fine, coarse, rgb):
_floating(fine, "Fine features")
_floating(coarse, "Coarse logits")
_rgb(rgb, centered=True)
if fine.ndim != 4 or fine.shape[0] != 1 or min(fine.shape[1:]) < 1:
raise ValueError("Expected one nonempty fine feature map (1, C, h, w)")
if coarse.ndim != 2 or min(coarse.shape) < 1 or rgb.shape[-2:] != coarse.shape:
raise ValueError("Coarse logits and RGB must have the same nonempty native shape")
for value in (coarse, rgb):
if value.dtype != fine.dtype or value.device != fine.device:
raise ValueError("Fine, coarse and RGB must share a dtype and device")
def _indices(indices, shape, device):
import torch
if (
not isinstance(indices, torch.Tensor)
or indices.ndim != 1
or indices.dtype != torch.long
or indices.device != device
):
raise ValueError("Expected flat int64 native indices on the image device")
if len(indices) and (bool((indices < 0).any()) or bool((indices >= shape[0] * shape[1]).any())):
raise ValueError("Point outside the native image")
def _patch(patch):
_floating(patch, "RGB patch")
if patch.ndim != 2 or patch.shape[1] != PATCH_CHANNELS:
raise ValueError("Expected RGB patches with shape (N, 75)")
if not bool(((patch >= -1) & (patch <= 1)).all()):
raise ValueError("Centered RGB patches must be in [-1, 1]")
def network(seed, channels=256, width=64):
"""Two shared Linear/ReLU layers with coarse concatenated at every layer.
Default parameter count is 25,602. The final layer is zero initialized, so
output is exactly the supplied coarse logit before fitting. Initialization is
on CPU and preserves the calling CPU RNG state; no CUDA RNG is reseeded.
"""
import torch
from torch import nn
if any(type(value) is not int or value < 1 for value in (channels, width)):
raise ValueError("Positive integer feature channel count and width required")
class Head(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.ModuleList(
[
nn.Linear(channels + PATCH_CHANNELS + 1, width, device="cpu"),
nn.Linear(width + 1, width, device="cpu"),
]
)
self.output = nn.Linear(width + 1, 1, device="cpu")
for layer in self.layers:
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
nn.init.zeros_(layer.bias)
nn.init.zeros_(self.output.weight)
nn.init.zeros_(self.output.bias)
def forward(self, fine, coarse, patch):
_floating(fine, "Fine points")
_floating(coarse, "Coarse points")
_patch(patch)
if fine.ndim != 2 or fine.shape[1] != channels:
raise ValueError("Expected points by fine channels")
if coarse.shape != (len(fine), 1) or len(patch) != len(fine):
raise ValueError("Fine, coarse and RGB points must be aligned")
for value in (fine, coarse, patch):
if (
value.dtype != self.output.weight.dtype
or value.device != self.output.weight.device
):
raise ValueError("Point inputs and head must share a dtype and device")
x = torch.cat((fine, patch), dim=1)
for layer in self.layers:
x = torch.relu(layer(torch.cat((x, coarse), dim=1)))
return coarse + self.output(torch.cat((x, coarse), dim=1))
with torch.random.fork_rng(devices=[]):
torch.random.default_generator.manual_seed(seed)
return Head()
def prepare_rgb(rgb, feature_shape, arm):
"""Prepare native-sized centered guidance once, before point sampling.
Input RGB is floating (1, 3, H, W) in [0, 1]. Low-pass uses the actual frozen
feature grid (normally 128x128), area downsampling, then bilinear upsampling
with align_corners=False. Both arms then apply (RGB - .5) / .5; no learned or
held-image statistics. The feature grid must not exceed either native axis.
"""
from torch.nn import functional as F
if arm not in ARMS:
raise ValueError("Unknown native-detail arm")
_rgb(rgb, centered=False)
feature_shape = _shape(feature_shape)
native_shape = rgb.shape[-2:]
if any(a > b for a, b in zip(feature_shape, native_shape, strict=True)):
raise ValueError("The low-pass feature grid must not exceed the native image")
guidance = rgb
if arm == "lowpass_rgb":
guidance = F.interpolate(guidance, size=feature_shape, mode="area")
guidance = F.interpolate(
guidance, size=native_shape, mode="bilinear", align_corners=False
)
return (guidance - 0.5) / 0.5
def _sample_patch(rgb, indices):
import torch
h, w = rgb.shape[-2:]
offsets = torch.arange(-2, 3, device=rgb.device)
ys = torch.div(indices, w, rounding_mode="floor")
xs = indices % w
rows = (ys[:, None, None] + offsets[None, :, None]).clamp(0, h - 1)
cols = (xs[:, None, None] + offsets[None, None, :]).clamp(0, w - 1)
# Shape C,N,5,5 -> N,C,5,5, never a full-image unfold allocation.
return rgb[0][:, rows, cols].permute(1, 0, 2, 3).reshape(len(indices), PATCH_CHANNELS)
def sample_patch(prepared_rgb, indices):
"""Sample centered 5x5 patches at integer native pixel centres.
Flattening is channel-major: R's 25 values, G's 25, then B's 25. Within each
channel, row-major offsets are dy=-2..2, dx=-2..2. Out-of-image offsets clamp
independently to the nearest valid row/column (replicate border).
"""
_rgb(prepared_rgb, centered=True)
_indices(indices, prepared_rgb.shape[-2:], prepared_rgb.device)
return _sample_patch(prepared_rgb, indices)
def _rotate_patch(patch, k):
import torch
return torch.rot90(patch.reshape(-1, 3, PATCH_SIZE, PATCH_SIZE), k, (-2, -1)).reshape(
len(patch), PATCH_CHANNELS
)
def rotate_patch(flat_patch, k):
"""Rotate each RGB patch k quarter-turns counterclockwise; keep RGB order.
k is exactly 0, 1, 2 or 3. Only the two 5x5 spatial axes rotate. Fine features,
coarse logits, centre labels and point order are unchanged. The runner owns
training's shared k=step%4 schedule; no rotation is selected from image data.
"""
_patch(flat_patch)
if type(k) is not int or k not in range(4):
raise ValueError("Patch rotation must be an integer from 0 through 3")
return _rotate_patch(flat_patch, k)
def _sample_points(fine, coarse, prepared_rgb, indices):
if not len(indices):
return (
fine.new_empty((0, fine.shape[1])),
coarse.new_empty((0, 1)),
prepared_rgb.new_empty((0, PATCH_CHANNELS)),
)
return (
sample_native(fine, coarse.shape, indices),
coarse.reshape(-1, 1)[indices],
_sample_patch(prepared_rgb, indices),
)
def sample_points(fine, coarse, prepared_rgb, indices):
"""Return frozen (fine points, coarse points, RGB patches) for a fit runner.
Fine sampling delegates to feature_refinement.sample_native, which uses
bilinear interpolation at native pixel centres with align_corners=False.
Integer indices are addressing only and never enter the learned head.
"""
_maps(fine, coarse, prepared_rgb)
_indices(indices, coarse.shape, fine.device)
return _sample_points(fine, coarse, prepared_rgb, indices)
def predict(net, fine, coarse, rgb, arm, chunk=8192):
"""Native-resolution logits, averaging all four patch rotations per point.
Coarse + mean(logit_k - coarse) is the mean of the four logits, computed with
a common coarse offset to preserve exact zero-residual identity. There are no
reflections, fine/coarse rotations, inferred orientations or learned resize.
Guidance is prepared once; only the current chunk's patches are materialized.
"""
import torch
if type(chunk) is not int or chunk < 1:
raise ValueError("Positive integer prediction chunk required")
_maps(fine, coarse, rgb)
prepared = prepare_rgb(rgb, fine.shape[-2:], arm)
out = []
with torch.inference_mode():
for start in range(0, coarse.numel(), chunk):
indices = torch.arange(
start, min(start + chunk, coarse.numel()), device=fine.device
)
points, logits, patch = _sample_points(fine, coarse, prepared, indices)
corrections = [net(points, logits, _rotate_patch(patch, k)) - logits for k in range(4)]
out.append((logits + torch.stack(corrections).mean(0))[:, 0])
return torch.cat(out).reshape(coarse.shape)
@@ -0,0 +1,58 @@
"""Bounded native-grid logit inference for one image, independent of scene IDs.
The predictor sees every tile. Labels and visibility masks are not inputs.
Overlaps average logits uniformly; softmax/threshold belongs to the caller.
"""
import numpy as np
def starts(length, tile, stride, *, limit=4096):
if any(type(v) is not int or v <= 0 for v in (length, tile, stride)) or stride > tile:
raise ValueError("Positive integer extent and stride <= tile required")
last = max(0, length - tile)
count = last // stride + 1 + bool(last % stride)
if type(limit) is not int or not 1 <= limit <= 4096 or count > limit:
raise ValueError("Tile grid budget exceeded")
return sorted(set(range(0, last + 1, stride)) | {last})
def sliding_logits(rgb, predict, *, tile=512, stride=256, classes=2,
max_pixels=4_194_304, max_tiles=256):
if (not isinstance(rgb, np.ndarray) or rgb.ndim != 3
or rgb.shape[2] != 3 or rgb.dtype != np.uint8):
raise ValueError("Native uint8 RGB required")
h, w = rgb.shape[:2]
if type(classes) is not int or not 1 <= classes <= 256:
raise ValueError("Bounded class count required")
if (type(max_pixels) is not int or type(max_tiles) is not int
or max_pixels <= 0 or not 1 <= max_tiles <= 4096 or h * w > max_pixels):
raise ValueError("Raster resource budget exceeded")
if type(tile) is not int or tile <= 0 or tile * tile > max_pixels:
raise ValueError("Tile working budget exceeded")
ys = starts(h, tile, stride, limit=max_tiles)
xs = starts(w, tile, stride, limit=max_tiles)
if len(ys) * len(xs) > max_tiles:
raise ValueError("Tile budget exceeded")
result = np.zeros((classes, h, w), np.float32)
counts = np.zeros((h, w), np.uint32)
for y in ys:
for x in xs:
hh, ww = min(tile, h-y), min(tile, w-x)
crop = np.zeros((tile, tile, 3), np.uint8)
crop[:hh, :ww] = rgb[y:y+hh, x:x+ww]
logits = np.asarray(predict(crop))
if (logits.shape != (classes, tile, tile)
or logits.dtype not in (np.float16, np.float32, np.float64)
or not np.isfinite(logits).all()):
raise ValueError("Predictor must return finite native class logits")
result[:, y:y+hh, x:x+ww] += logits[:, :hh, :ww].astype(np.float32)
counts[y:y+hh, x:x+ww] += 1
if not counts.all():
raise ValueError("Incomplete native coverage")
result /= counts[None]
if not np.isfinite(result).all():
raise ValueError("Accumulation overflow")
return result, dict(tile=tile, stride=stride, tiles=len(ys)*len(xs),
size=[w, h], minimum_overlap=int(counts.min()),
maximum_overlap=int(counts.max()),
aggregation="uniform_mean_native_class_logits")
@@ -0,0 +1,70 @@
"""TRAIN-only grouped score thresholds. Outer/evaluation labels are not inputs."""
import numpy as np
from score_diagnostic import curve, matched
def nested_folds(groups):
groups = list(groups)
if len(groups) < 3 or any(not isinstance(g, str) or not g for g in groups):
raise ValueError("At least three named groups required")
if len(set(groups)) != len(groups):
raise ValueError("Duplicate physical group")
return [
dict(outer=outer, inner=inner, training_groups=sorted(set(groups) - {outer, inner}))
for outer in sorted(groups)
for inner in sorted(set(groups) - {outer})
]
def calibrate_inner(rows, outer, groups):
"""One threshold per family obeying every inner-street background budget.
Each row aggregates one held-inner street and contains only its scores and
reviewed masks. Equal scores are indivisible; unreviewed pixels never supply
a threshold candidate. Both families receive the same old-fixed0 budgets.
"""
plans = [p for p in nested_folds(groups) if p["outer"] == outer]
if not plans or len(rows) != len(plans):
raise ValueError("Complete inner folds for a known outer group required")
by_group = {r["group"]: r for r in rows}
if len(by_group) != len(rows) or set(by_group) != {p["inner"] for p in plans}:
raise ValueError("Inner streets must exclude outer and cover the permitted groups")
arrays, masks, budgets, ids = [], [], {}, set()
for plan in plans:
r = by_group[plan["inner"]]
expected = plan["training_groups"]
if (
sorted(r["training_groups"]) != expected
or sorted(r["initialization_groups"]) != expected
):
raise ValueError("Fit and initialization must exclude both held streets")
if r["split"] != "train" or not r["sample_ids"]:
raise ValueError("Only identified TRAIN observations may calibrate")
if len(set(r["sample_ids"])) != len(r["sample_ids"]) or ids.intersection(r["sample_ids"]):
raise ValueError("Duplicate calibration observation")
ids.update(r["sample_ids"])
old, new = np.asarray(r["old"]), np.asarray(r["new"])
if old.shape != new.shape:
raise ValueError("Paired scores must align")
pos = {"paint": r["paint"]}
neg = {k: r[k] for k in ["original_bg", "added_bg"]}
curve(old, pos, neg)
curve(new, pos, neg)
arrays.append((old, new))
masks.append((r["paint"], neg))
for part, mask in neg.items():
budgets[r["group"] + "/" + part] = int(np.count_nonzero((old >= 0) & mask))
lengths = [len(a[0]) for a in arrays]
positive = {"paint": np.concatenate([m[0] for m in masks])}
negative = {}
for i, plan in enumerate(plans):
for part in ["original_bg", "added_bg"]:
negative[plan["inner"] + "/" + part] = np.concatenate(
[masks[j][1][part] if i == j else np.zeros(n, bool) for j, n in enumerate(lengths)]
)
points = {}
for i, origin in enumerate(["old", "new"]):
c = curve(np.concatenate([a[i] for a in arrays]), positive, negative)
points[origin] = matched(c, budgets)
return dict(outer=outer, calibration_groups=sorted(by_group), budgets=budgets, **points)
@@ -0,0 +1,423 @@
"""Fixed-data nonlinear capacity probe. Identities/coordinates never enter the head."""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, balanced_weights, counts, fit, resize_plane
from scipy.optimize import minimize
from scipy.special import expit
from supervision_density_probe import samples
def training_arrays(units):
if not units or any(u["split"] != "train" for u in units):
raise ValueError("Only nonempty training units may fit the head")
x = np.concatenate([u["x"] for u in units]).astype(float)
y = np.concatenate([u["y"] for u in units])
if x.ndim != 2 or len(x) != len(y) or not np.isfinite(x).all():
raise ValueError("Invalid training features")
weight = balanced_weights(units)
mean = (x * weight[:, None]).sum(0)
scale = np.maximum(np.sqrt(((x - mean) ** 2 * weight[:, None]).sum(0)), 1e-5)
return (x - mean) / scale, y, weight, mean, scale
def unpack(theta, dimensions, hidden):
end = dimensions * hidden
return (
theta[:end].reshape(dimensions, hidden),
theta[end : end + hidden],
theta[end + hidden : end + 2 * hidden],
theta[-1],
)
def objective(theta, x, y, weight, hidden, l2):
w1, b1, w2, b2 = unpack(theta, x.shape[1], hidden)
a = np.tanh(x @ w1 + b1)
z = a @ w2 + b2
loss = np.sum(weight * (np.logaddexp(0, z) - y * z)) + l2 * (np.sum(w1 * w1) + w2 @ w2) / 2
dz = weight * (expit(z) - y)
da = dz[:, None] * w2[None] * (1 - a * a)
grad = np.concatenate([(x.T @ da + l2 * w1).ravel(), da.sum(0), a.T @ dz + l2 * w2, [dz.sum()]])
return float(loss), grad
def fit_mlp(units, hidden, seed, l2, max_iterations, progress=None, timeout=180):
start = time.monotonic()
x, y, weight, mean, scale = training_arrays(units)
dimensions = x.shape[1]
rng = np.random.default_rng(seed)
initial = np.concatenate(
[
rng.normal(0, np.sqrt(2 / (dimensions + hidden)), dimensions * hidden),
np.zeros(hidden),
rng.normal(0, np.sqrt(2 / (hidden + 1)), hidden),
[0.0],
]
)
state = dict(theta=initial.copy(), iterations=0)
def callback(theta):
state["theta"] = theta.copy()
state["iterations"] += 1
if progress and state["iterations"] % 10 == 0:
progress(
dict(
seed=seed,
iterations=state["iterations"],
elapsed_seconds=time.monotonic() - start,
)
)
if time.monotonic() - start > timeout:
raise TimeoutError("Predeclared fitting wall-clock budget exceeded")
try:
result = minimize(
objective,
initial,
args=(x, y, weight, hidden, l2),
jac=True,
method="L-BFGS-B",
callback=callback,
options={"maxiter": max_iterations},
)
theta, success, message = result.x, bool(result.success), str(result.message)
iterations, evaluations = int(result.nit), int(result.nfev)
except TimeoutError as exc:
theta, success, message = state["theta"], False, str(exc)
iterations, evaluations = state["iterations"], None
loss, grad = objective(theta, x, y, weight, hidden, l2)
w1, b1, w2, b2 = unpack(theta, dimensions, hidden)
return dict(
kind="mlp",
hidden=hidden,
seed=seed,
activation="tanh",
mean=mean.tolist(),
scale=scale.tolist(),
w1=w1.tolist(),
b1=b1.tolist(),
w2=w2.tolist(),
b2=float(b2),
iterations=iterations,
evaluations=evaluations,
converged=success,
message=message,
objective=loss,
gradient_inf_norm=float(np.max(np.abs(grad))),
samples=len(y),
training_groups=sorted({u["group"] for u in units}),
seconds=time.monotonic() - start,
production_eligible=False,
)
def mlp_logits(x, model, normalized=False):
if not normalized:
x = (np.asarray(x, dtype=float) - np.array(model["mean"])) / np.array(model["scale"])
return (
np.tanh(x @ np.array(model["w1"]) + np.array(model["b1"])) @ np.array(model["w2"])
+ model["b2"]
)
def native_mlp_predictions(features, size, models, threshold, rows=32):
"""Evaluate the nonlinear function after interpolating features, as during fit."""
import torch
h, w = size
mean, scale = (
np.array(next(iter(models.values()))["mean"]),
np.array(next(iter(models.values()))["scale"]),
)
if any(
not np.array_equal(mean, m["mean"]) or not np.array_equal(scale, m["scale"])
for m in models.values()
):
raise ValueError("Model normalization differs")
source = torch.from_numpy(features)[None]
predictions = {name: np.empty((h, w), dtype=bool) for name in models}
for top in range(0, h, rows):
yy, xx = np.meshgrid(np.arange(top, min(top + rows, h)), np.arange(w), indexing="ij")
grid = np.stack([2 * (xx + 0.5) / w - 1, 2 * (yy + 0.5) / h - 1], -1).astype("float32")
sampled = (
torch.nn.functional.grid_sample(
source,
torch.from_numpy(grid)[None],
mode="bilinear",
padding_mode="border",
align_corners=False,
)[0]
.permute(1, 2, 0)
.reshape(-1, features.shape[0])
.numpy()
)
x = (sampled.astype(float) - mean) / scale
for name, model in models.items():
predictions[name][top : top + len(yy)] = (
expit(mlp_logits(x, model, normalized=True)) >= threshold
).reshape(yy.shape)
return predictions
def qualify(metrics, diagnostic, candidates, converged, reproduced, historical):
trials = {}
for name in candidates:
failures, historical_failures = [], []
if not reproduced:
failures.append("linear baseline reproduction")
if not converged[name]:
failures.append("optimizer did not converge")
for group, variants in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
value = variants[name][metric]
for reference, destination in [
(variants["linear"], failures),
(historical[group], historical_failures),
]:
if (
value is not None
and reference[metric] is not None
and sign * (value - reference[metric]) < -1e-12
):
destination.append(group + ": " + metric)
if diagnostic[name]["recall"] < diagnostic["linear"]["recall"]:
failures.append("P1 diagnostic paint recall")
if diagnostic[name]["fpr"] >= diagnostic["linear"]["fpr"]:
failures.append("P1 gap FPR not strictly improved")
trials[name] = dict(
accepted=not failures,
failures=failures,
historical_regressions_repaired=not historical_failures,
historical_failures=historical_failures,
)
return dict(
capacity_test_passed=all(t["accepted"] for t in trials.values()),
historical_repair_all_seeds=all(
t["historical_regressions_repaired"] for t in trials.values()
),
trials=trials,
selected_model=None,
production_eligible=False,
)
def checked_setup(root, store):
from dataset_store import checksum, read
p, frozen, f = (
read(root / "protocol.json"),
read(root / "review-frozen.json"),
read(root / "feature-manifest.json"),
)
parent = store / "experiments" / p["parent"]
assert frozen["source_sha256"] == checksum(Path(__file__))
assert frozen["protocol_sha256"] == f["protocol_sha256"] == checksum(root / "protocol.json")
assert (
read(root / "supervision-receipt.json")
== read(parent / "supervision-receipt.json")
== frozen["supervision"]
== f["supervision"]
)
assert f["supervision"]["sha256"] == p["parent_release_sha256"]
assert p["fit"] == read(parent / "protocol.json")["fit"]
assert checksum(root / "model-inventory.json") == checksum(parent / "model-inventory.json")
assert (
frozen["audit_sha256"]
== checksum(root / "p1-audit-runs-final.json")
== checksum(parent / "p1-audit-runs-final.json")
)
old = {r["sample_id"]: r for r in read(parent / "feature-manifest.json")["records"]}
assert set(old) == {r["sample_id"] for r in f["records"]}
for r in f["records"]:
# NPZ identity covers features and targets; identical extraction is required.
for key in ["name", "group", "split", "input", "target_sha256", "size", "sha256"]:
assert r[key] == old[r["sample_id"]][key], key
assert checksum(root / r["cache"]) == r["sha256"]
return p, f, parent
def fit_stage(root, store):
import torch
from dataset_store import checksum, read, write
torch.set_num_threads(3)
p, f, parent = checked_setup(root, store)
assert not (root / "models-frozen.json").exists()
units = []
for r in f["records"]:
if r["split"] == "train":
with np.load(root / r["cache"]) as z:
units.append(samples(z["features"].astype("float32"), z["target"], r, p["fit"]))
models = dict(linear=fit(units, p["fit"]["l2"], p["fit"]["max_iterations"]))
old = read(parent / "models-frozen.json")["models"]["expanded"]
delta = max(
float(np.max(np.abs(np.array(models["linear"][k]) - np.array(old[k]))))
for k in ["mean", "scale", "coefficients"]
)
assert delta == 0, "linear baseline parameters changed"
config = p["nonlinear"]
for seed in config["seeds"]:
write(root / "fit-progress.json", dict(seed=seed, iterations=0))
m = fit_mlp(
units,
config["hidden"],
seed,
config["l2"],
config["max_iterations"],
progress=lambda status: write(root / "fit-progress.json", status),
timeout=config["fitting_timeout_per_seed_seconds"],
)
assert m["mean"] == models["linear"]["mean"] and m["scale"] == models["linear"]["scale"]
models["mlp-" + str(seed)] = m
print(
json.dumps(
dict(
seed=seed,
converged=m["converged"],
iterations=m["iterations"],
seconds=m["seconds"],
)
),
flush=True,
)
write(
root / "models-frozen.json",
dict(
models=models,
threshold=p["fit"]["threshold"],
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
features_sha256=checksum(root / "feature-manifest.json"),
review_sha256=checksum(root / "review-frozen.json"),
baseline_max_parameter_delta=delta,
frozen_before_evaluation=True,
),
)
def evaluate_stage(root, store):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
torch.set_num_threads(3)
start = time.monotonic()
p, f, parent = checked_setup(root, store)
assert not (root / "result.json").exists()
frozen = read(root / "models-frozen.json")
for key, name in [
("source_sha256", Path(__file__)),
("features_sha256", root / "feature-manifest.json"),
("protocol_sha256", root / "protocol.json"),
("review_sha256", root / "review-frozen.json"),
]:
assert frozen[key] == checksum(name)
models = frozen["models"]
candidates = {k: m for k, m in models.items() if k != "linear"}
rows, train_rows, diagnostic = [], [], None
for r in f["records"]:
with np.load(root / r["cache"]) as z:
features, target = z["features"].astype("float32"), z["target"]
m = models["linear"]
coef = np.array(m["coefficients"])
scaled = coef[1:] / np.array(m["scale"])
bias = coef[0] - np.array(m["mean"]) @ scaled
predictions = dict(
linear=expit(
resize_plane(
(np.einsum("chw,c->hw", features, scaled) + bias)[None], target.shape
)[0]
)
>= p["fit"]["threshold"]
)
predictions.update(
native_mlp_predictions(features, target.shape, candidates, p["fit"]["threshold"])
)
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
row = dict(
name=r["name"],
group=r["group"],
variants={k: counts(pred, target) for k, pred in predictions.items()},
)
(rows if r["split"] == "regression" else train_rows).append(row)
if r["name"] == "P1":
audit = np.frombuffer(
pixel_target(dict(read(root / "p1-audit-runs-final.json"), size=[512, 512])),
dtype="uint8",
).reshape(512, 512)
diagnostic = {
k: aggregate([counts(pred, audit)]) for k, pred in predictions.items()
}
write(
root / "eval-progress.json",
dict(last_completed=r["name"], elapsed_seconds=time.monotonic() - start),
)
metrics = {
g: {arm: aggregate([r["variants"][arm] for r in rows if r["group"] == g]) for arm in models}
for g in sorted({r["group"] for r in rows})
}
old = read(parent / "result.json")
old_rows = {r["name"]: r for r in old["rows"]}
reproduced = (
frozen["baseline_max_parameter_delta"] == 0
and all(
r["variants"]["linear"] == old_rows[r["name"]]["variants"]["expanded"] for r in rows
)
and diagnostic["linear"] == old["diagnostic"]["expanded"]
)
historical = {
g: m["dense"]
for g, m in read(store / "experiments/semantic-dense-20261023/result.json")[
"metrics"
].items()
}
outcome = qualify(
metrics,
diagnostic,
list(candidates),
{k: m["converged"] for k, m in candidates.items()},
reproduced,
historical,
)
result = dict(
**outcome,
rows=rows,
train_rows=train_rows,
metrics=metrics,
diagnostic=diagnostic,
baseline_reproduced=reproduced,
baseline_max_parameter_delta=frozen["baseline_max_parameter_delta"],
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
eval_seconds=time.monotonic() - start,
evaluated_utc=__import__("datetime")
.datetime.now(__import__("datetime").timezone.utc)
.isoformat(),
blind_generalization_claim=False,
)
write(root / "result.json", result)
print(
json.dumps(
{
**outcome,
"metrics": metrics,
"diagnostic": diagnostic,
"baseline_reproduced": reproduced,
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("stage", choices=["fit", "evaluate"])
parser.add_argument("root", type=Path)
parser.add_argument("--store", type=Path, default=Path("/store"))
args = parser.parse_args()
(fit_stage if args.stage == "fit" else evaluate_stage)(args.root, args.store)
@@ -0,0 +1,418 @@
"""Bounded single-view assembly/learning experiment, never a map publisher.
Inputs, annotation, policy, model selection and held-out evaluation are separate.
The retained two-view downstream row fitter is NOT qualified by this experiment.
"""
import json
import sys
from pathlib import Path
import cv2
import numpy as np
from object_proposal_study import (
aggregate,
descriptors,
labels,
masks,
overlap,
save_new,
score,
sha,
timestamp,
)
from object_proposal_study import (
propose as base_propose,
)
from paint_hypothesis_study import fit_classifier, probability
from PIL import Image
from shapely.geometry import mapping, shape
from shapely.ops import unary_union
MODEL_SIZES = {"expanded_shape_appearance": 14, "expanded_texture": 22}
def rectangle(poly, mpp):
box = np.asarray(poly.minimum_rotated_rectangle.exterior.coords)[:4]
edges = np.roll(box, -1, axis=0) - box
lengths = np.linalg.norm(edges, axis=1)
k = int(np.argmax(lengths))
axis = edges[k] / max(lengths[k], 1e-9)
if axis[0] < 0 or (axis[0] == 0 and axis[1] < 0):
axis = -axis
return dict(
center=box.mean(axis=0),
axis=axis,
length=float(lengths.max() * mpp),
width=float(lengths.min() * mpp),
fill=poly.area / max(poly.minimum_rotated_rectangle.area, 1e-9),
)
def texture(poly, rgb):
mask = masks(poly.minimum_rotated_rectangle)
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
residual = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 * 512 / 12)
gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0)
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1)
mag = np.hypot(gx, gy)[mask]
xx, yy, xy = np.mean(gx[mask] ** 2), np.mean(gy[mask] ** 2), np.mean(gx[mask] * gy[mask])
coherence = np.hypot(xx - yy, 2 * xy) / max(xx + yy, 1e-9)
values = [
gray[mask].std() / 255,
residual[mask].std() / 255,
(np.quantile(gray[mask], 0.9) - np.quantile(gray[mask], 0.1)) / 255,
np.mean(gray[mask] < 75),
mag.mean() / 1020,
np.quantile(mag, 0.9) / 1020,
coherence,
np.mean(cv2.Canny(gray.astype(np.uint8), 40, 100)[mask] > 0),
]
return [float(v) for v in values]
def evidence_masks(rgb, fields, policy):
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
contrast = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 / policy["mpp"])
white = (gray > 80) & (hsv[..., 1] < 100) & (contrast > 3)
yellow = (
(hsv[..., 0] > 12) & (hsv[..., 0] < 40) & (hsv[..., 1] > 40) & (gray > 70) & (contrast > 2)
)
size = max(3, int(0.25 / policy["mpp"]))
vehicles = cv2.dilate(
(fields["vehicle"] > 0.25).astype(np.uint8), np.ones((size, size), np.uint8)
)
return white | yellow, (fields["alpha"] > 0.65) & (vehicles == 0)
def linear_descriptor(poly, policy):
d = rectangle(poly, policy["mpp"])
if (
policy["min_length"] <= d["length"] <= policy["max_length"]
and policy["min_width"] <= d["width"] <= policy["max_width"]
and d["length"] / max(d["width"], 1e-9) >= policy["min_aspect"]
and d["fill"] >= policy["min_fill"]
):
return d
return None
def pair_allowed(p, q, a, b, policy):
if abs(a["axis"] @ b["axis"]) < np.cos(np.deg2rad(policy["max_pair_angle_deg"])):
return False
if max(a["width"], b["width"]) / min(a["width"], b["width"]) > policy["max_pair_width_ratio"]:
return False
normal = np.array([-a["axis"][1], a["axis"][0]])
lateral = abs((b["center"] - a["center"]) @ normal) * policy["mpp"]
if lateral > policy["max_pair_lateral_fraction"] * min(a["width"], b["width"]):
return False
return p.distance(q) * policy["mpp"] <= policy["max_join_gap"]
def supported_envelope(source, weak, physical, policy):
# Convex-envelope intersection cannot extrapolate beyond original observations.
proposed = source.minimum_rotated_rectangle.intersection(source.convex_hull)
if proposed.geom_type != "Polygon" or proposed.area <= 0:
return None, "non_polygon"
desc = linear_descriptor(proposed, policy)
if desc is None or source.area / proposed.area < policy["min_group_fill"]:
return None, "geometry"
mask = masks(proposed)
original = np.zeros_like(mask)
for p in [source] if source.geom_type == "Polygon" else source.geoms:
original |= masks(p)
added = mask & ~original
if np.mean(physical[mask]) < policy["min_physical_valid"]:
return None, "physical"
if np.mean(weak[mask]) < policy["min_total_weak_paint"]:
return None, "total_paint"
if added.any() and np.mean(weak[added]) < policy["min_added_weak_paint"]:
return None, "added_paint"
return proposed, "supported"
def assemble(candidates, rgb, fields, policy):
out = [
dict(c, features=c["features"][:14] + texture(shape(c["geometry"]), rgb))
for c in candidates
]
polys = [shape(c["geometry"]) for c in candidates]
desc = [linear_descriptor(p, policy) for p in polys]
parent = list(range(len(polys)))
def find(i):
while parent[i] != i:
i = parent[i]
return i
for i in range(len(polys)):
for j in range(i):
if desc[i] and desc[j] and pair_allowed(polys[i], polys[j], desc[i], desc[j], policy):
a, b = find(i), find(j)
parent[max(a, b)] = min(a, b)
groups = {}
for i, d in enumerate(desc):
if d:
groups.setdefault(find(i), []).append(i)
weak, physical = evidence_masks(rgb, fields, policy)
audit = []
def append(poly, members, kind):
if any(overlap(poly, shape(c["geometry"])) > 0.95 for c in out):
return
out.append(
dict(
id="assembled-" + str(len(out)),
geometry=mapping(poly),
properties=dict(kind=kind, parent_ids=[candidates[i]["id"] for i in members]),
features=descriptors(poly, rgb, fields)[:14] + texture(poly, rgb),
fixed_admitted=any(candidates[i]["fixed_admitted"] for i in members),
)
)
for ids in groups.values():
if len(ids) > policy["max_group"]:
audit.append(dict(parents=ids, verdict="group_limit"))
continue
union = unary_union([polys[i] for i in ids])
if len(ids) > 1:
for p in [union] if union.geom_type == "Polygon" else union.geoms:
if p.geom_type == "Polygon":
append(p, ids, "exact_union")
fitted, verdict = supported_envelope(union, weak, physical, policy)
audit.append(dict(parents=ids, verdict=verdict))
if fitted is not None:
append(fitted, ids, "supported_envelope")
return out, audit
def merged_count(candidates, reviewed):
truth = [shape(o["geometry"]) for o in reviewed["objects"] if o["complete"]]
return sum(
sum(shape(c["geometry"]).intersection(t).area / max(t.area, 1e-9) >= 0.2 for t in truth)
>= 2
for c in candidates
)
def measured(candidates, reviewed):
result = score(candidates, reviewed)
result["merged"] = int(merged_count(candidates, reviewed))
return result
def pooled(rows):
result = aggregate(rows)
result["merged"] = sum(r["merged"] for r in rows)
return result
def admitted(record, assembly, scorer, model=None, threshold=0):
channel = "hard" if scorer == "fixed_admission" else "retained"
cs = record["variants"][channel + "_" + assembly]
if scorer == "fixed_admission":
return [c for c in cs if c["fixed_admitted"]]
count = 14 if scorer == "previous_shape_appearance" else MODEL_SIZES[scorer]
ps = probability(np.array([c["features"][:count] for c in cs]), model) if cs else []
return [c for c, p in zip(cs, ps, strict=True) if p >= threshold]
def fit_models(records, review, thresholds):
train = [a for a in records if a["split"] == "train"]
val = [a for a in records if a["split"] == "validation"]
x, y = [], []
for a in train:
cs = a["variants"]["retained_on"]
for c, label in zip(cs, labels(cs, review[a["id"]]), strict=True):
if label >= 0:
x.append(c["features"])
y.append(label)
x, y = np.asarray(x), np.asarray(y)
if min(np.sum(y == 0), np.sum(y == 1)) < 2:
raise ValueError("Insufficient reviewed training examples")
baselines = {
arm: pooled([measured(admitted(a, arm, "fixed_admission"), review[a["id"]]) for a in val])
for arm in ["off", "on"]
}
models, choices = {}, []
for name, count in MODEL_SIZES.items():
model = fit_classifier(x[:, :count], y, 0.01, 500)
arms = {}
for arm in ["off", "on"]:
rows = []
for threshold in thresholds:
result = pooled(
[
measured(admitted(a, arm, name, model, threshold), review[a["id"]])
for a in val
]
)
rows.append(dict(threshold=threshold, **result))
feasible = [
v
for v in rows
if v["unsupported"] <= baselines[arm]["unsupported"]
and v["merged"] <= baselines[arm]["merged"]
]
selected = (
min(feasible, key=lambda v: (-v["found"], v["unsupported"], -v["threshold"]))
if feasible
else None
)
arms[arm] = dict(selected=selected, grid=rows)
if selected:
choices.append(dict(scorer=name, assembly=arm, feature_count=count, **selected))
models[name] = dict(model=model, arms=arms)
chosen = (
min(
choices,
key=lambda v: (
-v["found"],
v["unsupported"],
v["feature_count"],
v["assembly"] != "off",
),
)
if choices
else None
)
return dict(
models=models,
chosen=chosen,
validation_fixed=baselines,
training=dict(positive=int(sum(y == 1)), negative=int(sum(y == 0)), windows=len(train)),
)
def propose(root):
base_propose(root)
original = json.loads((root / "candidates.json").read_text())
policy = json.loads((root / "assembly-policy.json").read_text())
out = []
for a in original["records"]:
rgb = np.asarray(Image.open(root / "data" / (a["id"] + ".png")).convert("RGB"))
z = dict(np.load(root / "data" / (a["id"] + ".npz")))
variants, audit = {}, {}
for mode in ["hard", "retained"]:
cs, log = assemble(a["variants"][mode], rgb, z, policy)
variants[mode + "_off"] = cs[: len(a["variants"][mode])]
variants[mode + "_on"] = cs
audit[mode] = log
out.append(
dict(
id=a["id"],
street=a["street"],
split=a["split"],
variants=variants,
assembly_audit=audit,
)
)
save_new(
root / "assembled-candidates.json",
dict(**timestamp(), records=out, policy_sha256=sha(root / "assembly-policy.json")),
)
print(json.dumps({k: sum(len(a["variants"][k]) for a in out) for k in out[0]["variants"]}))
def train(root):
records = json.loads((root / "assembled-candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
usable = [a for a in records if a["split"] != "heldout"]
result = fit_models(
usable, {a["id"]: review[a["id"]] for a in usable}, [i / 20 for i in range(1, 20)]
)
previous = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]
result["previous"] = dict(model=previous["model"], threshold=previous["selected"]["threshold"])
result.update(timestamp())
names = [
"assembled-candidates.json",
"review-frozen.json",
"protocol.json",
"assembly-policy.json",
"input-hashes.json",
"object_assembly_study.py",
"object_proposal_study.py",
"paint_observations.py",
"paint_hypothesis_study.py",
"paint_evidence_probe.py",
"layer_common.py",
"fit_scene.py",
]
result["frozen_sha256"] = {name: sha(root / name) for name in names}
save_new(root / "models-frozen.json", result)
print(json.dumps({k: result[k] for k in ["chosen", "training", "validation_fixed"]}))
def evaluate(root):
frozen = json.loads((root / "models-frozen.json").read_text())
for name, digest in frozen["frozen_sha256"].items():
if sha(root / name) != digest:
raise ValueError("Frozen dependency changed: " + name)
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
if sha(root / name) != digest:
raise ValueError("Frozen input changed: " + name)
records = json.loads((root / "assembled-candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
results = []
for a in records:
sets = {}
for arm in ["off", "on"]:
sets["proposals_" + arm] = a["variants"]["retained_" + arm]
sets["fixed_admission_" + arm] = admitted(a, arm, "fixed_admission")
sets["previous_shape_appearance_" + arm] = admitted(
a, arm, "previous_shape_appearance", **frozen["previous"]
)
for name, info in frozen["models"].items():
selected = info["arms"][arm]["selected"]
sets[name + "_" + arm] = admitted(
a, arm, name, info["model"], selected["threshold"] if selected else 2
)
results.append(
dict(
id=a["id"],
street=a["street"],
split=a["split"],
scores={k: measured(cs, review[a["id"]]) for k, cs in sets.items()},
accepted_ids={k: [c["id"] for c in cs] for k, cs in sets.items()},
)
)
streets = {
s: {
k: pooled([a["scores"][k] for a in results if a["street"] == s])
for k in results[0]["scores"]
}
for s in sorted({a["street"] for a in results})
}
control = {
k: pooled([a["scores"][k] for a in results if a["split"] == "heldout"])
for k in results[0]["scores"]
}
save_new(
root / "results.json",
dict(
**timestamp(),
chosen=frozen["chosen"],
streets=streets,
control=control,
windows=results,
promotion=False,
),
)
print(
json.dumps(
dict(
control=control,
streets={
k: v for k, v in streets.items() if k in ["pokrovka", "sadovaya-karetnaya"]
},
)
)
)
if __name__ == "__main__":
cv2.setNumThreads(3)
{"propose": propose, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
@@ -0,0 +1,374 @@
"""Offline, frozen object-proposal comparison; never publishes map features.
The production proposal generator is reused. Downstream family fitting and the
full mapping pipeline are deliberately outside this admission-stage experiment.
"""
import hashlib
import json
import sys
import time
from datetime import UTC, datetime
from pathlib import Path
import cv2
import numpy as np
from paint_hypothesis_study import fit_classifier, probability
from paint_observations import collect
from PIL import Image
from scipy.optimize import linear_sum_assignment
from shapely import affinity
from shapely.geometry import Polygon, mapping, shape
from shapely.ops import unary_union
SHAPE = ["area", "length", "width", "aspect", "fill", "solidity", "holes", "compactness"]
APPEARANCE = ["gray_mean", "gray_p10", "saturation", "contrast", "yellow", "white"]
CONTEXT = ["road", "roadway", "sidewalk", "marking", "crosswalk"]
VARIANTS = {"shape": 8, "shape_appearance": 14, "shape_appearance_context": 19}
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def save_new(path, value):
with Path(path).open("x") as f:
json.dump(value, f, indent=2, allow_nan=False)
def timestamp():
return dict(utc=datetime.now(UTC).isoformat(), monotonic=time.monotonic())
def masks(poly, size=512):
mask = np.zeros((size, size), np.uint8)
cv2.fillPoly(mask, [np.rint(poly.exterior.coords).astype(np.int32)], 1)
for hole in poly.interiors:
cv2.fillPoly(mask, [np.rint(hole.coords).astype(np.int32)], 0)
return mask.astype(bool)
def to_pixel(poly):
return affinity.translate(affinity.scale(poly, 512 / 12, -512 / 12, origin=(0, 0)), -0.5, 511.5)
def deduplicate(items):
out = []
for p, props in sorted(items, key=lambda x: (-x[0].area, x[0].wkt)):
if any(p.intersection(q).area / p.union(q).area > 0.85 for q, _ in out):
continue
out.append((p, props))
return out
def descriptors(poly, rgb, fields):
mask = masks(poly)
if not mask.any():
raise ValueError("Empty rasterized candidate")
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
contrast = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 * 512 / 12)
short, long = sorted(cv2.minAreaRect(np.asarray(poly.exterior.coords, np.float32))[1])
area = poly.area
values = [
area * (12 / 512) ** 2,
long * 12 / 512,
short * 12 / 512,
long / max(short, 1e-8),
area / max(short * long, 1e-8),
area / max(poly.convex_hull.area, 1e-8),
len(poly.interiors),
4 * np.pi * area / max(poly.length**2, 1e-8),
gray[mask].mean() / 255,
np.quantile(gray[mask], 0.1) / 255,
hsv[..., 1][mask].mean() / 255,
contrast[mask].mean() / 255,
np.mean(((hsv[..., 0] > 12) & (hsv[..., 0] < 36) & (hsv[..., 1] > 55))[mask]),
np.mean(((hsv[..., 1] < 85) & (gray > 115))[mask]),
]
values.extend(
float(np.mean(fields[k][mask]))
for k in ["road", "roadway", "sidewalk", "road marking", "crosswalk"]
)
return [float(v) for v in values]
def propose(root):
records = json.loads((root / "inputs.json").read_text())["records"]
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
if sha(root / name) != digest:
raise ValueError("Changed frozen input: " + name)
g = dict(
view=np.array([[1, 0, 0, -6], [0, -1, 0, 6], [0, 0, -1, 10], [0, 0, 0, 1]], float),
intrinsics=np.array([[100, 0, 600], [0, 100, 600], [0, 0, 1]], float),
)
results = []
for a in records:
rgb = np.asarray(Image.open(root / "data" / (a["id"] + ".png")).convert("RGB"))
z = dict(np.load(root / "data" / (a["id"] + ".npz")))
road = cv2.resize(
z["road"].astype(np.uint8), (120, 120), interpolation=cv2.INTER_NEAREST
).astype(bool)
distance = cv2.resize(z["road_dist"].astype(np.float32), (120, 120))
variants = {}
for mode in ["hard", "retained"]:
paint, cross = collect(
rgb,
z["vehicle"],
g,
z["road marking"],
z["crosswalk"],
road,
[0, 0],
[12, 12],
{"id": a["id"]},
distance,
span_m=12,
retain_uncertain=mode == "retained",
valid=z["alpha"],
)
candidates = []
for i, (poly, props) in enumerate(deduplicate(paint + cross)):
pp = to_pixel(poly)
# Fixed comparator stops at candidate admission; no family fitting.
admitted = (
props.get("subtype") == "crosswalk"
or props.get("proposal_contract") == "semantic-paint-v1"
or (
props.get("semantic_support", 0) >= 0.10
and props.get("semantic_peak", 0) >= 0.3
)
)
candidates.append(
dict(
id=f"{mode}-{i}",
geometry=mapping(pp),
properties=props,
features=descriptors(pp, rgb, z),
fixed_admitted=bool(admitted),
)
)
variants[mode] = candidates
results.append(dict(id=a["id"], street=a["street"], split=a["split"], variants=variants))
save_new(
root / "candidates.json",
dict(
**timestamp(),
records=results,
feature_names=SHAPE + APPEARANCE + CONTEXT,
generator_sha256=sha(Path(__file__).with_name("paint_observations.py")),
),
)
print(
json.dumps(
{
"windows": len(results),
"candidates": {
mode: sum(len(a["variants"][mode]) for a in results)
for mode in ["hard", "retained"]
},
}
)
)
def overlap(a, b):
return a.intersection(b).area / max(a.union(b).area, 1e-9)
def labels(candidates, reviewed):
truth = [shape(o["geometry"]) for o in reviewed["objects"]]
negative = unary_union([Polygon(p) for p in reviewed["negative"]])
out = []
for c in candidates:
p = shape(c["geometry"])
best = max([overlap(p, t) for t in truth], default=0)
if best >= 0.5:
out.append(1)
elif not negative.is_empty and p.intersection(negative).area / p.area >= 0.90:
out.append(0)
else:
out.append(-1)
return np.array(out)
def matched(candidates, reviewed, complete=True):
truth = [o for o in reviewed["objects"] if o["complete"] == complete]
ious = np.array(
[[overlap(shape(c["geometry"]), shape(t["geometry"])) for t in truth] for c in candidates]
)
best = np.max(ious, axis=0).tolist() if candidates and truth else [0.0] * len(truth)
found = set()
if candidates and truth:
rows, cols = linear_sum_assignment(-2 * (ious >= 0.5).astype(float) - 0.001 * ious)
found = {int(j) for i, j in zip(rows, cols, strict=True) if ious[i, j] >= 0.5}
return dict(
total=len(truth),
found=len(found),
recall=len(found) / len(truth) if truth else None,
objects=[
dict(id=t["id"], family=t["family"], best_iou=best[i], matched=i in found)
for i, t in enumerate(truth)
],
)
def score(candidates, reviewed):
result = matched(candidates, reviewed)
result["unsupported"] = int(np.sum(labels(candidates, reviewed) == 0))
result["accepted"] = len(candidates)
result["clipped_components"] = matched(candidates, reviewed, complete=False)
return result
def aggregate(rows):
total = sum(r["total"] for r in rows)
found = sum(r["found"] for r in rows)
return dict(
total=total,
found=found,
recall=found / total if total else None,
unsupported=sum(r["unsupported"] for r in rows),
accepted=sum(r["accepted"] for r in rows),
)
def fit_models(records, review, thresholds):
train = [a for a in records if a["split"] == "train"]
val = [a for a in records if a["split"] == "validation"]
baseline = aggregate(
[
score([c for c in a["variants"]["hard"] if c["fixed_admitted"]], review[a["id"]])
for a in val
]
)
x, y = [], []
for a in train:
cs = a["variants"]["retained"]
ls = labels(cs, review[a["id"]])
for c, label in zip(cs, ls, strict=True):
if label >= 0:
x.append(c["features"])
y.append(label)
x, y = np.asarray(x), np.asarray(y)
if min(np.sum(y == 0), np.sum(y == 1)) < 2:
raise ValueError("Insufficient independent training candidates")
models, choices = {}, []
for variant, count in VARIANTS.items():
model = fit_classifier(x[:, :count], y, 0.01, 500)
rows = []
for threshold in thresholds:
scores = []
for a in val:
cs = a["variants"]["retained"]
ps = probability(np.array([c["features"][:count] for c in cs]), model) if cs else []
scores.append(
score(
[c for c, p in zip(cs, ps, strict=True) if p >= threshold], review[a["id"]]
)
)
summary = aggregate(scores)
rows.append(dict(threshold=threshold, **summary))
feasible = [v for v in rows if v["unsupported"] <= baseline["unsupported"]]
selected = (
min(feasible, key=lambda v: (-v["found"], v["unsupported"], v["threshold"]))
if feasible
else None
)
models[variant] = dict(model=model, validation=rows, selected=selected)
if selected:
choices.append(dict(variant=variant, **selected))
chosen = (
min(choices, key=lambda v: (-v["found"], v["unsupported"], v["variant"]))
if choices
else None
)
return dict(
models=models,
chosen=chosen,
baseline_validation=baseline,
training=dict(positive=int(sum(y == 1)), negative=int(sum(y == 0)), windows=len(train)),
)
def train(root):
records = json.loads((root / "candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
# Never pass heldout labels to fitting or selection.
usable = [a for a in records if a["split"] != "heldout"]
limited_review = {a["id"]: review[a["id"]] for a in usable}
protocol = json.loads((root / "protocol.json").read_text())
result = fit_models(usable, limited_review, protocol["fixed_design"]["threshold_grid"])
result.update(timestamp())
result["source_sha256"] = sha(__file__)
result["input_sha256"] = {
n: sha(root / n)
for n in ["candidates.json", "review-frozen.json", "protocol.json", "input-hashes.json"]
}
save_new(root / "models-frozen.json", result)
print(json.dumps({k: result[k] for k in ["chosen", "baseline_validation", "training"]}))
def evaluate(root):
frozen = json.loads((root / "models-frozen.json").read_text())
if frozen["source_sha256"] != sha(__file__):
raise ValueError("Source changed after model freeze")
for name, digest in frozen["input_sha256"].items():
if sha(root / name) != digest:
raise ValueError("Input changed after model freeze: " + name)
records = json.loads((root / "candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
result = []
for a in records:
sets = {
"hard_proposals": a["variants"]["hard"],
"retained_proposals": a["variants"]["retained"],
"fixed_admission": [c for c in a["variants"]["hard"] if c["fixed_admitted"]],
}
for variant, count in VARIANTS.items():
item = frozen["models"][variant]
cs = a["variants"]["retained"]
ps = (
probability(np.array([c["features"][:count] for c in cs]), item["model"])
if cs
else []
)
threshold = item["selected"]["threshold"] if item["selected"] else 2
sets[variant] = [
dict(c, probability=float(p)) for c, p in zip(cs, ps, strict=True) if p >= threshold
]
result.append(
dict(
id=a["id"],
street=a["street"],
split=a["split"],
scores={k: score(cs, review[a["id"]]) for k, cs in sets.items()},
accepted_ids={k: [c["id"] for c in cs] for k, cs in sets.items()},
)
)
streets = {
street: {
mode: aggregate([a["scores"][mode] for a in result if a["street"] == street])
for mode in result[0]["scores"]
}
for street in sorted({a["street"] for a in result})
}
save_new(
root / "results.json",
dict(
**timestamp(),
chosen=frozen["chosen"],
streets=streets,
windows=result,
scope=(
"Object proposal/admission stage only; "
"no downstream fit or full-pipeline acceptance."
),
),
)
print(json.dumps(streets))
if __name__ == "__main__":
cv2.setNumThreads(3)
{"propose": propose, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
@@ -0,0 +1,206 @@
"""Known-support digital connectivity; caller binds evidence, never full-object topology."""
import hashlib
from collections import deque
import numpy as np
from scipy.ndimage import label
def _sha(array):
return hashlib.sha256(array.tobytes()).hexdigest()
def _path(allowed, start, goal, offsets, budget, origin, max_path):
h, w = allowed.shape
parents = np.full(h * w, -2, np.int32)
seeds = np.flatnonzero(start & allowed)
parents[seeds] = -1
queue = deque(map(int, seeds))
while queue:
if budget[0] <= 0:
raise ValueError("Connectivity work budget exceeded")
budget[0] -= 1
here = queue.popleft()
y, x = divmod(here, w)
if goal[y, x]:
path = []
while here != -1:
y, x = divmod(here, w)
path.append([x + origin[0], y + origin[1]])
if len(path) > max_path:
raise ValueError("Complete witness exceeds path budget")
here = int(parents[here])
return path[::-1]
for dy, dx in offsets:
yy, xx = y + dy, x + dx
if 0 <= yy < h and 0 <= xx < w:
nxt = yy * w + xx
if parents[nxt] == -2 and allowed[yy, xx]:
parents[nxt] = here
queue.append(nxt)
return None
def audit_topology(
probability, target, cores, relations, *, roi, connectivity, max_nodes=1_000_000, max_path=4096
):
"""Native bool cores by ID; relations are {left,right,gap:bool mask}.
Exclusive ROI [x0,y0,x1,y1], fixed >=.5, native integer path centres.
Each known-core CC is independent; no full-object/exterior claim.
Resource refusal returns no partial result or truncated witness.
"""
if (
not isinstance(target, np.ndarray)
or target.ndim != 2
or target.dtype != np.uint8
or not 0 < target.size <= 1_048_576
or not np.isin(target, [0, 1, 255]).all()
):
raise ValueError("Bounded native uint8 0/1/255 target required")
if (
not isinstance(probability, np.ndarray)
or probability.shape != target.shape
or probability.dtype.kind != "f"
or not np.isfinite(probability).all()
or not ((probability >= 0) & (probability <= 1)).all()
):
raise ValueError("Aligned finite probabilities in [0,1] required")
h, w = target.shape
if (
len(roi) != 4
or any(type(v) is not int for v in roi)
or not 0 <= roi[0] < roi[2] <= w
or not 0 <= roi[1] < roi[3] <= h
):
raise ValueError("Exclusive native ROI required")
if type(connectivity) is not int or connectivity not in (4, 8):
raise ValueError("Explicit connectivity 4 or 8 required")
if any(type(v) is not int or not 0 < v <= 1_000_000 for v in (max_nodes, max_path)):
raise ValueError("Positive bounded work/path limits required")
if (
not isinstance(cores, dict)
or not 1 <= len(cores) <= 32
or any(not isinstance(k, str) or not k for k in cores)
or not isinstance(relations, list)
or len(relations) > 32
):
raise ValueError("Bounded named cores/relations required")
x0, y0, x1, y1 = roi
sl = np.s_[y0:y1, x0:x1]
t, pred = target[sl], probability[sl] >= 0.5
if t.size * (3 * len(cores) + 2 * len(relations)) > 64_000_000:
raise ValueError("Array work budget exceeded")
structure = np.ones((3, 3), bool)
if connectivity == 4:
structure[[0, 0, 2, 2], [0, 2, 0, 2]] = False
offsets = [(int(y) - 1, int(x) - 1) for y, x in np.argwhere(structure) if (y, x) != (1, 1)]
budget = [max_nodes]
def mask(value, wanted):
if (
not isinstance(value, np.ndarray)
or value.dtype != bool
or value.shape != target.shape
or np.any(value & (target != wanted))
or int(value.sum()) != int(value[sl].sum())
):
raise ValueError("Mask must match its known class and stay inside ROI")
return value[sl]
def find_path(allowed, start, goal):
return _path(allowed, start, goal, offsets, budget, (x0, y0), max_path)
checked, occupied, objects = {}, np.zeros(t.shape, bool), []
for name, raw in cores.items():
core = mask(raw, 1)
if not core.any() or (occupied & core).any():
raise ValueError("Nonempty disjoint accepted paint cores required")
occupied |= core
checked[name] = core
truth, nt = label(core, structure)
recovered, nr = label(core & pred, structure)
ids = np.unique(truth[core & pred].astype(np.int64) * (nr + 1) + recovered[core & pred])
counts = np.bincount(ids // (nr + 1), minlength=nt + 1)
fragments = np.flatnonzero(counts[1:] > 1) + 1
witness = None
if len(fragments):
component = truth == fragments[0]
rs = np.unique(recovered[component])
rs = rs[rs != 0]
witness = find_path(component, recovered == rs[0], recovered == rs[1])
objects.append(
dict(
id=name,
core_sha256=_sha(raw),
known_pixels=int(core.sum()),
recovered_pixels=int((core & pred).sum()),
original_components=nt,
recovered_components=nr,
fragmented_original_components=len(fragments),
fully_missed_original_components=int((counts[1:] == 0).sum()),
known_core_fragmentation_witness=witness,
touches_roi_edge=bool(
core[0].any() or core[-1].any() or core[:, 0].any() or core[:, -1].any()
),
full_object_split_assessed=False,
)
)
pairs, seen = [], set()
for relation in relations:
left, right = relation["left"], relation["right"]
if left not in checked or right not in checked or left == right:
raise ValueError("Declared distinct core IDs required")
key = tuple(sorted((left, right)))
if key in seen:
raise ValueError("Duplicate relation")
seen.add(key)
gap = mask(relation["gap"], 0)
start, goal = checked[left] & pred, checked[right] & pred
corridor = checked[left] | checked[right] | gap
path = None
if not start.any() or not goal.any():
status = "unassessed_missing_predicted_endpoint"
elif not gap.any():
status = "unassessed_no_known_gap"
else:
path = find_path(pred & corridor, start, goal)
if path is not None:
status = (
"confirmed_known_support_bridge"
if any(gap[y - y0, x - x0] for x, y in path)
else "unassessed_core_adjacency_without_background"
)
else:
path = find_path(pred & (corridor | (t == 255)), start, goal)
status = (
"indeterminate_unknown_connection"
if path is not None
else "no_connection_within_reviewed_corridor"
)
pairs.append(
dict(
left=left,
right=right,
status=status,
witness=path,
gap_pixels=int(gap.sum()),
gap_sha256=_sha(relation["gap"]),
witness_unknown_pixels=int(sum(t[y - y0, x - x0] == 255 for x, y in path or [])),
exterior_connection_assessed=False,
full_object_merge_assessed=False,
)
)
return dict(
schema="missioncore.observed-topology/v1",
threshold=0.5,
connectivity=connectivity,
roi=list(roi),
shape=list(target.shape),
target_sha256=_sha(target),
probability_sha256=_sha(probability),
cores=objects,
relations=pairs,
graph_nodes_visited=max_nodes - budget[0],
semantics="Known-support connectivity only; unassessed is not separation.",
)
@@ -0,0 +1,89 @@
"""Source-local scoring of observed paint; unknown is never ground truth.
Instance polygons only identify observed cores. Gap contamination is not a
merge verdict; uncertainty prevents topology/physical-boundary claims.
"""
import hashlib
import numpy as np
from PIL import Image, ImageDraw
from scipy.spatial import ConvexHull
def array_sha(value):
return hashlib.sha256(value.tobytes()).hexdigest()
def polygon_mask(points, shape):
image = Image.new("1", (shape[1], shape[0]))
ImageDraw.Draw(image).polygon([tuple(p) for p in points], fill=1)
return np.array(image, dtype=bool)
def support(target, instances):
if target.ndim != 2 or target.dtype != np.uint8 or not np.isin(target, [0, 1, 255]).all():
raise ValueError("Native uint8 0/1/255 target required")
cores, gaps, rows = [], [], []
for obj in instances:
core = polygon_mask(obj["outline_native_pixels"], target.shape) & (target == 1)
if int(core.sum()) != obj["final_paint_pixels"] or not core.any():
raise ValueError("Reviewed visible core differs: " + obj["id"])
if any((core & other).any() for other in cores):
raise ValueError("Overlapping instance cores")
cores.append(core)
rows.append(dict(id=obj["id"], visibility=obj["visibility"],
core_pixels=int(core.sum()), core_sha256=array_sha(core)))
if cores and not np.array_equal(np.logical_or.reduce(cores), target == 1):
raise ValueError("Instance observations do not cover exactly the reviewed paint")
# Annotation order is frozen. Only adjacent members of the same crossing
# have a declared between-bars region; partial line fragments do not.
for left, right in zip(instances, instances[1:], strict=False):
if (left["kind"] != "observed_crosswalk_bar"
or right["kind"] != "observed_crosswalk_bar"
or left.get("semantic_group") != right.get("semantic_group")):
continue
pts = np.asarray(left["outline_native_pixels"] + right["outline_native_pixels"])
hull = pts[ConvexHull(pts).vertices]
mask = polygon_mask(hull, target.shape) & (target == 0)
mask &= ~polygon_mask(left["outline_native_pixels"], target.shape)
mask &= ~polygon_mask(right["outline_native_pixels"], target.shape)
gaps.append((dict(pair=[left["id"], right["id"]],
background_pixels=int(mask.sum()), mask_sha256=array_sha(mask)), mask))
return cores, rows, gaps
def score(probability, target, instances):
if (probability.shape != target.shape or not np.isfinite(probability).all()
or not ((probability >= 0) & (probability <= 1)).all()):
raise ValueError("Finite native-grid probabilities required")
pred = probability >= .5
pos, neg = target == 1, target == 0
cores, rows, gaps = support(target, instances)
tp, fn = int((pred & pos).sum()), int((~pred & pos).sum())
fp, tn = int((pred & neg).sum()), int((~pred & neg).sum())
return dict(
prediction_sha256=array_sha(probability), target_sha256=array_sha(target),
tp=tp, fn=fn, fp=fp, tn=tn, paint_pixels=tp+fn, background_pixels=fp+tn,
unknown_pixels=int((target == 255).sum()),
fnr=fn/(tp+fn) if tp+fn else None, fpr=fp/(fp+tn) if fp+tn else None,
observations=[dict(row, tp=int((pred & core).sum()),
fn=int((~pred & core).sum()),
recall=float((pred & core).sum()/core.sum()),
missed_core=not bool((pred & core).any()))
for row, core in zip(rows, cores, strict=True)],
gaps=[dict(row, fp=int((pred & mask).sum()),
fpr=float((pred & mask).sum()/mask.sum()) if mask.any() else None,
assessed=bool(mask.any())) for row, mask in gaps],
not_assessed=["full_window_recall", "whole_crossing_count", "holes",
"physical_boundary_accuracy", "instance_merge_split"],
)
def paired_changes(candidate, baseline, target):
a, b = candidate >= .5, baseline >= .5
if a.shape != target.shape or b.shape != target.shape:
raise ValueError("Paired native shapes differ")
return dict(new_fn=int((~a & b & (target == 1)).sum()),
recovered_fn=int((a & ~b & (target == 1)).sum()),
new_fp=int((a & ~b & (target == 0)).sum()),
removed_fp=int((~a & b & (target == 0)).sum()))
@@ -0,0 +1,279 @@
"""Bounded offline paint-evidence experiment. Never writes production maps.
Training: reviewed weak vector interiors. Evaluation: separately frozen sparse
positive strokes and verified non-paint polygons. This is not a full-map metric.
"""
import hashlib
import json
import time
from datetime import UTC, datetime
from pathlib import Path
import cv2
import numpy as np
from PIL import Image, ImageDraw
from scipy.optimize import minimize
from scipy.special import expit
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def polygon_mask(polygons, size=(512, 512)):
image = Image.new("L", size)
draw = ImageDraw.Draw(image)
for polygon in polygons:
draw.polygon([tuple(p) for p in polygon], fill=255)
return np.array(image) > 0
def probe_masks(record):
image = Image.new("L", (512, 512))
draw = ImageDraw.Draw(image)
for stroke in record["positive"]:
draw.line([tuple(p) for p in stroke], fill=255, width=2)
positive = np.array(image) > 0
negative = polygon_mask(record["negative"])
assert not (positive & negative).any(), "Conflicting review probes"
return positive, negative
def features(rgb):
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
g = gray.astype(np.float32) / 255
planes = [g, hsv[..., 1] / 255, (rgb[..., 0].astype(float) - rgb[..., 2]) / 255]
names = ["brightness", "saturation", "red_minus_blue"]
for size in [9, 25, 51]:
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size))
planes.append(cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, kernel) / 255)
names.append(f"bright_ridge_{size}px")
avg = cv2.boxFilter(g, -1, (size, size))
planes.append(g - avg)
names.append(f"local_contrast_{size}px")
avg = cv2.boxFilter(g, -1, (9, 9))
planes.append(np.sqrt(np.maximum(0, cv2.boxFilter(g * g, -1, (9, 9)) - avg * avg)))
names.append("local_std_9px")
# Exact pre-morphology predicate from marking_pass.line_reconstruction.extract.
ridge = cv2.morphologyEx(
gray, cv2.MORPH_TOPHAT, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25, 25))
)
white = (hsv[..., 1] < 100) & (gray > 100)
yellow = (hsv[..., 0] > 12) & (hsv[..., 0] < 36) & (hsv[..., 1] > 50) & (gray > 100)
fixed = (ridge > 12) & (white | yellow)
return np.stack(planes, axis=-1).astype(np.float32), fixed, names
def spatial_rule(mask):
closed = cv2.morphologyEx(mask.astype("uint8"), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
count, labels, stats, _ = cv2.connectedComponentsWithStats(closed, 8)
eligible = np.zeros(count, bool)
eligible[1:] = stats[1:, cv2.CC_STAT_AREA] >= 12
return eligible[labels]
def counts(prediction, positive, negative):
return dict(
tp=int((prediction & positive).sum()),
fn=int((~prediction & positive).sum()),
fp=int((prediction & negative).sum()),
tn=int((~prediction & negative).sum()),
)
def aggregate(rows):
result = {key: sum(row[key] for row in rows) for key in ["tp", "fn", "fp", "tn"]}
result["recall"] = result["tp"] / max(1, result["tp"] + result["fn"])
result["false_positive_rate"] = result["fp"] / max(1, result["fp"] + result["tn"])
return result
def choose_threshold(rows, grid):
values = []
for threshold in grid:
c = aggregate([counts(p >= threshold, pos, neg) for p, pos, neg in rows])
values.append(dict(threshold=threshold, **c))
accepted = [v for v in values if v["false_positive_rate"] <= 0.01]
best = (
max(accepted, key=lambda v: (v["recall"], -v["false_positive_rate"]))
if accepted
else min(values, key=lambda v: (v["false_positive_rate"], -v["recall"]))
)
return best["threshold"], values
def main(root):
start = time.monotonic()
split = json.loads((root / "split.json").read_text())
review = json.loads((root / "review-frozen.json").read_text())
assert review["reviewed_before_fit"] and not review["human_approved"]
assert not (root / "result.json").exists(), "Immutable first result already exists"
method = review["method"]
rng = np.random.default_rng(method["seed"])
records = split["records"]
assert len({a["id"] for a in records}) == len(records)
for a in records:
assert digest(Path(a["path"]) / "top.png") == a["raw_sha256"]
# All Maroseyka train/validation/test windows are physically nonoverlapping.
local = [a for a in records if "center" in a]
for a in local:
for b in local:
if a["split"] != b["split"]:
assert abs(a["center"][0] - b["center"][0]) >= 28
data = {}
xx, yy, train_counts = [], [], []
for a in records:
rgb = np.array(Image.open(Path(a["path"]) / "top.png").convert("RGB").resize((512, 512)))
f, fixed, names = features(rgb)
data[a["id"]] = dict(rgb=rgb, f=f, fixed=fixed)
if a["split"] != "train":
continue
target = np.array(Image.open(root / "review" / (a["id"] + "-mask.png"))) > 0
roi = polygon_mask([a["roi"]])
positive = cv2.erode(target.astype("uint8"), np.ones((5, 5), np.uint8)) > 0
positive &= roi
excluded = cv2.dilate(target.astype("uint8"), np.ones((15, 15), np.uint8)) > 0
negative = (roi | polygon_mask(review["train_extra_negatives"][a["id"]])) & ~excluded
assert positive.any() and negative.any()
train_counts.append(
dict(id=a["id"], positive=int(positive.sum()), negative=int(negative.sum()))
)
for label, mask in [(1, positive), (0, negative)]:
indices = np.flatnonzero(mask)
indices = rng.choice(
indices,
min(len(indices), method["maximum_samples_per_class_per_window"]),
replace=False,
)
xx.append(f.reshape(-1, f.shape[-1])[indices])
yy.append(np.full(len(indices), label))
x = np.concatenate(xx).astype(float)
y = np.concatenate(yy)
mean, scale = x.mean(axis=0), np.maximum(x.std(axis=0), 1e-5)
design = np.column_stack([np.ones(len(x)), (x - mean) / scale])
weight = np.where(y == 1, 0.5 / max(1, sum(y == 1)), 0.5 / max(1, sum(y == 0)))
l2 = method["l2"]
def objective(w):
z = design @ w
loss = np.sum(weight * (np.logaddexp(0, z) - y * z)) + l2 * np.sum(w[1:] ** 2) / 2
grad = design.T @ (weight * (expit(z) - y))
grad[1:] += l2 * w[1:]
return loss, grad
fit_start = time.monotonic()
fit = minimize(
objective,
np.zeros(design.shape[1]),
jac=True,
method="L-BFGS-B",
options={"maxiter": method["maximum_iterations"]},
)
fit_seconds = time.monotonic() - fit_start
assert fit.success, str(fit.message)
validation = []
for a in records:
v = data[a["id"]]
v["probability"] = expit(fit.x[0] + ((v["f"] - mean) / scale) @ fit.x[1:])
if a["split"] == "validation":
pos, neg = probe_masks(review["records"][a["id"]])
validation.append((v["probability"], pos, neg))
threshold, curve = choose_threshold(validation, method["threshold_grid"])
model = dict(
kind="linear-logistic-regression",
names=names,
mean=mean.tolist(),
scale=scale.tolist(),
coefficients=fit.x.tolist(),
threshold=threshold,
seed=method["seed"],
split_sha256=digest(root / "split.json"),
review_sha256=digest(root / "review-frozen.json"),
samples=len(x),
positive_samples=int(y.sum()),
converged=bool(fit.success),
iterations=int(fit.nit),
fit_seconds=fit_seconds,
production_eligible=False,
)
# Publish immutable model before examining held-out metrics.
(root / "fitted-model.json").write_text(json.dumps(model, indent=2))
rows = []
for a in records:
if a["split"] == "train":
continue
v = data[a["id"]]
pos, neg = probe_masks(review["records"][a["id"]])
predictions = dict(
fixed=v["fixed"],
fixed_spatial=spatial_rule(v["fixed"]),
learned=v["probability"] >= threshold,
learned_spatial=spatial_rule(v["probability"] >= threshold),
)
row = dict(
id=a["id"],
split=a["split"],
variants={k: counts(p, pos, neg) for k, p in predictions.items()},
)
rows.append(row)
# Raw frame, fixed predicate, learned predicate, learned + local spatial rule.
sheet = Image.new("RGB", (2048, 550), "#171717")
draw = ImageDraw.Draw(sheet)
for j, key in enumerate(["raw", "fixed", "learned", "learned_spatial"]):
rgb = v["rgb"].copy()
if key != "raw":
pred = predictions[key]
rgb[pred] = (rgb[pred] * 0.35 + np.array([0, 255, 150]) * 0.65).astype("uint8")
sheet.paste(Image.fromarray(rgb), (j * 512, 38))
text = a["id"] + " | " + key
if key != "raw":
c = aggregate([row["variants"][key]])
text += f" R {c['recall']:.1%} FPR {c['false_positive_rate']:.1%}"
draw.text((j * 512 + 5, 10), text, fill="white")
sheet.save(root / (a["id"] + "-result.jpg"), quality=94)
metrics = {}
for split_name in ["validation", "test", "external"]:
metrics[split_name] = {
key: aggregate([row["variants"][key] for row in rows if row["split"] == split_name])
for key in rows[0]["variants"]
}
result = dict(
schema="missioncore.paint-evidence-result/v1",
utc=datetime.now(UTC).isoformat(),
started_monotonic=start,
elapsed_seconds=time.monotonic() - start,
model=model,
train_counts=train_counts,
threshold_validation=curve,
metrics=metrics,
windows=rows,
source_sha256=digest(Path(__file__)),
map_writes=False,
production_eligible=False,
limitations=[
"Sparse assistant-reviewed probes, not dense human-verified benchmark.",
"Fixed comparator is paint-evidence predicate only, not complete production pipeline.",
"Spatial filter is local image morphology, not GOST or topology reconstruction.",
"No object-class recognition, no boundary learning, no full-street completion.",
"Two external windows from historically seen scene; insufficient generalization proof.",
],
)
(root / "result.json").write_text(json.dumps(result, indent=2))
print(
json.dumps(
dict(
metrics=metrics,
threshold=threshold,
fit_seconds=fit_seconds,
samples=len(x),
seconds=result["elapsed_seconds"],
model_sha256=digest(root / "fitted-model.json"),
)
)
)
if __name__ == "__main__":
main(Path("/experiment"))
@@ -0,0 +1,178 @@
"""Exact, offline observed-paint geometry; no inference, fitting or map publication.
Input is a discrete 0=background, 1=paint, 255=unknown grid. Coordinates refer to
pixel EDGES, not centres. A connected component is an observation, not a semantic
instance. Raw geometry remains 2-D until an explicit height provider is supplied.
"""
import copy
import hashlib
import json
import numpy as np
from shapely import affinity, normalize
from shapely.geometry import box, mapping, shape
from shapely.ops import unary_union
SCHEMA = "missioncore.paint-geometry/v1"
MAX_CELLS = 1024 * 1024
MAX_RUNS = 32768
MAX_EDITOR_RINGS = 128
MAX_EDITOR_WORK = 2_000_000
def digest(value):
return hashlib.sha256(
json.dumps(value, sort_keys=True, allow_nan=False, separators=(",", ":")).encode()
).hexdigest()
def _runs(mask):
padded = np.pad(mask.astype(np.int8), ((0, 0), (1, 1)))
rows, starts = np.where(np.diff(padded, axis=1) == 1)
end_rows, ends = np.where(np.diff(padded, axis=1) == -1)
if not np.array_equal(rows, end_rows):
raise ValueError("Unpaired raster runs")
if len(rows) > MAX_RUNS:
raise ValueError("Raster run budget exceeded; no lossy fallback")
return list(zip(rows.tolist(), starts.tolist(), ends.tolist(), strict=True))
def _cells_geometry(runs):
return unary_union([box(start, row, end, row + 1) for row, start, end in runs])
def vectorize(labels, *, pixel_to_scene, source_id):
"""Return a bounded 2-D proposal, with exact cells and explicit unknown support.
pixel_to_scene is Shapely's [a,b,d,e,xoff,yoff] affine: x=a*col+b*row+xoff.
Source identity is caller-owned (tile/revision); the complete label bytes and
transform are additionally bound into the proposal hash.
"""
labels = np.asarray(labels)
matrix = np.asarray(pixel_to_scene, dtype=float)
if (
labels.ndim != 2 or not labels.size or labels.size > MAX_CELLS
or labels.dtype.kind not in "biu" or not np.isin(labels, [0, 1, 255]).all()
):
raise ValueError("Expected bounded integer 0/1/255 grid")
if (
matrix.shape != (6,) or not np.isfinite(matrix).all()
or abs(matrix[0] * matrix[3] - matrix[1] * matrix[2]) < 1e-12
):
raise ValueError("Finite non-singular pixel-edge affine required")
if not isinstance(source_id, str) or not 1 <= len(source_id) <= 256:
raise ValueError("Source identity required")
label_sha = hashlib.sha256(labels.astype(np.uint8).tobytes()).hexdigest()
identity = dict(
source_id=source_id, labels_sha256=label_sha, shape=list(labels.shape),
pixel_to_scene=matrix.tolist(),
)
source_sha = digest(identity)
paint = _cells_geometry(_runs(labels == 1))
unknown = _cells_geometry(_runs(labels == 255))
height, width = labels.shape
edge = box(0, 0, width, height).boundary
polygons = [] if paint.is_empty else (
[paint] if paint.geom_type == "Polygon" else list(paint.geoms)
)
# Zero tolerance only removes collinear run endpoints; assert no area change.
features = []
for poly in polygons:
if poly.geom_type != "Polygon" or not poly.is_valid:
raise ValueError("Unsupported raster topology; no automatic repair")
compact = poly.simplify(0, preserve_topology=True)
if not compact.equals(poly):
raise ValueError("Polygon compaction changed observed paint")
world = normalize(affinity.affine_transform(compact, matrix))
if not world.is_valid or world.is_empty:
raise ValueError("Invalid transformed geometry")
geometry = json.loads(json.dumps(mapping(world)))
flags = []
if poly.intersects(edge):
flags.append("tile-edge")
if not unknown.is_empty and poly.intersects(unknown):
flags.append("unknown-support")
features.append(dict(
type="Feature", id="paint-" + digest([source_sha, geometry])[:24],
geometry=geometry,
properties=dict(
observation_role="observed-paint-component",
source_id=source_id, source_sha256=source_sha,
support_boundary=flags, instance_completeness="not-assessed",
review_status="unreviewed",
),
))
features.sort(key=lambda f: f["id"])
result = dict(
schema_version=SCHEMA, source=identity, source_sha256=source_sha,
counts=dict(paint=int(np.count_nonzero(labels == 1)),
background=int(np.count_nonzero(labels == 0)),
unknown=int(np.count_nonzero(labels == 255))),
features=features,
)
result["proposal_sha256"] = digest(result)
return result
def editor_features(proposal, *, height_at, height_source):
"""Validate and lift exact components, WITHOUT inferring a subtype/template/group.
Caller supplies observed surface heights at the returned XY vertices. There
is no flat/nearest-height fallback. This creates features only: the caller
must independently verify scene identity/admission before any map import.
"""
from k1link.simulation.ai_polygon.semantic_edits import validate_holes, validate_path
payload = {k: v for k, v in proposal.items() if k != "proposal_sha256"}
if proposal.get("schema_version") != SCHEMA or digest(payload) != proposal.get(
"proposal_sha256"
):
raise ValueError("Changed or unsupported geometry proposal")
if not isinstance(height_source, str) or not 1 <= len(height_source) <= 256:
raise ValueError("Explicit height provenance required")
# Existing editor validators have quadratic segment/ring comparisons.
# Budget the WHOLE proposal before any geometry validator or height callback.
work = 0
vertices = 0
if len(proposal["features"]) > 20000:
raise ValueError("Editor feature budget exceeded")
for raw in proposal["features"]:
geo = raw["geometry"]
if geo["type"] != "Polygon":
raise ValueError("Unsupported editor geometry")
rings = geo["coordinates"]
if not rings or len(rings) > MAX_EDITOR_RINGS:
raise ValueError("Editor ring budget exceeded; no lossy fallback")
if any(not 4 <= len(ring) <= 4096 for ring in rings):
raise ValueError("Editor path budget exceeded")
edges = sum(len(ring) - 1 for ring in rings)
vertices += sum(len(ring) for ring in rings)
work += edges * edges
if vertices > 300000 or work > MAX_EDITOR_WORK:
raise ValueError("Editor validation work budget exceeded; no lossy fallback")
result = []
for raw in proposal["features"]:
feature = copy.deepcopy(raw)
geometry = feature["geometry"]
if geometry["type"] != "Polygon" or not shape(geometry).is_valid:
raise ValueError("Unsupported editor geometry")
rings = []
for ring in geometry["coordinates"]:
xy = np.asarray(ring[:-1], dtype=float)
z = np.asarray(height_at(xy.copy()), dtype=float)
if z.shape != (len(xy),) or not np.isfinite(z).all():
raise ValueError("Missing observed height support")
points = np.column_stack([xy, z]).tolist()
points.append(points[0][:])
validate_path(points, True)
rings.append(points)
validate_holes(rings)
feature["geometry"]["coordinates"] = rings
feature["properties"].update({
"class": "road_marking", "authority": "observation-only",
"route_permission": "unassigned", "confidence": None,
"confidence_status": "not-assessed", "annotation_origin": "mask-observation",
"height_source": height_source,
})
result.append(feature)
return result
@@ -0,0 +1,380 @@
"""Frozen factorial diagnostic of photometry, label quality and road context.
Two explicit phases prevent holdout outcomes from selecting thresholds/models.
No production maps, inferred labels, street IDs or coordinates enter the fit.
"""
import argparse
import hashlib
import json
import time
from datetime import UTC, datetime
from pathlib import Path
import cv2
import numpy as np
from paint_evidence_probe import (
aggregate,
choose_threshold,
counts,
features,
polygon_mask,
probe_masks,
)
from PIL import Image, ImageDraw
from scipy.optimize import minimize
from scipy.special import expit
APPEARANCES = ("absolute", "augmented", "relative")
CONTEXTS = ("none", "semantic", "fused")
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def save_new(path, value):
with path.open("x") as stream:
json.dump(value, stream, indent=2)
def transformed(rgb, kind, value):
if kind == "identity":
return rgb.copy()
x = rgb.astype(np.float32) / 255
x = x * value if kind == "gain" else x**value
return np.rint(np.clip(x, 0, 1) * 255).astype(np.uint8)
def representation(rgb, kind):
f, fixed, names = features(rgb)
if kind != "relative":
return f, fixed, names
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) / 255
saturation = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)[..., 1] / 255
chroma = (rgb[..., 0].astype(float) - rgb[..., 2]) / np.maximum(
rgb.astype(float).sum(axis=2), 1
)
planes = [saturation, chroma]
names = ["saturation", "normalized_red_blue"]
for index, size in enumerate([9, 25, 51]):
avg = cv2.boxFilter(gray, -1, (size, size))
planes.extend([f[..., 3 + index * 2] / (avg + 0.05), (gray - avg) / (avg + 0.05)])
names.extend([f"relative_ridge_{size}", f"relative_contrast_{size}"])
avg = cv2.boxFilter(gray, -1, (9, 9))
planes.append(f[..., -1] / (avg + 0.05))
names.append("relative_std_9")
return np.stack(planes, axis=-1).astype(np.float32), fixed, names
def fit_classifier(x, y, l2, maxiter):
mean, scale = x.mean(axis=0), np.maximum(x.std(axis=0), 1e-5)
design = np.c_[np.ones(len(x)), (x - mean) / scale]
weights = np.where(y == 1, 0.5 / sum(y == 1), 0.5 / sum(y == 0))
def objective(w):
z = design @ w
loss = np.sum(weights * (np.logaddexp(0, z) - y * z)) + l2 * np.sum(w[1:] ** 2) / 2
grad = design.T @ (weights * (expit(z) - y))
grad[1:] += l2 * w[1:]
return loss, grad
fit = minimize(
objective,
np.zeros(design.shape[1]),
jac=True,
method="L-BFGS-B",
options={"maxiter": maxiter},
)
if not fit.success:
raise RuntimeError(str(fit.message))
return dict(
mean=mean.tolist(),
scale=scale.tolist(),
coefficients=fit.x.tolist(),
iterations=int(fit.nit),
samples=len(y),
)
def probability(f, model):
w = np.array(model["coefficients"])
return expit(w[0] + ((f - np.array(model["mean"])) / np.array(model["scale"])) @ w[1:])
def context(root, record, mode):
if mode == "none":
return np.ones((512, 512), bool)
path = root / "data" / (record["id"] + "-context.npz")
if not path.exists():
return None
with np.load(path) as z:
if mode == "fused":
return z["fused"].astype(bool)
return (z["road"] > 0.35) & (z["road"] >= z["sidewalk"])
def load(root):
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
if sha(root / name) != digest:
raise ValueError(f"Changed input: {name}")
inputs = json.loads((root / "study-inputs.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())
prior = json.loads(Path("/prior/review-frozen.json").read_text())
protocol = json.loads((root / "protocol.json").read_text())
return inputs, review, prior, protocol
def rgb(root, record):
return np.array(Image.open(root / "data" / record["raw_file"]).convert("RGB"))
def choose_candidate(rows):
admissible = [a for a in rows if a["false_positive_rate"] <= 0.01]
if admissible:
return sorted(
admissible, key=lambda a: (-a["recall"], a["false_positive_rate"], a["variant"])
)[0]
return sorted(rows, key=lambda a: (a["false_positive_rate"], -a["recall"], a["variant"]))[0]
def train(root):
start = time.monotonic()
records, review, prior, protocol = load(root)
method = protocol["design"]
rng = np.random.default_rng(method["seed"])
sampling, audit = {}, []
for a in records:
if a["split"] != "train":
continue
pos, neg = probe_masks(review["train"][a["id"]])
weak = np.array(Image.open(root / "data" / (a["id"] + "-weak.png"))) > 0
weak = (cv2.erode(weak.astype("uint8"), np.ones((5, 5), np.uint8)) > 0) & polygon_mask(
[a["roi"]]
)
if (weak & neg).any():
raise ValueError("Weak positives conflict with certain negatives")
n = min(2500, int(weak.sum()), int(pos.sum()), int(neg.sum()))
if n < 50:
raise ValueError("Insufficient matched training samples")
sampling[a["id"]] = {
name: rng.choice(np.flatnonzero(mask), n, replace=False)
for name, mask in [("weak", weak), ("reviewed", pos), ("negative", neg)]
}
audit.append(
dict(
id=a["id"],
matched_per_class=n,
weak=int(weak.sum()),
reviewed=int(pos.sum()),
negative=int(neg.sum()),
reviewed_inside_weak=int((pos & weak).sum()),
)
)
models, validation = {}, []
for label in ["weak", "reviewed"]:
for appearance in APPEARANCES:
key = label + "-" + appearance
xx, yy = [], []
for a in records:
if a["split"] != "train":
continue
image = rgb(root, a)
transforms = (
method["augmentation"] if appearance == "augmented" else [["identity", 1]]
)
for kind, value in transforms:
f, _, names = representation(transformed(image, kind, value), appearance)
for target, indices in [
(1, sampling[a["id"]][label]),
(0, sampling[a["id"]]["negative"]),
]:
xx.append(f.reshape(-1, f.shape[-1])[indices])
yy.append(np.full(len(indices), target))
model = fit_classifier(
np.concatenate(xx).astype(float),
np.concatenate(yy),
method["l2"],
method["maxiter"],
)
model.update(appearance=appearance, labels=label, names=names)
rows = []
validation_records = [a for a in records if a["split"] == "validation"]
for a in validation_records:
f, _, _ = representation(rgb(root, a), appearance)
pos, neg = probe_masks(prior["records"][a["id"]])
rows.append((probability(f, model), pos, neg))
model["threshold"], model["validation_curve"] = choose_threshold(
rows, method["threshold_grid"]
)
models[key] = model
for mode in CONTEXTS:
values = [
counts((p >= model["threshold"]) & context(root, a, mode), pos, neg)
for a, (p, pos, neg) in zip(validation_records, rows, strict=True)
]
validation.append(dict(variant=key + "/" + mode, **aggregate(values)))
chosen = choose_candidate(validation)
artifact = dict(
schema="paint-hypothesis-models/v1",
utc=datetime.now(UTC).isoformat(),
monotonic=start,
seconds=time.monotonic() - start,
models=models,
validation=validation,
chosen=chosen,
sampling=audit,
source_sha256=sha(Path(__file__)),
inputs_sha256=sha(root / "input-hashes.json"),
review_sha256=sha(root / "review-frozen.json"),
protocol_sha256=sha(root / "protocol.json"),
production_eligible=False,
)
save_new(root / "models-frozen.json", artifact)
print(
json.dumps(
dict(chosen=chosen, validation=validation, sampling=audit, seconds=artifact["seconds"])
)
)
def evaluate(root):
start = time.monotonic()
records, review, prior, protocol = load(root)
artifact = json.loads((root / "models-frozen.json").read_text())
if artifact["source_sha256"] != sha(Path(__file__)):
raise ValueError("Source changed between fit and evaluation")
models = artifact["models"]
results, stress, gates = [], [], []
chosen_key, chosen_mode = artifact["chosen"]["variant"].split("/")
for a in records:
if a["split"] == "train":
continue
probes = (
review["holdout"][a["id"]] if a["split"] == "holdout" else prior["records"][a["id"]]
)
pos, neg = probe_masks(probes)
image = rgb(root, a)
f, fixed, _ = representation(image, "absolute")
relative, _, _ = representation(image, "relative")
group = a.get("street", a["split"])
masks = {mode: context(root, a, mode) for mode in CONTEXTS}
preds = {"fixed/none": fixed}
for mode in CONTEXTS[1:]:
if masks[mode] is not None:
preds["fixed/" + mode] = fixed & masks[mode]
gates.append(
dict(id=a["id"], group=group, mode=mode, **counts(masks[mode], pos, neg))
)
for key, model in models.items():
predicted = (
probability(relative if model["appearance"] == "relative" else f, model)
>= model["threshold"]
)
for mode in CONTEXTS:
if masks[mode] is not None:
preds[key + "/" + mode] = predicted & masks[mode]
results.append(
dict(
id=a["id"],
group=group,
positive=int(pos.sum()),
negative=int(neg.sum()),
variants={key: counts(value, pos, neg) for key, value in preds.items()},
)
)
# Controlled photometric counterfactuals use identical labels; never tune on them.
if a["split"] in ["test", "external"]:
for kind, value in protocol["design"]["stress"]:
transformed_rgb = transformed(image, kind, value)
fs = {k: representation(transformed_rgb, k)[0] for k in ["absolute", "relative"]}
stress.append(
dict(
id=a["id"],
group=group,
transform=[kind, value],
variants={
key: counts(
probability(
fs["relative" if m["appearance"] == "relative" else "absolute"],
m,
)
>= m["threshold"],
pos,
neg,
)
for key, m in models.items()
},
)
)
if a["id"] in ["sretenka-2", "sadovaya-triumfalnaya-3", "control-05", "tile-59--2"]:
keys = ["raw", "weak-absolute/none", chosen_key + "/none"]
if masks.get(chosen_mode) is not None and chosen_mode != "none":
keys.append(chosen_key + "/" + chosen_mode)
elif masks["fused"] is not None:
keys.append(chosen_key + "/fused")
sheet = Image.new("RGB", (512 * len(keys), 552), "#171717")
draw = ImageDraw.Draw(sheet)
for j, key in enumerate(keys):
im = image.copy()
caption = key
if key != "raw":
pred = preds[key]
im[pred] = (im[pred] * 0.35 + np.array([0, 255, 145]) * 0.65).astype("uint8")
m = aggregate([counts(pred, pos, neg)])
caption += f" R={m['recall']:.1%} FP={m['false_positive_rate']:.1%}"
sheet.paste(Image.fromarray(im), (512 * j, 40))
draw.text((512 * j + 5, 5), a["id"], fill="white")
draw.text((512 * j + 5, 20), caption, fill="white")
sheet.save(root / (a["id"] + "-study.jpg"), quality=95)
metrics = {}
for group in sorted({r["group"] for r in results}):
rows = [r for r in results if r["group"] == group]
keys = set.intersection(*(set(r["variants"]) for r in rows))
metrics[group] = {
key: aggregate([r["variants"][key] for r in rows]) for key in sorted(keys)
}
candidate = {
group: variants.get(artifact["chosen"]["variant"]) for group, variants in metrics.items()
}
qualified = all(
candidate.get(group)
and candidate[group]["recall"] >= 0.95
and candidate[group]["false_positive_rate"] <= 0.02
for group in ["sretenka", "sadovaya-triumfalnaya"]
)
save_new(
root / "evaluation.json",
dict(
utc=datetime.now(UTC).isoformat(),
monotonic=start,
seconds=time.monotonic() - start,
models_sha256=sha(root / "models-frozen.json"),
rows=results,
stress=stress,
gate_rows=gates,
metrics=metrics,
candidate=candidate,
qualifies_sparse_gate=qualified,
production_eligible=False,
),
)
print(
json.dumps(
dict(
candidate=artifact["chosen"]["variant"],
metrics=metrics,
qualifies_sparse_gate=qualified,
seconds=time.monotonic() - start,
)
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("phase", choices=["train", "evaluate"])
parser.add_argument("--root", type=Path, default=Path("/experiment"))
args = parser.parse_args()
cv2.setNumThreads(1)
(train if args.phase == "train" else evaluate)(args.root)
@@ -0,0 +1,363 @@
"""Offline fixed-recipe pixel growth probe; explicit admitted pixels only.
Frozen visual features, training-only normalization and class/area/window balance.
No source identities or coordinates enter inference. No production publication.
"""
import argparse
import hashlib
import json
import time
from pathlib import Path
import numpy as np
from scipy.optimize import minimize
from scipy.special import expit
def balanced_weights(units):
"""Each class has half the mass; areas then windows share that mass equally."""
if set(np.concatenate([u["y"] for u in units])) != {0, 1}:
raise ValueError("Both reviewed classes are required")
weights = [np.zeros(len(u["y"])) for u in units]
for label in [0, 1]:
groups = sorted({u["group"] for u in units if np.any(u["y"] == label)})
for group in groups:
indices = [
i for i, u in enumerate(units) if u["group"] == group and np.any(u["y"] == label)
]
for i in indices:
m = units[i]["y"] == label
weights[i][m] = 0.5 / len(groups) / len(indices) / m.sum()
return np.concatenate(weights)
def fit(units, l2=0.01, max_iterations=500):
if any(u["split"] != "train" for u in units):
raise ValueError("Only training units may fit the classifier")
x = np.concatenate([u["x"] for u in units]).astype(float)
y = np.concatenate([u["y"] for u in units])
if not np.isfinite(x).all() or x.ndim != 2 or len(x) != len(y):
raise ValueError("Invalid feature samples")
weight = balanced_weights(units)
mean = (x * weight[:, None]).sum(0)
scale = np.maximum(np.sqrt(((x - mean) ** 2 * weight[:, None]).sum(0)), 1e-5)
design = np.column_stack([np.ones(len(x)), (x - mean) / scale])
def objective(w):
z = design @ w
loss = np.sum(weight * (np.logaddexp(0, z) - y * z)) + l2 * np.sum(w[1:] ** 2) / 2
grad = design.T @ (weight * (expit(z) - y))
grad[1:] += l2 * w[1:]
return loss, grad
result = minimize(
objective,
np.zeros(design.shape[1]),
jac=True,
method="L-BFGS-B",
options={"maxiter": max_iterations},
)
if not result.success:
raise RuntimeError("Fit did not converge: " + str(result.message))
return dict(
mean=mean.tolist(),
scale=scale.tolist(),
coefficients=result.x.tolist(),
iterations=int(result.nit),
samples=len(y),
training_groups=sorted({u["group"] for u in units}),
production_eligible=False,
)
def counts(pred, target):
pred = np.asarray(pred, dtype=bool)
target = np.asarray(target)
if pred.shape != target.shape or not set(np.unique(target)) <= {0, 1, 255}:
raise ValueError("Target shape or label contract violated")
return dict(
tp=int((pred & (target == 1)).sum()),
fn=int((~pred & (target == 1)).sum()),
fp=int((pred & (target == 0)).sum()),
tn=int((~pred & (target == 0)).sum()),
ignored=int((target == 255).sum()),
)
def aggregate(rows):
c = {k: sum(r[k] for r in rows) for k in ["tp", "fn", "fp", "tn", "ignored"]}
c["recall"] = c["tp"] / (c["tp"] + c["fn"]) if c["tp"] + c["fn"] else None
c["fpr"] = c["fp"] / (c["fp"] + c["tn"]) if c["fp"] + c["tn"] else None
return c
def resize_plane(a, size):
import torch
return torch.nn.functional.interpolate(
torch.from_numpy(a.astype("float32"))[None], size=size, mode="bilinear", align_corners=False
)[0].numpy()
def extract(root, store):
import torch
from admission_store import Supervision, pixel_target
from dataset_store import checksum, read, write
from PIL import Image
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
torch.set_num_threads(3)
receipt = read(root / "supervision-receipt.json")
frozen = read(root / "review-frozen.json")
assert frozen["supervision"] == receipt and frozen["protocol_sha256"] == checksum(
root / "protocol.json"
)
inventory = {
p.name: dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in Path("/model").iterdir()
if p.is_file() and p.suffix in [".json", ".safetensors", ".bin"]
}
write(root / "model-inventory.json", inventory)
processor = AutoImageProcessor.from_pretrained("/model", local_files_only=True)
model = (
Mask2FormerForUniversalSegmentation.from_pretrained("/model", local_files_only=True)
.eval()
.to("cuda")
)
for p in model.parameters():
p.requires_grad_(False)
assert (
model.config.id2label[23] == "Lane Marking - Crosswalk"
and model.config.id2label[24] == "Lane Marking - General"
)
cache = root / "cache"
cache.mkdir(exist_ok=False)
refs = read(root / "selected-references.json")
names = {r["id"]: n for n, r in refs.items()}
records = []
with Supervision(store, receipt["path"], receipt["sha256"]) as reader:
for split in ["train", "regression"]:
for batch in reader.batches("observed_paint", split, batch_size=1):
e = batch[0]
assert len(e["targets"]) == 1
t = e["targets"][0]
desc = next(
v
for v in e["inputs"]
if v["view"] == t["view"] and v["sample_id"] == e["sample_id"]
)
with reader.open_image(desc) as stream:
im = Image.open(stream)
im.load()
im = im.convert("RGB")
assert list(im.size) == t["size"]
rgb = np.asarray(im.resize((512, 512), Image.Resampling.BICUBIC))
features = []
semantic = []
for k in range(4):
tensors = processor(
images=Image.fromarray(np.rot90(rgb, k).copy()),
return_tensors="pt",
size={"height": 512, "width": 512},
).to("cuda")
assert tuple(tensors["pixel_values"].shape[-2:]) == (512, 512)
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
out = model(**tensors, output_hidden_states=True)
f = torch.rot90(out.pixel_decoder_last_hidden_state[0].float(), -k, [-2, -1])
assert tuple(f.shape) == (256, 128, 128)
sem = torch.einsum(
"qc,qhw->chw",
out.class_queries_logits[0].float().softmax(-1)[:, :-1],
out.masks_queries_logits[0].float().sigmoid(),
)
sem = torch.rot90(sem, -k, [-2, -1])
features.append(f.cpu().numpy())
semantic.append(sem.cpu().numpy())
del out, tensors, f, sem
n = names[e["sample_id"]]
path = cache / (n + ".npz")
target = np.frombuffer(pixel_target(t), dtype=np.uint8).reshape(im.height, im.width)
np.savez_compressed(
path,
features=np.mean(features, axis=0).astype("float16"),
semantic=np.mean(semantic, axis=0).astype("float16"),
target=target,
)
records.append(
dict(
name=n,
sample_id=e["sample_id"],
group=e["physical_group"],
split=split,
cache=path.relative_to(root).as_posix(),
sha256=checksum(path),
input=desc,
target_sha256=hashlib.sha256(target.tobytes()).hexdigest(),
size=list(im.size),
)
)
assert len(records) <= 32
print("extracted " + n, flush=True)
write(
root / "feature-manifest.json",
dict(
records=records,
model_inventory_sha256=checksum(root / "model-inventory.json"),
supervision=receipt,
script_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
),
)
def fit_and_evaluate(root):
import torch
from dataset_store import checksum, read, write
torch.set_num_threads(3)
manifest = read(root / "feature-manifest.json")
protocol = read(root / "protocol.json")
params = protocol["fit"]
plan = read(root / "experiment-plan.json")
assert checksum(root / "protocol.json") == manifest["protocol_sha256"]
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
units = []
for r in manifest["records"]:
assert checksum(root / r["cache"]) == r["sha256"]
if r["split"] != "train":
continue
with np.load(root / r["cache"]) as z:
target = z["target"]
f = z["features"].astype("float32")
h, w = target.shape
rng = np.random.default_rng(params["seed"] + int(r["sample_id"][:8], 16))
chosen = []
for label in [0, 1]:
indices = np.flatnonzero(target == label)
chosen.extend(
rng.choice(
indices,
min(len(indices), params["max_samples_per_class_per_window"]),
replace=False,
)
)
chosen = np.asarray(chosen)
ys, xs = np.unravel_index(chosen, (h, w))
grid = np.stack([2 * (xs + 0.5) / w - 1, 2 * (ys + 0.5) / h - 1], -1).astype("float32")
x = torch.nn.functional.grid_sample(
torch.from_numpy(f)[None],
torch.from_numpy(grid)[None, None],
mode="bilinear",
padding_mode="border",
align_corners=False,
)[0, :, 0].T.numpy()
units.append(
dict(
name=r["name"],
group=r["group"],
split=r["split"],
x=x,
y=target.ravel()[chosen],
)
)
models = {}
for arm, groups in plan["arms"].items():
selected = [u for u in units if u["group"] in groups]
assert {u["group"] for u in selected} == set(groups)
models[arm] = fit(selected, params["l2"], params["max_iterations"])
write(
root / "models-frozen.json",
dict(
models=models,
features_sha256=checksum(root / "feature-manifest.json"),
review_sha256=checksum(root / "review-frozen.json"),
threshold=params["threshold"],
protocol_sha256=checksum(root / "protocol.json"),
),
)
# Both heads are immutable before any control metric or prediction is examined.
results = []
for r in manifest["records"]:
if r["split"] != "regression":
continue
with np.load(root / r["cache"]) as z:
f = z["features"].astype("float32")
target = z["target"]
sem = resize_plane(z["semantic"], target.shape)
preds = {"pretrained": np.isin(sem.argmax(0), [23, 24])}
for arm, m in models.items():
coef = np.array(m["coefficients"])
scaled = coef[1:] / np.array(m["scale"])
bias = coef[0] - np.array(m["mean"]) @ scaled
logits = np.einsum("chw,c->hw", f, scaled) + bias
preds[arm] = (
expit(resize_plane(logits[None], target.shape)[0]) >= params["threshold"]
)
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **preds)
results.append(
dict(
name=r["name"],
group=r["group"],
scope="reviewed-road-roi"
if r["name"] in plan["complete_roi_names"]
else "explicit-reviewed-probes",
variants={arm: counts(pred, target) for arm, pred in preds.items()},
)
)
groups = sorted({r["group"] for r in results})
metrics = {
g: {
arm: aggregate([r["variants"][arm] for r in results if r["group"] == g])
for arm in ["pretrained", "single", "expanded"]
}
for g in groups
}
failures = []
gains = []
for g, m in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
a = m["single"][metric]
b = m["expanded"][metric]
if a is None or b is None:
continue
if sign * (b - a) < -1e-12:
failures.append(dict(group=g, metric=metric, single=a, expanded=b))
if sign * (b - a) > 1e-12:
gains.append(dict(group=g, metric=metric, single=a, expanded=b))
write(
root / "result.json",
dict(
metrics=metrics,
rows=results,
accepted=not failures and bool(gains),
failures=failures,
gains=gains,
models_sha256=checksum(root / "models-frozen.json"),
production_eligible=False,
blind_generalization_claim=False,
protocol_sha256=checksum(root / "protocol.json"),
evaluated_utc=__import__("datetime")
.datetime.now(__import__("datetime").timezone.utc)
.isoformat(),
),
)
print(
json.dumps(dict(metrics=metrics, accepted=not failures and bool(gains), failures=failures)),
flush=True,
)
def main():
p = argparse.ArgumentParser()
p.add_argument("phase", choices=["extract", "fit"])
p.add_argument("root", type=Path)
p.add_argument("--store", type=Path, default=Path("/store"))
args = p.parse_args()
start = time.monotonic()
(extract(args.root, args.store) if args.phase == "extract" else fit_and_evaluate(args.root))
print("seconds", round(time.monotonic() - start, 2))
if __name__ == "__main__":
main()
@@ -0,0 +1,22 @@
"""Exact D4 training transforms; no RNG, interpolation or new supervision."""
import numpy as np
def permute_training_pair(rgb, target, element):
"""Rotate counterclockwise element%4 times, then reflect if element>=4.
Input must already be a square crop/padded tile. This is training-only:
scene-coordinate metadata is not transformed or exported by this function.
"""
if (type(element) is not int or not 0 <= element < 8
or not isinstance(rgb, np.ndarray) or not isinstance(target, np.ndarray)
or target.ndim != 2 or rgb.shape != (*target.shape, 3)
or not target.shape[0] or target.shape[0] != target.shape[1]
or rgb.dtype != np.uint8 or target.dtype != np.uint8
or not np.isin(target, [0, 1, 255]).all()):
raise ValueError("Square uint8 RGB/0,1,255 target and D4 integer 0..7 required")
image = np.rot90(rgb, element % 4, axes=(0, 1))
labels = np.rot90(target, element % 4, axes=(0, 1))
if element >= 4:
image, labels = image[:, ::-1], labels[:, ::-1]
return image.copy(order="C"), labels.copy(order="C")
@@ -0,0 +1,237 @@
"""Complete reviewed ROI -> existing sparse paint/background/unknown contract.
The explicit background declaration is an annotation decision, not evidence
inferred from a missing polygon. Numeric coverage cannot establish visual truth.
"""
import hashlib
import math
from admission_store import Supervision, pixel_runs, pixel_target
from dataset_store import checksum, confined
def sha(data):
return hashlib.sha256(data).hexdigest()
def runs(data, size, view):
width, height = size
result = dict(view=view, paint=[], background=[], unknown=[])
names = {0: "background", 1: "paint", 255: "unknown"}
for y in range(height):
x = 0
while x < width:
value, start = data[y * width + x], x
while x < width and data[y * width + x] == value:
x += 1
result[names[value]].append([y, start, x])
return result
def roi_bounds(size, roi):
if len(size) != 2 or any(type(v) is not int or not 0 < v <= 2048 for v in size):
raise ValueError("Bounded integer image dimensions required")
if len(roi) != 4 or any(type(v) is not int for v in roi):
raise ValueError("Integer exclusive ROI required")
x0, y0, x1, y1 = roi
if not 0 <= x0 < x1 <= size[0] or not 0 <= y0 < y1 <= size[1]:
raise ValueError("ROI outside source view")
if (x1 - x0) * (y1 - y0) > 65536:
raise ValueError("Review at most 65536 native pixels per unit")
return x0, y0, x1, y1
def polygon_contains(points, x, y):
inside = False
for a, b in zip(points, points[1:] + points[:1], strict=True):
if (a[1] > y) != (b[1] > y) and x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0]:
inside = not inside
return inside
def raster_proposal(packet, proposal):
"""Rasterize source-view polygons at pixel centres; uncertain borders ignored."""
size, roi = packet["size"], packet["roi"]
x0, y0, x1, y1 = roi_bounds(size, roi)
if proposal.get("background_reviewed") is not True or not proposal.get("reason", "").strip():
raise ValueError("Explicit whole-ROI background review required")
margin = proposal["boundary_ignore_px"]
if type(margin) is not int or not 1 <= margin <= 4:
raise ValueError("Native-pixel uncertainty margin required")
shapes = proposal["paint_polygons"]
unknown = proposal["unknown_polygons"]
if not 1 <= len(shapes) <= 32 or len(unknown) > 32:
raise ValueError("Bounded visible-paint polygons required")
for points in shapes + unknown:
if not 3 <= len(points) <= 64 or any(
len(p) != 2
or any(type(v) not in (int, float) or not math.isfinite(v) for v in p)
or not x0 <= p[0] <= x1
or not y0 <= p[1] <= y1
for p in points
):
raise ValueError("Polygon outside pinned ROI")
if unknown and not proposal.get("unknown_reason", "").strip():
raise ValueError("Explain uncertain source regions")
width = size[0]
data = bytearray([255]) * (width * size[1])
for y in range(y0, y1):
for x in range(x0, x1):
data[y * width + x] = int(any(polygon_contains(p, x + 0.5, y + 0.5) for p in shapes))
output = data.copy()
explicit_unknown = bytearray(len(data))
for y in range(y0, y1):
for x in range(x0, x1):
i = y * width + x
ambiguous = any(polygon_contains(p, x + 0.5, y + 0.5) for p in unknown)
if ambiguous:
explicit_unknown[i] = 255
for yy in range(max(y0, y - margin), min(y1, y + margin + 1)):
if ambiguous:
break
ambiguous = any(
data[yy * width + xx] != data[i]
for xx in range(max(x0, x - margin), min(x1, x + margin + 1))
)
if ambiguous:
output[i] = 255
record = runs(output, size, packet["view"])
# Outside ROI is not part of the review, even though both use ignore=255.
record["unknown"] = [
[y, max(a, x0), min(b, x1)]
for y, a, b in record["unknown"]
if y0 <= y < y1 and max(a, x0) < min(b, x1)
]
# Keep explicit source uncertainty distinct from automatic edge margins.
record["source_unknown"] = runs(explicit_unknown, size, packet["view"])["unknown"]
return record
def merge(packet, record, original, protected=b""):
"""Require explicit complete ROI, preserve existing labels and protected unknown."""
size, roi = packet["size"], packet["roi"]
x0, y0, x1, y1 = roi_bounds(size, roi)
width, height = size
if (
len(original) != width * height
or set(original) - {0, 1, 255}
or sha(original) != packet["target_sha256"]
):
raise ValueError("Pinned labels changed")
if protected and (len(protected) != len(original) or set(protected) - {0, 1}):
raise ValueError("Aligned protected unknown required")
if protected and any(p and old != 255 for p, old in zip(protected, original, strict=True)):
raise ValueError("Protected mask must contain only unknown labels")
if packet.get("protected_sha256") != sha(protected):
raise ValueError("Protected unknown identity changed")
if record["view"] != packet["view"]:
raise ValueError("Source view mismatch")
checked = pixel_runs(record, size)
covered = set()
for spans in checked.values():
for y, a, b in spans:
if not y0 <= y < y1 or not x0 <= a < b <= x1:
raise ValueError("Labels outside reviewed ROI")
covered.update(range(y * width + a, y * width + b))
if len(covered) != (x1 - x0) * (y1 - y0):
raise ValueError("Incomplete ROI: missing pixels are not background")
candidate = pixel_target(dict(size=size, **record))
source_unknown = pixel_runs(
dict(paint=[], background=[], unknown=record.get("source_unknown", [])), size
)["unknown"]
for y, a, b in source_unknown:
if not y0 <= y < y1 or not x0 <= a < b <= x1:
raise ValueError("Source uncertainty outside reviewed ROI")
for i in range(y * width + a, y * width + b):
if candidate[i] != 255:
raise ValueError("Source uncertainty must be excluded from labels")
if original[i] != 255:
raise ValueError(
"Explicit source uncertainty conflicts with accepted labels; "
"review a separate baseline revision before publication"
)
output, counts = bytearray(original), {"paint": 0, "background": 0, "unknown": 0}
added = {"paint": 0, "background": 0}
for i in covered:
value, old = candidate[i], original[i]
if value != 255 and old != 255 and old != value:
raise ValueError("Proposal conflicts with accepted labels")
if protected and protected[i] and value != 255:
raise ValueError("Proposal fills protected unknown")
if value != 255:
output[i] = value
counts[{0: "background", 1: "paint", 255: "unknown"}[value]] += 1
if old == 255 and value != 255:
added[{0: "background", 1: "paint"}[value]] += 1
return bytes(output), dict(
roi_pixels=len(covered),
coverage=counts,
added=added,
original_sha256=sha(original),
merged_sha256=sha(output),
)
def validate_packet(store, unit):
"""Resolve TRAIN identity from immutable corpus, never trust declared split."""
p = unit["payload"]
if set(p) != {
"supervision",
"sample_id",
"view",
"size",
"roi",
"target_sha256",
"protected_sha256",
}:
raise ValueError("Pinned region packet required")
roi_bounds(p["size"], p["roi"])
pointer = p["supervision"]
with Supervision(store, pointer["path"], pointer["sha256"]) as reader:
reference = reader.corpus.reference(p["sample_id"])
if (
reference["split"] != "train"
or unit["split"] != reference["split"]
or unit["physical_group"] != reference["physical_group"]
):
raise ValueError("Unit disagrees with frozen physical split")
entry = next(
(
e
for b in reader.training_batches("observed_paint")
for e in b
if e["sample_id"] == p["sample_id"]
),
None,
)
if entry is None:
raise ValueError("Sample is not admitted TRAIN")
view = next(
v
for v in entry["inputs"]
if v["sample_id"] == p["sample_id"] and v["view"] == p["view"]
)
target = next(t for t in entry["targets"] if t["view"] == p["view"])
if target["size"] != p["size"] or sha(pixel_target(target)) != p["target_sha256"]:
raise ValueError("Packet target differs from immutable supervision")
# Explicitly excluded pixels are protected; unreviewed complement is not.
protected = bytearray(p["size"][0] * p["size"][1]) if target["unknown"] else b""
for y, a, b in target["unknown"]:
protected[y * p["size"][0] + a : y * p["size"][0] + b] = bytes([1]) * (b - a)
if sha(protected) != p["protected_sha256"]:
raise ValueError("Packet omits protected unknown")
required = {
str(confined(store, reference["dataset"]) / v["name"])
for v in (view["rgb"], view["cameras_member"])
}
required.add(str(reader.root / "supervision.json"))
required.add(str(reader.root / reader.manifest["records"][p["sample_id"]]["path"]))
provided = {str(confined(store, pin["path"])) for pin in unit["sources"]}
if not required.issubset(provided):
raise ValueError("Packet does not pin source camera, image and decision")
if (
checksum(confined(store, reference["dataset"]) / view["rgb"]["name"])
!= view["rgb"]["sha256"]
):
raise ValueError("Raw source changed")
@@ -0,0 +1,188 @@
"""Read-only research proposals -> bounded root decision, never executable work.
The active root session supplies identities and verifies facts. This validates
artifact structure/provenance, not truth or authentication. It neither schedules
agents nor mutates the annotation queue, source labels, models or infrastructure.
"""
import argparse
import json
from pathlib import Path
from urllib.parse import urlparse
from dataset_store import checksum, confined, digest, write
SCHEMA = "missioncore.semantic-research/v1"
MAX_BYTES = 32 * 1024
def bounded(value):
if len(json.dumps(value, ensure_ascii=False, allow_nan=False).encode()) > MAX_BYTES:
raise ValueError("Research artifact byte limit exceeded")
return value
def keys(value, fields):
if not isinstance(value, dict) or set(value) != set(fields.split()):
raise ValueError("Unexpected research fields")
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 4000:
raise ValueError("Bounded nonempty explanation required")
def review_research(workspace, brief, report, decision):
for value in (brief, report, decision):
bounded(value)
keys(brief, "schema_version root_actor scout_actor trigger question baseline")
if brief["schema_version"] != SCHEMA:
raise ValueError("Unsupported research schema")
for field in ("root_actor", "scout_actor", "question"):
text(brief[field])
if brief["root_actor"] == brief["scout_actor"]:
raise ValueError("Scout cannot be root decision maker")
if brief["trigger"] not in {"user_request", "new_class", "stagnation", "cost_regression"}:
raise ValueError("An explicit research trigger is required")
keys(brief["baseline"], "path sha256")
baseline = confined(Path(workspace).resolve(), brief["baseline"]["path"])
if not baseline.is_file() or baseline.stat().st_size > MAX_BYTES:
raise ValueError("Bounded existing baseline evidence required")
if checksum(baseline) != brief["baseline"]["sha256"]:
raise ValueError("Baseline evidence changed")
keys(report, "brief_sha256 baseline_option sources ideas unknowns recommendation")
if report["brief_sha256"] != digest(brief):
raise ValueError("Research answered a different brief")
for field in ("baseline_option", "unknowns", "recommendation"):
text(report[field])
if not isinstance(report["sources"], list) or len(report["sources"]) > 6:
raise ValueError("Research source budget exceeded")
sources = {}
for source in report["sources"]:
keys(source, "id title url kind checked_utc supports limitations")
for field in source:
text(source[field])
url = urlparse(source["url"])
if url.scheme != "https" or not url.hostname or url.username or url.password:
raise ValueError("Public HTTPS citation required")
if source["kind"] not in {"official_docs", "official_repo", "paper"}:
raise ValueError("Primary sources required")
if source["id"] in sources:
raise ValueError("Duplicate source")
sources[source["id"]] = source
if not isinstance(report["ideas"], list) or len(report["ideas"]) > 3:
raise ValueError("At most three research ideas")
ideas = {}
for idea in report["ideas"]:
keys(
idea,
"id title basis source_ids evidence hypothesis minimal_test "
"success failure cost risks not_applicable",
)
for field in set(idea) - {"source_ids"}:
text(idea[field])
refs = idea["source_ids"]
if (
not isinstance(refs, list)
or len(set(refs)) != len(refs)
or not set(refs).issubset(sources)
):
raise ValueError("Idea has unbound citations")
if idea["basis"] not in {"local_baseline", "external"} or (
idea["basis"] == "external" and not refs
):
raise ValueError("External idea needs evidence; baseline uses the pinned local result")
if idea["id"] in ideas:
raise ValueError("Duplicate idea")
ideas[idea["id"]] = idea
keys(decision, "actor report_sha256 source_checks verdicts test_plan")
if decision["actor"] != brief["root_actor"]:
raise ValueError("Only assigned root may decide")
if decision["report_sha256"] != digest(report):
raise ValueError("Stale root research review")
checks = decision["source_checks"]
if (
not isinstance(checks, list)
or len(set(checks)) != len(checks)
or not set(checks).issubset(sources)
):
raise ValueError("Unknown root source checks")
seen, selected = set(), []
for verdict in decision["verdicts"]:
keys(verdict, "idea_id outcome reason revisit_when")
idea_id = verdict["idea_id"]
if idea_id not in ideas or idea_id in seen:
raise ValueError("Every verdict needs one known idea")
seen.add(idea_id)
if verdict["outcome"] not in {"test", "defer", "reject"}:
raise ValueError("Root must test, defer or reject")
text(verdict["reason"])
text(verdict["revisit_when"])
if verdict["outcome"] == "test":
if not set(ideas[idea_id]["source_ids"]).issubset(checks):
raise ValueError("Root must verify a selected idea's source claims")
selected.append(idea_id)
if seen != set(ideas) or len(selected) > 1:
raise ValueError("Decide every idea and select at most one cheap test")
plan = decision["test_plan"]
if not selected:
if plan is not None:
raise ValueError("No test was selected")
else:
keys(plan, "idea_id control data_selection metric success failure budget")
if plan["idea_id"] != selected[0]:
raise ValueError("Test is not the root-selected idea")
for field in ("control", "data_selection", "metric", "success", "failure"):
text(plan[field])
keys(plan["budget"], "max_units max_dispatches max_wall_seconds gpu_training_runs")
for field, cap in (("max_units", 8), ("max_dispatches", 16), ("max_wall_seconds", 3600)):
value = plan["budget"][field]
if type(value) is not int or not 1 <= value <= cap:
raise ValueError("Cheap experiment draft budget exceeded")
if (
type(plan["budget"]["gpu_training_runs"]) is not int
or plan["budget"]["gpu_training_runs"] != 0
):
raise ValueError("Research cannot authorize training")
return bounded(
dict(
schema_version=SCHEMA,
brief_sha256=digest(brief),
report_sha256=digest(report),
decision_sha256=digest(decision),
selected_idea=selected[0] if selected else None,
next_action="freeze_separate_experiment" if selected else "keep_current_workflow",
execution_authorized=False,
training_authorized=False,
map_write_authorized=False,
verdicts=decision["verdicts"],
draft_test=plan,
)
)
def load(path):
path = Path(path)
if path.stat().st_size > MAX_BYTES:
raise ValueError("Research input exceeds byte limit")
return json.loads(path.read_text(encoding="utf-8"))
def main():
parser = argparse.ArgumentParser(description=__doc__)
for field in ("workspace", "brief", "report", "decision", "output"):
parser.add_argument("--" + field, required=True)
args = parser.parse_args()
result = review_research(
args.workspace, load(args.brief), load(args.report), load(args.decision)
)
output = Path(args.output)
if output.exists() and load(output) != result:
raise ValueError("Research decision artifact already exists with different content")
if not output.exists():
write(output, result)
print(json.dumps(result, ensure_ascii=False))
if __name__ == "__main__":
main()
@@ -0,0 +1,136 @@
"""Lazy RGB/observed-paint input over the existing pinned Supervision reader.
This is a data adapter, not a trainer, admission policy or model-specific dataset.
It decodes only the current image, never builds C4 caches or copies a dataset.
"""
import copy
import hashlib
import numpy as np
from admission_store import dimensions, pixel_target
from PIL import Image
SPLITS = {"train", "validation", "test", "regression"}
def load_frame(reader, example, view, *, split):
"""Read one raw RGB view and its exact 0/1/255 target from a verified reader."""
if (
split not in SPLITS or example["split"] != split
or example["task"] != "observed_paint"
or example["training_eligible"] is not (split == "train")
or example["background_from_absence"] is not False
):
raise ValueError("Explicit observed-paint split required")
reference = reader.corpus.reference(example["sample_id"])
if any(reference[key] != example[key] for key in ("split", "source", "physical_group")):
raise ValueError("Example does not match pinned source split/group")
selected = [v for v in example["inputs"]
if v["sample_id"] == example["sample_id"] and v["view"] == view]
targets = [v for v in example["targets"] if v["view"] == view]
if len(selected) != 1 or len(targets) != 1:
raise ValueError("Exactly one aligned anchor view and target required")
selected, target = selected[0], targets[0]
size = dimensions(selected["camera"]["size"])
if target["size"] != size or target.get("ignore_index") != 255:
raise ValueError("Target/image alignment or ignore convention changed")
mask = np.frombuffer(pixel_target(target), dtype=np.uint8).reshape(size[1], size[0])
if not np.any(mask != 255):
return None
# open_image verifies source RGB bytes; dimensions checked before decode.
with reader.open_image(selected) as stream, Image.open(stream) as image:
if image.format != "PNG" or image.mode != "RGB" or list(image.size) != size:
raise ValueError("Expected aligned native RGB PNG")
rgb = np.array(image, dtype=np.uint8, copy=True)
return dict(
img=rgb, target=mask,
metadata=dict(
sample_id=example["sample_id"], view=view, split=split,
physical_group=example["physical_group"], source=copy.deepcopy(example["source"]),
review_sha256=example["review_sha256"], input=copy.deepcopy(selected),
target_sha256=hashlib.sha256(mask.tobytes()).hexdigest(),
color_order="RGB", ignore_index=255, background_from_absence=False,
),
)
def training_frames(reader):
"""Use only the reader's TRAIN API; context images are never implicit targets."""
for batch in reader.training_batches("observed_paint", batch_size=1):
for example in batch:
for target in example["targets"]:
frame = load_frame(reader, example, target["view"], split="train")
if frame is not None:
yield frame
def evaluation_frames(reader, *, split):
if split not in {"validation", "test", "regression"}:
raise ValueError("Explicit non-training evaluation split required")
for batch in reader.batches("observed_paint", split, batch_size=1):
for example in batch:
for target in example["targets"]:
frame = load_frame(reader, example, target["view"], split=split)
if frame is not None:
yield frame
def crop(frame, *, left, top, size=512):
"""Native-resolution square; pad unknown; keep exact crop-to-source mapping.
Returns None for a crop with no reviewed supervision. The caller must not
retry indefinitely or pass an all-ignore batch to the loss. This function
does not choose a sampling distribution, augment, rescale or alter cameras.
"""
if "crop_to_source_edges" in frame["metadata"]:
raise ValueError("Nested crop is unsupported; use the native source frame")
rgb, target = frame["img"], frame["target"]
if (
rgb.dtype != np.uint8 or target.dtype != np.uint8 or target.ndim != 2
or rgb.shape != (*target.shape, 3) or not np.isin(target, [0, 1, 255]).all()
):
raise ValueError("Aligned native RGB and 0/1/255 target required")
h, w = target.shape
if (
any(type(v) is not int for v in (left, top, size))
or not 0 <= left < w or not 0 <= top < h or not 1 <= size <= 1024
):
raise ValueError("Invalid bounded crop")
width, height = min(size, w - left), min(size, h - top)
labels = target[top:top + height, left:left + width]
if not np.any(labels != 255):
return None
out = np.full((size, size), 255, np.uint8)
out[:height, :width] = labels
image = np.zeros((size, size, 3), np.uint8)
image[:height, :width] = rgb[top:top + height, left:left + width]
metadata = copy.deepcopy(frame["metadata"])
metadata.update(
crop_to_source_edges=[1, 0, 0, 1, left, top],
source_window=[left, top, left + width, top + height],
native_crop_size=[width, height], padded_size=[size, size],
known_pixels=int(np.count_nonzero(out != 255)),
)
return dict(img=image, target=out, metadata=metadata)
def mmseg_overrides():
"""Model/data numeric contract ONLY; not an installed/runnable MMSeg config.
Raw frames are RGB already. Unknown must remain 255, including padding.
Upstream CE otherwise averages over ignored pixels as well by default.
"""
return dict(
model=dict(
data_preprocessor=dict(
bgr_to_rgb=False, rgb_to_bgr=False, seg_pad_val=255,
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375],
),
decode_head=dict(
num_classes=2, out_channels=2, ignore_index=255,
loss_decode=dict(type="CrossEntropyLoss", use_sigmoid=False,
loss_weight=1., avg_non_ignore=True),
),
),
dataset=dict(reduce_zero_label=False, ignore_index=255),
)
@@ -0,0 +1,128 @@
"""Offline paired ranking diagnosis. Oracle thresholds are never deployment policy."""
import numpy as np
def curve(scores, positives, negatives):
scores = np.asarray(scores)
if scores.ndim != 1 or not np.isfinite(scores).all() or not len(scores):
raise ValueError("Finite nonempty score vector required")
masks = dict(positives, **negatives)
if not positives or not negatives or len(masks) != len(positives) + len(negatives):
raise ValueError("Distinct positive and negative cohort names required")
for mask in masks.values():
if mask.dtype != bool or mask.shape != scores.shape:
raise ValueError("Aligned boolean cohort masks required")
fg = np.logical_or.reduce(list(positives.values()))
bg = np.zeros_like(fg)
for mask in negatives.values():
if np.any(mask & (fg | bg)):
raise ValueError("Negative cohorts must be disjoint from paint and each other")
bg |= mask
known = fg | bg
if not known.any():
raise ValueError("No reviewed support")
idx = np.flatnonzero(known)
idx = idx[np.argsort(-scores[idx], kind="stable")]
sorted_scores = scores[idx]
ends = np.r_[np.flatnonzero(sorted_scores[:-1] != sorted_scores[1:]), len(idx) - 1]
return {
"thresholds": np.r_[np.inf, sorted_scores[ends].astype(np.float64)],
"counts": {k: np.r_[0, np.cumsum(m[idx], dtype=np.int64)[ends]] for k, m in masks.items()},
"support": {k: int(m.sum()) for k, m in masks.items()},
"positive_names": list(positives),
"negative_names": list(negatives),
}
def point(c, index):
t = float(c["thresholds"][index])
return dict(
threshold=None if np.isinf(t) else t,
counts={k: int(v[index]) for k, v in c["counts"].items()},
rates={
k: float(v[index] / c["support"][k]) if c["support"][k] else None
for k, v in c["counts"].items()
},
)
def at_threshold(c, threshold):
if not np.isfinite(threshold):
raise ValueError("Finite threshold required")
return point(c, int(np.flatnonzero(c["thresholds"] >= threshold)[-1]))
def matched(c, budgets):
if set(budgets) != set(c["negative_names"]):
raise ValueError("One explicit budget for every negative cohort required")
valid = np.ones(len(c["thresholds"]), dtype=bool)
for name, budget in budgets.items():
if (
isinstance(budget, bool)
or not isinstance(budget, (int, np.integer))
or not 0 <= budget <= c["support"][name]
):
raise ValueError("Integer false-positive budgets within support required")
valid &= c["counts"][name] <= budget
return point(c, int(np.flatnonzero(valid)[-1]))
def ranking(
c,
positive,
negative_names,
grid=(0, 0.0001, 0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 1),
):
tp = c["counts"][positive]
fp = sum(c["counts"][n] for n in negative_names)
npos = c["support"][positive]
nneg = sum(c["support"][n] for n in negative_names)
if not npos or not nneg:
return dict(positives=npos, negatives=nneg, ap=None, auc=None, points=[])
recall = tp / npos
fpr = fp / nneg
precision = np.divide(tp, tp + fp, out=np.ones(len(tp), dtype=float), where=tp + fp > 0)
ap = float(np.sum(np.diff(recall) * precision[1:]))
auc = float(np.sum(np.diff(fpr) * (recall[1:] + recall[:-1]) * 0.5))
points = []
for rate in grid:
budget = int(np.floor(rate * nneg))
i = int(np.flatnonzero(fp <= budget)[-1])
points.append(
dict(
budget=budget,
fp=int(fp[i]),
tp=int(tp[i]),
precision=float(precision[i]),
recall=float(recall[i]),
)
)
return dict(positives=npos, negatives=nneg, ap=ap, auc=auc, points=points)
def paired(old, new, positives, negatives):
if np.shape(old) != np.shape(new):
raise ValueError("Paired score shapes differ")
curves = {k: curve(s, positives, negatives) for k, s in [("old", old), ("new", new)]}
assert curves["old"]["support"] == curves["new"]["support"]
fixed = {k: at_threshold(c, 0) for k, c in curves.items()}
budgets = {k: fixed["old"]["counts"][k] for k in negatives}
oracle = {k: matched(c, budgets) for k, c in curves.items()}
summaries = {}
for origin, c in curves.items():
summaries[origin] = {}
for name in positives:
summaries[origin][name] = {}
for part, names in [(k, [k]) for k in negatives] + [("combined", list(negatives))]:
summary = ranking(c, name, names)
if name not in ["overall", "weak"] or part != "combined":
summary.pop("points")
summaries[origin][name][part] = summary
return dict(
support=curves["old"]["support"],
fixed=fixed,
budgets=budgets,
oracle=oracle,
ranking=summaries,
)
@@ -0,0 +1,495 @@
"""Frozen-data, grouped comparison of label coverage and learned spatial residuals.
A 1x1 residual is an optimizer/capacity control for the 3x3 spatial head.
No street coordinates or manual geometry enters inference. No deployment.
"""
import argparse
import json
import os
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, counts, fit, resize_plane
from street_holdout_probe import folds
from supervision_density_probe import samples
def dense_weights(records):
if any(r["split"] != "train" for r in records):
raise ValueError("Only training records may define loss weights")
weights = {r["name"]: np.zeros(r["target"].shape, dtype="float32") for r in records}
for label in (0, 1):
groups = sorted({r["group"] for r in records if np.any(r["target"] == label)})
if not groups:
raise ValueError("Both reviewed classes required")
for group in groups:
present = [r for r in records if r["group"] == group and np.any(r["target"] == label)]
for r in present:
mask = r["target"] == label
weights[r["name"]][mask] = 0.5 / len(groups) / len(present) / mask.sum()
return weights
def choose(rows):
"""Each predefined seed must pass mean/worst-street gates; never select a seed."""
if any(r["phase"] != "development" for r in rows):
raise ValueError("Development only")
groups = {r["held_out"] for r in rows}
if len(groups) != 4:
raise ValueError("Four complete physical-street folds required")
arms = sorted({r["arm"] for r in rows})
summary = {}
for arm in arms:
rr = [r for r in rows if r["arm"] == arm]
if len(rr) != 4 or {r["held_out"] for r in rr} != groups:
raise ValueError("Incomplete arm")
ber = [(1 - r["metrics"]["recall"] + r["metrics"]["fpr"]) / 2 for r in rr]
summary[arm] = dict(
mean=float(np.mean(ber)), worst=max(ber), completed=all(r["completed"] for r in rr)
)
base = summary["old-linear"]
eligible = []
families = {
"new-linear": ["new-linear"],
**{
f: [f + "-" + str(s) for s in [20261023, 20261024, 20261025]]
for f in ["pointwise", "spatial"]
},
}
for family, members in families.items():
if all(
summary[a]["completed"]
and summary[a]["mean"] < base["mean"] - 1e-12
and summary[a]["worst"] <= base["worst"] + 1e-12
for a in members
):
eligible.append(family)
selected = (
min(
eligible,
key=lambda f: (
max(summary[a]["mean"] for a in families[f]),
max(summary[a]["worst"] for a in families[f]),
f,
),
)
if eligible
else "old-linear"
)
return dict(
selected_family=selected,
selected_arms=families.get(selected, ["old-linear"]),
summaries=summary,
eligible_families=eligible,
all_seeds_required=True,
frozen_before_controls=True,
)
def network(base, kernel, seed):
import torch
from torch import nn
if kernel not in (1, 3):
raise ValueError("Only preregistered kernels")
torch.manual_seed(seed)
class Residual(nn.Module):
def __init__(self):
super().__init__()
self.register_buffer(
"coef",
torch.tensor(base["coefficients"][1:], dtype=torch.float32)[None, :, None, None],
)
self.register_buffer("bias", torch.tensor(base["coefficients"][0], dtype=torch.float32))
self.layers = nn.Sequential(
nn.Conv2d(256, 16, 1),
nn.Tanh(),
nn.Conv2d(16, 16, kernel, padding=kernel // 2, padding_mode="replicate"),
nn.Tanh(),
nn.Conv2d(16, 1, 1),
)
nn.init.zeros_(self.layers[-1].weight)
nn.init.zeros_(self.layers[-1].bias)
def forward(self, x):
return (x * self.coef).sum(1, keepdim=True) + self.bias + self.layers(x)
return Residual()
def linear_prediction(record, model):
c = np.asarray(model["coefficients"])
scaled = c[1:] / np.asarray(model["scale"])
logits = (
np.einsum("chw,c->hw", record["features"], scaled)
+ c[0]
- np.asarray(model["mean"]) @ scaled
)
return resize_plane(logits[None], record["target"].shape)[0] >= 0
def residual_prediction(record, model, base, device):
import torch
f = torch.from_numpy(record["features"]).to(device)[None]
mean = torch.tensor(base["mean"], device=device, dtype=torch.float32)[None, :, None, None]
scale = torch.tensor(base["scale"], device=device, dtype=torch.float32)[None, :, None, None]
with torch.inference_mode():
logits = torch.nn.functional.interpolate(
model((f - mean) / scale),
size=record["target"].shape,
mode="bilinear",
align_corners=False,
)
return (logits[0, 0] >= 0).cpu().numpy()
def fit_residual(records, base, kernel, seed, root, tag, steps):
import torch
from dataset_store import write
start = time.monotonic()
weights = dense_weights(records)
device = "cuda"
net = network(base, kernel, seed).to(device)
mean = torch.tensor(base["mean"], device=device, dtype=torch.float32)[None, :, None, None]
scale = torch.tensor(base["scale"], device=device, dtype=torch.float32)[None, :, None, None]
batch = []
for r in records:
f = (torch.from_numpy(r["features"]).to(device)[None] - mean) / scale
known = r["target"] != 255
yy = torch.from_numpy(r["target"][known].astype("float32")).to(device)
ww = torch.from_numpy(weights[r["name"]][known]).to(device)
mask = torch.from_numpy(known).to(device)
batch.append((f, r["target"].shape, mask, yy, ww))
optimizer = torch.optim.AdamW(net.parameters(), lr=0.001, weight_decay=0.01)
first = None
last = []
for step in range(steps):
optimizer.zero_grad(set_to_none=True)
loss_value = 0.0
for f, size, mask, yy, ww in batch:
out = torch.nn.functional.interpolate(
net(f), size=size, mode="bilinear", align_corners=False
)[0, 0][mask]
loss = (
torch.nn.functional.binary_cross_entropy_with_logits(out, yy, reduction="none") * ww
).sum()
if not torch.isfinite(loss):
raise ValueError("Nonfinite training loss")
loss.backward()
loss_value += float(loss.detach())
if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in net.parameters()):
raise ValueError("Nonfinite gradient")
optimizer.step()
if first is None:
first = loss_value
last = (last + [loss_value])[-20:]
if step % 25 == 0:
write(
root / "fit-progress.json",
dict(
tag=tag,
step=step + 1,
total=steps,
loss=loss_value,
seconds=time.monotonic() - start,
),
)
if time.monotonic() - start > 240:
raise TimeoutError("Per-fit budget exceeded")
state = root / "models" / (tag + ".pt")
torch.save({k: v.detach().cpu() for k, v in net.state_dict().items()}, state)
metadata = dict(
kind="residual",
kernel=kernel,
seed=seed,
steps=steps,
first_loss=first,
last_loss=last[-1],
last20=last,
parameters=sum(p.numel() for p in net.parameters()),
base=base,
seconds=time.monotonic() - start,
completed=True,
optimizer_convergence_claim=False,
state=state.relative_to(root).as_posix(),
training_groups=sorted({r["group"] for r in records}),
)
net.eval()
return net, metadata
def load(root):
from dataset_store import checksum, read
p = read(root / "protocol.json")
f = read(root / "review-frozen.json")
manifest = read(root / "feature-manifest.json")
assert checksum(Path(__file__)) == f["source_sha256"]
assert checksum(root / "protocol.json") == f["protocol_sha256"] == manifest["protocol_sha256"]
assert f["supervision"] == manifest["supervision"]
data = []
for r in manifest["records"]:
assert checksum(root / r["cache"]) == r["sha256"]
with np.load(root / r["cache"]) as z:
new = z["target"].copy()
old = z["old_target"].copy()
known = old != 255
assert np.array_equal(new[known], old[known])
if r["split"] != "train":
assert np.array_equal(old, new)
data.append(
dict(r, features=z["features"].astype("float32"), target=new, old_target=old)
)
return p, data
def linear(records, which, params):
us = [samples(r["features"], r[which], r, params) for r in records]
return fit(us, 0.01, 500)
def prepare_torch():
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
import torch
torch.set_num_threads(3)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cuda.matmul.allow_tf32 = False
def development(root):
import torch
from dataset_store import checksum, write
prepare_torch()
p, data = load(root)
start = time.monotonic()
rows = []
(root / "models").mkdir(exist_ok=False)
for fi, (group, train, held) in enumerate(folds(data)):
assert all(r["group"] != group and r["split"] == "train" for r in train)
old = linear(train, "old_target", p["fit"])
new = linear(train, "target", p["fit"])
for arm in p["arms"]:
tag = f"fold{fi}-{arm}"
net = None
if arm in ["old-linear", "new-linear"]:
lm = old if arm == "old-linear" else new
metadata = dict(
kind="linear", base=lm, completed=True, training_groups=lm["training_groups"]
)
else:
family, seed = arm.split("-")
net, metadata = fit_residual(
train, new, 1 if family == "pointwise" else 3, int(seed), root, tag, p["steps"]
)
metadata["state_sha256"] = checksum(root / metadata["state"])
path = root / "models" / (tag + ".json")
write(path, metadata)
windows = []
for r in held:
pred = (
linear_prediction(r, metadata["base"])
if net is None
else residual_prediction(r, net, new, "cuda")
)
windows.append(dict(name=r["name"], **counts(pred, r["target"])))
row = dict(
phase="development",
arm=arm,
held_out=group,
completed=True,
metrics=aggregate(windows),
windows=windows,
model=path.relative_to(root).as_posix(),
model_sha256=checksum(path),
fitted_groups=metadata["training_groups"],
)
rows.append(row)
write(
root / "development-progress.json",
dict(completed=len(rows), total=32, last=row, seconds=time.monotonic() - start),
)
del net
torch.cuda.empty_cache()
choice = choose(rows)
write(
root / "development-result.json",
dict(
rows=rows,
selection=choice,
seconds=time.monotonic() - start,
protocol_sha256=checksum(root / "protocol.json"),
),
)
write(
root / "selection-frozen.json",
dict(
**choice,
development_sha256=checksum(root / "development-result.json"),
protocol_sha256=checksum(root / "protocol.json"),
),
)
print(json.dumps(choice))
def final_fit(root):
from dataset_store import checksum, read, write
prepare_torch()
p, data = load(root)
choice = read(root / "selection-frozen.json")
train = [r for r in data if r["split"] == "train"]
assert choice["development_sha256"] == checksum(root / "development-result.json")
old = linear(train, "old_target", p["fit"])
new = linear(train, "target", p["fit"])
previous = read(Path("/store/experiments/semantic-nonlinear-20261023/models-frozen.json"))[
"models"
]["linear"]
for k in ["mean", "scale", "coefficients"]:
assert old[k] == previous[k], k
models = {}
for arm in sorted(set(["old-linear"] + choice["selected_arms"])):
if arm in ["old-linear", "new-linear"]:
metadata = dict(kind="linear", base=old if arm == "old-linear" else new, completed=True)
else:
family, seed = arm.split("-")
net, metadata = fit_residual(
train,
new,
1 if family == "pointwise" else 3,
int(seed),
root,
"final-" + arm,
p["steps"],
)
del net
metadata["state_sha256"] = checksum(root / metadata["state"])
models[arm] = metadata
write(
root / "models-frozen.json",
dict(
models=models,
selection_sha256=checksum(root / "selection-frozen.json"),
baseline_exact=True,
protocol_sha256=checksum(root / "protocol.json"),
source_sha256=checksum(Path(__file__)),
production_eligible=False,
),
)
print(json.dumps({"fitted": list(models), "baseline_exact": True}))
def evaluate(root):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
prepare_torch()
p, data = load(root)
models = read(root / "models-frozen.json")
choice = read(root / "selection-frozen.json")
assert models["selection_sha256"] == checksum(root / "selection-frozen.json")
assert not (root / "result.json").exists()
nets = {}
for arm, m in models["models"].items():
if m["kind"] == "residual":
net = network(m["base"], m["kernel"], m["seed"]).cuda()
assert checksum(root / m["state"]) == m["state_sha256"]
net.load_state_dict(
torch.load(root / m["state"], map_location="cuda", weights_only=True)
)
net.eval()
nets[arm] = net
rows = []
audit = {}
for r in data:
if r["split"] != "regression":
continue
preds = {}
for arm, m in models["models"].items():
pred = (
linear_prediction(r, m["base"])
if m["kind"] == "linear"
else residual_prediction(r, nets[arm], m["base"], "cuda")
)
preds[arm] = pred
rows.append(
dict(name=r["name"], group=r["group"], arm=arm, **counts(pred, r["target"]))
)
if r["name"] == "P1":
t = np.frombuffer(
pixel_target(dict(read(root / "p1-audit-runs-final.json"), size=[512, 512])),
dtype="uint8",
).reshape(512, 512)
audit[arm] = aggregate([counts(pred, t)])
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **preds)
metrics = {
g: {
a: aggregate([r for r in rows if r["group"] == g and r["arm"] == a])
for a in models["models"]
}
for g in sorted({r["group"] for r in rows})
}
failures = []
for a in choice["selected_arms"]:
if a == "old-linear":
failures.append("No development improvement selected")
continue
for g, mm in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
if (
mm[a][metric] is not None
and sign * (mm[a][metric] - mm["old-linear"][metric]) < -1e-12
):
failures.append(a + ": " + g + " " + metric)
if (
audit[a]["recall"] < audit["old-linear"]["recall"]
or audit[a]["fpr"] >= audit["old-linear"]["fpr"]
):
failures.append(a + ": P1 gap gate")
old = read(Path("/store/experiments/semantic-nonlinear-20261023/result.json"))
for r in rows:
if r["arm"] == "old-linear":
before = next(x for x in old["rows"] if x["name"] == r["name"])["variants"]["linear"]
assert all(r[k] == before[k] for k in ["tp", "fn", "fp", "tn", "ignored"])
assert audit["old-linear"] == old["diagnostic"]["linear"]
result = dict(
rows=rows,
metrics=metrics,
diagnostic=audit,
selection=choice,
accepted=not failures,
failures=failures,
production_eligible=False,
baseline_exact=True,
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
)
write(root / "result.json", result)
print(
json.dumps(
{
"metrics": metrics,
"diagnostic": audit,
"accepted": not failures,
"failures": failures,
}
)
)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("phase", choices=["development", "fit", "evaluate"])
ap.add_argument("--root", type=Path, default=Path("/experiment"))
a = ap.parse_args()
{"development": development, "fit": final_fit, "evaluate": evaluate}[a.phase](a.root)
@@ -0,0 +1,364 @@
"""Bounded train-street development selection; exposed controls evaluated once afterwards.
No coordinates, street identity or hand-coded geometry enters the classifier.
Unknown pixels stay unknown. Every fold excludes a physical area from sampling,
normalization and fitting. The immutable admission split is not rewritten.
"""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from nonlinear_head_probe import fit_mlp, mlp_logits
from pixel_growth_probe import aggregate, counts, fit
from supervision_density_probe import samples
def folds(records):
train = [r for r in records if r["split"] == "train"]
if len({r["sample_id"] for r in records}) != len(records):
raise ValueError("Duplicate sample")
groups = sorted({r["group"] for r in train})
if len(groups) < 3:
raise ValueError("At least three training streets required")
for group in groups:
held = [r for r in train if r["group"] == group]
learn = [r for r in train if r["group"] != group]
if {r["input"]["rgb"]["sha256"] for r in held} & {
r["input"]["rgb"]["sha256"] for r in learn
}:
raise ValueError("Identical RGB across folds")
yield group, learn, held
def select_candidate(rows, baseline):
"""No control inputs accepted; macro BER, with a worst-street guard."""
if not rows or any(r["phase"] != "development" for r in rows):
raise ValueError("Development results only")
candidates = sorted({r["candidate"] for r in rows})
all_groups = {r["held_out"] for r in rows}
if len(all_groups) < 3:
raise ValueError("Incomplete development streets")
summaries = {}
for candidate in candidates:
rr = [r for r in rows if r["candidate"] == candidate]
if len(rr) != len(all_groups) or {r["held_out"] for r in rr} != all_groups:
raise ValueError("Missing or duplicate fold")
errors = []
for r in rr:
m = r["metrics"]
if m["recall"] is None or m["fpr"] is None:
raise ValueError("Both classes required per development street")
errors.append((1 - m["recall"] + m["fpr"]) / 2)
summaries[candidate] = dict(
macro_ber=float(np.mean(errors)),
worst_ber=max(errors),
converged=all(r["converged"] for r in rr),
)
base = summaries[baseline]
if not base["converged"]:
raise ValueError("Reference fit failed")
eligible = [
c
for c in candidates
if summaries[c]["converged"]
and summaries[c]["macro_ber"] < base["macro_ber"] - 1e-12
and summaries[c]["worst_ber"] <= base["worst_ber"] + 1e-12
]
winner = (
min(eligible, key=lambda c: (summaries[c]["macro_ber"], summaries[c]["worst_ber"], c))
if eligible
else baseline
)
return dict(
selected=winner,
development_improved=bool(eligible),
summaries=summaries,
rule="lower macro BER; worst-street BER not higher; rank macro, worst, id",
)
def features(z, representation):
if representation == "semantic":
return z["features"].astype("float32")
if representation == "detail":
return z["detail"].astype("float32")
if representation == "combined":
return np.concatenate([z["features"], z["detail"]], axis=0).astype("float32")
raise ValueError("Unknown representation")
def feature_pixels(f, size, indices):
import torch
h, w = size
y, x = np.unravel_index(indices, (h, w))
grid = np.stack([2 * (x + 0.5) / w - 1, 2 * (y + 0.5) / h - 1], -1).astype("float32")
return torch.nn.functional.grid_sample(
torch.from_numpy(f)[None],
torch.from_numpy(grid)[None, None],
mode="bilinear",
padding_mode="border",
align_corners=False,
)[0, :, 0].T.numpy()
def predict(f, size, indices, model, chunk=8192):
result = np.empty(len(indices), dtype=bool)
for lo in range(0, len(indices), chunk):
x = feature_pixels(f, size, indices[lo : lo + chunk])
if model["head"] == "linear":
m = model["parameters"]
coef = np.asarray(m["coefficients"])
scaled = coef[1:] / np.asarray(m["scale"])
z = x @ scaled + coef[0] - np.asarray(m["mean"]) @ scaled
else:
z = mlp_logits(x, model["parameters"])
result[lo : lo + chunk] = z >= 0
return result
def fit_candidate(units, candidate, held_out=None):
if held_out is not None and any(u["group"] == held_out for u in units):
raise ValueError("Held-out street entered fitting")
if candidate["head"] == "linear":
p = fit(units, candidate["l2"], 500)
p["converged"] = True
else:
p = fit_mlp(units, hidden=32, seed=20261023, l2=candidate["l2"], max_iterations=500)
return dict(candidate=candidate, head=candidate["head"], parameters=p)
def setup(root):
from dataset_store import checksum, read
protocol = read(root / "protocol.json")
frozen = read(root / "review-frozen.json")
manifest = read(root / "feature-manifest.json")
assert (
frozen["protocol_sha256"] == manifest["protocol_sha256"] == checksum(root / "protocol.json")
)
assert frozen["source_sha256"] == checksum(Path(__file__))
assert frozen["supervision"] == manifest["supervision"]
for name, sha in frozen["sources"].items():
assert checksum(root / name) == sha
for r in manifest["records"]:
assert checksum(root / r["cache"]) == r["sha256"]
return protocol, manifest["records"]
def development(root):
import torch
from dataset_store import checksum, write
torch.set_num_threads(3)
start = time.monotonic()
protocol, records = setup(root)
assert not (root / "development-selection.json").exists()
units = {k: [] for k in ["semantic", "detail", "combined"]}
for r in records:
if r["split"] != "train":
continue
with np.load(root / r["cache"]) as z:
for representation in units:
units[representation].append(
samples(features(z, representation), z["target"], r, protocol["fit"])
)
rows = []
(root / "models").mkdir(exist_ok=False)
for fi, (held_out, learn, held) in enumerate(folds(records)):
for candidate in protocol["candidates"]:
started = time.monotonic()
fitting = [u for u in units[candidate["representation"]] if u["group"] != held_out]
assert {u["name"] for u in fitting} == {r["name"] for r in learn}
model = fit_candidate(fitting, candidate, held_out)
mp = root / "models" / ("fold" + str(fi) + "-" + candidate["id"] + ".json")
write(mp, model)
metrics = []
for r in held:
with np.load(root / r["cache"]) as z:
target = z["target"]
indices = np.flatnonzero(target != 255)
pred = predict(
features(z, candidate["representation"]), target.shape, indices, model
)
c = counts(pred, target.ravel()[indices])
c["ignored"] = int((target == 255).sum())
metrics.append(dict(name=r["name"], **c))
rows.append(
dict(
phase="development",
candidate=candidate["id"],
held_out=held_out,
fitted_groups=model["parameters"]["training_groups"],
model_path=mp.relative_to(root).as_posix(),
model_sha256=checksum(mp),
converged=model["parameters"]["converged"],
iterations=model["parameters"]["iterations"],
metrics=aggregate(metrics),
windows=metrics,
seconds=time.monotonic() - started,
)
)
write(
root / "development-progress.json",
dict(
completed=len(rows),
total=4 * len(protocol["candidates"]),
last=rows[-1],
elapsed_seconds=time.monotonic() - start,
),
)
choice = select_candidate(rows, protocol["baseline"])
write(
root / "development-result.json",
dict(
rows=rows,
selection=choice,
seconds=time.monotonic() - start,
protocol_sha256=checksum(root / "protocol.json"),
source_sha256=checksum(Path(__file__)),
),
)
write(
root / "development-selection.json",
dict(
**choice,
development_sha256=checksum(root / "development-result.json"),
protocol_sha256=checksum(root / "protocol.json"),
frozen_before_control_evaluation=True,
),
)
print(json.dumps(choice))
def final_fit(root):
import torch
from dataset_store import checksum, read, write
torch.set_num_threads(3)
protocol, records = setup(root)
choice = read(root / "development-selection.json")
assert choice["development_sha256"] == checksum(root / "development-result.json")
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
selected = {protocol["baseline"], choice["selected"]}
result = {}
for candidate in protocol["candidates"]:
if candidate["id"] not in selected:
continue
units = []
for r in records:
if r["split"] != "train":
continue
with np.load(root / r["cache"]) as z:
units.append(
samples(
features(z, candidate["representation"]), z["target"], r, protocol["fit"]
)
)
result[candidate["id"]] = fit_candidate(units, candidate)
assert result[candidate["id"]]["parameters"]["converged"]
parent = read(Path("/store/experiments/semantic-nonlinear-20261023/models-frozen.json"))
# Exact numeric baseline identity is checked against the previous fixed experiment.
previous = parent["models"]["linear"]
current = result[protocol["baseline"]]["parameters"]
for key in ["mean", "scale", "coefficients"]:
assert np.array_equal(current[key], previous[key]), key
write(
root / "models-frozen.json",
dict(
models=result,
selection_sha256=checksum(root / "development-selection.json"),
protocol_sha256=checksum(root / "protocol.json"),
baseline_exactly_reproduced=True,
production_eligible=False,
frozen_before_controls=True,
),
)
print(json.dumps({"fitted": sorted(result), "baseline_exactly_reproduced": True}))
def control_evaluation(root):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
torch.set_num_threads(3)
protocol, records = setup(root)
choice = read(root / "development-selection.json")
frozen = read(root / "models-frozen.json")
assert frozen["selection_sha256"] == checksum(root / "development-selection.json")
assert not (root / "result.json").exists()
rows = []
audit = {}
for r in records:
if r["split"] != "regression":
continue
with np.load(root / r["cache"]) as z:
target = z["target"]
predictions = {}
for key, model in frozen["models"].items():
pred = predict(
features(z, model["candidate"]["representation"]),
target.shape,
np.arange(target.size),
model,
).reshape(target.shape)
predictions[key] = pred
rows.append(
dict(name=r["name"], group=r["group"], candidate=key, **counts(pred, target))
)
if r["name"] == "P1":
runs = read(root / "p1-audit-runs-final.json")
from admission_store import pixel_target
t = np.frombuffer(
pixel_target(dict(runs, size=[target.shape[1], target.shape[0]])),
dtype="uint8",
).reshape(target.shape)
audit[key] = aggregate([counts(pred, t)])
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
metrics = {
g: {
c: aggregate([r for r in rows if r["group"] == g and r["candidate"] == c])
for c in frozen["models"]
}
for g in sorted({r["group"] for r in rows})
}
b, s = protocol["baseline"], choice["selected"]
failures = []
for g, mm in metrics.items():
for key, sign in [("recall", 1), ("fpr", -1)]:
if mm[b][key] is not None and sign * (mm[s][key] - mm[b][key]) < -1e-12:
failures.append(g + ": " + key)
if audit[s]["recall"] < audit[b]["recall"] or audit[s]["fpr"] >= audit[b]["fpr"]:
failures.append("P1 diagnostic recall/gap gate")
if s == b:
failures.append("No development improvement selected")
write(
root / "result.json",
dict(
rows=rows,
metrics=metrics,
p1_diagnostic=audit,
selection=choice,
qualification=dict(accepted=not failures, failures=failures, production_eligible=False),
protocol_sha256=checksum(root / "protocol.json"),
source_sha256=checksum(Path(__file__)),
models_sha256=checksum(root / "models-frozen.json"),
control_selection=False,
),
)
print(json.dumps({"metrics": metrics, "audit": audit, "failures": failures}))
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("phase", choices=["development", "fit", "evaluate"])
ap.add_argument("--root", type=Path, default=Path("/experiment"))
args = ap.parse_args()
{"development": development, "fit": final_fit, "evaluate": control_evaluation}[args.phase](
args.root
)
@@ -0,0 +1,107 @@
"""Offline loss policy for two immutable annotation releases.
History cohorts are not paint-quality labels. Keep class/street/window mass fixed;
only split that mass equally between original and newly reviewed pixels.
"""
import math
import numpy as np
from spatial_decoder_probe import dense_weights
from transfer_gates import component_regressions
def release_balanced_weights(records):
if not records or any(r["split"] != "train" for r in records):
raise ValueError("Training records only")
if len({r["name"] for r in records}) != len(records):
raise ValueError("Duplicate sample")
for r in records:
t, old = r["target"], r["old_target"]
if (
t.shape != old.shape
or not set(np.unique(t)) <= {0, 1, 255}
or not set(np.unique(old)) <= {0, 1, 255}
):
raise ValueError("Invalid target contract")
if not np.array_equal(t[old != 255], old[old != 255]):
raise ValueError("Original labels changed")
weights = dense_weights(records)
for r in records:
t, old, w = r["target"], r["old_target"], weights[r["name"]]
for label in (0, 1):
mask = t == label
cohorts = [mask & (old != 255), mask & (old == 255)]
present = [part for part in cohorts if part.any()]
if len(present) == 2:
mass = w[mask].sum(dtype=np.float64)
for part in present:
w[part] = mass / 2 / part.sum()
return weights
def assess_balance(rows, seeds):
expected = {"old-linear", "new-linear"} | {
f"{policy}-{family}-{seed}"
for policy in ["uniform", "balanced"]
for family in ["head", "decoder"]
for seed in seeds
}
if not seeds or len(set(seeds)) != len(seeds):
raise ValueError("Unique preregistered seeds required")
if not rows or any(r["phase"] != "development" for r in rows):
raise ValueError("Development only")
if {r["arm"] for r in rows} != expected:
raise ValueError("Incomplete arms")
groups = {r["held_out"] for r in rows}
if len(groups) != 4:
raise ValueError("Four physical streets required")
summary = {}
for arm in sorted(expected):
rr = [r for r in rows if r["arm"] == arm]
if len(rr) != 4 or {r["held_out"] for r in rr} != groups:
raise ValueError("Unpaired or duplicate folds")
if any(not r["completed"] or r["held_out"] in r["fitted_groups"] for r in rr):
raise ValueError("Incomplete or leaked fit")
errors = []
for r in rr:
m = r["metrics"]
if any(
m[k] is None or not math.isfinite(m[k]) or not 0 <= m[k] <= 1
for k in ["recall", "fpr"]
):
raise ValueError("Invalid development support")
errors.append((1 - m["recall"] + m["fpr"]) / 2)
summary[arm] = dict(mean=sum(errors) / 4, worst=max(errors))
audits = []
eligible = []
policy_non_regressing = []
for family in ["head", "decoder"]:
passed = True
paired_passed = True
for seed in seeds:
arm = f"balanced-{family}-{seed}"
references = {"old-linear", "new-linear", f"uniform-{family}-{seed}"}
if family == "decoder":
references.add(f"balanced-head-{seed}")
for ref in sorted(references):
cc = component_regressions(rows, ref, [arm])
a, b = summary[arm], summary[ref]
composite = a["mean"] < b["mean"] - 1e-12 and a["worst"] <= b["worst"] + 1e-12
audits.append(dict(arm=arm, composite_pass=composite, **cc))
passed &= composite and cc["all_components_non_regressing"]
if ref == f"uniform-{family}-{seed}":
paired_passed &= composite and cc["all_components_non_regressing"]
if passed:
eligible.append("balanced-" + family)
if paired_passed:
policy_non_regressing.append("balanced-" + family)
return dict(
eligible_families=eligible,
paired_policy_pass=policy_non_regressing,
summaries=summary,
audits=audits,
all_seeds_required=True,
production_eligible=False,
control_selection=False,
)
@@ -0,0 +1,234 @@
"""Offline paired review-coverage experiment over frozen visual features."""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, counts, fit, resize_plane
from scipy.special import expit
def check_pair(sparse, dense, before, after):
for field in ["sample_id", "source", "physical_group", "split", "inputs"]:
if sparse[field] != dense[field]:
raise ValueError("Changed paired input: " + field)
if before.shape != after.shape or not set(np.unique(after)) <= {0, 1, 255}:
raise ValueError("Invalid dense target")
known = before != 255
if not np.array_equal(before[known], after[known]):
raise ValueError("Existing reviewed labels changed")
if sparse["split"] != "train" and not np.array_equal(before, after):
raise ValueError("Original control target changed")
def qualify(metrics, audit, reproduced):
failures, gains = [], []
if not reproduced:
failures.append("sparse baseline did not reproduce prior control counts")
for group, variants in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
a, b = variants["sparse"][metric], variants["dense"][metric]
if a is None or b is None:
continue
if sign * (b - a) < -1e-12:
failures.append(group + ": " + metric)
if sign * (b - a) > 1e-12:
gains.append(group + ": " + metric)
if audit["dense"]["recall"] < audit["sparse"]["recall"]:
failures.append("diagnostic paint recall")
if audit["dense"]["fpr"] >= audit["sparse"]["fpr"]:
failures.append("diagnostic gap false positives not strictly reduced")
if not gains:
failures.append("no strict gain on original regression")
return dict(accepted=not failures, failures=failures, gains=gains)
def load_examples(store, receipt):
from admission_store import Supervision, pixel_target
examples, targets = {}, {}
with Supervision(store, receipt["path"], receipt["sha256"]) as reader:
for split in ["train", "regression"]:
for batch in reader.batches("observed_paint", split, batch_size=1):
e = batch[0]
assert len(e["targets"]) == 1
t = e["targets"][0]
examples[e["sample_id"]] = e
targets[e["sample_id"]] = np.frombuffer(pixel_target(t), dtype="uint8").reshape(
t["size"][1], t["size"][0]
)
return examples, targets
def samples(features, target, record, params):
if record["split"] != "train":
raise ValueError("Only train records may provide fitting samples")
import torch
h, w = target.shape
rng = np.random.default_rng(params["seed"] + int(record["sample_id"][:8], 16))
chosen = []
for label in [0, 1]:
indices = np.flatnonzero(target == label)
chosen.extend(
rng.choice(
indices,
min(len(indices), params["max_samples_per_class_per_window"]),
replace=False,
)
)
chosen = np.asarray(chosen)
ys, xs = np.unravel_index(chosen, (h, w))
grid = np.stack([2 * (xs + 0.5) / w - 1, 2 * (ys + 0.5) / h - 1], -1).astype("float32")
x = torch.nn.functional.grid_sample(
torch.from_numpy(features)[None],
torch.from_numpy(grid)[None, None],
mode="bilinear",
padding_mode="border",
align_corners=False,
)[0, :, 0].T.numpy()
return dict(
name=record["name"], group=record["group"], split="train", x=x, y=target.ravel()[chosen]
)
def run(root, store):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
torch.set_num_threads(3)
start = time.monotonic()
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
protocol = read(root / "protocol.json")
frozen = read(root / "review-frozen.json")
manifest = read(root / "feature-manifest.json")
parent = store / "experiments" / protocol["parent"]
assert frozen["source_sha256"] == checksum(Path(__file__))
assert (
manifest["protocol_sha256"] == frozen["protocol_sha256"] == checksum(root / "protocol.json")
)
assert frozen["audit_sha256"] == checksum(root / "p1-audit-runs-final.json")
assert frozen["pixel_runs_sha256"] == checksum(root / "pixel-runs-final.json")
assert frozen["regions_sha256"] == checksum(root / "regions-final.json")
assert checksum(root / "model-inventory.json") == checksum(parent / "model-inventory.json")
params = protocol["fit"]
assert params == read(parent / "protocol.json")["fit"]
old_receipt = read(parent / "supervision-receipt.json")
assert old_receipt["sha256"] == protocol["parent_release_sha256"]
old, before = load_examples(store, old_receipt)
new, after = load_examples(store, read(root / "supervision-receipt.json"))
assert set(old) == set(new) == {r["sample_id"] for r in manifest["records"]}
units = {"sparse": [], "dense": []}
for r in manifest["records"]:
sid = r["sample_id"]
check_pair(old[sid], new[sid], before[sid], after[sid])
assert checksum(root / r["cache"]) == r["sha256"]
with np.load(root / r["cache"]) as z:
assert np.array_equal(z["target"], after[sid])
if r["split"] == "train":
for arm, target in [("sparse", before[sid]), ("dense", after[sid])]:
units[arm].append(samples(z["features"].astype("float32"), target, r, params))
models = {arm: fit(us, params["l2"], params["max_iterations"]) for arm, us in units.items()}
fit_seconds = time.monotonic() - start
write(
root / "models-frozen.json",
dict(
models=models,
threshold=params["threshold"],
protocol_sha256=checksum(root / "protocol.json"),
review_sha256=checksum(root / "review-frozen.json"),
features_sha256=checksum(root / "feature-manifest.json"),
source_sha256=checksum(Path(__file__)),
frozen_before_evaluation=True,
),
)
rows = []
diagnostic = None
old_rows = {r["name"]: r for r in read(parent / "result.json")["rows"]}
for r in manifest["records"]:
if r["split"] != "regression":
continue
with np.load(root / r["cache"]) as z:
features = z["features"].astype("float32")
target = z["target"]
predictions = {}
for arm, m in models.items():
coef = np.array(m["coefficients"])
scaled = coef[1:] / np.array(m["scale"])
bias = coef[0] - np.array(m["mean"]) @ scaled
logits = np.einsum("chw,c->hw", features, scaled) + bias
predictions[arm] = (
expit(resize_plane(logits[None], target.shape)[0]) >= params["threshold"]
)
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
rows.append(
dict(
name=r["name"],
group=r["group"],
variants={arm: counts(p, target) for arm, p in predictions.items()},
)
)
if r["name"] == "P1":
t = read(root / "p1-audit-runs-final.json")
audit_target = np.frombuffer(
pixel_target(dict(t, size=[512, 512])), dtype="uint8"
).reshape(512, 512)
diagnostic = {
arm: aggregate([counts(p, audit_target)]) for arm, p in predictions.items()
}
assert diagnostic is not None
metrics = {
g: {arm: aggregate([r["variants"][arm] for r in rows if r["group"] == g]) for arm in models}
for g in sorted({r["group"] for r in rows})
}
reproduced = all(
r["variants"]["sparse"] == old_rows[r["name"]]["variants"]["expanded"] for r in rows
)
prior_model = read(parent / "models-frozen.json")["models"]["expanded"]
delta = max(
float(np.max(np.abs(np.array(models["sparse"][k]) - np.array(prior_model[k]))))
for k in ["mean", "scale", "coefficients"]
)
outcome = qualify(metrics, diagnostic, reproduced)
write(
root / "result.json",
dict(
**outcome,
metrics=metrics,
rows=rows,
diagnostic=diagnostic,
sparse_reproduced=reproduced,
sparse_max_parameter_delta=delta,
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
fit_and_load_seconds=fit_seconds,
total_seconds=time.monotonic() - start,
evaluated_utc=__import__("datetime")
.datetime.now(__import__("datetime").timezone.utc)
.isoformat(),
production_eligible=False,
blind_generalization_claim=False,
),
)
print(
json.dumps(
dict(
**outcome,
metrics=metrics,
diagnostic=diagnostic,
sparse_reproduced=reproduced,
parameter_delta=delta,
)
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("root", type=Path)
parser.add_argument("--store", type=Path, default=Path("/store"))
args = parser.parse_args()
run(args.root, args.store)
@@ -0,0 +1,56 @@
"""Separate recall and false-positive regressions by physical validation group.
Diagnostic/future protocol helper. Does not rewrite an experiment's frozen choice.
"""
import math
def component_regressions(rows, reference, candidates):
if not rows or any(r["phase"] != "development" for r in rows):
raise ValueError("Development rows only")
selected = {reference, *candidates}
by_arm = {a: {} for a in selected}
for row in rows:
if row["arm"] not in selected:
continue
group = row["held_out"]
if group in row["fitted_groups"] or group in by_arm[row["arm"]]:
raise ValueError("Leaked or duplicate physical group")
if not row["completed"]:
raise ValueError("Incomplete fit")
by_arm[row["arm"]][group] = row["metrics"]
groups = set(by_arm[reference])
if not groups or any(set(by_arm[a]) != groups for a in candidates):
raise ValueError("Unmatched physical groups")
regressions = []
for arm in candidates:
for group in sorted(groups):
for metric, direction in [("recall", 1), ("fpr", -1)]:
before = by_arm[reference][group][metric]
after = by_arm[arm][group][metric]
if before is None and after is None:
continue
if (
before is None
or after is None
or not all(math.isfinite(x) and 0 <= x <= 1 for x in [before, after])
):
raise ValueError("Inconsistent metric support")
if direction * (after - before) < -1e-12:
regressions.append(
dict(
arm=arm,
group=group,
metric=metric,
before=before,
after=after,
delta=after - before,
)
)
return dict(
reference=reference,
candidates=list(candidates),
regressions=regressions,
all_components_non_regressing=not regressions,
)
@@ -0,0 +1,374 @@
"""Frozen visual representation probe. Offline only; no map publication."""
import json
import sys
from pathlib import Path
import cv2
import numpy as np
from grouped_selection_study import objective, select, transfer_gate
from object_assembly_study import measured
from object_proposal_study import aggregate, labels, masks, save_new, sha, timestamp
from paint_hypothesis_study import fit_classifier, probability
from PIL import Image
from shapely.geometry import shape
from shapely.ops import unary_union
VARIANTS = ["handcrafted14", "visual512", "fused526", "native_paint"]
def fractional_weights(mask, shape_hw):
"""Retain thin-object support when pooling stride-four image features."""
h, w = shape_hw
weights = cv2.resize(mask.astype(np.float32), (w, h), interpolation=cv2.INTER_AREA)
total = float(weights.sum())
if total <= 0:
raise ValueError("Empty pooling support")
return weights / total
def assessed(candidates, reviewed):
result = measured(candidates, reviewed)
result["unsupported_sparse"] = result["unsupported"]
bg = unary_union([shape(g) for g in reviewed.get("complete_background", [])])
ls = labels(candidates, reviewed)
bad = []
for c, label in zip(candidates, ls, strict=True):
p = shape(c["geometry"])
if label == 0 or (
label != 1 and not bg.is_empty and p.intersection(bg).area / max(p.area, 1e-9) >= 0.9
):
bad.append(c["id"])
result["unsupported"] = len(bad)
result["false_ids"] = bad
return result
def check_inputs(root):
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
if sha(root / name) != digest:
raise ValueError("Changed frozen input: " + name)
def extract(root):
import torch
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
torch.set_num_threads(3)
cv2.setNumThreads(3)
check_inputs(root)
inventory = json.loads((root / "model-inventory.json").read_text())
for name, digest in inventory["files"].items():
assert sha(Path("/model") / name) == digest
processor = AutoImageProcessor.from_pretrained("/model", local_files_only=True)
model = (
Mask2FormerForUniversalSegmentation.from_pretrained("/model", local_files_only=True)
.cuda()
.eval()
)
for p in model.parameters():
p.requires_grad_(False)
records = json.loads((root / "candidates.json").read_text())["records"]
folder = root / "features"
folder.mkdir(exist_ok=True)
receipts = []
for i, record in enumerate(records):
rgb_path = root / "data" / (record["id"] + ".png")
tensors = processor(
images=Image.open(rgb_path).convert("RGB"),
return_tensors="pt",
size={"height": 512, "width": 512},
).to("cuda")
assert tuple(tensors["pixel_values"].shape[-2:]) == (512, 512)
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
output = model(**tensors, output_hidden_states=True)
feature = output.pixel_decoder_last_hidden_state[0].float()
assert feature.shape[0] == 256, feature.shape
classes = output.class_queries_logits[0].float().softmax(-1)[:, :-1]
queries = output.masks_queries_logits[0].float().sigmoid()
semantic = torch.einsum("qc,qhw->chw", classes, queries)
native = semantic[[23, 24]].sum(0) / semantic.sum(0).clamp_min(1e-8)
cs = record["variants"]["retained"]
inside, rings, native_weights = [], [], []
for c in cs:
mask = masks(shape(c["geometry"]))
ring = (
cv2.dilate(
mask.astype(np.uint8), cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (23, 23))
)
> 0
) & ~mask
inside.append(fractional_weights(mask, feature.shape[-2:]).ravel())
rings.append(fractional_weights(ring, feature.shape[-2:]).ravel())
native_weights.append(fractional_weights(mask, native.shape).ravel())
if cs:
w = torch.as_tensor(np.asarray(inside + rings), device="cuda")
pooled = (w @ feature.flatten(1).T).cpu().numpy()
visual = np.concatenate([pooled[: len(cs)], pooled[len(cs) :]], axis=1)
native_score = (
(torch.as_tensor(np.asarray(native_weights), device="cuda") @ native.flatten())
.cpu()
.numpy()
)
else:
visual, native_score = np.empty((0, 512)), np.empty(0)
path = folder / (record["id"] + ".npz")
assert not path.exists()
np.savez_compressed(
path, visual=visual, native=native_score, ids=np.asarray([c["id"] for c in cs])
)
receipts.append(
dict(
id=record["id"],
path=str(path.relative_to(root)),
sha256=sha(path),
rgb_sha256=sha(rgb_path),
feature_shape=list(feature.shape),
candidates=len(cs),
)
)
del output, tensors, feature, semantic, native
print(json.dumps(dict(completed=i + 1, total=len(records))), flush=True)
save_new(
root / "features.json",
dict(
**timestamp(),
source_sha256=sha(Path(__file__)),
candidate_sha256=sha(root / "candidates.json"),
model_inventory_sha256=sha(root / "model-inventory.json"),
records=receipts,
max_gpu_bytes=int(torch.cuda.max_memory_allocated()),
),
)
def loaded(root):
records = json.loads((root / "candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
feature_receipt = json.loads((root / "features.json").read_text())
if feature_receipt["source_sha256"] != sha(Path(__file__)):
raise ValueError("Feature implementation changed")
data = {}
for r in records:
path = root / "features" / (r["id"] + ".npz")
receipt = next(a for a in feature_receipt["records"] if a["id"] == r["id"])
assert sha(path) == receipt["sha256"]
z = np.load(path)
cs = r["variants"]["retained"]
assert z["ids"].tolist() == [c["id"] for c in cs]
hand = np.asarray([c["features"][:14] for c in cs]).reshape(-1, 14)
data[r["id"]] = dict(
handcrafted14=hand,
visual512=z["visual"],
fused526=np.concatenate([hand, z["visual"]], axis=1),
native_paint=z["native"],
)
return records, review, data
def fit_head(records, review, data, variant, l2):
x, y = [], []
for r in records:
labs = labels(r["variants"]["retained"], review[r["id"]])
eligible = labs >= 0
x.append(data[r["id"]][variant][eligible])
y.append(labs[eligible])
xx, yy = np.concatenate(x), np.concatenate(y)
if min(np.sum(yy == 0), np.sum(yy == 1)) < 2:
raise ValueError("Insufficient reviewed classes")
model = fit_classifier(xx, yy, l2, 500)
model["positive"] = int(np.sum(yy == 1))
model["negative"] = int(np.sum(yy == 0))
return model
def predict(records, data, variant, model=None):
return {
r["id"]: (
data[r["id"]][variant].tolist()
if variant == "native_paint"
else probability(data[r["id"]][variant], model).tolist()
if len(r["variants"]["retained"])
else []
)
for r in records
}
def evaluation(records, review, probabilities, threshold):
rows = []
for r in records:
accepted = [
c
for c, p in zip(r["variants"]["retained"], probabilities[r["id"]], strict=True)
if p >= threshold
]
rows.append(
dict(
id=r["id"],
street=r["street"],
accepted_ids=[c["id"] for c in accepted],
**assessed(accepted, review[r["id"]]),
)
)
return dict(
rows=rows,
summary=aggregate(rows),
streets={
s: aggregate([r for r in rows if r["street"] == s])
for s in sorted({r["street"] for r in records})
},
)
def rank(choice):
return choice["worst_street"], choice["macro_family"], choice["found"]
def train(root):
check_inputs(root)
records, review, data = loaded(root)
dev = [r for r in records if r["split"] == "development"]
assert not ({r["street"] for r in dev} & {"pokrovka", "sadovaya-karetnaya"})
protocol = json.loads((root / "protocol.json").read_text())
ceiling = {r["id"]: measured(r["variants"]["retained"], review[r["id"]]) for r in dev}
variants = {}
for variant in VARIANTS:
experiments = []
for l2 in [0.0] if variant == "native_paint" else protocol["regularization"]:
scores, folds = {}, {}
if variant == "native_paint":
scores = predict(dev, data, variant)
else:
for street in sorted({r["street"] for r in dev}):
training = [r for r in dev if r["street"] != street]
validation = [r for r in dev if r["street"] == street]
model = fit_head(training, review, data, variant, l2)
scores.update(predict(validation, data, variant, model))
folds[street] = dict(
training_streets=sorted({r["street"] for r in training}), model=model
)
sweep = []
for threshold in protocol["thresholds"]:
result = evaluation(dev, review, scores, threshold)
sweep.append(
dict(
threshold=threshold,
**result["summary"],
**objective(result["rows"], ceiling),
)
)
selected = select(sweep)
experiments.append(dict(l2=l2, selected=selected, folds=folds, sweep=sweep))
feasible = [e for e in experiments if e["selected"] is not None]
best = max(feasible, key=lambda e: (*rank(e["selected"]), e["l2"])) if feasible else None
model = (
fit_head(dev, review, data, variant, best["l2"])
if best and variant != "native_paint"
else None
)
variants[variant] = dict(
selected=best["selected"] if best else None,
l2=best["l2"] if best else None,
model=model,
experiments=experiments,
)
print(
json.dumps(
dict(
variant=variant,
selected=variants[variant]["selected"],
l2=variants[variant]["l2"],
)
),
flush=True,
)
choices = [v for v in VARIANTS if variants[v]["selected"] is not None]
chosen = (
max(choices, key=lambda v: (*rank(variants[v]["selected"]), -VARIANTS.index(v)))
if choices
else None
)
save_new(
root / "models-frozen.json",
dict(
**timestamp(),
chosen=chosen,
variants=variants,
source_sha256=sha(Path(__file__)),
hashes={
n: sha(root / n)
for n in [
"protocol.json",
"review-frozen.json",
"inputs.json",
"input-hashes.json",
"candidates.json",
"features.json",
"model-inventory.json",
]
},
),
)
print("chosen", chosen)
def evaluate(root):
check_inputs(root)
records, review, data = loaded(root)
frozen = json.loads((root / "models-frozen.json").read_text())
assert frozen["source_sha256"] == sha(Path(__file__))
for n, h in frozen["hashes"].items():
assert sha(root / n) == h, n
old = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]["model"]
results = {}
for cohort in ["regression", "heldout"]:
rows = [r for r in records if r["split"] == cohort]
baseline = evaluation(rows, review, predict(rows, data, "handcrafted14", old), 0.15)
variants = {}
for v, artifact in frozen["variants"].items():
if artifact["selected"] is not None:
out = evaluation(
rows,
review,
predict(rows, data, v, artifact["model"]),
artifact["selected"]["threshold"],
)
variants[v] = dict(**out, gate_vs_frozen=transfer_gate(baseline, out))
for out in variants.values():
if "handcrafted14" in variants:
out["gate_vs_same_data_handcrafted"] = transfer_gate(variants["handcrafted14"], out)
ceiling = evaluation(
rows, review, {r["id"]: [1.0] * len(r["variants"]["retained"]) for r in rows}, 0.0
)
results[cohort] = dict(baseline=baseline, variants=variants, ceiling=ceiling)
save_new(
root / "results.json",
dict(
**timestamp(),
chosen=frozen["chosen"],
models_sha256=sha(root / "models-frozen.json"),
cohorts=results,
),
)
print(
json.dumps(
{
k: dict(
baseline=v["baseline"]["summary"],
variants={
n: dict(**x["summary"], gate=x["gate_vs_frozen"])
for n, x in v["variants"].items()
},
ceiling=v["ceiling"]["summary"],
)
for k, v in results.items()
}
)
)
if __name__ == "__main__":
{"extract": extract, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
@@ -0,0 +1,63 @@
"""Explicit TRAIN-only paint additions over immutable labels; never infer background."""
import hashlib
import numpy as np
from condition_inventory import raster
from PIL import Image, ImageFilter
def add_fragments(sample, review, old, approved_roi):
if sample["split"] != "train" or review["name"] != sample["name"]:
raise ValueError("Pinned TRAIN sample required")
if review["input_sha256"] != sample["rgb_sha256"]:
raise ValueError("Image identity changed")
if old.dtype != np.uint8 or list(old.shape[::-1]) != sample["size"]:
raise ValueError("Invalid target shape/type")
if not np.isin(old, [0, 1, 255]).all():
raise ValueError("Invalid target classes")
expected = sample["target_sha256"]
if sample["kind"] == "existing":
if expected is None or hashlib.sha256(old.tobytes()).hexdigest() != expected:
raise ValueError("Existing target changed")
elif sample["kind"] != "candidate" or expected is not None or np.any(old != 255):
raise ValueError("Candidate already has unbound labels")
if review["target_sha256"] != expected or review["boundary_ignore_px"] != 1:
raise ValueError("Pinned target/uncertainty policy required")
polygons = review["paint_fragments"]
if not isinstance(polygons, list) or not 1 <= len(polygons) <= 64:
raise ValueError("Bounded explicit fragments required")
mask = np.zeros(old.shape, dtype=bool)
roi = raster(approved_roi, sample["size"])
for polygon in polygons:
part = raster(polygon, sample["size"])
if np.any(part & ~roi):
raise ValueError("Fragment escaped prereviewed region")
mask |= part
core = (
np.array(Image.fromarray(mask.astype("uint8") * 255).filter(ImageFilter.MinFilter(3))) > 0
)
if np.any(core & (old == 0)):
raise ValueError("Paint conflicts with accepted background")
added = core & (old == 255)
if not added.any():
raise ValueError("No new visible paint survived uncertainty erosion")
result = old.copy()
result[added] = 1
return result, added
def runs(target):
result = dict(view="top", paint=[], background=[], unknown=[])
for name, label in [("paint", 1), ("background", 0)]:
for y, row in enumerate(target == label):
edges = np.diff(np.pad(row.astype("int8"), (1, 1)))
result[name].extend(
[
[y, int(a), int(b)]
for a, b in zip(
np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True
)
]
)
return result
@@ -0,0 +1,72 @@
"""Paired whole-street guards for a fixed weak-paint coverage intervention."""
import math
def assess(rows, seeds):
arms = {f"{policy}-{seed}" for policy in ["base", "added"] for seed in seeds}
if not seeds or len(set(seeds)) != len(seeds) or {r["arm"] for r in rows} != arms:
raise ValueError("Complete preregistered seed pairs required")
groups = {r["held_out"] for r in rows}
if len(groups) != 4 or len(rows) != 2 * len(seeds) * 4:
raise ValueError("Four complete physical-street pairs required")
keyed = {}
for r in rows:
key = r["held_out"], r["arm"]
if key in keyed or r["phase"] != "development" or not r["completed"]:
raise ValueError("Duplicate/incomplete/non-development row")
if set(r["fitted_groups"]) != groups - {r["held_out"]}:
raise ValueError("Incomplete or leaked physical groups")
for part, metric in [
("weak", "recall"),
("clear", "recall"),
("original", "recall"),
("original", "fpr"),
]:
value = r[part][metric]
if value is None or not math.isfinite(value) or not 0 <= value <= 1:
raise ValueError("Required evaluation support missing")
keyed[key] = r
summary = []
for seed in seeds:
failures = []
deltas = []
for group in sorted(groups):
a, b = keyed[group, f"added-{seed}"], keyed[group, f"base-{seed}"]
for part in ["weak", "clear", "original", "added"]:
for k in ["tp", "fn", "fp", "tn"]:
if k in ["tp", "fp"]:
opposite = "fn" if k == "tp" else "tn"
if a[part][k] + a[part][opposite] != b[part][k] + b[part][opposite]:
raise ValueError("Unpaired evaluation targets")
for part, metric, sign in [
("weak", "recall", 1),
("clear", "recall", 1),
("original", "recall", 1),
("original", "fpr", -1),
]:
if sign * (a[part][metric] - b[part][metric]) < -1e-12:
failures.append(
dict(
group=group,
part=part,
metric=metric,
before=b[part][metric],
after=a[part][metric],
)
)
deltas.append(a["weak"]["recall"] - b["weak"]["recall"])
mean_delta = sum(deltas) / 4
if mean_delta <= 1e-12:
failures.append(dict(metric="mean weak recall", delta=mean_delta))
summary.append(
dict(
seed=seed, mean_weak_recall_gain=mean_delta, passed=not failures, failures=failures
)
)
return dict(
passed=all(r["passed"] for r in summary),
seeds=summary,
production_eligible=False,
all_seeds_required=True,
)
@@ -0,0 +1,36 @@
"""Native Torch weighted CE on reviewed paint/background; unknown contributes zero."""
import math
def weighted_paint_cross_entropy(logits, target, class_weights):
"""Mean divides by summed valid class weights, including BG-only batches.
Weights are supplied by a frozen TRAIN-only recipe; this function never
estimates them from evaluation labels or adjusts a prediction threshold.
Torch is optional until training calls this function.
"""
import torch
from torch.nn import functional as functional
if len(class_weights) != 2 or any(
not math.isfinite(float(w)) or float(w) <= 0 for w in class_weights
):
raise ValueError("Two finite positive class weights required")
if logits.ndim != 4 or logits.shape[1] != 2:
raise ValueError("Native NCHW logits with two classes required")
if target.shape != (logits.shape[0], *logits.shape[2:]):
raise ValueError("Native NHW target must match logits")
if target.dtype != torch.long:
raise ValueError("Integer class indices required")
valid = target != 255
if not bool(valid.any()):
raise ValueError("All-unknown loss forbidden")
if not bool(((target == 0) | (target == 1) | ~valid).all()):
raise ValueError("Target classes must be 0, 1 or 255")
weights = logits.new_tensor(class_weights)
if not bool(torch.isfinite(weights).all() & (weights > 0).all()):
raise ValueError("Class weights not representable in logits dtype")
return functional.cross_entropy(
logits, target, weight=weights, ignore_index=255, reduction="mean"
)
+434
View File
@@ -0,0 +1,434 @@
"""Separate Worker inbox/builder. No local-Mac fallback; no inference changes."""
import argparse
import json
import logging
import os
import shutil
import subprocess
import time
from logging.handlers import RotatingFileHandler
from pathlib import Path
from core_client import CoreClient
from dataset_store import Store, checksum, read, verify, write
from final_snapshot import plan
from infrastructure_gaussian_sources import resolve_gaussian_entry
HERE = Path(__file__).resolve().parent
IMAGE = "sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0"
def docker(*args, **kw):
return subprocess.run(["docker", *map(str, args)], capture_output=True, check=True, **kw)
def source_for(envelope, store, state):
bundle = envelope["source"]["bundle_sha256"]
for root in (store.root / "sources", state / "infrastructure-sources"):
for receipt in sorted(root.glob("*/source.json")):
source = read(receipt)
if source.get("bundle_sha256") == bundle:
if checksum(receipt.parent / source["ply"]) != source["sha256"]:
raise ValueError("Cached Gaussian source changed")
return receipt.parent, source
# Complete conversion is shared across subsequent crops and kept only on
# Worker, inside the learning quota. Producer inputs remain read-only.
store.capacity(6 * 1024**3)
profile = dict(
producer_data="D:/NDC_GAUSSIAN_PIPELINE/data",
sevenzip="C:/Program Files/7-Zip/7z.exe",
splat_transform="tools/splat-transform-3.4.0/node_modules/@playcanvas/splat-transform/bin/cli.mjs",
)
entry, native = resolve_gaussian_entry(
envelope["source"], envelope["world"], Path(profile["producer_data"])
)
converter = state.parent / profile["splat_transform"]
from dataset_store import digest
key = digest(
dict(
bundle=bundle,
converter=checksum(converter),
adapter="learning-lcc-lod1-native-frame-v1",
)
)
root = store.root / "sources" / key
root.mkdir(exist_ok=True)
ply = root / "full-lod1.ply"
partial = root / "building.ply"
command = [
shutil.which("node"),
"--max-old-space-size=8192",
str(converter),
"--gpu",
"cpu",
"--max-workers",
"4",
"-w",
"--select-lod",
"1",
str(entry),
"-r",
"180,0,0",
str(partial),
]
from native_children import NativeChildren
children = NativeChildren()
with (root / "conversion.log").open("wb") as log:
proc = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
try:
children.assign(proc)
deadline = time.monotonic() + 900
while proc.poll() is None:
store.capacity(0)
if time.monotonic() > deadline:
raise TimeoutError("Gaussian conversion budget exceeded")
time.sleep(2)
if proc.returncode:
raise RuntimeError("Gaussian conversion failed; see bounded source log")
finally:
if proc.poll() is None:
subprocess.run(
["taskkill", "/PID", str(proc.pid), "/T", "/F"], capture_output=True, timeout=30
)
proc.wait(timeout=30)
children.close()
store.capacity(0)
with partial.open("rb") as stream:
header = stream.read(65536).split(b"end_header", 1)[0]
if not all(name in header for name in (b"opacity", b"scale_0", b"rot_0", b"f_dc_0")):
raise ValueError("Conversion lacks Gaussian attributes")
os.replace(partial, ply)
source = dict(
ply=ply.name,
sha256=checksum(ply),
bundle_sha256=bundle,
lod=1,
converter_sha256=checksum(converter),
native_entrypoint=native["entrypoint"],
source_to_world=[[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]],
gaussian_only=True,
collider_input=False,
point_cloud_input=False,
trajectory_used=False,
camera_source="explicit-local-review-window",
)
write(root / "source.json", source)
return root, source
def sync(client, store):
for item in client.request("/worker/semantic-edits/pending")["jobs"]:
try:
key, world = item["revision"], item["world_id"]
annotation = client.request(
f"/worker/worlds/{world}/semantic-edits/{key}", max_response_bytes=24 * 1024**2
)
envelope = dict(
annotation=annotation,
world=client.request("/worlds/" + world),
source=client.request(
"/worker/worlds/" + world + "/infrastructure-source",
max_response_bytes=24 * 1024**2,
),
renderer_image=IMAGE,
)
store.accept(envelope)
except Exception:
logging.exception("Delivery deferred for revision %s", item["revision"])
acknowledge(client, store)
def acknowledge(client, store):
# ACK after a durable inbox commit; replay also covers a lost HTTP response.
for key, receipt in store.db.execute(
"SELECT id,receipt FROM jobs WHERE acknowledged IS NULL "
"OR acknowledged != receipt ORDER BY rowid"
).fetchall():
envelope = read(store.root / "inbox" / (key + ".json"))
world = envelope["world"]["world_id"]
client.request(f"/worker/worlds/{world}/semantic-edits/{key}/receipt", json.loads(receipt))
with store.db:
store.db.execute("UPDATE jobs SET acknowledged=? WHERE id=?", (receipt, key))
def occupied(state):
return any(
(state / name).exists()
for name in (
"active.json",
"editor-active.json",
"route-active.json",
"infrastructure-active.json",
)
)
def build(key, store, state):
container = "ndc-semantic-sample-" + key[:16]
# Only our exact owned name, left after a killed host process, is reconciled.
prior = subprocess.run(
["docker", "inspect", container, "--format", '{{index .Config.Labels "com.nodedc.role"}}'],
capture_output=True,
timeout=15,
)
if prior.returncode == 0:
if prior.stdout.decode().strip() != "semantic-sample":
raise ValueError("Container name belongs to another owner")
docker("rm", "-f", container, timeout=30)
staging = store.root / "work" / key
staging.mkdir(exist_ok=True)
output = staging / "dataset"
output.mkdir(exist_ok=True)
envelope = read(store.root / "inbox" / (key + ".json"))
if store.accept(envelope) != key:
raise ValueError("Stored inbox revision changed")
snapshot = plan(envelope["annotation"]["package"])
plan_path = staging / "plan.json"
if plan_path.exists() and read(plan_path) != snapshot:
raise ValueError("Resumed snapshot identity changed")
write(plan_path, snapshot)
execution = dict(
release=read(HERE / "release.json")["id"],
renderer=IMAGE,
annotation=envelope["annotation"]["sha256"],
)
execution_path = staging / "execution.json"
if execution_path.exists() and read(execution_path) != execution:
raise ValueError("Resume requires the original builder/image/annotation identity")
write(execution_path, execution)
source_dir, source = source_for(envelope, store, state)
source = dict(
source,
world_sha256=envelope["world"]["sha256"],
collider_sha256=envelope["world"].get("collider_sha256"),
)
store.capacity(512 * 1024**2)
write(staging / "envelope.json", envelope)
write(staging / "source.json", source)
kernels = store.root / "cache" / IMAGE.removeprefix("sha256:")
kernels.mkdir(parents=True, exist_ok=True)
image_env = json.loads(
docker("image", "inspect", IMAGE, "--format", "{{json .Config.Env}}", timeout=20).stdout
)
inherited = next((e.partition("=")[2] for e in image_env if e.startswith("PYTHONPATH=")), "")
cmd = [
"run",
"--detach",
"--name",
container,
"--gpus",
"all",
"--memory",
"6g",
"--cpus",
"4",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--tmpfs",
"/tmp:rw,exec,size=1073741824",
"--label",
"com.nodedc.product=mission-core",
"--label",
"com.nodedc.stack=semantic-learning",
"--label",
"com.nodedc.role=semantic-sample",
"--label",
"com.nodedc.managed-by=semantic-learning-worker",
"--log-driver",
"local",
"--log-opt",
"max-size=2m",
"--log-opt",
"max-file=2",
"-e",
"PYTHONPATH=/builder:" + inherited,
"-e",
"PYTHONDONTWRITEBYTECODE=1",
"-e",
"XDG_CACHE_HOME=/tmp/cache",
"-e",
"TORCH_EXTENSIONS_DIR=/kernels",
"-v",
str(HERE) + ":/builder:ro",
"-v",
str(kernels) + ":/kernels",
"-v",
str(source_dir) + ":/input:ro",
"-v",
str(staging) + ":/job:ro",
"-v",
str(output) + ":/output",
"--entrypoint",
"python3",
IMAGE,
"-B",
"/builder/build_samples.py",
]
started = time.monotonic()
shards = {}
for start in range(0, len(snapshot["windows"]), 4):
name = f"part-{start // 4:03d}"
part = output / name
if (part / "dataset.json").exists():
shards[name] = verify(part)
continue
if part.exists():
shutil.rmtree(part) # Only the unfinished owned shard; complete shards are immutable.
if occupied(state):
raise InterruptedError("Yielding GPU before next shard")
store.capacity(512 * 1024**2)
write(
staging / "batch.json",
dict(name=name, start=start, stop=start + 4, classes=snapshot["classes"]),
)
run_shard(cmd, container, store, state)
shards[name] = verify(part)
write(
staging / "progress.json",
dict(
completed=len(shards),
total=(len(snapshot["windows"]) + 3) // 4,
seconds=time.monotonic() - started,
),
)
write(output / "plan.json", snapshot)
(output / "dataset_reader.py").write_bytes((HERE / "dataset_store.py").read_bytes())
files = {
p.name: dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in (output / "plan.json", output / "dataset_reader.py")
}
write(
output / "dataset.json",
dict(
schema_version="missioncore.semantic-collection/v1",
shards=shards,
files=files,
training_eligible=False,
revision=key,
world_sha256=snapshot["world_sha256"],
split_group=snapshot["world_sha256"],
classes=snapshot["classes"],
seconds=time.monotonic() - started,
),
)
result = store.publish(key, output)
shutil.rmtree(staging)
return result
def run_shard(cmd, container, store, state):
try:
docker(*cmd, timeout=30)
deadline = time.monotonic() + 600
while True:
status = json.loads(
docker("inspect", container, "--format", "{{json .State}}", timeout=15).stdout
)
if not status["Running"]:
if status["ExitCode"]:
logs = docker("logs", "--tail", "30", container, timeout=15)
log = (logs.stdout + logs.stderr).decode(errors="replace")
raise RuntimeError("Renderer failed: " + log[-4000:])
break
store.capacity(0)
if occupied(state):
raise InterruptedError("Yielding GPU to simulation/infrastructure")
if time.monotonic() > deadline:
raise TimeoutError("Sample rendering budget exceeded")
time.sleep(1)
finally:
subprocess.run(["docker", "rm", "-f", container], capture_output=True, timeout=30)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--state", type=Path, required=True)
parser.add_argument("--token-file", type=Path, required=True)
parser.add_argument("--core", default="http://127.0.0.1:18080")
parser.add_argument("--once", action="store_true")
args = parser.parse_args()
if os.name != "nt" or not args.root.is_absolute() or args.root.resolve().is_relative_to(HERE):
raise ValueError("Durable learning requires a separate Worker Windows store")
store = Store(args.root)
import msvcrt
lock = (args.root / "worker.lock").open("a+b")
lock.seek(0)
lock.write(b"0")
lock.flush()
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
handler = RotatingFileHandler(
args.root / "logs/worker.log", maxBytes=2 * 1024**2, backupCount=2, encoding="utf-8"
)
logging.basicConfig(
level=logging.INFO, handlers=[handler], format="%(asctime)s %(levelname)s %(message)s"
)
# A process death does not kill Docker. Reconcile only this store's names
# before resuming an unfinished build or acknowledging a published sample.
for (key,) in store.db.execute(
"SELECT id FROM jobs WHERE acknowledged IS NULL "
"OR acknowledged != receipt OR state='building'"
).fetchall():
name = "ndc-semantic-sample-" + key[:16]
found = subprocess.run(
["docker", "inspect", name, "--format", '{{index .Config.Labels "com.nodedc.role"}}'],
capture_output=True,
timeout=15,
)
if found.returncode == 0 and found.stdout.decode().strip() == "semantic-sample":
docker("rm", "-f", name, timeout=30)
client = CoreClient(args.core, args.token_file, "semantic-learning-v1")
while True:
try:
sync(client, store)
except Exception:
logging.exception("Core delivery/receipt unavailable; durable Worker inbox retained")
try:
if not occupied(args.state):
key = store.next()
if key:
logging.info("Preparing revision %s", key)
started = time.monotonic()
try:
try:
acknowledge(client, store)
except Exception:
logging.warning(
"Progress receipt deferred; preparation stays on Worker"
)
result = build(key, store, args.state)
logging.info(
"Published %s samples=%s seconds=%.3f",
key,
result["sample_count"],
time.monotonic() - started,
)
except InterruptedError:
# Scheduling yield is not an invalid annotation attempt.
with store.db:
store.db.execute(
"UPDATE jobs SET attempts=attempts-1 WHERE id=?", (key,)
)
logging.info("GPU yielded for %s", key)
except Exception as exc:
logging.exception("Sample failed %s", key)
store.update(key, "failed", error=str(exc)[:4096])
except Exception:
logging.exception("Worker build cycle unavailable")
if args.once:
break
time.sleep(10)
if __name__ == "__main__":
main()
+244
View File
@@ -0,0 +1,244 @@
"""Completion ownership, persistence and terminal-state race regressions."""
import sqlite3
import pytest
from test_agent_cycle import done, m, verdict
from test_agent_cycle import setup as cycle_setup
setup = cycle_setup
@pytest.mark.parametrize(
("lease_seconds", "expired_at"), [(10, 110.0), (100, 200.0)], ids=["lease", "deadline"]
)
def test_completion_rechecks_expiry_after_source_validation(
setup, monkeypatch, lease_seconds, expired_at
):
c, plan, clock = setup
plan["limits"]["lease_seconds"] = lease_seconds
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
monkeypatch.setattr(m, "validate_packet", lambda *args: clock.__setitem__(0, expired_at))
with pytest.raises(ValueError, match="(?i)expired|deadline|lease"):
c.complete(claim["token"], "author", dict(reason="source inspected"))
attempt = c.db.execute(
"SELECT finished,result,result_sha FROM agent_attempts WHERE token=?", (claim["token"],)
).fetchone()
assert tuple(attempt) == (None, None, None)
tasks = c.db.execute(
"SELECT stage,result FROM agent_tasks WHERE cycle=?", (identity,)
).fetchall()
assert [tuple(task) for task in tasks] == [("annotate", None)]
def test_root_decision_cannot_close_a_newly_interrupted_executor(setup, monkeypatch):
c, plan, clock = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
other = m.Cycle(c.root, clock=c.clock)
status = c.status
def status_with_competing_expiry(identity):
snapshot = status(identity)
# The old implementation releases its status transaction before decide.
# Do not attempt a second writer if the fixed implementation keeps it held.
if not c.db.in_transaction:
clock[0] = claim["expires"]
assert other.status(identity)["tasks"][0]["state"] == "interrupted"
return snapshot
monkeypatch.setattr(c, "status", status_with_competing_expiry)
rejected = dict(verdict(), verdict="rejected", next="revise", admitted_units=[])
try:
with pytest.raises(ValueError, match="(?i)root decision|executor|terminal|interrupted"):
c.decide(identity, "root", rejected)
assert other.status(identity)["state"] != "closed"
c.reconcile(claim["token"], "root", "Executor confirmed stopped")
assert other.status(identity)["tasks"][0]["state"] == "blocked"
finally:
other.close()
def test_completion_rejects_unknown_token_and_wrong_actor(setup):
c, plan, _ = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
result = dict(reason="source inspected")
for token, actor in (("unknown-token", "author"), (claim["token"], "other")):
with pytest.raises(ValueError, match="ownership"):
c.complete(token, actor, result)
task = c.status(identity)["tasks"][0]
assert task["state"] == "active" and task["result"] is None
c.complete(claim["token"], "author", result)
def test_completion_replay_after_reopen_preserves_evidence_and_review(setup):
c, plan, clock = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
result = dict(reason="source inspected", geometry=[1, 2])
sha = c.complete(claim["token"], "author", result)
original = dict(
c.db.execute("SELECT * FROM agent_attempts WHERE token=?", (claim["token"],)).fetchone()
)
c.close()
clock[0] = 201.0
reopened = m.Cycle(c.root, clock=c.clock)
try:
assert reopened.complete(claim["token"], "author", result) == sha
with pytest.raises(ValueError, match="ownership"):
reopened.complete(claim["token"], "other", result)
with pytest.raises(ValueError, match="Changed duplicate"):
reopened.complete(claim["token"], "author", dict(reason="changed"))
persisted = dict(
reopened.db.execute(
"SELECT * FROM agent_attempts WHERE token=?", (claim["token"],)
).fetchone()
)
assert persisted == original
assert reopened.db.execute(
"SELECT COUNT(*) FROM agent_tasks WHERE cycle=? AND stage='review'", (identity,)
).fetchone()[0] == 1
assert reopened.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
).fetchone()[0] == 1
finally:
reopened.close()
def test_executor_actor_cannot_reconcile_or_decide(setup):
c, plan, _ = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
with pytest.raises(ValueError, match="Root reconciliation"):
c.reconcile(claim["token"], "author", "Executor stopped")
assert c.status(identity)["tasks"][0]["state"] == "active"
c.reconcile(claim["token"], "root", "Executor confirmed stopped", retry=True)
done(c, identity)
with pytest.raises(ValueError, match="Root decision"):
c.decide(identity, "author", verdict())
assert c.status(identity)["root_review"] is None
c.decide(identity, "root", verdict())
def test_sqlite_failure_rolls_back_completion_and_allows_same_claim_retry(setup):
c, plan, _ = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
result = dict(reason="source inspected")
c.db.executescript("""
CREATE TEMP TRIGGER fail_review_creation BEFORE INSERT ON agent_tasks
WHEN NEW.stage = 'review'
BEGIN SELECT RAISE(ABORT, 'injected review insert failure'); END;
""")
with pytest.raises(sqlite3.IntegrityError, match="injected review insert failure"):
c.complete(claim["token"], "author", result)
attempt = c.db.execute(
"SELECT finished,result,result_sha FROM agent_attempts WHERE token=?", (claim["token"],)
).fetchone()
assert tuple(attempt) == (None, None, None)
tasks = c.status(identity)["tasks"]
assert len(tasks) == 1 and tasks[0]["state"] == "active" and tasks[0]["result"] is None
c.db.execute("DROP TRIGGER fail_review_creation")
assert c.complete(claim["token"], "author", result) == m.digest(result)
tasks = c.status(identity)["tasks"]
assert [(task["stage"], task["state"]) for task in tasks] == [
("annotate", "done"),
("review", "ready"),
]
def test_ready_cancellation_rejects_foreign_actor_without_changing_state(setup):
c, plan, _ = setup
identity = c.begin(plan)
before = c.status(identity)
with pytest.raises(ValueError, match="(?i)root"):
c.cancel_ready(identity, "author", "Stop the bounded trial")
assert c.status(identity) == before
def test_ready_cancellation_preserves_evidence_and_requires_executor_reconciliation(setup):
c, plan, clock = setup
plan["limits"]["parallel"] = 3
plan["units"].extend(
dict(plan["units"][0], id=unit) for unit in ["two", "three", "four", "five"]
)
identity = c.begin(plan)
done(c, identity)
interrupted = c.claim(identity, "three", "annotate", "stopped-author")
proposed = c.claim(identity, "four", "annotate", "finished-author")
c.complete(proposed["token"], "finished-author", dict(reason="Preserve this proposal"))
clock[0] = 105.0
active = c.claim(identity, "two", "annotate", "active-author")
clock[0] = 110.0
before = c.status(identity)
frozen = tuple(
c.db.execute(
"SELECT plan,created,deadline FROM agent_cycles WHERE id=?", (identity,)
).fetchone()
)
attempts = [
dict(row)
for row in c.db.execute(
"SELECT * FROM agent_attempts WHERE cycle=? ORDER BY token", (identity,)
)
]
untouched = {
(task["unit"], task["stage"]): task for task in before["tasks"] if task["state"] != "ready"
}
reason = "Abort this trial after the dispatched authors stopped; revise before resuming"
c.cancel_ready(identity, "root", reason)
reopened = m.Cycle(c.root, clock=c.clock)
try:
after = reopened.status(identity)
tasks = {(task["unit"], task["stage"]): task for task in after["tasks"]}
for key, task in untouched.items():
assert tasks[key] == task
for key in [("four", "review"), ("five", "annotate")]:
task = tasks[key]
assert task["state"] == "blocked" and task["token"] is None
assert task["attempt"] == 0 and task["result"]["reason"] == reason
assert task["result_sha"] == m.digest(task["result"])
assert after["root_review"] is None
assert after["dispatches"] == before["dispatches"]
assert tuple(
reopened.db.execute(
"SELECT plan,created,deadline FROM agent_cycles WHERE id=?", (identity,)
).fetchone()
) == frozen
assert [
dict(row)
for row in reopened.db.execute(
"SELECT * FROM agent_attempts WHERE cycle=? ORDER BY token", (identity,)
)
] == attempts
# A retry with nothing left to cancel must not replace the recorded reason.
reopened.cancel_ready(identity, "root", "A different later explanation")
assert reopened.status(identity) == after
rejected = dict(
verdict(),
verdict="rejected",
next="revise",
admitted_units=[],
inspected_units=[unit["id"] for unit in plan["units"]],
)
with pytest.raises(ValueError, match="(?i)root decision|executor|terminal"):
reopened.decide(identity, "root", rejected)
reopened.reconcile(active["token"], "root", "Active executor confirmed stopped")
with pytest.raises(ValueError, match="executors"):
reopened.decide(identity, "root", rejected)
reopened.reconcile(interrupted["token"], "root", "Expired executor confirmed stopped")
reopened.decide(identity, "root", rejected)
closed = reopened.status(identity)
assert closed["state"] == "closed" and closed["root_review"] == rejected
with pytest.raises(ValueError, match="(?i)root|closed"):
reopened.cancel_ready(identity, "root", reason)
assert reopened.status(identity) == closed
finally:
reopened.close()
+295
View File
@@ -0,0 +1,295 @@
"""Failure paths that must stop an autonomous annotation loop."""
import copy
import importlib.util
import sys
from pathlib import Path
import pytest
SOURCE = Path(__file__).parents[1] / "simulation/semantic-learning"
sys.path.insert(0, str(SOURCE))
checksum = __import__("dataset_store").checksum
spec = importlib.util.spec_from_file_location("tested_agent_cycle", SOURCE / "agent_cycle.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
@pytest.fixture
def setup(tmp_path, monkeypatch):
monkeypatch.setattr(m, "validate_packet", lambda *args: None)
source = tmp_path / "raw.bin"
source.write_bytes(b"bounded synthetic evidence")
clock = [100.0]
c = m.Cycle(tmp_path, clock=lambda: clock[0])
plan = dict(
schema_version=m.SCHEMA,
root_actor="root",
objective="complete ROI",
baseline_sha256="a" * 64,
recipe="v1",
acceptance="source review",
limits=dict(parallel=2, attempts=2, dispatches=8, seconds=100, lease_seconds=10),
units=[
dict(
id="one",
physical_group="area",
split="train",
sources=[
dict(path="raw.bin", sha256=checksum(source), bytes=source.stat().st_size)
],
payload={},
)
],
parent=None,
)
yield c, plan, clock
c.close()
def annotated(c, identity):
claim = c.claim(identity, "one", "annotate", "author")
result = dict(reason="source inspected", geometry=[1, 2])
sha = c.complete(claim["token"], "author", result)
return claim, result, sha
def done(c, identity):
_, _, sha = annotated(c, identity)
claim = c.claim(identity, "one", "review", "reviewer")
c.complete(
claim["token"],
"reviewer",
dict(reason="raw + proposal checked", proposal_sha256=sha, verdict="accept"),
)
def verdict():
return dict(
verdict="accepted",
next="continue",
reason="reviewed",
inspected_units=["one"],
admitted_units=["one"],
checks=dict(coverage=True),
tuning="keep limits",
)
def test_root_gate_and_restart(setup):
c, plan, _ = setup
identity = c.begin(plan)
done(c, identity)
other = m.Cycle(c.root, clock=c.clock)
try:
assert other.status(identity)["state"] == "root_pending"
next_plan = dict(plan, parent=identity, recipe="v2")
with pytest.raises(ValueError, match="close"):
other.begin(next_plan)
other.decide(identity, "root", verdict())
assert other.begin(next_plan) != identity
finally:
other.close()
def test_review_identity_and_exact_proposal(setup):
c, plan, _ = setup
identity = c.begin(plan)
_, _, sha = annotated(c, identity)
with pytest.raises(ValueError, match="own"):
c.claim(identity, "one", "review", "author")
review = c.claim(identity, "one", "review", "reviewer")
with pytest.raises(ValueError, match="exact"):
c.complete(
review["token"],
"reviewer",
dict(reason="x", verdict="accept", proposal_sha256="f" * 64),
)
assert review["proposal_sha256"] == sha
def test_expired_claim_reserves_resource_until_stopped(setup):
c, plan, clock = setup
plan["limits"]["parallel"] = 1
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
clock[0] += 11
assert c.status(identity)["state"] == "root_pending"
with pytest.raises(ValueError, match="Expired"):
c.complete(claim["token"], "author", dict(reason="late"))
with pytest.raises(ValueError, match="executors"):
c.decide(identity, "root", verdict())
c.reconcile(claim["token"], "root", "executor terminated, receipt abc", retry=True)
replacement = c.claim(identity, "one", "annotate", "author")
assert replacement["token"] != claim["token"]
with pytest.raises(ValueError, match="superseded"):
c.complete(claim["token"], "author", dict(reason="stale"))
clock[0] += 11
c.status(identity)
with pytest.raises(ValueError, match="budget"):
c.reconcile(replacement["token"], "root", "stopped", retry=True)
def test_idempotent_completion_and_source_mutation(setup):
c, plan, _ = setup
identity = c.begin(plan)
claim, result, sha = annotated(c, identity)
assert c.complete(claim["token"], "author", result) == sha
with pytest.raises(ValueError, match="Changed duplicate"):
c.complete(claim["token"], "author", dict(reason="changed"))
(c.root / "raw.bin").write_bytes(b"mutation")
with pytest.raises(ValueError, match="source changed"):
c.claim(identity, "one", "review", "reviewer")
def test_dispatch_budget_and_no_claim_twice(setup):
c, plan, _ = setup
plan["limits"]["dispatches"] = 1
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
other = m.Cycle(c.root, clock=c.clock)
try:
with pytest.raises(ValueError):
other.claim(identity, "one", "annotate", "other")
finally:
other.close()
c.complete(claim["token"], "author", dict(reason="done"))
assert c.status(identity)["state"] == "root_pending"
with pytest.raises(ValueError, match="incomplete"):
c.decide(identity, "root", verdict())
def test_rejection_cannot_be_retried_without_changed_evidence(setup):
c, plan, _ = setup
identity = c.begin(plan)
_, _, sha = annotated(c, identity)
review = c.claim(identity, "one", "review", "reviewer")
c.complete(
review["token"],
"reviewer",
dict(reason="bad boundary", verdict="reject", proposal_sha256=sha),
)
root = dict(verdict(), verdict="rejected", next="revise", admitted_units=[])
c.decide(identity, "root", root)
with pytest.raises(ValueError, match="No progress"):
c.begin(dict(plan, parent=identity))
new = dict(plan, parent=identity, recipe="review finer source crop")
c.begin(new)
def test_input_validation_and_deadline(setup):
c, plan, clock = setup
bad = copy.deepcopy(plan)
bad["units"][0]["split"] = "test"
with pytest.raises(ValueError, match="TRAIN"):
c.begin(bad)
identity = c.begin(plan)
clock[0] += 101
assert c.status(identity)["state"] == "root_pending"
with pytest.raises(ValueError):
c.claim(identity, "one", "annotate", "author")
assert c.status(identity)["dispatches"] == 0
def test_concurrency_across_connections(setup):
c, plan, _ = setup
plan["limits"]["parallel"] = 1
plan["units"].append(dict(plan["units"][0], id="two"))
identity = c.begin(plan)
c.claim(identity, "one", "annotate", "author")
other = m.Cycle(c.root, clock=c.clock)
try:
with pytest.raises(ValueError, match="concurrency"):
other.claim(identity, "two", "annotate", "other")
finally:
other.close()
def test_accepted_iteration_cannot_repeat_same_work_with_new_id(setup):
c, plan, _ = setup
identity = c.begin(plan)
done(c, identity)
c.decide(identity, "root", verdict())
new = copy.deepcopy(plan)
new["parent"] = identity
new["units"][0]["id"] = "renamed"
with pytest.raises(ValueError, match="No progress"):
c.begin(new)
def test_parallel_claims_cannot_exceed_dispatch_budget(setup):
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
c, plan, _ = setup
plan["limits"].update(parallel=2, dispatches=1)
plan["units"].append(dict(plan["units"][0], id="two"))
identity = c.begin(plan)
gate = Barrier(2)
def compete(unit):
other = m.Cycle(c.root, clock=c.clock)
try:
gate.wait(timeout=5)
try:
other.claim(identity, unit, "annotate", unit)
return True
except ValueError:
return False
finally:
other.close()
with ThreadPoolExecutor(max_workers=2) as pool:
assert sum(pool.map(compete, ["one", "two"])) == 1
assert c.status(identity)["dispatches"] == 1
def test_root_quarantines_rejected_unit_without_repeating_accepted_work(setup):
c, plan, _ = setup
plan["units"].append(dict(plan["units"][0], id="two"))
identity = c.begin(plan)
done(c, identity)
claim = c.claim(identity, "two", "annotate", "other")
sha = c.complete(claim["token"], "other", dict(reason="uncertain source"))
review = c.claim(identity, "two", "review", "reviewer")
c.complete(
review["token"],
"reviewer",
dict(reason="insufficient evidence", verdict="reject", proposal_sha256=sha),
)
root = dict(verdict(), inspected_units=["one", "two"])
with pytest.raises(ValueError, match="failed"):
c.decide(identity, "root", dict(root, admitted_units=["one", "two"]))
c.decide(identity, "root", root)
assert c.status(identity)["root_review"]["admitted_units"] == ["one"]
def test_deadline_rechecked_after_source_verification(setup, monkeypatch):
c, plan, clock = setup
identity = c.begin(plan)
monkeypatch.setattr(m, "validate_packet", lambda *args: clock.__setitem__(0, 201))
with pytest.raises(ValueError, match="deadline passed"):
c.claim(identity, "one", "annotate", "author")
assert c.status(identity)["dispatches"] == 0
def test_evidence_quota_never_silently_drops_completion(setup, monkeypatch):
c, plan, _ = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
monkeypatch.setattr(m, "MAX_LEDGER_JSON", 1)
with pytest.raises(ValueError, match="quota"):
c.complete(claim["token"], "author", dict(reason="bounded output"))
state = c.status(identity)
assert state["tasks"][0]["state"] == "active"
assert state["tasks"][0]["result"] is None
def test_large_output_is_rejected_before_it_can_bloat_root_packet(setup):
c, plan, _ = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
with pytest.raises(ValueError, match="Result byte"):
c.complete(claim["token"], "author", dict(reason="x", dump="x" * m.MAX_RESULT))
assert c.status(identity)["tasks"][0]["state"] == "active"
+292
View File
@@ -0,0 +1,292 @@
"""Regression coverage for accountable dispatch and annotation objective outcomes."""
import copy
import pytest
from test_agent_cycle import m, verdict
from test_agent_cycle import setup as legacy_setup
setup = legacy_setup
@pytest.fixture
def v2(setup):
c, plan, clock = setup
plan["schema_version"] = m.SCHEMA_V2
plan["objective_contract"] = dict(
deliverable="Approved annotation evidence for the bounded packet",
min_admitted_units=1,
required_checks=["artifact_verified", "regressions_resolved"],
)
return c, plan, clock
def add_unit(plan, name):
plan["units"].append(dict(plan["units"][0], id=name))
def sent(c, identity, unit, stage, actor):
claim = c.claim(identity, unit, stage, actor)
c.confirm_dispatch(claim["token"], "root", actor, "Actual handoff receipt")
return claim
def finish(c, identity, unit="one", accepted=True):
claim = sent(c, identity, unit, "annotate", "author")
sha = c.complete(claim["token"], "author", dict(reason="Source inspected"))
claim = sent(c, identity, unit, "review", "critic")
c.complete(
claim["token"],
"critic",
dict(
reason="Source and proposal checked",
proposal_sha256=sha,
verdict="accept" if accepted else "reject",
),
)
def outcome(**changes):
result = dict(
verdict(),
objective_outcome="achieved",
objective_checks=dict(artifact_verified=True, regressions_resolved=True),
outcome_reason="Approved proposals checked against the frozen packet target",
remaining_work=[],
)
result.update(changes)
return result
def test_unconfirmed_handoff_blocks_new_work_and_receipt_is_fenced(v2):
c, plan, _ = v2
add_unit(plan, "two")
identity = c.begin(plan)
first = c.claim(identity, "one", "annotate", "author")
state = c.status(identity)
assert state["unconfirmed_handoffs"][0]["token"] == first["token"]
assert state["progress"]["proposed"] == 0
with pytest.raises(ValueError, match="handoff"):
c.claim(identity, "two", "annotate", "second")
with pytest.raises(ValueError, match="root"):
c.confirm_dispatch(first["token"], "author", "executor/one", "sent")
receipt = c.confirm_dispatch(first["token"], "root", "executor/one", "sent")
assert c.confirm_dispatch(first["token"], "root", "executor/one", "sent") == receipt
with pytest.raises(ValueError, match="Conflicting"):
c.confirm_dispatch(first["token"], "root", "executor/other", "sent")
assert c.status(identity)["unconfirmed_handoffs"] == []
assert c.claim(identity, "two", "annotate", "second")["token"] != first["token"]
def test_fast_completion_before_root_receipt_is_not_rejected(v2):
c, plan, _ = v2
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
result = dict(reason="Executor finished before root recorded dispatch")
sha = c.complete(claim["token"], "author", result)
c.confirm_dispatch(claim["token"], "root", "executor/one", "actual message reference")
assert c.complete(claim["token"], "author", result) == sha
assert c.status(identity)["ready_tasks"] == [dict(unit="one", stage="review")]
def test_unconfirmed_expired_handoff_never_releases_capacity(v2):
c, plan, clock = v2
add_unit(plan, "two")
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
clock[0] = claim["expires"]
assert c.status(identity)["progress"]["unreconciled"] == 1
with pytest.raises(ValueError, match="handoff"):
c.claim(identity, "two", "annotate", "second")
c.reconcile(claim["token"], "root", "Verified no running executor; explicit recovery")
with pytest.raises(ValueError, match="superseded"):
c.confirm_dispatch(claim["token"], "root", "executor/one", "late")
assert c.claim(identity, "two", "annotate", "second")
def test_review_streams_while_other_author_is_running(v2):
c, plan, _ = v2
add_unit(plan, "two")
identity = c.begin(plan)
first = sent(c, identity, "one", "annotate", "author-a")
sent(c, identity, "two", "annotate", "author-b")
sha = c.complete(first["token"], "author-a", dict(reason="First packet ready"))
with pytest.raises(ValueError, match="own"):
c.claim(identity, "one", "review", "author-a")
review = sent(c, identity, "one", "review", "critic")
assert review["proposal_sha256"] == sha
tasks = c.status(identity)["tasks"]
assert any(t["unit"] == "two" and t["state"] == "active" for t in tasks)
def test_ready_review_has_priority_over_new_author(v2):
c, plan, _ = v2
add_unit(plan, "two")
identity = c.begin(plan)
first = sent(c, identity, "one", "annotate", "author")
c.complete(first["token"], "author", dict(reason="Ready"))
assert c.status(identity)["ready_tasks"][0] == dict(unit="one", stage="review")
with pytest.raises(ValueError, match="Ready reviews"):
c.claim(identity, "two", "annotate", "second")
def test_partial_admission_is_preserved_without_false_objective_completion(v2):
c, plan, _ = v2
add_unit(plan, "two")
plan["objective_contract"]["min_admitted_units"] = 2
identity = c.begin(plan)
finish(c, identity)
c.cancel_ready(identity, "root", "Second unit unavailable; preserve accepted first unit")
review = outcome(inspected_units=["one", "two"])
with pytest.raises(ValueError, match="not achieved"):
c.decide(identity, "root", review)
review.update(objective_outcome="not_achieved", remaining_work=["Review second unit"])
c.decide(identity, "root", review)
state = c.status(identity)
assert state["root_review"]["admitted_units"] == ["one"]
assert state["progress"]["admitted"] == 1
assert state["progress"]["objective_outcome"] == "not_achieved"
def test_frozen_one_of_two_target_can_be_achieved(v2):
c, plan, _ = v2
add_unit(plan, "two")
identity = c.begin(plan)
finish(c, identity)
finish(c, identity, "two", accepted=False)
c.decide(identity, "root", outcome(inspected_units=["one", "two"]))
state = c.status(identity)
assert state["progress"]["reviewed"] == 2
assert state["progress"]["review_accepted"] == 1
assert state["progress"]["objective_outcome"] == "achieved"
@pytest.mark.parametrize(
"checks",
[
{},
dict(artifact_verified=True),
dict(artifact_verified=True, regressions_resolved=True, invented=True),
dict(artifact_verified=True, regressions_resolved="true"),
dict(artifact_verified=True, regressions_resolved=False),
],
)
def test_achievement_requires_exact_frozen_boolean_checks(v2, checks):
c, plan, _ = v2
identity = c.begin(plan)
finish(c, identity)
with pytest.raises(ValueError, match="(?i)objective"):
c.decide(identity, "root", outcome(objective_checks=checks))
assert c.status(identity)["state"] == "root_pending"
def test_budget_exhaustion_is_inconclusive_not_achievement(v2):
c, plan, clock = v2
identity = c.begin(plan)
clock[0] += plan["limits"]["seconds"]
review = outcome(verdict="rejected", next="revise", admitted_units=[])
with pytest.raises(ValueError, match="not achieved"):
c.decide(identity, "root", review)
review.update(
objective_outcome="inconclusive",
remaining_work=["No units executed; repair dispatch"],
objective_checks=dict(artifact_verified=False, regressions_resolved=True),
)
c.decide(identity, "root", review)
assert c.status(identity)["progress"]["objective_outcome"] == "inconclusive"
@pytest.mark.parametrize("target", [0, 2, True])
def test_infeasible_annotation_target_is_rejected_before_claim(v2, target):
c, plan, _ = v2
plan["objective_contract"]["min_admitted_units"] = target
with pytest.raises(ValueError, match="feasible"):
c.begin(plan)
assert c.db.execute("SELECT count(*) FROM agent_attempts").fetchone()[0] == 0
def test_weaker_acceptance_alone_does_not_authorize_repeating_same_work(v2):
c, plan, _ = v2
add_unit(plan, "two")
plan["objective_contract"]["min_admitted_units"] = 2
identity = c.begin(plan)
finish(c, identity)
finish(c, identity, "two")
c.decide(
identity, "root", outcome(inspected_units=["one", "two"], admitted_units=["one", "two"])
)
successor = copy.deepcopy(plan)
successor["parent"] = identity
successor["objective_contract"]["min_admitted_units"] = 1
with pytest.raises(ValueError, match="No progress"):
c.begin(successor)
def test_v1_history_keeps_original_decision_and_does_not_require_dispatch_receipt(setup):
from test_agent_cycle import done
c, plan, _ = setup
identity = c.begin(plan)
done(c, identity)
decision = verdict()
sha = c.decide(identity, "root", decision)
reopened = m.Cycle(c.root, clock=c.clock)
try:
assert reopened.begin(plan) == identity
state = reopened.status(identity)
assert state["plan"] == plan and state["root_review"] == decision
assert m.digest(state["root_review"]) == sha
assert "progress" not in state
finally:
reopened.close()
@pytest.mark.parametrize(
("target", "dispatches", "feasible"),
[
(1, 1, False),
(1, 2, True),
(2, 3, False),
(2, 4, True),
],
)
def test_target_requires_both_author_and_review_budget(v2, target, dispatches, feasible):
c, plan, _ = v2
add_unit(plan, "two")
plan["objective_contract"]["min_admitted_units"] = target
plan["limits"]["dispatches"] = dispatches
if feasible:
assert c.begin(plan)
else:
with pytest.raises(ValueError, match="Dispatch budget"):
c.begin(plan)
assert c.db.execute("SELECT count(*) FROM agent_cycles").fetchone()[0] == 0
def test_receipt_recovery_after_close_preserves_frozen_outcome(v2):
c, plan, _ = v2
identity = c.begin(plan)
author = c.claim(identity, "one", "annotate", "author")
sha = c.complete(author["token"], "author", dict(reason="Fast completion"))
review = c.claim(identity, "one", "review", "critic")
c.complete(
review["token"], "critic", dict(reason="Checked", verdict="accept", proposal_sha256=sha)
)
c.decide(identity, "root", outcome())
before = c.status(identity)
reopened = m.Cycle(c.root, clock=c.clock)
try:
receipt = reopened.confirm_dispatch(
author["token"], "root", "executor/author", "Recovered actual message reference"
)
assert (
reopened.confirm_dispatch(
author["token"], "root", "executor/author", "Recovered actual message reference"
)
== receipt
)
with pytest.raises(ValueError, match="Conflicting"):
reopened.confirm_dispatch(author["token"], "root", "executor/wrong", "different")
assert reopened.status(identity) == before
finally:
reopened.close()
+182
View File
@@ -0,0 +1,182 @@
"""Real immutable admission/corpus binding for the agent's TRAIN boundary."""
import copy
import importlib.util
from pathlib import Path
import pytest
from test_semantic_admission import (
admission as admission_fixture,
)
from test_semantic_admission import (
corpus as corpus_fixture,
)
from test_semantic_admission import (
dataset,
decision,
release,
)
from test_semantic_corpus import group, opened, plan, refs
from test_semantic_delivery import ds
admission = admission_fixture
corpus = corpus_fixture
@pytest.fixture
def regions(admission, monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/semantic-learning"))
monkeypatch.setitem(__import__("sys").modules, "admission_store", admission)
spec = importlib.util.spec_from_file_location(
"agent_binding_regions",
Path(__file__).parents[1] / "simulation/semantic-learning/region_coverage.py",
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize("split", ["train", "regression"])
def test_pinned_physical_split_cannot_be_relabeled(regions, admission, corpus, tmp_path, split):
source = dataset(tmp_path, "source")
receipt = corpus.build(
tmp_path, plan(corpus, [source], [group("physical", split, "a" * 64)]), "corpora/v1"
)
with opened(corpus, tmp_path, receipt) as reader:
ref = refs(reader, split=split)[0]
d = decision(admission, ref)
ptr, _ = release(admission, tmp_path, receipt, [ref], [d])
with admission.Supervision(tmp_path, ptr["path"], ptr["sha256"]) as reader:
e = next(e for b in reader.batches("observed_paint", split) for e in b)
v, t = e["inputs"][0], e["targets"][0]
protected = bytearray(48)
protected[18:21] = bytes([1]) * 3
payload = dict(
supervision=ptr,
sample_id=e["sample_id"],
view="top",
size=[8, 6],
roi=[0, 0, 8, 6],
target_sha256=regions.sha(admission.pixel_target(t)),
protected_sha256=regions.sha(protected),
)
files = [
tmp_path / ref["dataset"] / v["rgb"]["name"],
tmp_path / ref["dataset"] / v["cameras_member"]["name"],
reader.root / "supervision.json",
reader.root / reader.manifest["records"][e["sample_id"]]["path"],
]
unit = dict(
id="roi",
split="train",
physical_group="physical",
payload=payload,
sources=[
dict(
path=f.relative_to(tmp_path).as_posix(),
sha256=ds.checksum(f),
bytes=f.stat().st_size,
)
for f in files
],
)
if split == "regression":
with pytest.raises(ValueError, match="physical split"):
regions.validate_packet(tmp_path, unit)
else:
regions.validate_packet(tmp_path, unit)
bad = copy.deepcopy(unit)
bad["physical_group"] = "wrong street"
with pytest.raises(ValueError, match="physical split"):
regions.validate_packet(tmp_path, bad)
bad = copy.deepcopy(unit)
bad["payload"]["protected_sha256"] = regions.sha(b"")
with pytest.raises(ValueError, match="protected unknown"):
regions.validate_packet(tmp_path, bad)
def test_root_accepted_publication_preserves_labels_and_replays(
regions, admission, corpus, tmp_path, monkeypatch
):
source = dataset(tmp_path, "source")
receipt = corpus.build(
tmp_path, plan(corpus, [source], [group("physical", "train", "a" * 64)]), "corpora/v1"
)
with opened(corpus, tmp_path, receipt) as reader:
ref = refs(reader)[0]
d = decision(admission, ref)
ptr, _ = release(admission, tmp_path, receipt, [ref], [d])
with admission.Supervision(tmp_path, ptr["path"], ptr["sha256"]) as reader:
e = next(e for b in reader.training_batches("observed_paint") for e in b)
before = admission.pixel_target(e["targets"][0])
protected = bytearray(48)
protected[18:21] = bytes([1]) * 3
payload = dict(
supervision=ptr,
sample_id=e["sample_id"],
view="top",
size=[8, 6],
roi=[0, 0, 8, 2],
target_sha256=regions.sha(before),
protected_sha256=regions.sha(protected),
)
unit = dict(id="roi", physical_group="physical", split="train", payload=payload)
proposal = dict(
reason="synthetic stripe",
background_reviewed=True,
boundary_ignore_px=1,
paint_polygons=[[[1, 0], [6, 0], [6, 2], [1, 2]]],
unknown_polygons=[],
)
state = dict(
state="root_pending",
plan=dict(root_actor="root", units=[unit, dict(unit, id="quarantined")]),
root_review=None,
tasks=[
dict(unit="roi", stage="annotate", result=proposal),
dict(unit="quarantined", stage="annotate", result=proposal),
],
)
spec = importlib.util.spec_from_file_location(
"tested_agent_admission",
Path(__file__).parents[1] / "simulation/semantic-learning/agent_admission.py",
)
pub = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pub)
class FakeCycle:
def __init__(self, *args):
pass
def status(self, identity):
return state
def close(self):
pass
monkeypatch.setattr(pub, "Cycle", FakeCycle)
with pytest.raises(ValueError, match="Root acceptance"):
pub.publish(tmp_path, "c" * 64, "supervision/agent")
state.update(
state="closed",
root_review=dict(verdict="accepted", admitted_units=["roi"], reason="synthetic test root"),
)
out = pub.publish(tmp_path, "c" * 64, "supervision/agent")
assert pub.publish(tmp_path, "c" * 64, "supervision/agent") == out
assert ds.checksum(tmp_path / ptr["path"] / "supervision.json") == ptr["sha256"]
with admission.Supervision(tmp_path, out["path"], out["sha256"]) as reader:
new = next(e for b in reader.training_batches("observed_paint") for e in b)
after = admission.pixel_target(new["targets"][0])
assert all(after[i] == value for i, value in enumerate(before) if value != 255)
assert after[2:5] == bytes([1, 1, 1])
assert after[18:21] == bytes([255, 255, 255])
assert all(y < 3 for y, _, _ in new["targets"][0]["unknown"])
assert new["physical_group"] == "physical" and new["split"] == "train"
# A later explicit source uncertainty cannot silently retain baseline paint.
proposal["unknown_polygons"] = [[[2, 1], [3, 1], [3, 2], [2, 2]]]
proposal["unknown_reason"] = "New source review finds ambiguity"
with pytest.raises(ValueError, match="Explicit source uncertainty"):
pub.publish(tmp_path, "d" * 64, "supervision/conflicting-uncertainty")
assert not (tmp_path / "supervision/conflicting-uncertainty").exists()
assert not (tmp_path / "agent-reviews" / ("d" * 64)).exists()
+92
View File
@@ -0,0 +1,92 @@
import copy
import hashlib
import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
from annotation_boundary_review import withdraw_labels
def fixture():
target = np.full((8, 9), 255, dtype="uint8")
target[1:7, 1:4] = 0
target[1:7, 5:8] = 1
h = hashlib.sha256(target.tobytes()).hexdigest()
sample = dict(
name="frame",
input=dict(rgb=dict(sha256="raw")),
size=[9, 8],
target_sha256=h,
components=[dict(id="B1", sha256="b"), dict(id="P1", sha256="p")],
)
review = dict(
name="frame",
input_sha256="raw",
target_sha256=h,
raw_first=True,
reviewed_components={"B1": "b", "P1": "p"},
reason="All regions inspected",
withdrawals=[
dict(
id="edge",
label=0,
polygon=[[0, 0], [6, 0], [6, 3], [0, 3]],
reason="Visible contradictory edge",
)
],
)
return sample, review, target
def test_only_explicit_old_class_withdrawn_without_mutating_source():
s, r, t = fixture()
before = t.copy()
got, stats = withdraw_labels(s, r, t)
assert np.array_equal(t, before)
assert np.all(got[t == 255] == 255) and np.array_equal(got[t == 1], t[t == 1])
assert stats["removed_background"] == 9 and stats["removed_paint"] == 0
assert np.array_equal(got[4:], t[4:])
def test_foreground_uncertainty_and_overlapping_zones_count_once():
s, r, t = fixture()
r["withdrawals"][0]["label"] = 1
duplicate = copy.deepcopy(r["withdrawals"][0])
duplicate["id"] = "overlap"
r["withdrawals"].append(duplicate)
got, stats = withdraw_labels(s, r, t)
assert stats["removed_paint"] == 6 and stats["removed_background"] == 0
assert stats["zones"][1]["newly_withdrawn"] == 0
assert not np.any((got != t) & (got != 255))
def test_empty_review_preserves_every_pixel():
s, r, t = fixture()
r["withdrawals"] = []
got, stats = withdraw_labels(s, r, t)
assert np.array_equal(got, t) and stats["revised_sha256"] == s["target_sha256"]
@pytest.mark.parametrize(
"change",
[
lambda s, r, t: r.update(input_sha256="other"),
lambda s, r, t: r.update(target_sha256="other"),
lambda s, r, t: s.update(target_sha256="other"),
lambda s, r, t: r.update(reviewed_components={"B1": "b"}),
lambda s, r, t: r.update(raw_first=False),
lambda s, r, t: r["withdrawals"][0].update(label=255),
lambda s, r, t: r["withdrawals"][0].update(reason=""),
lambda s, r, t: r["withdrawals"][0].update(polygon=[[0, 0], [9, 0], [0, 3]]),
lambda s, r, t: r["withdrawals"][0].update(polygon=[[0, 0], [float("nan"), 0], [0, 3]]),
lambda s, r, t: r["withdrawals"][0].update(polygon=[[0, 0], [0, 7], [0, 3]]),
],
)
def test_invalid_or_unbound_review_rejected(change):
s, r, t = fixture()
change(s, r, t)
with pytest.raises(ValueError):
withdraw_labels(s, r, t)
+278
View File
@@ -0,0 +1,278 @@
"""Provenance validates mechanics without changing labels or inventing evidence."""
import copy
import importlib.util
import json
import sys
from pathlib import Path
import pytest
from test_semantic_admission import admission as admission_fixture
from test_semantic_admission import corpus as corpus_fixture
from test_semantic_admission import dataset, decision, release
from test_semantic_corpus import group, opened, plan, refs
admission = admission_fixture
corpus = corpus_fixture
sys.path.insert(0, str(Path(__file__).parents[1] / "simulation/semantic-learning"))
import annotation_provenance as a # noqa: E402
import region_coverage as r # noqa: E402
def case():
old = bytearray([255]) * 48
old[0] = 0 # Outside ROI: earlier known background, not a new review.
old[18] = 1 # Inside automatic margin: preserve prior paint.
protected = bytearray(48)
protected[47] = 1 # Historical protected unknown, subtype unavailable.
packet = dict(
size=[8, 6],
roi=[1, 1, 7, 5],
view="top",
target_sha256=a.sha(old),
protected_sha256=a.sha(protected),
)
proposal = dict(
background_reviewed=True,
reason="synthetic complete ROI",
boundary_ignore_px=1,
paint_polygons=[[[2, 1], [6, 1], [6, 5], [2, 5]]],
unknown_polygons=[[[4, 2], [5, 2], [5, 3], [4, 3]]],
unknown_reason="synthetic source ambiguity",
)
record = r.raster_proposal(packet, proposal)
merged, stats = r.merge(packet, record, old, protected)
return packet, record, old, bytearray(merged), protected, stats
def check(values):
p, rec, old, merged, protected, stats = values
return a.audit_unit(p, rec, old, merged, protected, merged_sha256=stats["merged_sha256"])
def test_exact_partition_old_known_survives_and_outside_is_not_reviewed():
values = case()
snapshots = copy.deepcopy(values)
proof = check(values)
assert values == snapshots
assert proof["source_subtypes_known"] is True
assert proof["reviewed_pixels"] == 24
assert proof["categories"]["source_unknown"]["pixels"] == 1
assert proof["categories"]["source_unknown"]["remaining_unknown"] == 1
margin = proof["categories"]["automatic_margin"]
assert margin["retained_old_paint"] == 1
assert margin["remaining_unknown"] == margin["pixels"] - 1
assert proof["prior_protected_untyped"] == dict(
pixels=1, inside_roi=0, outside_roi=1, remaining_unknown=1
)
assert proof["outside_roi"] == dict(
pixels=24, prior_known=1, prior_protected_untyped=1, unassigned_unknown=22
)
assert proof["merged_sha256"] == a.sha(values[3])
def test_legacy_record_does_not_invent_source_or_margin_subtypes():
values = case()
del values[1]["source_unknown"]
proof = check(values)
assert proof["source_subtypes_known"] is False
assert proof["categories"]["source_unknown"]["pixels"] == 0
assert proof["categories"]["automatic_margin"]["pixels"] == 0
assert proof["categories"]["untyped_unknown"]["pixels"] > 0
@pytest.mark.parametrize("known", [0, 1])
def test_source_unknown_cannot_retain_prior_known(known):
p, rec, old, merged, protected, stats = case()
old[20] = merged[20] = known
p["target_sha256"] = a.sha(old)
stats["merged_sha256"] = a.sha(merged)
with pytest.raises(ValueError, match="Source unknown conflicts"):
check((p, rec, old, merged, protected, stats))
@pytest.mark.parametrize(
"change",
[
"target_sha",
"merged_sha",
"protected_sha",
"outside",
"old_known",
"source_known",
"missing",
"overlap",
"source_overlap",
"source_outside",
"view",
"protected_change",
],
)
def test_tamper_and_false_coverage_fail_closed(change):
p, rec, old, merged, protected, stats = case()
if change == "target_sha":
p["target_sha256"] = "0" * 64
elif change == "merged_sha":
stats["merged_sha256"] = "0" * 64
elif change == "protected_sha":
p["protected_sha256"] = "0" * 64
elif change == "outside":
merged[1] = 0
elif change == "old_known":
merged[18] = 255
elif change == "source_known":
merged[20] = 0
elif change == "missing":
rec["unknown"].pop()
elif change == "overlap":
rec["paint"] += [rec["paint"][0]]
rec["paint"].sort()
elif change == "source_overlap":
rec["source_unknown"] *= 2
elif change == "source_outside":
rec["source_unknown"] = [[0, 1, 2]]
elif change == "view":
rec["view"] = "other"
elif change == "protected_change":
merged[47] = 0
if change in {"outside", "old_known", "source_known", "protected_change"}:
stats["merged_sha256"] = a.sha(merged) # Valid checksum cannot hide invalid semantics.
with pytest.raises(ValueError):
check((p, rec, old, merged, protected, stats))
@pytest.fixture
def publication(admission, corpus, tmp_path, monkeypatch):
source = dataset(tmp_path, "source")
receipt = corpus.build(
tmp_path, plan(corpus, [source], [group("physical", "train", "a" * 64)]), "corpora/v1"
)
with opened(corpus, tmp_path, receipt) as reader:
ref = refs(reader)[0]
ptr, _ = release(admission, tmp_path, receipt, [ref], [decision(admission, ref)])
with admission.Supervision(tmp_path, ptr["path"], ptr["sha256"]) as reader:
entry = next(e for b in reader.training_batches("observed_paint") for e in b)
target = entry["targets"][0]
original = admission.pixel_target(target)
protected = bytearray(len(original))
for y, start, end in target["unknown"]:
protected[y * 8 + start : y * 8 + end] = bytes([1]) * (end - start)
payload = dict(
supervision=ptr,
sample_id=entry["sample_id"],
view="top",
size=[8, 6],
roi=[0, 0, 8, 2],
target_sha256=a.sha(original),
protected_sha256=a.sha(protected),
)
unit = dict(id="roi", physical_group="physical", split="train", payload=payload)
proposal = dict(
reason="reviewed synthetic stripe",
background_reviewed=True,
boundary_ignore_px=1,
paint_polygons=[[[1, 0], [6, 0], [6, 2], [1, 2]]],
unknown_polygons=[],
)
state = dict(
state="closed",
plan=dict(root_actor="root", units=[unit]),
root_review=dict(verdict="accepted", admitted_units=["roi"]),
tasks=[dict(unit="roi", stage="annotate", result=proposal)],
)
monkeypatch.setitem(sys.modules, "admission_store", admission)
spec = importlib.util.spec_from_file_location(
"provenance_publish_test",
Path(__file__).parents[1] / "simulation/semantic-learning/agent_admission.py",
)
pub = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pub)
class FakeCycle:
def __init__(self, *args):
pass
def status(self, identity):
return state
def close(self):
pass
monkeypatch.setattr(pub, "Cycle", FakeCycle)
identity = "c" * 64
result = pub.publish(tmp_path, identity, "supervision/published")
return pub, result, tmp_path / "agent-reviews" / identity, identity
@pytest.mark.parametrize("corrupt_legacy", [False, True])
def test_real_publication_legacy_retry_preserves_every_existing_byte(
publication, tmp_path, corrupt_legacy
):
pub, expected, journal, identity = publication
path = journal / "audit.json"
current = json.loads(path.read_bytes())
assert "provenance" in current["units"][0] # New publication includes proof.
legacy = copy.deepcopy(current)
for unit in legacy["units"]:
del unit["provenance"]
if corrupt_legacy:
legacy["units"][0]["coverage"]["paint"] += 1
# Model an actual historical audit, including different insignificant whitespace.
path.write_text(json.dumps(legacy, indent=4) + "\n")
saved = {
p: p.read_bytes()
for directory in (journal, tmp_path / "supervision/published")
for p in directory.rglob("*")
if p.is_file()
}
sidecar = journal / "audit-provenance-v1.json"
if corrupt_legacy:
with pytest.raises(ValueError, match="legacy audit differs"):
pub.publish(tmp_path, identity, "supervision/published")
assert not sidecar.exists()
else:
assert pub.publish(tmp_path, identity, "supervision/published") == expected
proof = json.loads(sidecar.read_bytes())
assert proof["legacy_audit_sha256"] == a.sha(saved[path])
assert proof["audit"] == current
exact_sidecar = sidecar.read_bytes()
assert pub.publish(tmp_path, identity, "supervision/published") == expected
assert sidecar.read_bytes() == exact_sidecar
# Existing sidecar is immutable too; even an otherwise valid legacy retry fails.
sidecar.write_text("{}\n")
with pytest.raises(ValueError, match="Published evidence changed"):
pub.publish(tmp_path, identity, "supervision/published")
assert sidecar.read_text() == "{}\n"
assert all(p.read_bytes() == before for p, before in saved.items())
@pytest.mark.parametrize("change", ["changed_to_current", "missing_audit"])
def test_existing_sidecar_blocks_audit_replacement_or_removal(publication, tmp_path, change):
pub, expected, journal, identity = publication
path = journal / "audit.json"
current_bytes = path.read_bytes()
legacy = json.loads(current_bytes)
for unit in legacy["units"]:
del unit["provenance"]
path.write_text(json.dumps(legacy, indent=4) + "\n")
assert pub.publish(tmp_path, identity, "supervision/published") == expected
sidecar = journal / "audit-provenance-v1.json"
sidecar_bytes = sidecar.read_bytes()
release_bytes = {
p: p.read_bytes() for p in (tmp_path / "supervision/published").rglob("*") if p.is_file()
}
if change == "changed_to_current":
path.write_bytes(current_bytes)
else:
path.unlink()
with pytest.raises(
ValueError, match="Published evidence changed|requires its original legacy audit"
):
pub.publish(tmp_path, identity, "supervision/published")
assert sidecar.read_bytes() == sidecar_bytes
assert all(p.read_bytes() == value for p, value in release_bytes.items())
if change == "changed_to_current":
assert path.read_bytes() == current_bytes
else:
assert not path.exists() # A rejected retry must not recreate audit.json.
+79
View File
@@ -0,0 +1,79 @@
import importlib.util
from pathlib import Path
import numpy as np
import pytest
spec = importlib.util.spec_from_file_location(
"annotation_training_view",
Path(__file__).parents[1] / "simulation/semantic-learning/annotation_training_view.py",
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
training_view = module.training_view
def example():
t = np.array([[1, 1, 0, 255], [1, 0, 1, 255]], dtype="uint8")
b = t.copy()
b[1, 2] = 255
added = (b == 255) & (t == 1)
weak = added.copy()
weak[0, 1] = True
return dict(
split="train", target=t, base_target=b, added=added, weak=weak, clear=(t == 1) & ~weak
)
def test_withdrawal_updates_both_targets_and_conditions_without_mutation():
r = example()
t = r["target"].copy()
t[0, 0] = t[0, 2] = 255
n = training_view(r, t)
assert n["target"][0, 0] == n["base_target"][0, 0] == 255
assert n["target"][0, 2] == n["base_target"][0, 2] == 255
assert not n["clear"][0, 0]
assert r["clear"][0, 0] and r["target"][0, 0] == 1
assert np.array_equal(n["weak"], r["weak"])
n["target"][1, 0] = 255
assert t[1, 0] == r["target"][1, 0] == 1
@pytest.mark.parametrize("split", ["regression", "test", "validation"])
def test_forbid_nontraining(split):
r = example()
r["split"] = split
with pytest.raises(ValueError):
training_view(r, r["target"])
@pytest.mark.parametrize(
"where,value",
[((0, 0), 0), ((0, 2), 1), ((0, 3), 0), ((0, 3), 1), ((0, 1), 255), ((1, 2), 255)],
)
def test_forbid_class_flips_new_labels_or_loss_of_weak_support(where, value):
r = example()
t = r["target"].copy()
t[where] = value
with pytest.raises(ValueError):
training_view(r, t)
def test_invalid_parent_and_condition():
r = example()
r["base_target"][0, 0] = 0
with pytest.raises(ValueError):
training_view(r, r["target"])
r = example()
r["clear"][0, 2] = True
with pytest.raises(ValueError):
training_view(r, r["target"])
def test_identity_and_wrong_shape():
r = example()
n = training_view(r, r["target"])
for key in ["target", "base_target", "weak", "clear", "added"]:
assert np.array_equal(n[key], r[key])
with pytest.raises(ValueError):
training_view(r, r["target"][:, :2])
+156
View File
@@ -0,0 +1,156 @@
import copy
import hashlib
import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
from background_admission import add_background, prepare_background
from coverage_mass_control import prepare, schedule_digest
def review_case():
t = np.full((64, 64), 255, dtype="uint8")
t[:5] = 1
t[55:] = 0
protected = np.zeros(t.shape, dtype=bool)
protected[25:28, 25:28] = True
s = dict(
name="sample",
split="train",
size=[64, 64],
rgb_sha256="a" * 64,
target_sha256=hashlib.sha256(t.tobytes()).hexdigest(),
protected_sha256=hashlib.sha256(protected.tobytes()).hexdigest(),
)
review = dict(
s,
boundary_ignore_px=2,
regions=[
dict(
id="inside",
reason="Visible non-paint interior",
polygon=[[128, 128], [384, 128], [384, 384], [128, 384]],
)
],
)
return s, review, t, protected
def test_background_admission_preserves_known_and_protected_pixels():
s, r, t, p = review_case()
before = t.copy()
out, added, audit = add_background(s, r, t, p)
assert added.any() and not added[p].any()
assert np.all(out[p] == 255)
assert np.array_equal(out[t != 255], t[t != 255])
assert np.array_equal(out == 1, t == 1)
assert not added[16, 16] and added[20, 20]
assert audit[0]["protected_excluded"] == 9
assert np.array_equal(t, before)
@pytest.mark.parametrize(
"bad", ["split", "image", "target", "protected", "margin", "paint", "overlap", "polygon"]
)
def test_invalid_or_conflicting_admission_is_rejected(bad):
s, r, t, p = review_case()
if bad == "split":
s["split"] = "regression"
if bad == "image":
r["rgb_sha256"] = "b" * 64
if bad == "target":
t[10, 10] = 0
if bad == "protected":
p[30, 30] = True
if bad == "margin":
r["boundary_ignore_px"] = 0
if bad == "paint":
r["regions"][0]["polygon"] = [[0, 0], [512, 0], [512, 512], [0, 512]]
if bad == "overlap":
r["regions"].append(dict(r["regions"][0], id="second"))
if bad == "polygon":
r["regions"][0]["polygon"][0] = [-1, 0]
with pytest.raises(ValueError):
add_background(s, r, t, p)
def records():
out = []
for j in range(2):
t = np.array([[1, 1, 0, 255], [1, 0, 255, 255]], dtype="uint8")
b = t.copy()
b[0, 1] = 255
added = np.zeros(t.shape, dtype=bool)
added[1, 2:] = True
out.append(
dict(
name=str(j),
sample_id=str(j),
group=str(j),
split="train",
target=t,
base_target=b,
added_background=added,
)
)
return out
@pytest.mark.parametrize("policy", ["base", "mass", "equal_window"])
def test_negative_mass_conserved_positive_weights_exact_and_order_unchanged(policy):
original = records()
before = copy.deepcopy(original)
rr, weights = prepare(original, policy)
out, ww = prepare_background(rr, weights)
assert schedule_digest(rr, 7, 120) == schedule_digest(out, 7, 120)
for old, new in zip(rr, out, strict=True):
n = old["name"]
paint = old["target"] == 1
bg = old["target"] == 0
added = old["added_background"]
assert np.array_equal(ww[n][paint], weights[n][paint])
assert float(ww[n][new["target"] == 0].sum()) == pytest.approx(float(weights[n][bg].sum()))
np.testing.assert_allclose(ww[n][bg], weights[n][bg] * 0.5)
assert np.all(new["target"][added] == 0) and not ww[n][new["target"] == 255].any()
assert all(
np.array_equal(x["target"], y["target"]) for x, y in zip(original, before, strict=True)
)
def test_zero_add_is_exact_identity_including_empty_window():
rr = records()
for r in rr:
r["added_background"][:] = False
rr[1]["target"][:] = 255
rr[1]["base_target"][:] = 255
prepared, w = prepare(rr, "base")
out, ww = prepare_background(prepared, w)
for a, b in zip(prepared, out, strict=True):
assert np.array_equal(a["target"], b["target"])
assert np.array_equal(w[a["name"]], ww[a["name"]])
@pytest.mark.parametrize(
"bad", ["split", "known", "negative", "nan", "unknown_weight", "empty_bg", "duplicate"]
)
def test_invalid_background_weight_inputs_rejected(bad):
rr, w = prepare(records(), "mass")
if bad == "split":
rr[0]["split"] = "test"
if bad == "known":
rr[0]["added_background"][0, 0] = True
if bad == "negative":
w["0"][0, 0] = -1
if bad == "nan":
w["0"][0, 0] = np.nan
if bad == "unknown_weight":
w["0"][1, 2] = 1
if bad == "empty_bg":
w["0"][rr[0]["target"] == 0] = 0
if bad == "duplicate":
rr.append(rr[0])
with pytest.raises(ValueError):
prepare_background(rr, w)
+83
View File
@@ -0,0 +1,83 @@
"""Numerical and fitting safeguards for the Worker-only ranking probe."""
import importlib
import importlib.util
import sys
import unittest
from pathlib import Path
import numpy as np
if importlib.util.find_spec("cv2") is None:
raise unittest.SkipTest("Scientific probe checks run in the pinned Worker renderer image")
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "simulation/semantic-learning"))
sys.path.insert(0, str(ROOT / "simulation/urban-plan-research/pipeline/base"))
PhysicalFields = importlib.import_module("boundary_anchors").PhysicalFields
probe = importlib.import_module("boundary_rank_probe")
components, describe, fit, PRIOR = probe.components, probe.describe, probe.fit, probe.PRIOR
class ProbeTests(unittest.TestCase):
def fields(self):
rgb = np.zeros((128, 128, 3), np.uint8)
rgb[:, 64:] = 160
z = np.zeros((128, 128), np.float32)
z[:, 64:] = 0.12
one = np.ones(z.shape, np.float32)
zero = np.zeros_like(one)
return PhysicalFields(rgb, z, one, zero, zero, zero, 0.05)
def test_reference_score_preserved_exactly(self):
f = self.fields()
uv = np.array([[63.0, 40.0], [64.0, 60.0], [67.0, 90.0]])
before = [a.copy() for a in (f.gray, f.z, f.alpha)]
expected, mask = f.measure(uv, [1, 0])
terms, got = components(f, uv, [1, 0])
np.testing.assert_array_equal(got, expected * mask)
np.testing.assert_allclose(terms @ PRIOR, got, atol=1e-7, rtol=1e-6)
for a, b in zip(before, (f.gray, f.z, f.alpha), strict=True):
np.testing.assert_array_equal(a, b)
def test_missing_evidence_cannot_gain_score(self):
f = self.fields()
f.alpha[:] = 0
terms, score = components(f, np.array([[64.0, 64.0]]), [1, 0])
self.assertFalse(terms.any())
self.assertFalse(score.any())
def test_reverse_geometry_same_measurement(self):
f = self.fields()
path = np.array([[64.0, 25.0], [64.0, 95.0]])
a, sa = describe(f, path, [10, 10, 110, 110], [1, 0])
b, sb = describe(f, path[::-1], [10, 10, 110, 110], [1, 0])
np.testing.assert_allclose(a, b, atol=1e-7)
self.assertAlmostEqual(sa, sb, places=7)
def test_pair_fit_is_bounded_and_deterministic(self):
d = np.array([[0.3, 0, -0.1, 0], [0.2, 0.1, 0, 0], [0.1, 0, 0, 0.1]])
a = fit(d)
b = fit(d)
np.testing.assert_array_equal(a, b)
self.assertTrue(((a >= 0) & (a <= 2)).all())
self.assertGreater(a[0], PRIOR[0])
def test_invalid_pairs_fail_closed(self):
for d in [[], [[1, 2, 3, 4]], [[float("nan")] * 4] * 2]:
with self.assertRaises(ValueError):
fit(d)
def test_outside_review_has_no_target(self):
with self.assertRaises(ValueError):
describe(
self.fields(),
np.array([[1.0, 1.0], [5.0, 5.0]]),
[30, 30, 90, 90],
[1, 0],
)
if __name__ == "__main__":
unittest.main()
+174
View File
@@ -0,0 +1,174 @@
import copy
import importlib.util
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1] / "simulation" / "semantic-learning"
sys.path.insert(0, str(ROOT))
spec = importlib.util.spec_from_file_location("boundary_review", ROOT / "boundary_review.py")
review = importlib.util.module_from_spec(spec)
spec.loader.exec_module(review)
def fixture():
feature = dict(
id="curb",
properties={"class": "road_boundary"},
geometry=dict(type="LineString", coordinates=[[0.0, 0.0, 1.0], [10.0, 0.0, 1.0]]),
)
old = copy.deepcopy(feature)
old["geometry"]["coordinates"][0][1] = 2.0
labels = dict(
proposed_element=[feature],
original_element=[old],
projections=dict(
top=[dict(feature_id="curb", uv=[[-10.0, 40.0], [110.0, 40.0]], in_front=[True, True])]
),
)
cameras = dict(views=[dict(id="top", projection="ortho", size=[100, 100])])
decision = dict(
id="one",
sample="part-000/tile-0/sample.json",
feature_id="curb",
view="top",
rect_px=[20, 30, 80, 50],
evidence="visible",
reviewer="assistant-visual-review",
reason="Edited contour follows visible curb; original cuts pavement.",
preference="edited-better-than-original",
)
return labels, cameras, decision
def test_exact_ranges_and_no_implicit_background():
labels, cameras, decision = fixture()
before = copy.deepcopy(labels)
result = review.compile_record(labels, cameras, decision)
assert result["segment_ranges"] == [dict(segment=0, t=[0.25, 0.75])]
assert labels == before
assert result["ranking_trial_eligible"]
assert not result["dense_segmentation_eligible"]
assert not result["metric_ground_truth"]
assert result["background_targets"] == result["complete_regions"] == []
@pytest.mark.parametrize("evidence", ["context", "uncertain"])
def test_inferred_or_uncertain_cannot_enter_ranking(evidence):
labels, cameras, decision = fixture()
decision["evidence"] = evidence
with pytest.raises(ValueError, match="visible evidence"):
review.compile_record(labels, cameras, decision)
decision.pop("preference")
assert not review.compile_record(labels, cameras, decision)["ranking_trial_eligible"]
def test_editor_accepted_does_not_admit_training():
labels, cameras, decision = fixture()
labels["proposed_element"][0]["properties"]["review_status"] = "accepted"
decision.pop("preference")
assert not review.compile_record(labels, cameras, decision)["ranking_trial_eligible"]
@pytest.mark.parametrize("change", ["rejected", "marking", "nan", "empty", "perspective", "same"])
def test_invalid_target_fails_closed(change):
labels, cameras, decision = fixture()
if change == "rejected":
labels["proposed_element"][0]["properties"]["review_status"] = "rejected"
elif change == "marking":
labels["proposed_element"][0]["properties"]["class"] = "road_marking"
elif change == "nan":
labels["projections"]["top"][0]["uv"][0][0] = float("nan")
elif change == "empty":
decision["rect_px"] = [20, 60, 80, 90]
elif change == "perspective":
cameras["views"][0]["projection"] = "pinhole"
else:
labels["original_element"] = copy.deepcopy(labels["proposed_element"])
with pytest.raises(ValueError):
review.compile_record(labels, cameras, decision)
def test_control_scene_cannot_leak_into_training():
control = dict(
schema_version="missioncore.boundary-control/v1",
role="held-out-scene",
world_sha256="a" * 64,
model_sha256="b" * 64,
training_eligible=False,
windows=[dict(center=[0, 0, 0])],
frozen_utc="2026-10-21T00:00:00Z",
)
review.check_control(control, "c" * 64)
with pytest.raises(ValueError, match="distinct frozen"):
review.check_control(control, "a" * 64)
def test_clipping_is_direction_invariant():
assert review.clipped_range([-10, 40], [110, 40], [20, 30, 80, 50]) == [0.25, 0.75]
assert review.clipped_range([110, 40], [-10, 40], [20, 30, 80, 50]) == [0.25, 0.75]
assert review.clipped_range([40, -10], [40, 110], [30, 20, 50, 80]) == [0.25, 0.75]
def make_pack(root):
labels, cameras, decision = fixture()
folder = root / "observations/part-000/tile-0"
folder.mkdir(parents=True)
review.write(folder / "labels.json", labels)
review.write(folder / "cameras.json", cameras)
review.write(root / "decisions.json", {"records": [decision]})
review.write(root / "records.json", [review.compile_record(labels, cameras, decision)])
review.write(
root / "control.json",
dict(
schema_version="missioncore.boundary-control/v1",
role="held-out-scene",
world_sha256="a" * 64,
model_sha256="b" * 64,
training_eligible=False,
windows=[{"center": [0, 0, 0]}],
frozen_utc="2026-10-21T00:00:00Z",
),
)
review.write(
root / "pack.json",
dict(
schema_version=review.SCHEMA,
source={"world_sha256": "c" * 64},
files={
p.relative_to(root).as_posix(): dict(
sha256=review.checksum(p), bytes=p.stat().st_size
)
for p in root.rglob("*")
if p.is_file()
},
),
)
def test_pack_is_portable_and_detects_changed_observation(tmp_path):
root = tmp_path / "source"
make_pack(root)
before = review.verify_pack(root)
moved = tmp_path / "elsewhere"
root.rename(moved)
assert review.verify_pack(moved) == before
(moved / "observations/part-000/tile-0/cameras.json").write_text("{}")
with pytest.raises(ValueError, match="Pack member changed"):
review.verify_pack(moved)
def test_pack_recomputes_admission_instead_of_trusting_exported_flags(tmp_path):
make_pack(tmp_path)
records = review.read(tmp_path / "records.json")
records[0]["dense_segmentation_eligible"] = True
review.write(tmp_path / "records.json", records)
manifest = review.read(tmp_path / "pack.json")
manifest["files"]["records.json"] = dict(
sha256=review.checksum(tmp_path / "records.json"),
bytes=(tmp_path / "records.json").stat().st_size,
)
review.write(tmp_path / "pack.json", manifest)
with pytest.raises(ValueError, match="Admission differs"):
review.verify_pack(tmp_path)
+45
View File
@@ -0,0 +1,45 @@
"""Finite-group pooling, coordinate alignment and invalid input checks."""
import importlib
import sys
from pathlib import Path
import pytest
np = pytest.importorskip("numpy")
for dependency in ["cv2", "scipy", "shapely"]:
pytest.importorskip(dependency)
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
study = importlib.import_module("c4_admission_study")
def test_uniform_pool_is_cyclically_invariant_without_best_angle():
orbit = np.random.default_rng(61).normal(size=(4, 8, 512)).astype(np.float32)
mean = study.c4_mean(orbit)
for k in range(4):
assert np.array_equal(mean, study.c4_mean(np.roll(orbit, k, axis=0)))
assert np.allclose(mean, orbit.astype(np.float64).sum(0) / 4)
assert not np.array_equal(mean, orbit.max(0))
def test_mask_field_alignment_commutes_with_quarter_turns():
mask = np.zeros((512, 512), bool)
mask[51:211, 91:93] = True
mask[101:122, 50:211] = True
field = np.random.default_rng(19).normal(size=(128, 128)).astype(np.float32)
original = np.sum(study.fractional_weights(mask, (128, 128)) * field)
for k in range(4):
rotated = np.sum(
study.fractional_weights(np.rot90(mask, k), (128, 128)) * np.rot90(field, k)
)
assert rotated == pytest.approx(original, abs=1e-7)
restored = np.rot90(np.rot90(field, k), -k)
assert np.array_equal(restored, field)
def test_partial_or_nonfinite_orbit_refused():
with pytest.raises(ValueError):
study.c4_mean(np.zeros((3, 1, 512)))
with pytest.raises(ValueError):
study.c4_mean(np.full((4, 1, 512), np.nan))
assert study.c4_mean(np.empty((4, 0, 512))).shape == (0, 512)
+111
View File
@@ -0,0 +1,111 @@
import importlib.util
from pathlib import Path
import numpy as np
import pytest
spec = importlib.util.spec_from_file_location(
"context_background",
Path(__file__).parents[1] / "simulation/semantic-learning/context_background.py",
)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
def fixtures():
rr = [
dict(name="a", split="train", group="g", target=np.array([[1, 255]], np.uint8)),
dict(name="b", split="train", group="g", target=np.array([[0, 255]], np.uint8)),
dict(name="c", split="train", group="h", target=np.array([[0, 1]], np.uint8)),
]
w = {
"a": np.array([[0.25, 0]], np.float32),
"b": np.array([[0.3, 0]], np.float32),
"c": np.array([[0.2, 0.25]], np.float32),
}
a = {r["name"]: np.zeros((1, 2), bool) for r in rr}
return rr, w, a
def test_positive_only_window_receives_shared_negative_mass():
rr, w, a = fixtures()
a["a"][0, 1] = True
out, ww = m.prepare_context(rr, w, a)
assert out[0]["target"].tolist() == [[1, 0]]
np.testing.assert_array_equal(ww["a"], np.array([[0.25, 0.15]], np.float32))
np.testing.assert_array_equal(ww["b"], np.array([[0.15, 0]], np.float32))
np.testing.assert_array_equal(ww["c"], w["c"])
assert rr[0]["target"][0, 1] == 255 and w["a"][0, 1] == 0
def test_empty_additions_are_bit_exact():
rr, w, a = fixtures()
out, ww = m.prepare_context(rr, w, a)
for b, n in zip(rr, out, strict=True):
np.testing.assert_array_equal(n["target"], b["target"])
np.testing.assert_array_equal(ww[b["name"]], w[b["name"]])
def test_redistribute_known_background_without_new_window():
rr, w, a = fixtures()
a["b"][0, 1] = True
out, ww = m.prepare_context(rr, w, a)
np.testing.assert_array_equal(ww["b"], np.array([[0.15, 0.15]], np.float32))
np.testing.assert_array_equal(ww["a"], w["a"])
assert out[0]["target"][0, 1] == 255
@pytest.mark.parametrize(
"failure",
[
"paint",
"existing_bg",
"test",
"negative",
"unknown_weight",
"nan",
"missing",
"zero_street_mass",
],
)
def test_reject_invalid_admission(failure):
rr, w, a = fixtures()
if failure == "paint":
a["a"][0, 0] = True
if failure == "existing_bg":
a["b"][0, 0] = True
if failure == "test":
rr[0]["split"] = "test"
if failure == "negative":
w["b"][0, 0] = -1
if failure == "unknown_weight":
w["a"][0, 1] = 0.1
if failure == "nan":
w["a"][0, 0] = np.nan
if failure == "missing":
a.pop("b")
if failure == "zero_street_mass":
w["b"][0, 0] = 0
a["a"][0, 1] = True
with pytest.raises(ValueError):
m.prepare_context(rr, w, a)
def test_gate_rejects_paint_regression_despite_better_background():
context_gate = m.context_gate
old = dict(
context_fp=100,
bce=1.0,
original_fp=3,
prior_added_fp=2,
weak_fn=0,
clear_fn=0,
background_fp=105,
)
new = dict(old, context_fp=20, bce=0.2, background_fp=25)
assert context_gate(old, new, old)["passed"]
assert not context_gate(old, dict(new, weak_fn=1), old)["passed"]
assert not context_gate(old, dict(new, original_fp=4), old)["passed"]
assert not context_gate(old, dict(new, context_fp=51), old)["passed"]
assert not context_gate(old, dict(new, bce=1.0), old)["passed"]
+91
View File
@@ -0,0 +1,91 @@
"""Coverage experiments must not turn unknown into background or fit controls."""
import importlib
import sys
from pathlib import Path
import pytest
np = pytest.importorskip("numpy")
for dependency in ["cv2", "scipy", "shapely"]:
pytest.importorskip(dependency)
from shapely.geometry import box, mapping # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
study = importlib.import_module("coverage_admission_study")
def test_background_is_explicit_unknown_stays_unknown_and_paint_wins():
review = dict(
objects=[dict(geometry=mapping(box(10, 10, 20, 20)))],
negative=[],
complete_background=[mapping(box(0, 0, 100, 100))],
)
candidates = [
dict(geometry=mapping(g))
for g in [
box(10, 10, 20, 20),
box(40, 40, 60, 60),
box(110, 110, 130, 130),
box(90, 90, 110, 110),
]
]
assert study.labels(candidates, review).tolist() == [1, -1, -1, -1]
assert study.expanded_labels(candidates, review).tolist() == [1, 0, -1, -1]
def test_both_arms_exclude_control_and_regression_records():
records = [
dict(id=rid, split=split)
for rid, split in [
("old", "development"),
("new-coverage-1", "development"),
("control-coverage-1", "heldout"),
("old-control", "regression"),
]
]
assert [r["id"] for r in study.training_records(records, "old104")] == ["old"]
assert [r["id"] for r in study.training_records(records, "expanded")] == [
"old",
"new-coverage-1",
]
def test_expanded_fit_only_passed_records_and_unknown_excluded(monkeypatch):
geoms = [box(i * 20, 0, i * 20 + 10, 10) for i in range(5)]
record = dict(id="dev", variants={"retained": [dict(geometry=mapping(g)) for g in geoms]})
review = {
"dev": dict(
objects=[dict(geometry=mapping(g)) for g in geoms[:2]],
negative=[],
complete_background=[mapping(box(40, 0, 70, 10))],
)
}
data = {
"dev": {"c4_512": np.arange(15).reshape(5, 3)},
"control": {"c4_512": np.full((5, 3), 999)},
}
captured = []
def fitted(x, y, l2, maxiter):
captured.append((x.copy(), y.copy()))
return {}
monkeypatch.setattr(study, "fit_classifier", fitted)
model = study.fit([record], review, data, 0.1, True)
assert model == dict(positive=2, negative=2)
assert captured[0][1].tolist() == [1, 1, 0, 0]
assert np.array_equal(captured[0][0], data["dev"]["c4_512"][:4])
data["control"]["c4_512"] *= 2
study.fit([record], review, data, 0.1, True)
assert np.array_equal(captured[0][0], captured[1][0])
def test_clipped_identity_loss_cannot_be_hidden_by_another_gain():
def result(ids):
return {
"rows": [{"clipped_components": {"objects": [{"id": i, "matched": True} for i in ids]}}]
}
assert study.partial_gate(result(["a", "b"]), result(["a", "c"])) == ["b"]
assert study.partial_gate(result(["a"]), result(["a", "b"])) == []
+135
View File
@@ -0,0 +1,135 @@
import copy
import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
import coverage_mass_control as m
def records():
out = []
for group in ["a", "b"]:
for j in range(2):
old = np.array([[1, 1, 0, 255], [1, 0, 255, 255]], dtype="uint8")
out.append(
dict(
name=f"{group}{j}",
sample_id=f"id-{group}{j}",
group=group,
split="train",
target=old.copy(),
base_target=old,
)
)
new = np.full((2, 4), 255, dtype="uint8")
out.append(
dict(
name="new",
sample_id="id-new",
group="a",
split="train",
target=new.copy(),
base_target=new,
)
)
return out
def test_zero_add_preserves_exact_weights_including_zero_window():
rr = records()
_, base = m.prepare(rr, "base")
for policy in ["mass", "equal_window"]:
_, ww = m.prepare(rr, policy)
for name in base:
assert np.array_equal(ww[name], base[name])
_, small = m.prepare(rr[:-1], "base")
assert all(np.array_equal(v, base[n]) for n, v in small.items())
def test_positive_mass_and_background_are_preserved_without_small_window_bonus():
rr = records()
rr[-1]["target"][0, 0] = 1
_, old = m.prepare(rr, "base")
_, ww = m.prepare(rr, "mass")
_, equal = m.prepare(rr, "equal_window")
assert ww["new"].sum() == pytest.approx(0.25 / 7)
assert equal["new"].sum() == pytest.approx(0.25 / 3)
for group in ["a", "b"]:
g = [r for r in rr if r["group"] == group]
assert sum(float(ww[r["name"]][r["target"] == 1].sum()) for r in g) == pytest.approx(0.25)
for r in g:
bg = r["base_target"] == 0
assert np.array_equal(ww[r["name"]][bg], old[r["name"]][bg])
assert not ww[r["name"]][r["target"] == 255].any()
for r in rr[:2]:
known = r["base_target"] == 1
np.testing.assert_allclose(ww[r["name"]][known], old[r["name"]][known] * 6 / 7)
def test_controls_do_not_mutate_targets_or_depend_on_window_order():
rr = records()
rr[0]["target"][1, 2] = 1
before = copy.deepcopy(rr)
for policy in m.POLICIES:
a, wa = m.prepare(rr, policy)
b, wb = m.prepare(list(reversed(rr)), policy)
assert [r["sample_id"] for r in a] == [r["sample_id"] for r in b]
for n in wa:
assert np.array_equal(wa[n], wb[n])
for a, b in zip(rr, before, strict=True):
assert np.array_equal(a["target"], b["target"])
assert np.array_equal(a["base_target"], b["base_target"])
def test_augmentation_does_not_shift_when_a_window_is_added():
rr = records()
assert m.schedule_digest(rr, 7, 120) == m.schedule_digest(rr[::-1], 7, 120)
for step in range(120):
small = {r["sample_id"]: m.rotation(7, step, r["sample_id"]) for r in rr[:-1]}
full = {r["sample_id"]: m.rotation(7, step, r["sample_id"]) for r in rr}
assert all(full[k] == v for k, v in small.items())
assert len({m.rotation(7, step, rr[0]["sample_id"]) for step in range(120)}) == 4
@pytest.mark.parametrize(
"bad",
[
"split",
"duplicate",
"old_changed",
"background_added",
"shape",
"class",
"dtype",
"unsupported",
"no_old_paint",
],
)
def test_invalid_or_leaking_inputs_are_rejected(bad):
rr = records()
policy = "mass"
if bad == "split":
rr[0]["split"] = "regression"
if bad == "duplicate":
rr.append(copy.deepcopy(rr[0]))
if bad == "old_changed":
rr[0]["target"][0, 0] = 0
if bad == "background_added":
rr[-1]["target"][0, 0] = 0
if bad == "shape":
rr[0]["target"] = rr[0]["target"][:1]
if bad == "class":
rr[0]["target"][0, 3] = 2
if bad == "dtype":
rr[0]["target"] = rr[0]["target"].astype("int16")
if bad == "unsupported":
policy = "other"
if bad == "no_old_paint":
for r in rr[:2]:
r["base_target"][r["base_target"] == 1] = 255
r["target"][:] = r["base_target"]
with pytest.raises(ValueError):
m.prepare(rr, policy)
+106
View File
@@ -0,0 +1,106 @@
import importlib.util
from pathlib import Path
import pytest
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning/detail_refinement.py"
if not SRC.exists():
SRC = Path(__file__).with_name("detail_refinement.py")
spec = importlib.util.spec_from_file_location("detail_refinement", SRC)
probe = importlib.util.module_from_spec(spec)
spec.loader.exec_module(probe)
def test_group_exclusion_rejects_parent_and_record_leakage():
groups = ["a", "b", "c", "d"]
rr = [dict(sample_id=g, split="train", group=g) for g in groups[1:]]
probe.validate_groups(rr, "a", groups, groups[1:])
for parent, rows in [
(groups, rr),
(groups[1:], rr + [rr[0]]),
(groups[1:], rr[:-1]),
(groups[1:], [dict(rr[0], split="regression"), *rr[1:]]),
(groups[1:], [dict(rr[0], group="a"), *rr[1:]]),
]:
with pytest.raises(ValueError):
probe.validate_groups(rows, "a", groups, parent)
def torch_fixture():
torch = pytest.importorskip("torch")
torch.set_num_threads(2)
torch.manual_seed(19)
return (
torch,
torch.randn(1, 1, 17, 23),
torch.randint(0, 256, (1, 3, 17, 23), dtype=torch.uint8),
)
@pytest.mark.parametrize("arm", ["coarse_only", "native_rgb"])
def test_zero_initialization_is_exact_parent_under_c4_and_tiles(arm):
t, coarse, rgb = torch_fixture()
net = probe.network(12)
x = probe.inputs(coarse, rgb, arm)
for tile in [None, 1, 7, 32]:
with t.no_grad():
got = probe.prediction(net, coarse, x, tile)
assert t.equal(got, coarse)
assert t.equal(got >= 0, coarse >= 0)
def test_shared_initialization_and_rgb_ablation():
t, coarse, rgb = torch_fixture()
a, b = probe.network(42), probe.network(42)
assert all(t.equal(v, b.state_dict()[k]) for k, v in a.state_dict().items())
x = probe.inputs(coarse, rgb, "coarse_only")
assert t.equal(x[:, :1], coarse) and not x[:, 1:].any()
y = probe.inputs(coarse, rgb, "native_rgb")
assert t.equal(y[:, :1], coarse) and t.equal(y[:, 1:], rgb.float() / 127.5 - 1)
assert sum(p.numel() for p in a.parameters()) == 2929
@pytest.mark.parametrize("bad", ["shape", "dtype", "nonfinite", "gradient", "arm"])
def test_input_contract_rejects_invalid_pairs(bad):
t, coarse, rgb = torch_fixture()
arm = "native_rgb"
if bad == "shape":
rgb = rgb[..., :-1]
elif bad == "dtype":
rgb = rgb.float()
elif bad == "nonfinite":
coarse[0, 0, 0, 0] = float("nan")
elif bad == "gradient":
coarse.requires_grad_(True)
else:
arm = "street_patch"
with pytest.raises(ValueError):
probe.inputs(coarse, rgb, arm)
def test_nonzero_correction_tiling_c4_equivariance_and_gradients():
t, coarse, rgb = torch_fixture()
net = probe.network(42)
x = probe.inputs(coarse, rgb, "native_rgb")
opt = t.optim.AdamW(net.parameters(), lr=0.001)
yy = (rgb[:, :1].float() / 255 > 0.5).float()
for _ in range(3):
opt.zero_grad()
t.nn.functional.binary_cross_entropy_with_logits(coarse + net(x), yy).backward()
opt.step()
assert net[0].weight.grad[:, 1:].abs().sum() > 0
assert coarse.grad is None
assert net[-1].weight.abs().sum() > 0
with t.no_grad():
expected = probe.prediction(net, coarse, x)
for tile in [1, 7, 32]:
assert t.allclose(
probe.prediction(net, coarse, x, tile), expected, atol=2e-6, rtol=1e-6
)
for k in range(4):
xx = probe.inputs(t.rot90(coarse, k, [-2, -1]), t.rot90(rgb, k, [-2, -1]), "native_rgb")
got = t.rot90(probe.prediction(net, t.rot90(coarse, k, [-2, -1]), xx), -k, [-2, -1])
assert t.allclose(got, expected, atol=2e-6, rtol=1e-6)
assert not t.equal(expected, coarse)
with pytest.raises(ValueError):
probe.residual(net, x, 0)
+162
View File
@@ -0,0 +1,162 @@
"""Mass conservation and sampling budgets for paired data-diversity fits."""
import copy
import json
import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
import diversity_mass as mass
FAMILIES = {"a": "fa", "a-extra": "fa", "b": "fb", "held": "fh"}
def records():
return [
dict(name="a1", sample_id="20", group="a", split="original-role",
target=np.array([[1, 1, 1, 0, 255]], dtype=np.uint8)),
dict(name="a2", sample_id="30", group="a", split="original-role",
target=np.array([[1, 255]], dtype=np.uint8)),
dict(name="b1", sample_id="10", group="b", split="original-role",
target=np.array([[1, 0, 0, 0, 255]], dtype=np.uint8)),
]
def test_mass_is_equal_per_class_family_and_supported_frame_not_pixel_count():
original = records()
out, weights, audit = mass.prepare(original, "fh", FAMILIES)
assert [r["sample_id"] for r in out] == ["10", "20", "30"]
np.testing.assert_allclose(weights["a1"], [[1 / 24, 1 / 24, 1 / 24, 1 / 4, 0]])
np.testing.assert_allclose(weights["a2"], [[1 / 8, 0]])
np.testing.assert_allclose(weights["b1"], [[1 / 4, 1 / 12, 1 / 12, 1 / 12, 0]])
assert audit["total_mass"] == pytest.approx(1)
assert [r["mass"] for r in audit["classes"]] == pytest.approx([0.5, 0.5])
assert all(r["mass"] == pytest.approx(0.25) for r in audit["family_classes"])
assert {r["name"]: r["mass"] for r in audit["frames"]} == pytest.approx(
{"a1": 3 / 8, "a2": 1 / 8, "b1": 1 / 2}
)
assert json.loads(json.dumps(audit)) == audit
for r in out:
assert r["split"] == "original-role"
assert weights[r["name"]].dtype == np.float64
assert (weights[r["name"]][r["target"] != 255] > 0).all()
assert not weights[r["name"]][r["target"] == 255].any()
def test_bg_only_frame_redistributes_only_its_family_background_mass():
old = records()
added = dict(name="new", sample_id="40", group="a-extra", split="regression",
target=np.array([[0, 0, 255]], dtype=np.uint8))
_, before, ba = mass.prepare(old, "fh", FAMILIES)
out, after, aa = mass.prepare(old + [added], "fh", FAMILIES)
for r in old:
np.testing.assert_array_equal(before[r["name"]][r["target"] == 1],
after[r["name"]][r["target"] == 1])
np.testing.assert_array_equal(before["b1"], after["b1"])
assert after["a1"][0, 3] == pytest.approx(1 / 8)
np.testing.assert_allclose(after["new"], [[1 / 16, 1 / 16, 0]])
assert [r["mass"] for r in ba["classes"]] == pytest.approx(
[r["mass"] for r in aa["classes"]]
)
assert [r["mass"] for r in ba["family_classes"]] == pytest.approx(
[r["mass"] for r in aa["family_classes"]]
)
assert next(r for r in out if r["name"] == "new")["group"] == "a-extra"
assert next(r for r in out if r["name"] == "new")["split"] == "regression"
def test_no_input_mutation_and_permutation_independence():
source = records()
previous = copy.deepcopy(source)
out, weights, audit = mass.prepare(source, "fh", FAMILIES)
other, ww, aa = mass.prepare(source[::-1], "fh", dict(reversed(list(FAMILIES.items()))))
assert audit == aa
assert [r["sample_id"] for r in other] == [r["sample_id"] for r in out]
for r, old in zip(source, previous, strict=True):
np.testing.assert_array_equal(r["target"], old["target"])
np.testing.assert_array_equal(weights[r["name"]], ww[r["name"]])
out[0]["target"][:] = 255
out[0]["group"] = "changed"
np.testing.assert_array_equal(source[2]["target"], previous[2]["target"])
assert source[2]["group"] == "b"
@pytest.mark.parametrize("fault", [
"held", "duplicate-name", "duplicate-id", "missing-group", "missing-family",
"one-class-family", "one-class-global", "unknown-only", "bad-label", "float",
"nan", "infinity", "empty-target", "one-dimensional", "missing-target", "empty",
"missing-held-map", "bad-mapping", "blank-id",
])
def test_invalid_admissions_fail_closed(fault):
rows, mapping = records(), dict(FAMILIES)
if fault == "held":
rows[0]["group"] = "held"
elif fault == "duplicate-name":
rows[1]["name"] = rows[0]["name"]
elif fault == "duplicate-id":
rows[1]["sample_id"] = rows[0]["sample_id"]
elif fault == "missing-group":
del mapping["a"]
elif fault == "missing-family":
mapping["extra-unseen-group"] = "extra-family"
elif fault == "one-class-family":
rows[2]["target"][rows[2]["target"] == 1] = 0
elif fault == "one-class-global":
for r in rows:
r["target"][r["target"] == 1] = 0
elif fault == "unknown-only":
rows[0]["target"][:] = 255
elif fault == "bad-label":
rows[0]["target"][0, 0] = 2
elif fault in ("float", "nan", "infinity"):
rows[0]["target"] = rows[0]["target"].astype(float)
rows[0]["target"][0, 0] = {"float": 1.0, "nan": np.nan, "infinity": np.inf}[fault]
elif fault == "empty-target":
rows[0]["target"] = np.empty((0, 2), dtype=np.uint8)
elif fault == "one-dimensional":
rows[0]["target"] = rows[0]["target"].reshape(-1)
elif fault == "missing-target":
del rows[0]["target"]
elif fault == "empty":
rows = []
elif fault == "missing-held-map":
del mapping["held"]
elif fault == "bad-mapping":
mapping["a"] = None
elif fault == "blank-id":
rows[0]["sample_id"] = ""
with pytest.raises(ValueError):
mass.prepare(rows, "fh", mapping)
@pytest.mark.parametrize("budget,frames", [(10, 3), (10240, 12), (10240, 14), (9216, 11),
(8, 8), (7, 1)])
def test_quotas_exact_budget_positive_and_fair_over_a_full_cycle(budget, frames):
cycle = np.stack([mass.quotas(budget, frames, step) for step in range(frames)])
assert cycle.dtype == np.int64 and (cycle > 0).all()
np.testing.assert_array_equal(cycle.sum(axis=1), np.full(frames, budget))
np.testing.assert_array_equal(cycle.sum(axis=0), np.full(frames, budget))
assert cycle.max() - cycle.min() <= 1
np.testing.assert_array_equal(mass.quotas(budget, frames, 0),
mass.quotas(budget, frames, frames))
def test_remainder_wraps_and_arms_have_equal_total_draws():
np.testing.assert_array_equal(mass.quotas(11, 4, 3), [3, 3, 2, 3])
np.testing.assert_array_equal(mass.quotas(11, 4, 4), [3, 3, 3, 2])
for step in range(20):
assert mass.quotas(10240, 10, step).sum() == mass.quotas(10240, 14, step).sum()
np.testing.assert_array_equal(mass.quotas(np.int64(5), np.int64(2), np.int64(1)), [2, 3])
@pytest.mark.parametrize("args", [
(0, 1, 0), (2, 3, 0), (2, 0, 0), (2, -1, 0), (4, 2, -1),
(3.0, 2, 0), (3, 2.0, 0), (3, 2, 0.0), (True, 1, 0), (3, True, 0),
(3, 2, False), (np.nan, 2, 0), (np.inf, 2, 0), (2**63, 2, 0),
])
def test_invalid_quotas_rejected(args):
with pytest.raises(ValueError):
mass.quotas(*args)
+78
View File
@@ -0,0 +1,78 @@
import importlib.util
from pathlib import Path
import pytest
spec = importlib.util.spec_from_file_location(
"feature_refinement",
Path(__file__).parents[1] / "simulation/semantic-learning/feature_refinement.py",
)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
def tensor():
return pytest.importorskip("torch")
def test_identity_and_ablation():
t = tensor()
n = m.network(12, channels=4, width=8)
f, c = t.randn(31, 4), t.randn(31, 1)
assert t.equal(n(f, c, "scene_features"), c)
with t.no_grad():
n.output.weight.fill_(0.02)
assert t.equal(n(f, c, "coarse_only"), n(f * 100, c, "coarse_only"))
assert not t.equal(n(f, c, "scene_features"), n(f * 100, c, "scene_features"))
@pytest.mark.parametrize("shape", [(8, 9), (13, 17), (1, 1)])
def test_native_alignment(shape):
t = tensor()
f = t.arange(2 * 3 * 5).float().reshape(1, 2, 3, 5)
ids = t.arange(shape[0] * shape[1])
got = m.sample_native(f, shape, ids)
expected = t.nn.functional.interpolate(f, size=shape, mode="bilinear", align_corners=False)
t.testing.assert_close(got, expected[0].flatten(1).T, atol=1e-5, rtol=1e-6)
def test_tiled_full_and_c4():
t = tensor()
n = m.network(7, channels=4, width=8)
with t.no_grad():
n.output.weight.fill_(0.02)
f, c = t.randn(1, 4, 7, 7), t.randn(21, 21)
a = m.predict(n, f, c, "scene_features", chunk=441)
b = m.predict(n, f, c, "scene_features", chunk=37)
t.testing.assert_close(a, b, atol=2e-5, rtol=1e-6)
for k in range(4):
z = m.predict(n, t.rot90(f, k, [-2, -1]), t.rot90(c, k), "scene_features")
t.testing.assert_close(a, t.rot90(z, -k), atol=2e-5, rtol=1e-6)
def test_seed_and_no_fine_gradient():
t = tensor()
a, b = m.network(8, 4, 8), m.network(8, 4, 8)
assert all(t.equal(x, y) for x, y in zip(a.parameters(), b.parameters(), strict=True))
with t.no_grad():
a.output.weight.fill_(0.02)
a(t.randn(7, 4), t.ones(7, 1), "coarse_only").sum().backward()
assert t.count_nonzero(a.layers[0].weight.grad[:, :4]) == 0
def test_outside_points_rejected():
t = tensor()
with pytest.raises(ValueError):
m.sample_native(t.ones(1, 4, 2, 2), (4, 4), t.tensor([16]))
def test_capacity_gate():
b = dict(bce=1.0, weak_fn=2, clear_fn=4, background_fp=100)
a = dict(bce=0.4, weak_fn=1, clear_fn=3, background_fp=40)
c = dict(bce=0.8, weak_fn=2, clear_fn=4, background_fp=80)
assert m.capacity_screen(b, a, c)["passed"]
for key, bad in [("bce", 0.6), ("weak_fn", 3), ("clear_fn", 5), ("background_fp", 51)]:
assert not m.capacity_screen(b, dict(a, **{key: bad}), c)["passed"]
assert not m.capacity_screen(b, a, dict(c, weak_fn=0))["passed"]
with pytest.raises(ValueError):
m.capacity_screen(b, dict(a, bce=float("nan")), c)
+67
View File
@@ -0,0 +1,67 @@
import importlib.util
from pathlib import Path
import pytest
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning/fit_capacity.py"
if not SRC.exists():
SRC = Path(__file__).with_name("fit_capacity.py")
spec = importlib.util.spec_from_file_location("fit_capacity", SRC)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
def before():
return dict(bce=0.2, weak_fn=10, background_fp=20, clear_fn=2)
def test_exact_half_boundary_passes_without_promotion():
a = dict(bce=0.1, weak_fn=5, background_fp=10, clear_fn=2)
r = m.capacity_screen(before(), a)
assert r["passed"] and not r["production_eligible"]
@pytest.mark.parametrize(
"metric,value", [("bce", 0.100001), ("weak_fn", 6), ("background_fp", 11), ("clear_fn", 3)]
)
def test_each_guard_fails_even_when_other_metrics_improve(metric, value):
a = dict(bce=0.01, weak_fn=0, background_fp=0, clear_fn=0)
a[metric] = value
r = m.capacity_screen(before(), a)
assert not r["passed"] and r["failures"] == [metric]
def test_zero_baseline_cannot_hide_new_errors_or_divide_by_zero():
z = dict(bce=0.0, weak_fn=0, background_fp=0, clear_fn=0)
assert m.capacity_screen(z, z)["passed"]
a = dict(z, background_fp=1)
assert m.capacity_screen(z, a)["failures"] == ["background_fp"]
@pytest.mark.parametrize(
"metric,value",
[
("bce", float("nan")),
("bce", float("inf")),
("bce", -1),
("bce", True),
("weak_fn", 1.5),
("background_fp", -1),
("clear_fn", True),
],
)
def test_invalid_metrics_are_rejected(metric, value):
a = before()
a[metric] = value
for left, right in [(a, before()), (before(), a)]:
with pytest.raises(ValueError):
m.capacity_screen(left, right)
def test_extra_or_missing_cohorts_are_rejected():
for a in [
dict(before(), street_threshold=1),
{k: v for k, v in before().items() if k != "weak_fn"},
]:
with pytest.raises(ValueError):
m.capacity_screen(a, before())
+64
View File
@@ -0,0 +1,64 @@
"""Scientific isolation and nonregression gates for grouped threshold selection."""
import importlib
import sys
from pathlib import Path
import pytest
for dependency in ["numpy", "cv2", "scipy", "shapely"]:
pytest.importorskip(dependency)
ROOT = Path(__file__).resolve().parents[1]
for directory in [
"simulation/semantic-learning",
"simulation/urban-plan-research/systematic",
"simulation/urban-plan-research/marking_pass",
]:
sys.path.insert(0, str(ROOT / directory))
study = importlib.import_module("grouped_selection_study")
def test_control_street_never_enters_development():
records = [dict(street="a", split="heldout"), dict(street="control", split="train")]
assert study.development(records, ["a"]) == [records[0]]
def test_threshold_rejects_known_false_positives_and_uses_interior_plateau():
rows = [
dict(threshold=t, unsupported=0, worst_street=0.8, macro_family=0.9, found=10)
for t in [0.2, 0.25, 0.3, 0.35, 0.4]
]
rows.append(dict(threshold=0.1, unsupported=1, worst_street=1, macro_family=1, found=20))
assert study.select(rows)["threshold"] == 0.3
assert study.select([rows[-1]]) is None
def cohort(found, fp=0):
return dict(
rows=[dict(id="window", objects=[dict(id=i, matched=True) for i in found])],
streets={"a": dict(unsupported=fp)},
summary=dict(found=len(found), unsupported=fp),
)
def test_equal_count_cannot_hide_loss_of_a_previously_found_object():
verdict = study.transfer_gate(cohort(["x", "y"]), cohort(["x", "z", "w"]))
assert verdict["lost_objects"] == ["y"]
assert not verdict["passed"]
def test_improvement_requires_no_loss_and_no_extra_false_positive():
assert study.transfer_gate(cohort(["x"], 1), cohort(["x"], 0))["passed"]
assert not study.transfer_gate(cohort(["x"]), cohort(["x", "y"], 1))["passed"]
assert not study.transfer_gate(cohort(["x"]), cohort(["x"]))["passed"]
def test_unmatchable_objects_do_not_distort_threshold_objective():
objects = [
dict(id="a", family="arrow", matched=True),
dict(id="b", family="bar", matched=False),
]
rows = [dict(id="w", street="s", objects=objects)]
result = study.objective(rows, {"w": dict(objects=objects)})
assert result["worst_street"] == 1
assert result["family_matchable"] == {"arrow": [1, 1]}
+41
View File
@@ -0,0 +1,41 @@
import importlib.util
from pathlib import Path
import numpy as np
import pytest
p = Path(__file__).resolve().parents[1]/"simulation/semantic-learning/label_extension.py"
s = importlib.util.spec_from_file_location("label_extension", p)
m = importlib.util.module_from_spec(s)
s.loader.exec_module(m)
def test_expanding_background_keeps_old_uncertain_band_and_known_labels():
base = np.full((5, 8), 255, np.uint8)
base[2, 3:5] = 1
base[1, 3:5] = 0
base[4, 7] = 1
lock = np.zeros(base.shape, bool)
lock[1:4, 2:6] = True
proposal = np.zeros(base.shape, np.uint8)
proposal[0, 0] = 1
got = m.extend_reviewed_target(base, proposal, lock)
np.testing.assert_array_equal(got[lock], base[lock])
np.testing.assert_array_equal(got[base != 255], base[base != 255])
assert got[0, 0] == got[4, 7] == 1 and got[0, 1] == 0
assert got[2, 2] == 255 and proposal[4, 7] == 0
def test_omitted_or_misaligned_protection_rejected():
base = np.full((2, 3), 255, np.uint8)
for lock in [None, np.zeros((3, 2), bool), np.zeros((2, 3), np.uint8)]:
with pytest.raises(ValueError):
m.extend_reviewed_target(base, base, lock)
def test_out_of_vocabulary_labels_rejected():
base = np.full((2, 3), 255, np.uint8)
proposal = base.copy()
proposal[0, 0] = 2
with pytest.raises(ValueError):
m.extend_reviewed_target(base, proposal, np.zeros(base.shape, bool))
+540
View File
@@ -0,0 +1,540 @@
"""Resume, lost acknowledgement and provenance failures must never duplicate fit."""
import copy
import importlib.util
import json
import subprocess
import sys
from pathlib import Path
import pytest
SOURCE = Path(__file__).parents[1] / "simulation/semantic-learning"
sys.path.insert(0, str(SOURCE))
spec = importlib.util.spec_from_file_location(
"tested_learning_execution", SOURCE / "learning_execution.py"
)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
@pytest.fixture
def setup(tmp_path):
(tmp_path / "runner.py").write_text("# synthetic pinned runner\n")
(tmp_path / "release.json").write_text('{"accepted":true}\n')
calls = []
def invoke(root, argv, timeout):
calls.append(argv[1])
phase = argv[1].removeprefix("verify-")
name = phase + ".json"
if argv[1].startswith("verify-"):
return json.dumps(
dict(
valid=True,
outputs={name: m.pin(root, name)},
artifacts={name: m.pin(root, name)},
)
)
(root / name).write_text(json.dumps(dict(phase=phase)))
return ""
plan = dict(
schema=m.SCHEMA,
objective="synthetic resumable fit/replay",
inputs={name: m.pin(tmp_path, name) for name in ["runner.py", "release.json"]},
phases=[
dict(
name=n,
run=["runner.py", n],
verify=["runner.py", "verify-" + n],
outputs=[n + ".json"],
run_timeout_seconds=5,
verify_timeout_seconds=5,
)
for n in ["fit", "replay"]
],
)
ledger = m.Execution(tmp_path, runner=invoke)
yield ledger, plan, calls, invoke
ledger.close()
def test_restart_reuses_completed_fit_and_checks_order(setup):
ledger, plan, calls, runner = setup
identity = ledger.register(plan)
with pytest.raises(ValueError, match="Previous"):
ledger.execute(identity, "replay")
first = ledger.execute(identity, "fit")
assert first["artifact_validation"] and first["model_acceptance"] is False
reopened = m.Execution(ledger.root, runner=runner)
try:
assert reopened.register(plan) == identity
assert reopened.execute(identity, "fit") == first
reopened.execute(identity, "replay")
assert calls == ["fit", "verify-fit", "replay", "verify-replay"]
finally:
reopened.close()
def test_lost_acknowledgement_no_retry_and_root_recovers_outputs(setup):
ledger, plan, calls, runner = setup
identity = ledger.register(plan)
def lost_ack(root, argv, timeout):
result = runner(root, argv, timeout)
if argv[1] == "fit":
raise ConnectionError("acknowledgement lost after artifacts were written")
return result
ledger.runner = lost_ack
with pytest.raises(ConnectionError):
ledger.execute(identity, "fit")
state = ledger.status(identity)["phases"][0]
assert state["state"] == "unknown"
ledger.clock = lambda: 10**15
with pytest.raises(ValueError, match="reconciliation"):
ledger.execute(identity, "fit")
with pytest.raises(ValueError, match="matching"):
ledger.reconcile(identity, "fit", "wrong-token", "process stopped")
recovered = ledger.reconcile(
identity, "fit", state["token"], "trusted root verified PID stopped"
)
assert ledger.execute(identity, "fit") == recovered
assert calls.count("fit") == 1
def test_failure_with_partial_outputs_does_not_become_success(setup):
ledger, plan, _, _ = setup
identity = ledger.register(plan)
def crash(root, argv, timeout):
(root / "partial-model.pt").write_bytes(b"synthetic partial checkpoint")
raise TimeoutError("training stopped before receipt")
ledger.runner = crash
with pytest.raises(TimeoutError):
ledger.execute(identity, "fit")
state = ledger.status(identity)["phases"][0]
with pytest.raises(ValueError, match="Missing"):
ledger.reconcile(identity, "fit", state["token"], "process stopped")
assert ledger.status(identity)["phases"][0]["state"] == "unknown"
(ledger.root / "failure-archive.txt").write_text("synthetic archived diagnostics")
archive = {"failure-archive.txt": m.pin(ledger.root, "failure-archive.txt")}
result = ledger.close_failed(identity, "fit", state["token"], "verified stopped", archive)
assert result["retry_authorized"] is False
assert (ledger.root / "partial-model.pt").exists()
with pytest.raises(ValueError, match="reconciliation"):
ledger.execute(identity, "fit")
def test_two_controllers_cannot_start_same_phase(setup):
ledger, plan, calls, runner = setup
identity = ledger.register(plan)
competitor = m.Execution(ledger.root, runner=runner)
def during(root, argv, timeout):
if argv[1] == "fit":
with pytest.raises(ValueError, match="reconciliation"):
competitor.execute(identity, "fit")
return runner(root, argv, timeout)
ledger.runner = during
try:
ledger.execute(identity, "fit")
assert calls.count("fit") == 1
finally:
competitor.close()
@pytest.mark.parametrize("changed", ["release.json", "runner.py", "fit.json"])
def test_changed_provenance_blocks_completed_resume_and_next_phase(setup, changed):
ledger, plan, calls, _ = setup
identity = ledger.register(plan)
ledger.execute(identity, "fit")
(ledger.root / changed).write_text("changed")
for phase in ["fit", "replay"]:
with pytest.raises(ValueError, match="changed"):
ledger.execute(identity, phase)
assert calls.count("fit") == 1 and "replay" not in calls
@pytest.mark.parametrize("mode", ["false", "missing-output", "mutated-after-pin", "extra-field"])
def test_invalid_verifier_cannot_complete_phase(setup, mode):
ledger, plan, _, runner = setup
identity = ledger.register(plan)
def bad(root, argv, timeout):
raw = runner(root, argv, timeout)
if not argv[1].startswith("verify-"):
return raw
value = json.loads(raw)
if mode == "false":
value["valid"] = False
if mode == "missing-output":
value["outputs"] = {}
if mode == "extra-field":
value["promote"] = True
if mode == "mutated-after-pin":
(root / "fit.json").write_text("tampered")
return json.dumps(value)
ledger.runner = bad
with pytest.raises(ValueError):
ledger.execute(identity, "fit")
assert ledger.status(identity)["phases"][0]["state"] == "unknown"
@pytest.mark.parametrize("member", ["../escape", "/absolute", "a\\b", "a:stream"])
def test_unsafe_outputs_are_rejected(setup, member):
ledger, plan, _, _ = setup
plan["phases"][0]["outputs"] = [member]
with pytest.raises(ValueError, match="Unsafe"):
ledger.register(plan)
def test_existing_outputs_require_explicit_ownership(setup):
ledger, plan, calls, _ = setup
(ledger.root / "fit.json").write_text("existing result")
with pytest.raises(ValueError, match="Unowned"):
ledger.register(plan)
assert not calls
def test_unfinished_owner_blocks_different_plan(setup):
ledger, plan, _, _ = setup
identity = ledger.register(plan)
ledger.runner = lambda *args: (_ for _ in ()).throw(ConnectionError("lost"))
with pytest.raises(ConnectionError):
ledger.execute(identity, "fit")
changed = copy.deepcopy(plan)
changed["objective"] = "another run"
with pytest.raises(ValueError, match="owns resources"):
ledger.register(changed)
def test_real_bounded_subprocess_verifier(tmp_path):
code = """import sys,json,hashlib
from pathlib import Path
p=Path('result.json')
if sys.argv[1]=='fit': p.write_text('{"value":42}')
else:
h=hashlib.sha256(p.read_bytes()).hexdigest()
outputs={'result.json':dict(bytes=p.stat().st_size,sha256=h)}
print(json.dumps(dict(valid=True,outputs=outputs,artifacts=outputs)))
"""
(tmp_path / "runner.py").write_text(code)
plan = dict(
schema=m.SCHEMA,
objective="real synthetic subprocess",
inputs={"runner.py": m.pin(tmp_path, "runner.py")},
phases=[
dict(
name="fit",
run=["runner.py", "fit"],
verify=["runner.py", "verify"],
outputs=["result.json"],
run_timeout_seconds=5,
verify_timeout_seconds=5,
)
],
)
ledger = m.Execution(tmp_path)
try:
identity = ledger.register(plan)
receipt = ledger.execute(identity, "fit")
assert receipt["outputs"]["result.json"]["bytes"] == 12
assert ledger.execute(identity, "fit") == receipt
finally:
ledger.close()
def test_small_output_cap_and_deadline(tmp_path, monkeypatch):
monkeypatch.setattr(m, "MAX_LOG", 16)
(tmp_path / "runner.py").write_text("print('x'*32)\n")
with pytest.raises(ValueError, match="output exceeded"):
m.invoke(tmp_path, ["runner.py"], 2)
(tmp_path / "runner.py").write_text("import time; time.sleep(2)\n")
with pytest.raises(subprocess.TimeoutExpired):
m.invoke(tmp_path, ["runner.py"], 0.02)
def test_manifest_payload_tamper_blocks_resume_and_next_phase(setup):
ledger, plan, calls, runner = setup
identity = ledger.register(plan)
def with_payload(root, argv, timeout):
raw = runner(root, argv, timeout)
if argv[1] == "fit":
(root / "model.pt").write_bytes(b"synthetic model")
if argv[1] == "verify-fit":
value = json.loads(raw)
value["artifacts"]["model.pt"] = m.pin(root, "model.pt")
return json.dumps(value)
return raw
ledger.runner = with_payload
receipt = ledger.execute(identity, "fit")
assert set(receipt["artifacts"]) == {"fit.json", "model.pt"}
(ledger.root / "model.pt").write_bytes(b"corrupted model")
for phase in ["fit", "replay"]:
with pytest.raises(ValueError, match="changed: model.pt"):
ledger.execute(identity, phase)
assert calls.count("fit") == 1 and "replay" not in calls
def test_verifier_cannot_omit_output_from_closure(setup):
ledger, plan, _, runner = setup
identity = ledger.register(plan)
def missing(root, argv, timeout):
raw = runner(root, argv, timeout)
if argv[1].startswith("verify-"):
value = json.loads(raw)
value["artifacts"] = {}
return json.dumps(value)
return raw
ledger.runner = missing
with pytest.raises(ValueError, match="closure"):
ledger.execute(identity, "fit")
def test_separate_process_budgets_and_compact_status(setup):
ledger, plan, _, runner = setup
plan["phases"][0].update(run_timeout_seconds=7, verify_timeout_seconds=3)
calls = []
def budget(root, argv, timeout):
calls.append(timeout)
return runner(root, argv, timeout)
ledger.runner = budget
identity = ledger.register(plan)
ledger.execute(identity, "fit")
assert calls == [7, 3]
phase = ledger.status(identity)["phases"][0]
assert "receipt" not in phase and phase["artifact_count"] == 1
assert len(phase["receipt_sha256"]) == 64
def test_readonly_input_root_with_separate_state_checks_real_external_files(tmp_path):
store = tmp_path / "store"
store.mkdir()
state = tmp_path / "state"
(store / "release.json").write_text('{"target":42}')
(store / "runner.py").write_text("# trusted synthetic runner")
def invoke(root, argv, timeout):
if argv[1] == "fit":
(root / "output.json").write_text('{"result":42}')
return ""
values = {"output.json": m.pin(root, "output.json")}
return json.dumps(dict(valid=True, outputs=values, artifacts=values))
plan = dict(
schema=m.SCHEMA,
objective="separate ledger and explicit source pins",
inputs={n: m.pin(store, n) for n in ["release.json", "runner.py"]},
phases=[
dict(
name="fit",
run=["runner.py", "fit"],
verify=["runner.py", "verify"],
outputs=["output.json"],
run_timeout_seconds=5,
verify_timeout_seconds=5,
)
],
)
ledger = m.Execution(store, state_root=state, runner=invoke)
try:
identity = ledger.register(plan)
ledger.execute(identity, "fit")
assert (state / "learning-execution.sqlite3").exists()
assert not (store / "learning-execution.sqlite3").exists()
(store / "release.json").write_text("changed external target")
with pytest.raises(ValueError, match="changed: release.json"):
ledger.execute(identity, "fit")
finally:
ledger.close()
def test_input_closure_above_128_files_is_bounded_and_checked(tmp_path):
(tmp_path / "runner.py").write_text("# synthetic")
inputs = {"runner.py": m.pin(tmp_path, "runner.py")}
for i in range(130):
name = f"input-{i}.json"
(tmp_path / name).write_text(str(i))
inputs[name] = m.pin(tmp_path, name)
plan = dict(
schema=m.SCHEMA,
objective="explicit real closure",
inputs=inputs,
phases=[
dict(
name="fit",
run=["runner.py"],
verify=["runner.py"],
outputs=["out.json"],
run_timeout_seconds=1,
verify_timeout_seconds=1,
)
],
)
ledger = m.Execution(tmp_path)
try:
identity = ledger.register(plan)
(tmp_path / "input-129.json").write_text("changed")
with pytest.raises(ValueError, match="input-129.json"):
ledger.execute(identity, "fit")
finally:
ledger.close()
@pytest.fixture
def cumulative_artifacts(tmp_path):
"""Three real completed receipts retain the same model and earlier outputs."""
(tmp_path / "runner.py").write_text("# synthetic cumulative pipeline\n")
(tmp_path / "release.json").write_text('{"accepted":true}\n')
phases = ["fit", "score", "replay", "judge"]
calls, receipts = [], []
def invoke(root, argv, timeout):
calls.append(argv[1])
phase = argv[1].removeprefix("verify-")
index = phases.index(phase)
if not argv[1].startswith("verify-"):
(root / (phase + ".json")).write_text(json.dumps(dict(phase=phase)))
if phase == "fit":
for name in ("model.pt", "copy.pt"):
(root / name).write_bytes(b"same bytes, distinct physical paths")
if phase == "score":
(root / "held.npz").write_bytes(b"synthetic prediction payload")
return ""
names = [n + ".json" for n in phases[: index + 1]] + ["model.pt", "copy.pt"]
if index >= 1:
names.append("held.npz")
return json.dumps(
dict(
valid=True,
outputs={phase + ".json": m.pin(root, phase + ".json")},
artifacts={name: m.pin(root, name) for name in names},
)
)
plan = dict(
schema=m.SCHEMA,
objective="cumulative synthetic artifact closure",
inputs={name: m.pin(tmp_path, name) for name in ["runner.py", "release.json"]},
phases=[
dict(
name=name,
run=["runner.py", name],
verify=["runner.py", "verify-" + name],
outputs=[name + ".json"],
run_timeout_seconds=5,
verify_timeout_seconds=5,
)
for name in phases
],
)
ledger = m.Execution(tmp_path, runner=invoke)
try:
identity = ledger.register(plan)
for phase in phases[:3]:
receipts.append(ledger.execute(identity, phase))
yield ledger, identity, plan, receipts, calls, invoke
finally:
ledger.close()
def test_cumulative_boundary_hashes_unique_paths_and_rechecks_next_boundary(
cumulative_artifacts, monkeypatch
):
ledger, identity, plan, receipts, _, _ = cumulative_artifacts
old_entries = [item for receipt in receipts for item in receipt["artifacts"].items()]
unique = dict(old_entries)
assert len(old_entries) == 14 and len(unique) == 6
assert unique["model.pt"] == unique["copy.pt"] # Equal hashes must not merge physical paths.
original = m.checksum
reads = []
def counted(path):
reads.append((path.relative_to(ledger.root).as_posix(), path.stat().st_size))
return original(path)
monkeypatch.setattr(m, "checksum", counted)
for _ in range(2):
reads.clear()
ledger._context(identity, "judge")
assert len(reads) == len(plan["inputs"]) + len(unique) == 8
assert {name for name, _ in reads} == set(plan["inputs"]) | set(unique)
assert sum(size for _, size in reads) == sum(
pin["bytes"] for pin in [*plan["inputs"].values(), *unique.values()]
)
assert sum(size for _, size in reads) < sum(
pin["bytes"] for pin in [*plan["inputs"].values(), *(pin for _, pin in old_entries)]
)
# The previous loop made16 calls/boundary (2 inputs +14 prior artifact entries).
# This is a structural count, not a latency or disk-throughput benchmark.
@pytest.mark.parametrize("mode", ["missing", "tampered"])
def test_cumulative_payload_change_blocks_next_and_completed_resume(cumulative_artifacts, mode):
ledger, identity, _, _, calls, _ = cumulative_artifacts
path = ledger.root / "copy.pt"
if mode == "missing":
path.unlink()
else:
path.write_bytes(b"corrupted despite model.pt remaining valid")
before = list(calls)
for phase in ("judge", "replay"):
with pytest.raises(
ValueError, match="(?:Missing regular artifact|Artifact changed): copy.pt"
):
ledger.execute(identity, phase)
assert calls == before
assert ledger.status(identity)["phases"][-1]["state"] == "pending"
@pytest.mark.parametrize("field,value", [("sha256", "0" * 64), ("bytes", 999)])
def test_conflicting_previous_pins_fail_before_any_payload_hash(
cumulative_artifacts, monkeypatch, field, value
):
ledger, identity, _, receipts, calls, _ = cumulative_artifacts
conflict = copy.deepcopy(receipts[-1])
conflict["artifacts"]["model.pt"][field] = value
with ledger.db:
ledger.db.execute(
"UPDATE learning_phases SET receipt=? WHERE run=? AND name='replay'",
(json.dumps(conflict), identity),
)
reads = []
original = m.checksum
def counted(path):
reads.append(path)
return original(path)
monkeypatch.setattr(m, "checksum", counted)
before = list(calls)
with pytest.raises(ValueError, match="Conflicting previous artifact pins: model.pt"):
ledger.execute(identity, "judge")
assert not reads and calls == before
def test_previous_payload_modified_during_phase_still_fails_post_verification(cumulative_artifacts):
ledger, identity, _, _, calls, runner = cumulative_artifacts
def corrupt_during_run(root, argv, timeout):
if argv[1] == "judge":
(root / "model.pt").write_bytes(b"mutated after precheck")
# The current verifier honestly reports new bytes; prior receipts still bind old bytes.
return runner(root, argv, timeout)
ledger.runner = corrupt_during_run
with pytest.raises(ValueError, match="Artifact changed: model.pt"):
ledger.execute(identity, "judge")
assert calls.count("judge") == 1
assert ledger.status(identity)["phases"][-1]["state"] == "unknown"
+208
View File
@@ -0,0 +1,208 @@
import importlib.util
from pathlib import Path
import pytest
def load_module(name):
source = Path(__file__).parents[1] / "simulation/semantic-learning" / f"{name}.py"
if not source.exists():
source = Path(__file__).with_name(f"{name}.py")
spec = importlib.util.spec_from_file_location(name, source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
m = load_module("linear_refinement")
def tensors():
t = pytest.importorskip("torch")
x = t.tensor([[-2., 1.], [-1., -1.], [0., 2.], [1., -2.], [2., 1.]], dtype=t.float64)
c = t.tensor([[0.4], [-0.2], [0.], [-0.4], [0.2]], dtype=t.float64)
y = t.tensor([0, 0, 0, 1, 1])
w = t.tensor([1., 2., 0., 3., 1.], dtype=t.float64)
return t, x, c, y, w
def test_identity_parameter_count_and_rng_preservation():
t = pytest.importorskip("torch")
rng = t.random.get_rng_state().clone()
a, b = m.network(1), m.network(999)
assert t.equal(rng, t.random.get_rng_state())
assert sum(p.numel() for p in a.parameters()) == 258
assert all(t.equal(p, q) for p, q in zip(a.parameters(), b.parameters(), strict=True))
fine, coarse = t.ones(7, 256), t.arange(7).float().reshape(-1, 1)
for arm in m.ARMS:
assert t.equal(a(fine, coarse, arm), coarse)
def test_predict_native_alignment_chunking_and_ablation():
t = pytest.importorskip("torch")
feature = load_module("feature_refinement")
net = m.network(channels=2)
with t.no_grad():
net.weight.copy_(t.tensor([[0.1, -0.2, 0.3]]))
net.bias.fill_(0.2)
fine = t.arange(2 * 3 * 5).float().reshape(1, 2, 3, 5) / 10
coarse = t.arange(7 * 9).float().reshape(7, 9) / 10
expected = feature.predict(net, fine, coarse, "scene_features", chunk=100)
actual = feature.predict(net, fine, coarse, "scene_features", chunk=11)
t.testing.assert_close(actual, expected)
for k in range(4):
rotated = feature.predict(
net, t.rot90(fine, k, [-2, -1]), t.rot90(coarse, k), "scene_features", chunk=11,
)
t.testing.assert_close(t.rot90(rotated, -k), expected, atol=2e-6, rtol=1e-6)
a = feature.predict(net, fine, coarse, "coarse_only")
b = feature.predict(net, fine * 100, coarse, "coarse_only")
assert t.equal(a, b)
@pytest.mark.parametrize("arm", ["coarse_only", "scene_features"])
def test_fit_stationarity_weight_scale_duplication_and_chunk_invariance(arm):
t, x, c, y, w = tensors()
a, report = m.fit(x, c, y, w, arm, chunk=2)
b, repeated = m.fit(x.repeat(2, 1), c.repeat(2, 1), y.repeat(2), w.repeat(2) * 9, arm)
assert report["converged"] and repeated["converged"]
assert report["status"] == "converged"
assert report["gradient_inf_norm"] <= 1e-4
assert report["evaluations"] <= 400
assert report["production_eligible"] is False
for p, q in zip(a.parameters(), b.parameters(), strict=True):
t.testing.assert_close(p, q, atol=1e-4, rtol=1e-4)
if arm == "coarse_only":
assert t.count_nonzero(a.weight[:, :-1]) == 0
# Independently recompute the full objective and every parameter gradient.
logits = a(x, c, arm)[:, 0]
per_point = t.nn.functional.binary_cross_entropy_with_logits(
logits, y.double(), reduction="none"
)
data = (per_point * w).sum() / w.sum()
penalty = 0.5 * 0.01 * sum(p.square().sum() for p in a.parameters())
objective = data + penalty
objective.backward()
grad = max(float(p.grad.abs().max()) for p in a.parameters())
assert float(data) == pytest.approx(report["data_loss"], abs=1e-12)
assert float(penalty) == pytest.approx(report["l2_loss"], abs=1e-12)
assert float(objective) == pytest.approx(report["loss"], abs=1e-12)
assert grad == pytest.approx(report["gradient_inf_norm"], abs=1e-12)
assert grad <= 1e-4
def test_bias_is_regularized_even_for_one_class():
t = pytest.importorskip("torch")
x, c = t.zeros(8, 2, dtype=t.float64), t.zeros(8, 1, dtype=t.float64)
net, report = m.fit(x, c, t.ones(8), t.ones(8, dtype=t.float64))
assert report["converged"]
assert 0 < float(net.bias) < 10
assert report["l2_loss"] == pytest.approx(0.005 * float(net.bias.square()), abs=1e-12)
assert abs(float(t.sigmoid(net.bias) - 1 + 0.01 * net.bias)) <= 1e-4
@pytest.mark.parametrize("unknown", [-1, 255, 0.5])
@pytest.mark.parametrize("weight", [0., 1.])
def test_unknown_rejected_even_at_zero_weight(unknown, weight):
t, x, c, y, w = tensors()
y = y.double()
y[0], w[0] = unknown, weight
with pytest.raises(ValueError, match="binary known"):
m.fit(x, c, y, w)
@pytest.mark.parametrize(
"bad",
[
"fine_shape", "coarse_shape", "target_shape", "weight_shape", "empty", "dtype",
"fine_nan", "coarse_inf", "target_nan", "weight_nan", "negative_weight", "zero_sum",
"input_gradient", "arm", "chunk",
],
)
def test_input_validation(bad):
t, x, c, y, w = tensors()
kwargs = {}
if bad == "fine_shape":
x = x[None]
elif bad == "coarse_shape":
c = c[:, 0]
elif bad == "target_shape":
y = y[:-1]
elif bad == "weight_shape":
w = w[:-1]
elif bad == "empty":
x, c, y, w = x[:0], c[:0], y[:0], w[:0]
elif bad == "dtype":
c = c.float()
elif bad == "fine_nan":
x[0, 0] = float("nan")
elif bad == "coarse_inf":
c[0] = float("inf")
elif bad == "target_nan":
y = y.double()
y[0] = float("nan")
elif bad == "weight_nan":
w[0] = float("nan")
elif bad == "negative_weight":
w[0] = -1
elif bad == "zero_sum":
w.zero_()
elif bad == "input_gradient":
x.requires_grad_(True)
elif bad == "arm":
kwargs["arm"] = "location_specific"
else:
kwargs["chunk"] = 0
with pytest.raises(ValueError):
m.fit(x, c, y, w, **kwargs)
def test_no_optimizer_progress_is_technical_stop(monkeypatch):
t, x, c, y, w = tensors()
real = t.optim.LBFGS
def stopped(parameters, **kwargs):
optimizer = real(parameters, **kwargs)
monkeypatch.setattr(optimizer, "step", lambda closure: closure())
return optimizer
monkeypatch.setattr(t.optim, "LBFGS", stopped)
_, report = m.fit(x, c, y, w)
assert not report["converged"]
assert report["status"] == "technical_stop"
assert report["stop_reason"] == "stationarity_not_met"
def test_total_timeout_cannot_be_reported_as_convergence(monkeypatch):
_, x, c, y, w = tensors()
now = iter([0., 121., 121., 121.])
monkeypatch.setattr(m.time, "monotonic", lambda: next(now, 121.))
net, report = m.fit(x, c, y, w)
assert not report["converged"]
assert report["stop_reason"] == "fit_timeout"
assert report["evaluations"] == 0
assert report["gradient_inf_norm"] is None
assert all(float(p.abs().sum()) == 0 for p in net.parameters())
def test_line_search_evaluation_budget_is_enforced(monkeypatch):
t, x, c, y, w = tensors()
real = t.optim.LBFGS
monkeypatch.setattr(m, "MAX_EVAL", 3)
def repeated(parameters, **kwargs):
optimizer = real(parameters, **kwargs)
def step(closure):
for _ in range(10):
closure()
monkeypatch.setattr(optimizer, "step", step)
return optimizer
monkeypatch.setattr(t.optim, "LBFGS", repeated)
_, report = m.fit(x, c, y, w)
assert report["status"] == "technical_stop"
assert report["stop_reason"] == "evaluation_limit"
assert report["evaluations"] == 2
+262
View File
@@ -0,0 +1,262 @@
"""Mixed admission rejects identity drift and preserves class mass across folds."""
import copy
import hashlib
import json
import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
import mixed_supervision as m
def target_view(target):
runs = {"paint": [], "background": [], "unknown": []}
for row, col in np.ndindex(target.shape):
label = int(target[row, col])
if label != 255:
runs["paint" if label else "background"].append([row, col, col + 1])
return dict(view="top", size=list(target.shape[::-1]), **runs)
def fixtures():
records, weights, entries = [], {}, {}
for name, group, values in [
("a", "g", [[1, 1, 0, 255], [255, 0, 255, 255]]),
("b", "g", [[1, 255, 0, 255], [255, 255, 255, 255]]),
("c", "h", [[1, 0, 255, 255], [255, 255, 255, 255]]),
]:
t = np.array(values, dtype=np.uint8)
image = dict(
sample_id=name,
view="top",
camera={"size": [4, 2]},
rgb={"path": name + "/top.png", "sha256": name * 64},
)
r = dict(name=name, sample_id=name, group=group, split="train", input=image, target=t)
records.append(r)
weights[name] = np.where(t == 255, 0, 0.2 if name == "a" else 0.1).astype(np.float32)
entries[name] = dict(
sample_id=name,
physical_group=group,
split="train",
task="observed_paint",
source={"world_sha256": name * 64},
inputs=[copy.deepcopy(image)],
targets=[target_view(t)],
)
return records, weights, entries, copy.deepcopy(entries)
def admission(records, new):
a = records[0]["target"].copy()
a[0, 1] = 255
a[1, 0] = 1
new["a"]["targets"] = [target_view(a)]
b = records[1]["target"].copy()
b[1, 0] = 0
new["b"]["targets"] = [target_view(b)]
def proof(records, old):
value = dict(
schema="missioncore.mixed-withdrawals/v1",
evidence=[dict(path="archive/review.json", sha256="e" * 64)],
records={
"a": dict(
source=old["a"]["source"],
input=records[0]["input"],
old_target_sha256=m._sha(records[0]["target"].tobytes()),
runs=[[0, 1, 2]],
)
},
)
return value
def kwargs(value):
payload = json.dumps(value, sort_keys=True).encode()
return dict(withdrawal_bytes=payload, withdrawal_sha256=hashlib.sha256(payload).hexdigest())
def test_mixed_growth_with_exact_withdrawal_and_conserved_group_class_mass():
records, weights, old, new = fixtures()
admission(records, new)
original = copy.deepcopy((records, weights, old, new))
out, ww, audit = m.prepare_mixed(records, weights, old, new, **kwargs(proof(records, old)))
assert out[0]["target"].tolist() == [[1, 255, 0, 255], [1, 0, 255, 255]]
assert out[0]["mixed_added_paint"].sum() == 1
assert out[0]["mixed_withdrawn"].sum() == 1
assert out[1]["mixed_added_background"].sum() == 1
assert audit["records"][0]["withdrawn_paint"] == 1
for mass in audit["masses"]:
assert mass["after"] == pytest.approx(mass["before"])
for label in (0, 1):
group_rows = [r for r in out if r["group"] == "g"]
amounts = [ww[r["name"]][r["target"] == label].sum() for r in group_rows]
assert amounts[0] == pytest.approx(amounts[1])
np.testing.assert_array_equal(ww["c"], weights["c"])
for r, previous in zip(records, original[0], strict=True):
np.testing.assert_array_equal(r["target"], previous["target"])
np.testing.assert_array_equal(weights[r["name"]], original[1][r["name"]])
assert old == original[2] and new == original[3]
assert all(not ww[r["name"]][r["target"] == 255].any() for r in out)
def test_identity_release_is_bit_exact_and_fold_can_use_global_proof():
records, weights, old, new = fixtures()
out, ww, _ = m.prepare_mixed(records, weights, old, new)
for r, n in zip(records, out, strict=True):
np.testing.assert_array_equal(r["target"], n["target"])
np.testing.assert_array_equal(weights[r["name"]], ww[r["name"]])
_, fold_weights, _ = m.prepare_mixed(
records[2:],
{"c": weights["c"]},
{"c": old["c"]},
{"c": new["c"]},
**kwargs(proof(records, old)),
)
np.testing.assert_array_equal(fold_weights["c"], weights["c"])
@pytest.mark.parametrize(
"field", ["source", "physical_group", "split", "sample_id", "task", "inputs"]
)
def test_release_identity_drift_is_rejected(field):
records, weights, old, new = fixtures()
new["a"][field] = "changed"
with pytest.raises(ValueError, match="binding changed"):
m.prepare_mixed(records, weights, old, new)
@pytest.mark.parametrize(
"fault",
[
"missing_proof",
"bad_hash",
"wrong_source",
"wrong_input",
"old_hash",
"extra",
"missing",
"duplicate",
"outside",
"no_evidence",
"flip",
"cached_target",
"unknown_weight",
"zero_weight",
"nan",
"wrong_record",
"duplicate_id",
],
)
def test_fail_closed_for_invalid_admission_or_provenance(fault):
records, weights, old, new = fixtures()
admission(records, new)
doc = proof(records, old)
p = doc["records"]["a"]
if fault == "wrong_source":
p["source"] = {}
elif fault == "wrong_input":
p["input"] = {}
elif fault == "old_hash":
p["old_target_sha256"] = "0" * 64
elif fault == "extra":
p["runs"].append([0, 0, 1])
elif fault == "missing":
p["runs"] = []
elif fault == "duplicate":
p["runs"].append([0, 1, 2])
elif fault == "outside":
p["runs"] = [[2, 0, 1]]
elif fault == "no_evidence":
doc["evidence"] = []
elif fault == "flip":
t = records[1]["target"].copy()
t[0, 0] = 0
new["b"]["targets"] = [target_view(t)]
elif fault == "cached_target":
records[1]["target"][0, 0] = 0
elif fault == "unknown_weight":
weights["b"][0, 1] = 0.1
elif fault == "zero_weight":
weights["b"][0, 0] = 0
elif fault == "nan":
weights["b"][0, 0] = np.nan
elif fault == "wrong_record":
records[1]["group"] = "g-other"
elif fault == "duplicate_id":
records[1]["sample_id"] = "a"
kw = kwargs(doc)
if fault == "missing_proof":
kw = {}
elif fault == "bad_hash":
kw["withdrawal_sha256"] = "0" * 64
with pytest.raises(ValueError):
m.prepare_mixed(records, weights, old, new, **kw)
def test_withdrawing_last_class_support_cannot_silently_discard_mass():
records, weights, old, new = fixtures()
records, old, new = records[2:], {"c": old["c"]}, {"c": new["c"]}
target = records[0]["target"].copy()
target[0, 0] = 255
new["c"]["targets"] = [target_view(target)]
doc = dict(
schema="missioncore.mixed-withdrawals/v1",
evidence=[dict(path="review.json", sha256="e" * 64)],
records={
"c": dict(
source=old["c"]["source"],
input=records[0]["input"],
old_target_sha256=m._sha(records[0]["target"].tobytes()),
runs=[[0, 0, 1]],
)
},
)
with pytest.raises(ValueError, match="baseline mass and final support"):
m.prepare_mixed(records, {"c": weights["c"]}, old, new, **kwargs(doc))
def test_target_view_order_does_not_choose_context_view():
records, weights, old, new = fixtures()
for entries in (old, new):
for entry in entries.values():
view = copy.deepcopy(entry["targets"][0])
view["view"] = "oblique"
entry["targets"].insert(0, view)
out, _, _ = m.prepare_mixed(records, weights, old, new)
for a, b in zip(records, out, strict=True):
np.testing.assert_array_equal(a["target"], b["target"])
new["a"]["targets"][-1]["size"] = [8, 1]
with pytest.raises(ValueError, match="dimensions differ"):
m.prepare_mixed(records, weights, old, new)
def test_new_class_without_baseline_mass_is_rejected():
records, weights, old, new = fixtures()
records = records[2:]
records[0]["target"][0, 0] = 0
old = {"c": old["c"]}
old["c"]["targets"] = [target_view(records[0]["target"])]
new = copy.deepcopy(old)
target = records[0]["target"].copy()
target[0, 2] = 1
new["c"]["targets"] = [target_view(target)]
with pytest.raises(ValueError, match="baseline mass and final support"):
m.prepare_mixed(records, {"c": weights["c"]}, old, new)
def test_paint_only_addition_preserves_background_weights_exactly():
records, weights, old, new = fixtures()
target = records[0]["target"].copy()
target[1, 0] = 1
new["a"]["targets"] = [target_view(target)]
out, ww, _ = m.prepare_mixed(records, weights, old, new)
for original, updated in zip(records, out, strict=True):
mask = updated["target"] == 0
np.testing.assert_array_equal(ww[original["name"]][mask], weights[original["name"]][mask])
+260
View File
@@ -0,0 +1,260 @@
import importlib.util
import sys
from pathlib import Path
import pytest
def load_module():
source = Path(__file__).parents[1] / "simulation/semantic-learning/native_detail.py"
if not source.exists():
source = Path(__file__).with_name("native_detail.py")
spec = importlib.util.spec_from_file_location("native_detail", source)
module = importlib.util.module_from_spec(spec)
# The standalone Worker package keeps native_detail and feature_refinement
# together; the repository tests import from their source directory instead.
sys.path.insert(0, str(source.parent))
try:
spec.loader.exec_module(module)
finally:
sys.path.pop(0)
return module
m = load_module()
def fixture():
t = pytest.importorskip("torch")
fine = t.arange(4 * 2 * 3).float().reshape(1, 4, 2, 3) / 20 - 0.5
coarse = t.linspace(-2, 2, 7 * 11).reshape(7, 11)
rgb = ((t.arange(3 * 7 * 11) * 17) % 101).float().reshape(1, 3, 7, 11) / 100
return t, fine, coarse, rgb
def test_network_shape_identity_seed_and_rng():
t, fine, coarse, rgb = fixture()
rng = t.random.get_rng_state().clone()
default = m.network(5)
assert sum(p.numel() for p in default.parameters()) == 25602
assert [layer.in_features for layer in default.layers] == [332, 65]
assert default.output.in_features == 65
a, b = m.network(12, channels=4), m.network(12, channels=4)
assert t.equal(rng, t.random.get_rng_state())
assert all(t.equal(p, q) for p, q in zip(a.parameters(), b.parameters(), strict=True))
for arm in sorted(m.ARMS):
got = m.predict(a, fine, coarse, rgb, arm, chunk=9)
assert t.equal(got, coarse)
def test_prepare_native_and_lowpass_have_same_shape_and_fixed_center():
t = pytest.importorskip("torch")
yy, xx = t.meshgrid(t.arange(8), t.arange(10), indexing="ij")
checker = ((yy + xx) % 2).float()[None, None].expand(1, 3, -1, -1).clone()
native = m.prepare_rgb(checker, (2, 5), "native_rgb")
lowpass = m.prepare_rgb(checker, (2, 5), "lowpass_rgb")
assert native.shape == lowpass.shape == checker.shape
assert t.equal(native, checker * 2 - 1)
assert t.equal(lowpass, t.zeros_like(lowpass))
assert not t.equal(native, lowpass)
for arm in m.ARMS:
constant = t.full((1, 3, 6, 8), 0.25)
t.testing.assert_close(m.prepare_rgb(constant, (2, 4), arm), constant - 0.75)
same_grid = m.prepare_rgb(checker, (8, 10), arm)
assert t.equal(same_grid, native)
def test_lowpass_matches_explicit_area_then_bilinear_on_noninteger_grid():
t, fine, _, rgb = fixture()
low = t.nn.functional.interpolate(rgb, size=fine.shape[-2:], mode="area")
expected = t.nn.functional.interpolate(
low, size=rgb.shape[-2:], mode="bilinear", align_corners=False
)
t.testing.assert_close(m.prepare_rgb(rgb, fine.shape[-2:], "lowpass_rgb"), expected * 2 - 1)
@pytest.mark.parametrize("shape", [(6, 8), (1, 1), (1, 4), (4, 1)])
def test_patch_rgb_order_centres_and_replicated_borders(shape):
t = pytest.importorskip("torch")
h, w = shape
image = t.arange(3 * h * w).double().reshape(1, 3, h, w) / (3 * h * w)
prepared = m.prepare_rgb(image, (1, 1), "native_rgb")
indices = t.tensor([0, (h // 2) * w + w // 2, h * w - 1], dtype=t.long)
actual = m.sample_patch(prepared, indices)
# Independent scalar lookup specifies the patch contract, including corners.
expected = []
for index in indices.tolist():
cy, cx = divmod(index, w)
expected.append([
prepared[0, channel, min(max(cy + dy, 0), h - 1), min(max(cx + dx, 0), w - 1)]
for channel in range(3) for dy in range(-2, 3) for dx in range(-2, 3)
])
assert t.equal(actual, t.tensor(expected, dtype=t.float64))
for channel in range(3):
t.testing.assert_close(
actual[:, channel * 25 + 12], prepared[0, channel].flatten()[indices]
)
def test_rotate_patch_keeps_channels_and_rotates_spatial_axes_only():
t = pytest.importorskip("torch")
patch = t.arange(75).float().reshape(1, 75) / 75
for k in range(4):
rotated = m.rotate_patch(patch, k).reshape(1, 3, 5, 5)
original = patch.reshape(1, 3, 5, 5)
for channel in range(3):
assert t.equal(rotated[:, channel], t.rot90(original[:, channel], k, (-2, -1)))
assert t.equal(rotated[:, :, 2, 2], original[:, :, 2, 2])
repeated = patch
for _ in range(4):
repeated = m.rotate_patch(repeated, 1)
assert t.equal(repeated, patch)
for bad in [-1, 4, 1.0, True]:
with pytest.raises(ValueError):
m.rotate_patch(patch, bad)
def test_sample_points_fine_alignment_coarse_centres_and_empty_indices():
t, fine, coarse, rgb = fixture()
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
indices = t.tensor([0, 4, 20, coarse.numel() - 1], dtype=t.long)
ff, cc, pp = m.sample_points(fine, coarse, prepared, indices)
expected_fine = t.nn.functional.interpolate(
fine, size=coarse.shape, mode="bilinear", align_corners=False
)[0].flatten(1).T[indices]
t.testing.assert_close(ff, expected_fine, atol=2e-6, rtol=1e-6)
assert t.equal(cc[:, 0], coarse.flatten()[indices])
assert t.equal(pp, m.sample_patch(prepared, indices))
empty = m.sample_points(fine, coarse, prepared, t.empty(0, dtype=t.long))
assert [value.shape for value in empty] == [(0, 4), (0, 1), (0, 75)]
assert m.sample_patch(prepared, t.empty(0, dtype=t.long)).shape == (0, 75)
@pytest.mark.parametrize("arm", ["native_rgb", "lowpass_rgb"])
def test_prediction_c4_equivariance_chunking_and_explicit_logit_average(arm):
t, fine, coarse, rgb = fixture()
net = m.network(8, channels=4, width=8)
with t.no_grad():
net.output.weight.copy_(t.linspace(-0.2, 0.2, 9).reshape(1, 9))
net.output.bias.fill_(0.1)
expected = m.predict(net, fine, coarse, rgb, arm, chunk=coarse.numel())
assert not t.equal(expected, coarse)
for chunk in [1, 13, 200]:
actual = m.predict(net, fine, coarse, rgb, arm, chunk=chunk)
t.testing.assert_close(actual, expected, atol=2e-6, rtol=1e-6)
for k in range(4):
actual = m.predict(
net, t.rot90(fine, k, (-2, -1)), t.rot90(coarse, k),
t.rot90(rgb, k, (-2, -1)), arm, chunk=13,
)
t.testing.assert_close(t.rot90(actual, -k), expected, atol=3e-6, rtol=1e-6)
prepared = m.prepare_rgb(rgb, fine.shape[-2:], arm)
points, logits, patches = m.sample_points(fine, coarse, prepared, t.arange(coarse.numel()))
with t.no_grad():
four = [net(points, logits, m.rotate_patch(patches, k)) for k in range(4)]
explicit_mean = t.stack(four).mean(0).reshape(coarse.shape)
t.testing.assert_close(expected, explicit_mean, atol=2e-6, rtol=1e-6)
def test_head_parameters_get_gradients_but_inputs_stay_frozen():
t, fine, coarse, rgb = fixture()
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
points = m.sample_points(fine, coarse, prepared, t.tensor([0, 11, 44]))
net = m.network(3, channels=4, width=8)
loss = net(*points).square().mean()
loss.backward()
assert net.output.weight.grad is not None
assert float(net.output.weight.grad.abs().sum()) > 0
assert all(
not value.requires_grad and value.grad is None for value in (*points, fine, coarse, rgb)
)
for index in range(3):
bad = list(points)
bad[index] = bad[index].clone().requires_grad_(True)
with pytest.raises(ValueError, match="frozen"):
net(*bad)
@pytest.mark.parametrize("bad", ["fine_channels", "coarse_shape", "patch_shape", "patch_nan"])
def test_head_rejects_invalid_point_shapes_and_nonfinite_patches(bad):
t, fine, coarse, rgb = fixture()
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
ff, cc, pp = m.sample_points(fine, coarse, prepared, t.tensor([0, 1]))
if bad == "fine_channels":
ff = ff[:, :-1]
elif bad == "coarse_shape":
cc = cc[:, 0]
elif bad == "patch_shape":
pp = pp[:, :-1]
else:
pp[0, 0] = float("nan")
with pytest.raises(ValueError):
m.network(1, channels=4, width=8)(ff, cc, pp)
@pytest.mark.parametrize("bad", [
"rgb_shape", "rgb_negative", "rgb_above_one", "rgb_nan", "rgb_dtype", "rgb_gradient",
"fine_shape", "fine_nan", "fine_gradient", "coarse_shape", "coarse_inf",
"coarse_gradient", "dtype_mismatch", "arm", "chunk",
])
def test_predict_rejects_invalid_maps(bad):
t, fine, coarse, rgb = fixture()
net = m.network(1, channels=4, width=8)
arm, chunk = "native_rgb", 9
if bad == "rgb_shape":
rgb = rgb[:, :2]
elif bad == "rgb_negative":
rgb[0, 0, 0, 0] = -0.1
elif bad == "rgb_above_one":
rgb[0, 0, 0, 0] = 1.1
elif bad == "rgb_nan":
rgb[0, 0, 0, 0] = float("nan")
elif bad == "rgb_dtype":
rgb = (rgb * 255).to(t.uint8)
elif bad == "rgb_gradient":
rgb.requires_grad_(True)
elif bad == "fine_shape":
fine = fine[0]
elif bad == "fine_nan":
fine[0, 0, 0, 0] = float("nan")
elif bad == "fine_gradient":
fine.requires_grad_(True)
elif bad == "coarse_shape":
coarse = coarse[:, :-1]
elif bad == "coarse_inf":
coarse[0, 0] = float("inf")
elif bad == "coarse_gradient":
coarse.requires_grad_(True)
elif bad == "dtype_mismatch":
coarse = coarse.double()
elif bad == "arm":
arm = "scene_specific"
else:
chunk = 0
with pytest.raises(ValueError):
m.predict(net, fine, coarse, rgb, arm, chunk)
@pytest.mark.parametrize("bad", ["negative", "outside", "dtype", "shape"])
def test_patch_rejects_invalid_native_indices(bad):
t, fine, coarse, rgb = fixture()
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
indices = t.tensor([0], dtype=t.long)
if bad == "negative":
indices[0] = -1
elif bad == "outside":
indices[0] = coarse.numel()
elif bad == "dtype":
indices = indices.float()
else:
indices = indices[None]
with pytest.raises(ValueError):
m.sample_patch(prepared, indices)
@pytest.mark.parametrize("shape", [(0, 1), (2,), (2.0, 3), (True, 2), (8, 2)])
def test_prepare_rejects_invalid_or_upsampling_feature_grid(shape):
_, _, _, rgb = fixture()
with pytest.raises(ValueError):
m.prepare_rgb(rgb, shape, "lowpass_rgb")
+66
View File
@@ -0,0 +1,66 @@
import importlib.util
from pathlib import Path
import numpy as np
import pytest
p = Path(__file__).resolve().parents[1]/"simulation/semantic-learning/native_sliding.py"
s = importlib.util.spec_from_file_location("native_sliding", p)
m = importlib.util.module_from_spec(s)
s.loader.exec_module(m)
def test_native_placement_and_irregular_last_tiles():
rgb = np.zeros((5, 7, 3), np.uint8)
rgb[:, :, 0] = np.arange(35).reshape(5, 7)
out, meta = m.sliding_logits(rgb, lambda a: np.stack([a[:, :, 0], a[:, :, 0]]).astype(float),
tile=4, stride=2)
np.testing.assert_array_equal(out[0], rgb[:, :, 0])
assert meta["tiles"] == 6 and meta["minimum_overlap"] == 1
def test_logits_uniformly_average_overlaps_before_activation():
rgb = np.zeros((5, 7, 3), np.uint8)
rgb[:, :, 0] = np.arange(7)
out, _ = m.sliding_logits(rgb, lambda a: np.full((2, 4, 4), a[0, 0, 0], np.float32),
tile=4, stride=2)
np.testing.assert_allclose(out[0], np.tile([0, 0, 1, 5/3, 2.5, 2.5, 3], (5, 1)))
def test_small_image_padding_does_not_change_native_extent():
rgb = np.full((2, 3, 3), 7, np.uint8)
def predict(a):
assert a.shape == (4, 4, 3)
assert not a[2:].any() and not a[:, 3:].any()
return np.stack([a[:, :, 0], a[:, :, 0]]).astype(np.float32)
out, meta = m.sliding_logits(rgb, predict, tile=4, stride=2)
assert out.shape == (2, 2, 3) and (out == 7).all() and meta["tiles"] == 1
@pytest.mark.parametrize("output", [np.full((2, 4, 4), np.nan), np.zeros((2, 3, 4))])
def test_bad_prediction_refused(output):
with pytest.raises(ValueError, match="finite native"):
m.sliding_logits(np.zeros((4, 4, 3), np.uint8), lambda _: output, tile=4, stride=2)
def test_resource_or_stride_rejection_before_predictor():
def fail(_):
raise AssertionError("Must reject before inference")
a = np.zeros((5, 7, 3), np.uint8)
for options in [dict(max_pixels=4), dict(tile=4, stride=2, max_tiles=1),
dict(tile=4, stride=5)]:
with pytest.raises(ValueError):
m.sliding_logits(a, fail, **options)
def test_declared_1024_recipe_has_nine_native_tiles():
assert m.starts(1024, 512, 256) == [0, 256, 512]
def test_oversized_tile_and_grid_rejected_before_allocation():
def fail(_):
raise AssertionError("Must not run predictor")
with pytest.raises(ValueError, match="Tile working budget"):
m.sliding_logits(np.zeros((2, 3, 3), np.uint8), fail, tile=100000, stride=256)
with pytest.raises(ValueError, match="Tile grid budget"):
m.starts(1000000, 2, 1, limit=256)
+116
View File
@@ -0,0 +1,116 @@
import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
from nested_calibration import calibrate_inner, nested_folds
GROUPS = ["a", "b", "c", "d"]
def rows():
out = []
for p in nested_folds(GROUPS):
if p["outer"] != "a":
continue
out.append(
dict(
group=p["inner"],
training_groups=p["training_groups"],
initialization_groups=p["training_groups"],
split="train",
sample_ids=[p["inner"]],
old=np.array([2.0, -1.0, -2.0, 99.0]),
new=np.array([1.0, -2.0, -3.0, 100.0]),
paint=np.array([True, False, False, False]),
original_bg=np.array([False, True, False, False]),
added_bg=np.array([False, False, True, False]),
)
)
return out
def test_nested_folds_no_leakage_and_reusable_fit_sets():
plans = nested_folds(GROUPS)
assert len(plans) == 12
assert len({tuple(p["training_groups"]) for p in plans}) == 6
for p in plans:
assert set(p["training_groups"]) == set(GROUPS) - {p["outer"], p["inner"]}
def test_common_threshold_ties_and_unknown_excluded():
rs = rows()
rs[0]["new"] = np.array([1.0, 1.0, -3.0, 100.0])
result = calibrate_inner(rs, "a", GROUPS)
assert result["new"]["threshold"] is None
assert result["new"]["counts"]["paint"] == 0
assert result["old"]["counts"]["paint"] == 3
def test_uniform_shift_changes_threshold_not_predictions():
rs = rows()
for r in rs:
r["new"] = r["old"] - 4
out = calibrate_inner(rs, "a", GROUPS)
assert out["new"]["threshold"] == out["old"]["threshold"] - 4
assert out["new"]["counts"] == out["old"]["counts"]
@pytest.mark.parametrize("field", ["training_groups", "initialization_groups"])
def test_excluded_street_in_fit_or_normalization_rejected(field):
rs = rows()
rs[0][field] = ["a", "c"]
with pytest.raises(ValueError, match="exclude both"):
calibrate_inner(rs, "a", GROUPS)
@pytest.mark.parametrize("mutation", ["missing", "duplicate", "outer", "control", "duplicate_id"])
def test_bad_calibration_membership_rejected(mutation):
rs = rows()
if mutation == "missing":
rs.pop()
elif mutation == "duplicate":
rs[1] = rs[0]
elif mutation == "outer":
rs[0]["group"] = "a"
elif mutation == "control":
rs[0]["split"] = "regression"
else:
rs[1]["sample_ids"] = rs[0]["sample_ids"]
with pytest.raises(ValueError):
calibrate_inner(rs, "a", GROUPS)
def test_exact_threshold_matches_independent_bruteforce():
rng = np.random.default_rng(123)
for _ in range(30):
rs = rows()
for r in rs:
r["old"] = rng.integers(-4, 5, 4).astype(float)
r["new"] = rng.integers(-4, 5, 4).astype(float)
out = calibrate_inner(rs, "a", GROUPS)
for origin in ["old", "new"]:
candidates = sorted(
{np.inf} | {float(v) for r in rs for v in r[origin][:3]}, reverse=True
)
valid = [
t
for t in candidates
if all(
int(np.count_nonzero((r[origin] >= t) & r[k]))
<= int(np.count_nonzero((r["old"] >= 0) & r[k]))
for r in rs
for k in ["original_bg", "added_bg"]
)
]
expected = valid[-1]
assert out[origin]["threshold"] == (None if np.isinf(expected) else expected)
def test_invalid_masks_rejected():
rs = rows()
rs[0]["added_bg"] = rs[0]["paint"]
with pytest.raises(ValueError):
calibrate_inner(rs, "a", GROUPS)
+122
View File
@@ -0,0 +1,122 @@
"""Safety and scientific-isolation checks for the offline assembly study."""
import copy
import importlib
import sys
from pathlib import Path
import pytest
np = pytest.importorskip("numpy")
pytest.importorskip("cv2")
pytest.importorskip("shapely")
pytest.importorskip("scipy")
ROOT = Path(__file__).resolve().parents[1]
for directory in [
"simulation/semantic-learning",
"simulation/urban-plan-research/systematic",
"simulation/urban-plan-research/marking_pass",
]:
sys.path.insert(0, str(ROOT / directory))
from shapely.geometry import box, mapping, shape # noqa: E402
from shapely.ops import unary_union # noqa: E402
study = importlib.import_module("object_assembly_study")
def policy():
return dict(
mpp=12 / 512,
min_length=0.35,
max_length=12,
min_width=0.045,
max_width=1.2,
min_aspect=2,
min_fill=0.4,
max_pair_angle_deg=6,
max_pair_lateral_fraction=0.25,
max_pair_width_ratio=1.8,
max_join_gap=0.15,
max_group=12,
min_group_fill=0.55,
min_total_weak_paint=0.85,
min_added_weak_paint=0.9,
min_physical_valid=0.97,
)
def candidate(poly, name, value=1):
return dict(id=name, geometry=mapping(poly), features=[value] * 22, fixed_admitted=True)
def test_supported_bridge_requires_observation_and_physical_validity():
source = unary_union([box(100, 100, 150, 110), box(154, 100, 204, 110)])
valid = np.ones((512, 512), bool)
weak = valid.copy()
fitted, verdict = study.supported_envelope(source, weak, valid, policy())
assert verdict == "supported"
assert fitted.bounds == source.bounds
weak[100:111, 151:154] = False
assert study.supported_envelope(source, weak, valid, policy())[1] == "added_paint"
valid[100:111, 149:155] = False
assert study.supported_envelope(source, np.ones_like(valid), valid, policy())[1] == "physical"
def test_exact_union_preserves_holes_and_original_candidates():
p = box(100, 100, 180, 110).difference(box(130, 102, 140, 108))
q = box(160, 100, 204, 110)
original = [candidate(p, "p"), candidate(q, "q")]
snapshot = copy.deepcopy(original)
rgb = np.full((512, 512, 3), 180, np.uint8)
fields = {
k: np.zeros((512, 512), np.float32)
for k in ["vehicle", "road", "roadway", "sidewalk", "road marking", "crosswalk"]
}
fields["alpha"] = np.ones((512, 512), np.float32)
out, _ = study.assemble(original, rgb, fields, policy())
unions = [
shape(c["geometry"]) for c in out if c.get("properties", {}).get("kind") == "exact_union"
]
assert len(unions) == 1
assert unions[0].symmetric_difference(p.union(q)).area < 1e-8
assert len(unions[0].interiors) == 1
assert original == snapshot
assert [c["id"] for c in out[:2]] == ["p", "q"]
def test_adjacent_crosswalk_bars_are_not_joined():
p, q = box(100, 100, 300, 110), box(100, 116, 300, 126)
assert not study.pair_allowed(
p, q, study.rectangle(p, 12 / 512), study.rectangle(q, 12 / 512), policy()
)
def test_merged_reference_objects_are_counted_even_with_one_match():
p, q = box(0, 0, 10, 100), box(12, 0, 22, 100)
review = {"objects": [dict(geometry=mapping(t), complete=True) for t in [p, q]]}
assert study.merged_count([candidate(p.union(q).convex_hull, "bad")], review) == 1
assert study.merged_count([candidate(p, "p"), candidate(q, "q")], review) == 0
def test_control_geometry_and_labels_cannot_change_fit_or_selection():
records, review = [], {}
for split in ["train", "validation", "heldout"]:
cs = [
candidate(box(10 + i * 20, 10, 20 + i * 20, 30), str(i), float(i % 2)) for i in range(6)
]
variants = {
k: copy.deepcopy(cs) for k in ["retained_on", "retained_off", "hard_off", "hard_on"]
}
records.append(dict(id=split, split=split, variants=variants))
review[split] = dict(
objects=[
dict(id=str(i), family="stripe", complete=True, geometry=cs[i]["geometry"])
for i in [1, 3, 5]
],
negative=[[(0, 0), (200, 0), (200, 100), (0, 100)]],
)
first = study.fit_models(records, review, [0.1, 0.5, 0.9])
records[-1]["variants"] = {"unreadable": "never accessed"}
review["heldout"] = {"corrupted": True}
second = study.fit_models(records, review, [0.1, 0.5, 0.9])
assert first == second
+106
View File
@@ -0,0 +1,106 @@
"""Focused checks for the offline object study and opt-in proposal policy."""
import importlib.util
import sys
from pathlib import Path
import pytest
np = pytest.importorskip("numpy")
cv2 = pytest.importorskip("cv2")
pytest.importorskip("shapely")
pytest.importorskip("scipy")
ROOT = Path(__file__).resolve().parents[1]
for path in [
ROOT / "simulation/semantic-learning",
ROOT / "simulation/urban-plan-research/systematic",
ROOT / "simulation/urban-plan-research/marking_pass",
]:
sys.path.insert(0, str(path))
spec = importlib.util.spec_from_file_location(
"object_study_test", ROOT / "simulation/semantic-learning/object_proposal_study.py"
)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
from shapely.geometry import box, mapping # noqa: E402
def candidate(poly, **kw):
return dict(geometry=mapping(poly), **kw)
def test_unknown_is_never_a_negative():
review = dict(
objects=[dict(geometry=mapping(box(0, 0, 1, 1)), complete=True, id="p", family="stripe")],
negative=[[(3, 3), (5, 3), (5, 5), (3, 5)]],
)
cs = [candidate(box(0, 0, 1, 1)), candidate(box(3.2, 3.2, 4, 4)), candidate(box(8, 8, 9, 9))]
assert m.labels(cs, review).tolist() == [1, 0, -1]
def test_one_proposal_cannot_recall_two_objects():
review = dict(
objects=[
dict(geometry=mapping(box(0, 0, 1, 1)), complete=True, id=str(i), family="stripe")
for i in range(2)
],
negative=[],
)
assert m.matched([candidate(box(0, 0, 1, 1))], review)["found"] == 1
def test_heldout_cannot_change_model_or_selection():
review, records = {}, []
for split in ["train", "validation", "heldout"]:
objects = [
dict(
geometry=mapping(box(i * 3, 0, i * 3 + 1, 1)),
complete=True,
id=str(i),
family="stripe",
)
for i in range(2)
]
review[split] = dict(objects=objects, negative=[[(0, 3), (6, 3), (6, 6), (0, 6)]])
cs = [
candidate(box(i * 3, 0, i * 3 + 1, 1), features=[1 + i * 0.1] * 19, fixed_admitted=True)
for i in range(2)
]
cs += [
candidate(
box(i * 3, 4, i * 3 + 1, 5), features=[-1 - i * 0.1] * 19, fixed_admitted=False
)
for i in range(2)
]
records.append(dict(id=split, split=split, variants=dict(hard=cs, retained=cs)))
a = m.fit_models(records, review, [0.1, 0.5, 0.9])
review["heldout"] = None
b = m.fit_models(records, review, [0.1, 0.5, 0.9])
assert a == b
def test_retaining_context_does_not_bypass_physical_validity():
image = np.full((512, 512, 3), 45, np.uint8)
image[245:253, 100:400] = 210
zero = np.zeros((512, 512), np.float32)
g = dict(
view=np.array([[1, 0, 0, -6], [0, -1, 0, 6], [0, 0, -1, 10], [0, 0, 0, 1]], float),
intrinsics=np.array([[100, 0, 600], [0, 100, 600], [0, 0, 1]], float),
)
args = (
image,
zero,
g,
zero,
zero,
np.zeros((120, 120), bool),
[0, 0],
[12, 12],
{"id": "test"},
np.full((120, 120), 100.0),
)
assert m.collect(*args, span_m=12) == ([], [])
assert m.collect(*args, span_m=12, retain_uncertain=True)[0]
assert m.collect(*args, span_m=12, retain_uncertain=True, valid=zero) == ([], [])
with pytest.raises(ValueError):
m.collect(*args, span_m=0)
+206
View File
@@ -0,0 +1,206 @@
"""Checkable partial-support paths; no implicit topology through unknown/exterior."""
import importlib.util
import json
from pathlib import Path
import numpy as np
import pytest
spec = importlib.util.spec_from_file_location(
"topology_test", Path(__file__).parents[1] / "simulation/semantic-learning/observed_topology.py"
)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
def pair():
t = np.zeros((5, 7), np.uint8)
left, right, gap = (np.zeros(t.shape, bool) for _ in range(3))
left[2, 1] = right[2, 5] = True
gap[2, 2:5] = True
t[left | right] = 1
p = np.zeros(t.shape, np.float32)
p[2, 1:6] = 1
return p, t, dict(left=left, right=right), [dict(left="left", right="right", gap=gap)]
def run(args, **kw):
return m.audit_topology(
*args, roi=kw.pop("roi", [0, 0, 7, 5]), connectivity=kw.pop("connectivity", 4), **kw
)
def test_confirmed_bridge_with_unknown_bypass_is_still_known_witness():
args = pair()
p, t, _, _ = args
t[1, 1:6] = 255
p[1, 1:6] = 1
before = [x.copy() for x in (p, t)]
result = run(args)
row = result["relations"][0]
assert row["status"] == "confirmed_known_support_bridge"
assert row["witness"] == [[x, 2] for x in range(1, 6)]
assert row["witness_unknown_pixels"] == 0
assert not row["full_object_merge_assessed"]
assert np.array_equal(p, before[0]) and np.array_equal(t, before[1])
json.dumps(result) # Public result must be plain JSON data.
def test_unknown_connection_requires_predicted_paint_on_unknown():
args = pair()
p, t, _, rel = args
t[2, 3] = 255
rel[0]["gap"][2, 3] = False
row = run(args)["relations"][0]
assert row["status"] == "indeterminate_unknown_connection"
assert row["witness_unknown_pixels"] == 1
p[2, 3] = 0
assert run(args)["relations"][0]["status"] == "no_connection_within_reviewed_corridor"
def test_missing_endpoint_never_proves_separation():
args = pair()
args[0][2, 1] = 0
result = run(args)
assert result["relations"][0]["status"] == "unassessed_missing_predicted_endpoint"
assert result["cores"][0]["fully_missed_original_components"] == 1
def test_exterior_bypass_is_not_an_inside_roi_connection():
args = pair()
p, t, _, rel = args
p[2, 3] = 0
p[1, 1:6] = 1
t[1, 1:6] = 255
row = run(args, roi=[0, 2, 7, 3])["relations"][0]
assert row["status"] == "no_connection_within_reviewed_corridor"
assert row["exterior_connection_assessed"] is False
def test_diagonal_is_explicitly_four_vs_eight_connectivity():
p, t, cores, relations = pair()
t[:] = 0
p[:] = 0
for mask in cores.values():
mask[:] = False
cores["left"][1, 1] = cores["right"][3, 3] = True
t[cores["left"] | cores["right"]] = 1
relations[0]["gap"][:] = False
relations[0]["gap"][2, 2] = True
p[1, 1] = p[2, 2] = p[3, 3] = 1
assert run((p, t, cores, relations), connectivity=4)["relations"][0]["witness"] is None
assert (
run((p, t, cores, relations), connectivity=8)["relations"][0]["status"]
== "confirmed_known_support_bridge"
)
def test_core_adjacency_without_background_is_not_false_bridge():
p, t, cores, relations = pair()
cores["right"][:] = False
cores["right"][2, 2] = True
t[2, 5] = 0
t[2, 2] = 1
relations[0]["gap"][2, 2] = False
assert (
run((p, t, cores, relations))["relations"][0]["status"]
== "unassessed_core_adjacency_without_background"
)
def test_fragmentation_is_per_original_known_component():
t = np.zeros((5, 7), np.uint8)
t[2, 1:6] = 1
p = (t == 1).astype(np.float32)
p[2, 3] = 0
core = t == 1
result = run((p, t, {"line": core}, []))["cores"][0]
assert result["fragmented_original_components"] == 1
assert result["known_core_fragmentation_witness"] == [[x, 2] for x in range(2, 5)]
assert result["full_object_split_assessed"] is False
t[2, 3] = 255
core[2, 3] = False
row = run((p, t, {"line": core}, []))["cores"][0]
assert row["original_components"] == 2 and row["recovered_components"] == 2
assert row["fragmented_original_components"] == 0
p[:] = 0
row = run((p, t, {"line": core}, []))["cores"][0]
assert row["fully_missed_original_components"] == 2
assert row["known_core_fragmentation_witness"] is None
@pytest.mark.parametrize(
"error",
[
"nan",
"range",
"shape",
"target",
"core_unknown",
"gap_paint",
"overlap",
"outside",
"duplicate",
],
)
def test_invalid_support_rejected(error):
p, t, cores, relations = pair()
kwargs = {}
if error == "nan":
p[0, 0] = np.nan
elif error == "range":
p[0, 0] = 1.1
elif error == "shape":
p = p[:-1]
elif error == "target":
t = t.astype(np.int64)
elif error == "core_unknown":
t[2, 1] = 255
elif error == "gap_paint":
relations[0]["gap"][2, 1] = True
elif error == "overlap":
cores["right"][2, 1] = True
elif error == "outside":
kwargs["roi"] = [0, 0, 4, 5]
elif error == "duplicate":
relations *= 2
with pytest.raises(ValueError):
run((p, t, cores, relations), **kwargs)
@pytest.mark.parametrize(
"kwargs", [dict(max_nodes=1), dict(max_path=2), dict(connectivity=6), dict(roi=[0, 0, 8, 5])]
)
def test_bounds_refuse_without_truncated_confirmed_witness(kwargs):
with pytest.raises(ValueError):
run(pair(), **kwargs)
def test_many_original_components_do_not_overflow_int32_pair_ids():
y, x = np.indices((384, 384))
core = (x + y) % 2 == 0
target = core.astype(np.uint8)
result = m.audit_topology(
target.astype(np.float32), target, {"many": core}, [], roi=[0, 0, 384, 384], connectivity=4
)
row = result["cores"][0]
assert row["original_components"] == row["recovered_components"] == 73728
assert row["fragmented_original_components"] == row["fully_missed_original_components"] == 0
def test_outside_core_bypass_does_not_erase_local_fragmentation():
target = np.zeros((5, 7), np.uint8)
target[2, 1:6] = 1
core = target == 1
probability = core.astype(np.float32)
probability[2, 3] = 0 # A genuine FN cuts the recovered known-positive core.
probability[1, 1:6] = 1 # Predicted paint reconnects it through known BG.
bypass = [(1, 2), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (5, 2)]
assert all(probability[y, x] == 1 for x, y in bypass)
row = run((probability, target, {"line": core}, []))["cores"][0]
assert row["original_components"] == 1 and row["recovered_components"] == 2
assert row["fragmented_original_components"] == 1
assert row["full_object_split_assessed"] is False
witness = row["known_core_fragmentation_witness"]
assert [3, 2] in witness and all(core[y, x] for x, y in witness)
+73
View File
@@ -0,0 +1,73 @@
import importlib.util
from pathlib import Path
import numpy as np
import pytest
p = Path(__file__).resolve().parents[1]/"simulation/semantic-learning/paint_comparison.py"
s = importlib.util.spec_from_file_location("paint_comparison", p)
m = importlib.util.module_from_spec(s)
s.loader.exec_module(m)
def fixture():
t = np.zeros((12, 16), np.uint8)
t[:, :2] = 255
objs = []
for i, x in enumerate([3, 10]):
t[2:10, x:x+3] = 1
objs.append(dict(id=str(i), outline_native_pixels=[[x,2],[x+2,2],[x+2,9],[x,9]],
final_paint_pixels=24, kind="observed_crosswalk_bar",
semantic_group="one", visibility="complete_in_view"))
return t, objs
def test_unknown_does_not_change_errors_or_create_instance_split():
t, objs = fixture()
t[5, 3:6] = 255
objs[0]["final_paint_pixels"] -= 3
a = (t == 1).astype(float)
before = m.score(a, t, objs)
a[t == 255] = 1
after = m.score(a, t, objs)
for key in ["tp", "fn", "fp", "tn", "observations", "gaps"]:
assert before[key] == after[key]
assert after["fn"] == after["fp"] == 0
assert "instance_merge_split" in after["not_assessed"]
def test_gap_is_known_background_only_and_not_merge_claim():
t, objs = fixture()
t[5, 6:10] = 255
p = np.ones_like(t, float)
got = m.score(p, t, objs)
assert got["gaps"][0]["background_pixels"] == 28
assert got["gaps"][0]["fp"] == 28
assert "instance_merge_split" in got["not_assessed"]
def test_partial_line_unknown_gap_not_assessed():
t, objs = fixture()
for o in objs:
o["kind"] = "observed_line_fragment"
assert not m.score((t == 1).astype(float), t, objs)["gaps"]
def test_corrupt_core_or_native_prediction_rejected():
t, objs = fixture()
objs[0]["final_paint_pixels"] += 1
with pytest.raises(ValueError):
m.score(np.zeros_like(t, float), t, objs)
with pytest.raises(ValueError):
m.score(np.zeros((2, 2)), t, [])
with pytest.raises(ValueError):
m.score(np.full_like(t, np.nan, dtype=float), t, [])
def test_paired_errors_exclude_unknown_and_reconcile():
t, objs = fixture()
b = (t == 1).astype(float)
a = 1-b
a[t == 255] = 1
got=m.paired_changes(a,b,t)
assert got==dict(new_fn=48,recovered_fn=0,new_fp=120,removed_fp=0)
+69
View File
@@ -0,0 +1,69 @@
"""Checks for isolation, ignored pixels, fixed comparator, and spatial limits."""
import importlib
import importlib.util
import sys
import unittest
from pathlib import Path
import numpy as np
if importlib.util.find_spec("cv2") is None:
raise unittest.SkipTest("Scientific checks run in the pinned Worker image")
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
probe = importlib.import_module("paint_evidence_probe")
class PaintEvidenceTests(unittest.TestCase):
def test_unknown_pixels_do_not_change_score(self):
pos = np.zeros((8, 8), bool)
pos[1, 1] = True
neg = np.zeros_like(pos)
neg[6, 6] = True
a = pos.copy()
b = np.ones_like(pos)
b[6, 6] = False
self.assertEqual(probe.counts(a, pos, neg), probe.counts(b, pos, neg))
def test_conflicting_review_rejected(self):
with self.assertRaises(AssertionError):
probe.probe_masks(
dict(positive=[[[1, 1], [5, 5]]], negative=[[[0, 0], [10, 0], [10, 10], [0, 10]]])
)
def test_threshold_uses_validation_false_positive_limit(self):
probability = np.array([[0.9, 0.7, 0.65, 0.2]])
positive = np.array([[True, True, False, False]])
negative = ~positive
threshold, _ = probe.choose_threshold(
[(probability, positive, negative)], [0.5, 0.6, 0.7, 0.8]
)
self.assertEqual(threshold, 0.7)
def test_spatial_filter_cannot_invent_empty_line(self):
mask = np.zeros((64, 64), bool)
self.assertFalse(probe.spatial_rule(mask).any())
mask[30:33, 5:20] = True
mask[30:33, 40:59] = True
out = probe.spatial_rule(mask)
self.assertFalse(out[:, 23:37].any())
self.assertTrue(out[31, 10])
def test_uniform_brightness_is_not_fixed_paint_evidence(self):
_, mask, _ = probe.features(np.full((64, 64, 3), 180, np.uint8))
self.assertFalse(mask.any())
def test_pixel_features_do_not_encode_position(self):
image = np.full((80, 80, 3), 110, np.uint8)
a, fixed, names = probe.features(image)
b, other, other_names = probe.features(image)
np.testing.assert_array_equal(a, b)
np.testing.assert_array_equal(fixed, other)
self.assertEqual(names, other_names)
self.assertEqual(a.shape, (80, 80, 10))
np.testing.assert_array_equal(a[30, 30], a[40, 40])
if __name__ == "__main__":
unittest.main()
+222
View File
@@ -0,0 +1,222 @@
"""Exact observed paint survives a supported editor path; lossy cases fail closed."""
import copy
import importlib
import json
import sys
from pathlib import Path
import pytest
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits, apply_operations
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore
np = pytest.importorskip("numpy")
pytest.importorskip("shapely", minversion="2.0")
from shapely import affinity # noqa: E402
from shapely.geometry import Polygon, box, shape # noqa: E402
from shapely.ops import unary_union # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
geometry = importlib.import_module("paint_geometry")
gate = importlib.import_module("geometry_contract_gate")
IDENTITY = [1, 0, 0, 1, 0, 0]
def proposal(labels, matrix=IDENTITY):
return geometry.vectorize(labels, pixel_to_scene=matrix, source_id="synthetic-test-only")
def lifted(p):
return geometry.editor_features(
p, height_at=lambda xy: 2 + .01 * xy[:, 0], height_source="synthetic-known-plane"
)
def test_all_512_three_by_three_masks_are_exact():
# Exhaustive small topology oracle, independent of run polygonization.
for bits in range(512):
labels = np.array([(bits >> k) & 1 for k in range(9)], dtype=np.uint8).reshape(3, 3)
p = proposal(labels)
union = unary_union([shape(f["geometry"]) for f in p["features"]])
assert union.area == np.count_nonzero(labels)
assert np.array_equal(gate.rasterize(p["features"], labels.shape, IDENTITY), labels == 1)
@pytest.mark.parametrize("matrix", [IDENTITY, [.2, .03, .04, -.3, 123.25, -72.125]])
def test_unknown_holes_gap_and_affine_pixel_edges(matrix):
labels = np.zeros((9, 13), np.uint8)
labels[1:8, 1:5] = 1
labels[3, 2] = 255
labels[4, 3] = 0
labels[1:8, 6:12] = 1
p = proposal(labels, matrix)
assert len(p["features"]) == 2
polys = [shape(f["geometry"]) for f in p["features"]]
assert sum(len(poly.interiors) for poly in polys) == 2
det = abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])
assert sum(poly.area for poly in polys) == pytest.approx(np.count_nonzero(labels == 1) * det)
assert np.array_equal(gate.rasterize(p["features"], labels.shape, matrix), labels == 1)
single = shape(proposal([[1]], matrix)["features"][0]["geometry"])
assert single.equals(affinity.affine_transform(box(0, 0, 1, 1), matrix))
assert p == proposal(labels.copy(), matrix)
assert p["source_sha256"] != proposal(labels, [1, 0, 0, 1, 1, 0])["source_sha256"]
def test_empty_unknown_diagonal_and_edge_connectivity():
for value in [0, 255]:
p = proposal(np.full((3, 3), value, dtype=np.uint8))
assert p["features"] == []
assert lifted(p) == []
assert len(proposal([[1, 0], [0, 1]])["features"]) == 2
assert len(proposal([[1, 1], [0, 1]])["features"]) == 1
def test_support_flags_never_claim_complete_instances():
labels = np.zeros((6, 12), np.uint8)
labels[2:4, :3] = 1
labels[2:4, 7:9] = 1
labels[:, 9:] = 255
p = proposal(labels)
assert sorted(f["properties"]["support_boundary"] for f in p["features"]) == [
["tile-edge"], ["unknown-support"]
]
assert all(f["properties"]["instance_completeness"] == "not-assessed" for f in p["features"])
def test_point_touching_hole_preserved_but_editor_refuses():
p = proposal([[1, 1, 1], [1, 0, 1], [1, 1, 0]])
assert sum(shape(f["geometry"]).area for f in p["features"]) == 7
assert np.array_equal(gate.rasterize(p["features"], (3, 3), IDENTITY),
np.array([[1, 1, 1], [1, 0, 1], [1, 1, 0]], bool))
with pytest.raises(ValueError, match="пересекаются|самопересечение"):
lifted(p)
@pytest.mark.parametrize("labels,matrix", [
([[2]], IDENTITY), ([[1.0]], IDENTITY), ([[1]], [0, 0, 0, 0, 0, 0]),
([[1]], [1, 0, 0, 1, float("nan"), 0]), ([], IDENTITY),
])
def test_invalid_input_refused(labels, matrix):
with pytest.raises(ValueError):
proposal(labels, matrix)
def test_complexity_bound_and_unsupported_height_fail_closed(monkeypatch):
monkeypatch.setattr(geometry, "MAX_RUNS", 2)
with pytest.raises(ValueError, match="budget"):
proposal([[1, 0, 1, 0, 1]])
p = proposal([[1]])
with pytest.raises(ValueError, match="height"):
geometry.editor_features(p, height_at=lambda xy: np.full(len(xy), np.nan),
height_source="missing")
changed = copy.deepcopy(p)
changed["features"][0]["geometry"]["coordinates"][0][0][0] += 1
with pytest.raises(ValueError, match="Changed"):
lifted(changed)
def synthetic_document(features):
# This envelope exists ONLY in pytest's deleted temporary store. It exercises
# the v3 API requirement; it is not an actual qualified Gaussian derivation.
return dict(
schema_version="missioncore.urban-map/v3", type="FeatureCollection",
coordinate_system=dict(frame="scene-local", units="metres", up="Z", georeferenced=False),
source=dict(world_sha256="a" * 64, collider_sha256=None, gaussian_only=True,
artifact_sha256="c" * 64, synthetic_fixture=True),
coverage=dict(cell_m=.1, accepted_cells=0), features=features,
)
@pytest.mark.parametrize("name", list(gate.fixtures()))
def test_actual_map_store_edit_store_restart_keep_components_and_holes(tmp_path, name):
labels = gate.fixtures()[name]
p = proposal(labels, [.1, 0, 0, -.1, 10, 20])
original = copy.deepcopy(p)
features = lifted(p)
assert p == original
assert all("subtype" not in f["properties"] and "semantic_element_id" not in f["properties"]
for f in features)
document = synthetic_document(features)
world = dict(sha256="a" * 64)
maps = UrbanMapStore(tmp_path)
receipt = maps.save(world, document)
assert maps.get(world) == document
chosen = features[0]
delta = [.5, -.25]
operation = dict(kind="transform", feature_id=chosen["id"], delta=delta, angle=0)
edits = SemanticEdits(tmp_path, maps)
saved = edits.save(world, dict(expected_revision=None, model_sha256=receipt["sha256"],
request_id="synthetic-geometry-0001", operations=[operation]))
assert saved["edited"]["schema_version"] == "missioncore.urban-edit/v1"
assert SemanticEdits(tmp_path, maps).get(world) == saved
assert not saved["learning"]["dataset_ready"]
assert maps.get(world) == document
for before, after in zip(features, saved["edited"]["features"], strict=True):
if before["id"] == chosen["id"]:
assert shape(after["geometry"]).equals(
affinity.translate(shape(before["geometry"]), *delta))
assert len(after["geometry"]["coordinates"]) == len(before["geometry"]["coordinates"])
else:
assert before == after
# Don't disguise arbitrary components as linear markings to claim vertex editing.
with pytest.raises(ValueError, match="вершины"):
apply_operations(document, [dict(kind="move", feature_id=chosen["id"], path=0, index=0,
position=[0, 0, 2])])
assert json.loads(json.dumps(p)) == p
def test_native_summary_representations_are_not_invertible():
# Information-content counterexamples, NOT execution of the upstream VMA model.
dashes_a = unary_union([box(0, 0, 2, 1), box(4, 0, 6, 1), box(8, 0, 12, 1)])
dashes_b = unary_union([box(0, 0, 3, 1), box(5, 0, 7, 1), box(9, 0, 12, 1)])
zebra_a = unary_union([box(x, 0, x + 1, 8) for x in [0, 3, 6, 9]])
zebra_b = unary_union([box(x, 0, x + 2, 8) for x in [0, 4, 8]])
for a, b in [(dashes_a, dashes_b), (zebra_a, zebra_b)]:
assert not a.equals(b)
assert a.envelope.equals(b.envelope)
holed = Polygon([(0, 0), (6, 0), (3, 8)], [[(2, 2), (4, 2), (3, 5)]])
solid = Polygon(holed.exterior)
assert holed.exterior.equals(solid.exterior)
assert not holed.equals(solid)
def test_editor_preflight_bounds_holes_before_callbacks(monkeypatch):
from k1link.simulation.ai_polygon import semantic_edits
labels = np.ones((40, 40), dtype=np.uint8)
labels[2:-1:3, 2:-1:3] = 0
p = proposal(labels)
def forbidden(*args):
raise AssertionError("Expensive validation or sampling ran before budget check")
monkeypatch.setattr(semantic_edits, "validate_path", forbidden)
monkeypatch.setattr(semantic_edits, "validate_holes", forbidden)
with pytest.raises(ValueError, match="budget"):
geometry.editor_features(p, height_at=forbidden, height_source="test")
def test_editor_work_bound_applies_to_whole_batch_before_sampling(monkeypatch):
p = proposal([[1, 0, 1]])
monkeypatch.setattr(geometry, "MAX_EDITOR_WORK", 20)
def forbidden(*args):
raise AssertionError("Height callback ran for partial batch")
with pytest.raises(ValueError, match="work budget"):
geometry.editor_features(p, height_at=forbidden, height_source="test")
def test_height_callback_cannot_move_xy():
p = proposal([[1, 1]])
def mutating_sampler(xy):
xy += 100
return np.full(len(xy), 3.)
features = geometry.editor_features(p, height_at=mutating_sampler, height_source="test")
for before, after in zip(p["features"], features, strict=True):
assert [[p[:2] for p in ring] for ring in after["geometry"]["coordinates"]] == (
before["geometry"]["coordinates"]
)

Some files were not shown because too many files have changed in this diff Show More