blog / 02_e1_precision_first_linking.md
Dv04's picture
Deep expansion pass: full mechanism taxonomy (01), WILDTRACK two-leg real-data campaign + Frigate gate (02), four-act CrowdHuman saga (03), per-product paragraphs + edge-box composition (04), refusal-gate mechanics + three-bug case study + 36/36 OOD demo (05); README index with reading times
686f3f6 verified
|
Raw
History Blame Contribute Delete
26 kB

Precision first cross camera linking (E1)

Dhi Labs, post 2 of 5: a deep dive into multicam reasoning memory

The job: a person walks past camera 0, disappears, and reappears on camera 1 as a brand new track ID. A cross camera system has to decide whether those two tracks are the same physical person, and it has to do that thousands of times a day, for weeks, without its memory exploding or its identities quietly corrupting. This post is a deep dive into how our multicam reasoning memory product (E1, package name fleetmind) makes that decision, what it costs, what it is built from, and, new since the last revision of this post, how it behaved the first time we ran it against real data: the WILDTRACK seven camera dataset, both as a ground truth replay and behind a real YOLO11n plus ByteTrack detection pipeline.

The design principle we started from is asymmetric on purpose:

No link beats a wrong link. A false merge poisons weeks of memory: every future query about either person returns the other person's history. A missed link only costs a duplicate row.

That asymmetry drives every decision below.

What goes in, what the code is built from

The input contract is deliberately narrow: any tracker's JSONL stream, one row per observation, defined in src/fleetmind/events.py:

{"t": 1720000000.0, "camera_id": "cam3", "track_id": "17",
 "class": "person", "position_m": [4.2, 11.0],
 "identity_ref": "plate:GJ01AB1234",
 "attributes": {"color": "red"}}

identity_ref is optional and is the only integration surface: a plate from an LPR engine, a face free embedding cluster id from a sister product, a badge swipe, any stable external identity. When present, linking is exact. When absent, the engine has to earn the link itself from timing alone, which is the harder and more interesting case below. Only t, camera_id, and track_id are actually required; position_m is stored for provenance only and, notably, the linker itself does not use spatial position, only per camera pair transit time.

The library is small on purpose and has no third party dependency beyond numpy: 9 Python files, 1,290 lines total (wc -l across src/fleetmind/*.py and src/fleetmind/integrations/*.py), stdlib sqlite3 for storage. Three modules carry the core logic:

  • memory.py (303 lines): MemoryStore, SQLite in WAL mode. Raw events never persist; each one extends an episode, one row per entity per camera per contiguous presence span, so storage is O(entities + episodes + links), not O(events). A retention policy (prune) ages episodes out by day and deactivates links for entities with nothing left. The distinction matters more than it sounds: a camera watching a person for one minute at 1 Hz produces 60 events and exactly one episode row, so the store's growth rate is set by how many visits happen, not by frame rate.
  • linker.py (179 lines): CrossCameraLinker, TransitPrior, LinkerConfig. An identity_ref match is exact; otherwise a candidate is scored by a per camera pair Gaussian transit time prior, learned online (Welford's algorithm for streaming mean and variance) only from ref confirmed links, never from the linker's own probabilistic guesses. That restriction is load bearing: a prior that learned from its own guesses would drift toward whatever it already believed, and a wrong early link would teach the prior to make more of them. A camera pair with no ref confirmed samples yet returns a flat, uninformative likelihood of 0.3 to every candidate, which matters in the WILDTRACK diagnosis below.
  • queries.py (97 lines): where_is, history, who_was_at, journeys, co_occurrences, summarize.

Supporting modules: synth.py (104 lines, the synthetic ground truth site generator and pairwise precision/recall scorer that produced every synthetic number below), cli.py (196 lines), and integrations/frigate.py (330 lines, covered in its own section below).

Three gates, and why the third one is not decorative

Our linker scores a candidate pairing on two things: transit time plausibility (the learned Gaussian prior over how long it takes to walk from camera i to camera j) and, when available, the identity_ref term. A natural design stops at two gates: score above a bar, and margin over the runner up above a bar. Concretely, in _assign_new_track (linker.py), a probabilistic (non identity_ref) link requires the best score to clear link_threshold (0.5) and beat the runner up by margin_threshold (0.2).

We measured what that natural, two gate design actually gets you. Margin alone gave 0.918 site precision. The failure mechanism is worth spelling out, because it is the counterintuitive heart of the design. Gaussian transit time scores are peaky: near the prior's mean they are high and fall off fast. So when two people leave camera A about 20 seconds apart and one arrival appears at camera B at a prior consistent time, both are genuinely plausible, but whichever one happens to sit closer to the prior mean scores far above the other. The margin gate sees a big margin and reads it as confidence. It is not confidence; it is the shape of a Gaussian. The winner is the wrong person often enough to put roughly one link in twelve silently wrong, which is exactly the failure the asymmetry above says we cannot tolerate. The linker's own code comment records the mechanism: any second candidate above a plausibility floor makes the arrival ambiguous, no link, full stop, because margin alone is not ambiguity when Gaussian scores are peaky and two travelers 20 seconds apart can produce a large margin with the wrong winner.

So there is a third gate, a uniqueness guard: at most one candidate may sit above a lower plausibility bar, plausible_threshold (0.2), at all. If a second candidate is also plausible, at any margin, the link is refused outright and a new entity is created instead. The test suite pins the exact scenario: two ref less people leave cam0 at t=5000.0 and t=5002.0, one arrival appears at cam1 at t=5046.0 at a prior consistent transit; the correct behavior, asserted by test_ambiguity_prefers_no_link, is a new entity, not a coin flip link. One clarification in the honest spirit of this series: "refusal gate" is our prose name for this mechanism, not a literal identifier in the source; the mechanism is real and load bearing, but there is no function named refusal_gate.

configuration site precision recall
margin only 0.918 higher, not separately reported
plus uniqueness guard 1.0 (measured across 24 sites) 0.0476 to 0.6788, scaling with reference coverage and camera count (grid below)

The synthetic evidence: a 24 site grid, not one lucky seed

A single demo run is a good walkthrough but a thin evidence base on its own. We scored the same linker, unchanged, against a 24 site synthetic benchmark suite spanning 3 to 8 cameras, 20 to 100 people per site, and 20% to 60% external identity reference coverage, 165,902 events total. The full per site output is published as linking_report.json on the benchmark dataset, and we downloaded and recomputed its aggregates directly for this revision rather than quoting a cached number:

result value
sites scored 24
total events 165,902
precision, every single site 1.0000 (zero false merges anywhere in the grid)
recall, full range across sites 0.0476 to 0.6788 (mean 0.4112)
recall by reference coverage (mean) 20%: 0.2008, 40%: 0.3904, 50%: 0.4490, 60%: 0.6044
recall by camera count (mean) 3 cam: 0.3606, 4 cam: 0.3990, 5 cam: 0.3998, 6 cam: 0.4016, 7 cam: 0.4292, 8 cam: 0.4767

Precision does not move: it is exactly 1.0000 on all 24 sites, so the uniqueness guard refuses every ambiguous pairing regardless of how sparse the reference coverage or how many cameras are in play. Recall is the variable the design deliberately trades away, and it moves exactly where the mechanism predicts: more reference coverage gives the transit prior more ref confirmed links to learn from, so mean recall climbs from 0.2008 at 20% coverage to 0.6044 at 60%; more cameras give the linker more transit legs to score, so mean recall climbs from 0.3606 at 3 cameras to 0.4767 at 8. Recall is the dial; coverage and topology turn it; and we report the honestly low end of the range instead of rounding it up.

For one seed unpacked in full detail: on the committed synthetic demo (seed=1, a four camera site, 20 people, 40% carrying an external identity reference, a configuration distinct from the 24 site grid and run separately), we reproduced the full pipeline again this session with PYTHONPATH=src python -m fleetmind.cli demo --seed 1:

metric value
synthetic events ingested 1,832
linking precision 1.0
linking recall 0.3768
true same person track pairs 69
correctly linked pairs 26
wrong links 0
entities in memory 46
episodes in memory 61
active links 61
relations (co presence) 58
memory store size 61,440 bytes (60.0 KB)

A regression gate lives in the test suite, test_site_linking_precision_over_recall, asserting precision >= 0.95 and recall >= 0.35 on this same synthetic site, so a future change that quietly eroded either bound would fail CI, not just this blog post.

While reproducing these numbers on an earlier pass we also found two small discrepancies between the repository's own README prose and a fresh run against the same fixed seed: the README stated memory size as "61 KB" (measured: 61,440 bytes, which is exactly 60.0 KB) and stated the cam0 -> cam1 journey transit range as "40 to 54 s" (fresh runs produce 37.85 s, 42.85 s, and 53.65 s). Both have since been corrected in the repository, and we note the history here rather than pretending the prose was always right; precision, recall, and pair counts matched exactly throughout, so the explanation was stale prose from an earlier run, not nondeterminism.

First contact with real data: WILDTRACK, two ways

Everything above is synthetic, with exact ground truth. This section is what happened when the same engine, unchanged, met WILDTRACK: seven overlapping HD cameras watching one university courtyard, 400 annotated frames at 2 fps (200 seconds), 313 unique people, person level bounding boxes per view. The evaluation ran as two legs feeding the same fleetmind ingest plus fleetmind score CLI and the same pairwise metric as the synthetic benchmark, so every row is directly comparable. We re ran the ingest and scoring stages of all four conditions ourselves, on CPU, from the converted event streams, and the numbers below are from those fresh runs; the GPU detector and tracker pass in leg 2 is attributed to the product's evidence log, which commits the tracker outputs it produced.

  • Leg 1, ground truth replay. Per camera track segments are derived from WILDTRACK's own annotation visibility runs; no detector, no GPU. This isolates the linker: perfect tracks in, linking quality out.
  • Leg 2, real pipeline. Ultralytics YOLO11n plus ByteTrack, person class only, confidence 0.25, run on a rented RTX 5060 Ti over all 2,807 frames (401 per camera, about 16.6 fps processing rate). fleetmind ingests the real tracker's output, fragmentation, false positives and all; ground truth is used only afterward, to label tracks for scoring.

Getting the data was its own small engineering story, and since the whole point of this series is showing work, here it is. The official download is gated behind a form, but the archive it points to serves over plain HTTPS with Range request support, and the same 6.8 GB file is mirrored publicly on Hugging Face. We only needed the 13 MB of annotation JSON plus, for leg 2, the camera frames, so the evidence tooling reads the zip central directory remotely and fetches individual entries by byte range instead of downloading 6.8 GB. Doing that surfaced a real bug: Python's zipfile machinery computes a spurious "prepended data" offset of exactly 2 to the power 32 for this archive, so every entry whose true offset is below 4 GB reports a header offset exactly 4,294,967,296 bytes too high, while entries above 4 GB (whose offsets live in zip64 extra fields) report correctly. Confirmed empirically: the first annotation JSON reports offset 4,294,968,051 but its local header magic sits at byte 755. The workaround probes both the reported offset and the reported offset minus 2 to the power 32, then inflates the raw deflate stream directly. All 400 annotation files round tripped as valid JSON, with an md5 over the sorted concatenation recorded in the evidence log.

Conversion was designed to avoid the obvious leak: track_id is built from per camera visibility runs, not from the ground truth person ID, because a real tracker does not know person IDs. For each person and view, visible frames are split into a new track segment whenever the gap exceeds 3.0 seconds; the threshold is empirical (annotation flicker gaps of 0.5 to 3.5 s are common, longer gaps are rare real departures) and the result is insensitive to it (1.5 s gives 1,693 segments, 3.0 s gives 1,663, 5.0 s gives 1,653, against a floor of 1,639 if you never split). In the refs=40% condition, 125 of 313 people (seed 42) carry an opaque pid:<personID> reference on their events, mirroring how a real deployment would attach a plate, badge, or embedding cluster id; the person ID never appears anywhere else.

The results, all four conditions, reproduced this session on CPU:

run precision recall true pairs linked pairs wrong links
synthetic seed 1 baseline (non overlapping 4 cam chain, refs 40%) 1.0 0.3768 69 26 0
WILDTRACK ground truth replay, refs 0% 1.0 0.0 3,903 0 0
WILDTRACK ground truth replay, refs 40% 1.0 0.4087 3,903 1,595 0
WILDTRACK real tracker (YOLO11n + ByteTrack), refs 0% 1.0 0.0 4,366 0 0
WILDTRACK real tracker (YOLO11n + ByteTrack), refs 40% 1.0 0.3502 4,366 1,529 0

Precision is 1.0 with zero wrong links in every condition. That includes the leg 2 stream, which is deliberately hostile: the 2 fps frame spacing fragments tracks heavily (1,373 track segments total, of which 993 matched to 253 real people), and the other 380 tracks (28 percent) matched no ground truth person at all, false positives and reflections kept in the stream as distractors, where linking any of them to anything would have counted against precision. The design promise, no link beats a wrong link, held under 313 real people and up to 1,023 simultaneous link candidates per arrival.

And recall without references is exactly zero, in both legs. We are publishing that as prominently as the precision, because it is the honest boundary of the current design, and the diagnosis is more useful than the number. The linker's world model is sequential: a candidate must have a closed episode on another camera before the new track's arrival, because the model of the world is "a person leaves camera A, then later arrives at camera B." WILDTRACK's seven cameras all overlap on one courtyard, so people are visible on several cameras at once, and "transits" between cameras are mostly zero lag co visibility, not walks. Measured, not guessed: in the refs 0% replay, 155 of 1,663 new track decisions had no candidates at all, and the rest saw hundreds of simultaneous candidates, every one scoring the flat unlearned prior likelihood of 0.3, so the uniqueness guard refused them all; with no references, no transit prior was ever learned. In the refs 40% replay, only 2 of 42 camera pairs ever accumulated a ref confirmed transit sample, with means of 0.5 to 1.8 seconds, which is cross view jitter, not walking time. In the leg 2 stream, 29 camera pairs learned priors (fragmented tracker tracks re link via references constantly), but every learned mean is 0.5 to 9.5 seconds of overlap jitter, and the crowded candidate field kept the guard closed: the decision mix was 1,003 new, 269 ref link, 101 ref new, and zero prior link. This is the refusal design working as specified in a topology it was not built for: it would rather link nothing than guess among hundreds of simultaneous candidates.

Two scoring subtleties, stated before anyone quotes these numbers. First, all WILDTRACK recall is 100 percent reference driven; the transit prior mechanism contributed zero links, so this eval validates the exact match path, the refusal behavior under extreme candidate pressure, and the full CLI path on real tracker output, but it does not validate the transit prior learning that the synthetic grid measures. A fair prior path real data eval needs a genuinely non overlapping camera topology, such as an AI City MTMC subset, and is still ahead of us. Second, in leg 2 the reference labels and the truth mapping both derive from the same IoU matching, so they simulate a perfect external identity source; leg 2 precision on ref links is partly correct by construction, and the leg 2 refs 40% recall (0.3502) lands below the sampled reference fraction (0.399) because fragmented tracks of ref less people contribute many unrecoverable pairs.

The Frigate bridge: meeting a real NVR's data where it is

integrations/frigate.py (330 lines) maps the open source Frigate NVR's frigate/events MQTT stream into the same TrackEvent contract, so a tracker that thousands of people already run at home and at small sites can feed this engine without a bespoke adapter. The interesting design decision is how it populates identity_ref, because that field is the engine's only integration surface and, per the asymmetry above, a wrong reference is the most expensive input the system can receive: references link exactly, so a bad one causes precisely the false merge the three gates exist to prevent.

Frigate attaches recognition results to its events in two places: a recognized license plate (with its own score field) and a sub_label, whose documented shape is a [name, score] pair (a face recognition hit, for example). The bridge applies a confidence gate to both: DEFAULT_MIN_IDENTITY_SCORE = 0.5. A plate or sub label whose score falls below the gate is dropped entirely, and the track falls back to probabilistic transit prior linking as if no recognition had happened. The rationale is the same asymmetry once more: a below threshold identity is worse than no identity, because the exact match path trusts it completely. When both a plate and a sub label are present, the plate wins for vehicle labels, since the plate is the thing Frigate actually recognized about the vehicle; plates are normalized (uppercased, whitespace stripped) into plate:<TEXT> and sub labels become face:<name>. And if the score field is absent, the reference passes through, which is a documented trust decision about Frigate's own defaults rather than an accident. The integration's tests exercise the no MQTT client fallback path explicitly, so the optional paho-mqtt dependency stays optional.

Bounded memory: a month of presence under 2 MB, asserted

A tracker that remembers everyone forever is a memory leak with a user interface. Our store prunes daily and keeps its footprint bounded by construction, and the bound is enforced by a test, not asserted in a README. test_month_of_events_stays_byte_bounded simulates a month of continuous per second presence: 30 days, 20 visits per day, 60 events per visit at 1 Hz, across 3 cameras, which is 36,000 events through the ingest path, with prune applied daily at 7 day retention. The test then asserts two literals: the episode count stays at or below 480 (20 visits times 3 cameras times about 8 retained days) and the database file stays strictly under 2_000_000 bytes. We re ran exactly that test in isolation this session; verbatim:

1 passed, 33 deselected in 2.67s

The mechanism is the episode aggregation described earlier: 36,000 events collapse into one episode row per visit per camera, and pruning ages out whole days. For scale, the entire seed 1 demo site, entities, episodes, links, and relations together, fits in 61,440 bytes; the WILDTRACK ground truth replay, 42,707 events from 313 people across 7 cameras, lands at 7,405,568 bytes before any pruning. Weeks scale memory in megabytes is what makes this deployable on a small box rather than a data center, and it is a measured property, not a projection. (That is a statement about the engine's measured footprint, not a claim that any particular deployment exists; no deployment claims are made anywhere in this series.)

Provenance, not vibes

Every answer the memory returns carries the episode IDs behind it. Concretely, in queries.py: where_is attaches "provenance": {"episode_id": ...}, history attaches a list of episode_ids, who_was_at attaches per entity episode lists, and journeys attaches {"from_episode": ..., "to_episode": ...}. The module's own docstring states the principle directly: "An answer without provenance is an assertion; these are receipts." This session's fresh demo run answered a where is query with "ent_9d0d3c5133e6 was last seen on cam3 at t=387 (episode 31)", episode id included, and a journeys query for cam0 to cam1 returned the three actual transit times it recovered, 37.85 s, 42.85 s, and 53.65 s, each tagged to a specific entity and episode rather than collapsed into an average:

journey(cam0 -> cam1):
  ent_580c7b77bfe5  37.85s   (episode ...)
  ent_9d0d3c5133e6  42.85s   (episode ...)
  ent_2b396d770e67  53.65s   (episode ...)

summarize can optionally narrate an answer through a local LLM (qwen3.5 via Ollama's native /api/chat), but the docstring and the CLI wiring are both explicit that the model only rephrases an answer already computed by the query functions; it is never a source of facts, and turning it off changes no number the query layer returns.

Test suite

Two test files, re run this session. Verbatim final line:

34 passed in 4.33s

Dependencies for the test run: numpy and pytest (both declared in pyproject.toml); the optional frigate extra (paho-mqtt) is not required. An earlier revision of this post flagged that the repository's README said "13 tests green" for one file while a fresh count found 14; that count has since been corrected in the repository, and we keep the note here as part of the record rather than silently retiring it.

What running it looks like

The repository is proprietary and not publicly clonable; the commands below are the exact sequence used to produce the numbers in this post, included for transparency about how the numbers were produced, not as an installation guide.

# proprietary repository, shown for reproducibility context only
cd multicam-reasoning-memory
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# Test suite
pytest tests/

# Synthetic end to end demo (ingest + scored linking + sample queries)
PYTHONPATH=src python -m fleetmind.cli demo --seed 1

# WILDTRACK evidence, ingest + score (any leg/condition)
PYTHONPATH=src python -m fleetmind.cli ingest --events evidence/wildtrack/events_refs40.jsonl --memory /tmp/wt.db
PYTHONPATH=src python -m fleetmind.cli score  --memory /tmp/wt.db --truth evidence/wildtrack/truth.json

Machine for this session's CPU numbers: macOS, Python 3.12.13, fresh virtualenv, numpy plus stdlib sqlite3 only, no GPU. The leg 2 detector and tracker pass ran on a rented RTX 5060 Ti (torch 2.12.0+cu130, ultralytics 8.4.90) and is attributed to the committed evidence log and its committed tracker outputs.

What we have NOT done yet, and what the limits are

  • The transit prior path has no real data validation yet. WILDTRACK's overlapping topology structurally starves it (diagnosed above, zero prior links in all four conditions), so the prior's synthetic grid numbers stand alone until a genuinely non overlapping real dataset, such as an AI City MTMC subset with disjoint coverage, is run. If the uniqueness guard costs more recall there than the 0.0476 to 0.6788 synthetic range suggests, we will publish that.

  • Timestamps are assumed clock aligned (NTP) across cameras. There is no per camera clock offset estimation yet; it is the documented v1 non feature and the natural upgrade, since it would tighten transit priors without touching the linking logic. Until then, a site with drifting camera clocks would silently widen or bias the learned priors.

  • Recall is deliberately partial, and scales with reference coverage. Concurrent ref less travelers at the same camera pair transit trip the uniqueness guard on purpose. A split costs one duplicate entity row; a wrong merge costs weeks of poisoned history.

  • position_m is stored as provenance only; the linker uses per camera pair transit time and nothing spatial.

  • No model weights ship with this product and none are needed; it is an algorithmic engine, so there is nothing to publish to a model hub.

  • Dataset (benchmark + per site grid report): multicam-reasoning-memory-benchmark

  • Live demo: multicam-reasoning-memory-demo

  • Code: proprietary, closed source; the open surface is the evidence quoted above. Partnership or access inquiries: dhi-tech.com.

  • Series: post 1, the thesis, post 3, A4 calibration, post 4, portfolio overview, post 5, Prompt2Model v0.1.0

Free AI Image Generator No sign-up. Instant results. Open Now