Skip to content

perf(core): batch the Kalman update across matched tracklets - #657

Open
rynwang wants to merge 5 commits into
roboflow:developfrom
rynwang:perf/batch-kalman-update
Open

rynwang wants to merge 5 commits into
roboflow:developfrom
rynwang:perf/batch-kalman-update

Conversation

@rynwang

@rynwang rynwang commented Nov 3, 2026 •

Copy link
Copy Markdown

What

The per-tracklet Kalman update is the largest cost in the ByteTrack and SORT frame loops: every matched track runs five small numpy calls plus a 4x4 inverse, and most of that time is Python/numpy call overhead rather than arithmetic.

Tracklets of one tracker share the measurement model, and only the state and covariance differ, so the same algebra can run once per frame over stacked arrays:

  • KalmanFilter.update_batch(filters, measurements, *, check_models=True) — stacks (N, dim_x, 1) states, (N, dim_x, dim_x) covariances and the measurements, then runs the existing update algebra once (Joseph form kept).

  • BaseStateEstimator.update_batch(estimators, bboxes) — batches estimators of one type, after comparing their observation_mtx and measurement_noise: a mixed list, a list whose estimators disagree on the model, or an estimator class that overrides update falls back to per-estimator updates. One tracker normally builds all its estimators from one class, so the comparison is the cheap safety net rather than the common path.

  • BaseTracklet.mark_updated() — the per-tracklet bookkeeping (time_since_update, hit counters) split out of update() so it can run after the batched step.

  • BaseTracker._update_matched(tracklets, bboxes) — used by ByteTrack (high- and low-confidence stages) and SORT.

  • BaseTracklet.update_batch(tracklets, bboxes) — the per-tracklet entry point, shaped like OCSORTTracklet.apply_camera_motion_batch, so the batched update reads update_batch at every level (KalmanFilter, BaseStateEstimator, BaseTracklet).

Numbers

MOT17-val public detections, 21 sequences, 7,939 frames, 13.5 detections/frame, CPU-only x86 WSL2. Detections are replayed — no detector in the loop — so these numbers are the tracking stage, which is where the change applies.

Interleaved A/B, six pairs, fresh process per run, median + two-sided exact sign test:

tracker before after delta
ByteTrack 4246.5 FPS 5548.6 FPS +30.7% (6/6 pairs, p=0.031)
SORT 4282.3 FPS 6063.2 FPS +41.6% (6/6 pairs, p=0.031)

KalmanFilter.update is ~44% of the ByteTrack loop in a cProfile run, which is the headroom the batching targets; the rest of the frame is IoU/association, prediction and supervision overhead.

Correctness

  • Tracker IDs and boxes are bit-identical to develop on all 7,939 frames for both trackers (per-frame SHA-256 over IDs + xyxy).
  • New tests in tests/utils/test_kalman_filter_batch.py assert the batched path equals per-filter update bit-for-bit, plus the length/model-mismatch errors, the mixed-type fallback, the two estimator-level fallbacks (differing measurement noise, overridden update), and use a nonzero observation matrix so the batched correction and Joseph update are actually exercised rather than a zero Kalman gain.
  • 1237 passed, 4 skipped locally (-m "not integration", excluding the torch-only masks/ReID/MCByte/CLI modules, since this machine has no working torch install); CI runs the full set.

Not in this PR

  • Batched predict (another ~10% of the loop). motion.apply builds F/Q per tracklet, so batching it needs a per-motion-model fast path — a separate change.
  • BoT-SORT and McByte: their update() recomputes each track's measurement noise from its box, so the tracklets of one frame do not share one measurement model. A batched update would apply the wrong noise to all but one track, so BaseStateEstimator.update_batch detects the mismatch and falls back to individual updates. Camera motion is not the blocker here.
  • OC-SORT: it also drives the Kalman filter directly (ORU), so the batched state update has to be separated out first — a separate PR.

AI assistance: the implementation and benchmark harness were written with an AI coding agent, reviewed and re-measured locally; the numbers above are from runs I reproduced on this machine.

Each matched tracklet ran its own Kalman update: five small numpy calls plus a
4x4 inverse, several microseconds of Python overhead per track, and it is the
largest single cost in the ByteTrack and SORT frame loops.

Tracklets of one tracker share the measurement model - only state and
covariance differ - so the same algebra can run once per frame on stacked
(N, dim_x, 1) / (N, dim_x, dim_x) arrays. This adds `KalmanFilter.update_batch`
and `BaseStateEstimator.update_batch`, keeps the per-tracklet bookkeeping in a
new `BaseTracklet.mark_updated` hook, and uses them for the matched tracklets.

MOT17-val, 21 sequences, 7,939 frames, 13.5 detections/frame, CPU-only x86
(interleaved 6-pair A/B, sign test):

  ByteTrack  4246 -> 5549 FPS  (+30.7%)  6/6 pairs, p=0.031
  SORT       4282 -> 6063 FPS  (+41.6%)  6/6 pairs, p=0.031

Tracker IDs and boxes are bit-identical on all 7,939 frames for both trackers.
OC-SORT and BoT-SORT keep the per-tracklet path - they add ORU/CMC work per
track, so batching is a separate question.
@rynwang

rynwang commented Nov 3, 2026

Copy link
Copy Markdown
Author

Integration tests also pass on the patched tree, not just the parity harness:

pytest tests/core/test_tracker_integration.py -q -m integration
10 passed in 118.12s

That covers the TrackEval-derived reference CLEAR / HOTA / Identity numbers on the bundled datasets, i.e. the tracker outputs still score identically, not merely that the boxes match my replay.

(For the record on the numbers above: the A/B was detections-only replay on MOT17-val, so the ~30–40% is the tracking stage; a real pipeline that also runs a detector will see a smaller end-to-end effect.)

@rynwang

rynwang commented Nov 3, 2026

Copy link
Copy Markdown
Author

To check the gain isn't specific to MOT17-val, I re-ran the same replay on the two datasets the integration tests use (ground-truth boxes as detections, tracking stage only, 3 alternating runs per arm, medians):

dataset frames tracker before after delta
DanceTrack 25,508 ByteTrack 5,876.9 FPS 8,105.2 FPS +37.9%
DanceTrack 25,508 SORT 6,103.3 FPS 8,643.0 FPS +41.6%
SportsMOT 26,970 ByteTrack 4,885.8 FPS 7,211.1 FPS +47.6%
SportsMOT 26,970 SORT 5,062.7 FPS 7,600.2 FPS +50.1%

That is the same direction as MOT17-val (+30.7% / +41.6%), and larger on the denser sequences, which is what the mechanism predicts: more tracks per frame means more per-tracklet Kalman calls collapse into one batched call. Output remains bit-identical on both datasets (covered by the integration tests already in this PR).

@rynwang

rynwang commented Nov 3, 2026

Copy link
Copy Markdown
Author

Small correction to my previous comment: the integration tests check the TrackEval reference metrics, not bit-parity. I ran the bit-parity check on those two datasets separately — SHA-256 over every frame's tracker IDs + boxes, base vs patched:

dancetrack  ByteTrack 5094332ebcd1d01b == 5094332ebcd1d01b
dancetrack  SORT      bedc28b35034b0b1 == bedc28b35034b0b1
sportsmot   ByteTrack 9bb80622338af9fe == 9bb80622338af9fe
sportsmot   SORT      7754acae954d3ab6 == 7754acae954d3ab6

So the +37.9%…+50.1% on those datasets is also output-preserving, not just the MOT17-val number.

@rynwang

rynwang commented Nov 4, 2026

Copy link
Copy Markdown
Author

I have read the CLA Document and I sign the CLA.

@Borda
Borda requested a balanced review from Copilot November 4, 2026 19:49
@Borda Borda added bug Something isn't working enhancement New feature or request and removed bug Something isn't working labels Nov 4, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Batch updates can silently use incorrect measurement noise and bypass custom estimator update logic, while zero-gain equivalence tests fail to exercise nontrivial corrections.

3 open issues
What changed in this PR

This PR reduces per-frame overhead in SORT and ByteTrack by batching Kalman corrections across matched tracklets. OC-SORT and BoT-SORT retain their individual update paths.

Changes:

  • Adds batched Kalman and state-estimator updates while retaining Joseph-form covariance calculations.
  • Separates tracklet bookkeeping from state correction and integrates batching into SORT and both ByteTrack association stages.
  • Adds equivalence, validation, and mixed-estimator fallback tests.
File Description
tests/​utils/​test_kalman_filter_batch.py Tests batch equivalence, validation, and fallback behavior.
src/​trackers/​utils/​state_representations.py Adds estimator-level batching and mixed-type fallback.
src/​trackers/​utils/​kalman_filter.py Implements batched Kalman corrections.
src/​trackers/​utils/​base_tracklet.py Adds shared post-update clock resets.
src/​trackers/​core/​sort/​tracklet.py Separates successful-update bookkeeping from correction.
src/​trackers/​core/​sort/​tracker.py Batches matched-track corrections.
src/​trackers/​core/​bytetrack/​tracklet.py Separates consecutive-hit bookkeeping from correction.
src/​trackers/​core/​bytetrack/​tracker.py Batches high- and low-confidence matched updates.
src/​trackers/​core/​base.py Adds the shared matched-track update helper.

Review effort: Balanced

if not estimators:
return
reference = estimators[0]
if any(type(estimator) is not type(reference) for estimator in estimators):
for estimator, bbox in zip(estimators, bboxes):
estimator.update(bbox)
return
KalmanFilter.update_batch(
"""Return `count` independent 8-state / 4-measurement filters."""
filters = []
for _ in range(count):
kf = KalmanFilter(dim_x=8, dim_z=4)
The state-estimator batch path assumed that equal estimator classes share one
measurement model and that no estimator overrides `update`. Neither holds:
`set_kf_covariances` can give each estimator its own measurement noise, and a
subclass may override `update` to refresh noise or keep bookkeeping.

Compare the observation and noise matrices of every estimator before batching and
fall back to individual updates when they differ or when `update` is overridden.

The randomized batch tests also used a zero observation matrix, which leaves the
Kalman gain at zero and never exercises the batched correction or the Joseph
covariance update; give the test filters a nonzero observation matrix and cover the
two new fallback paths.
@rynwang

rynwang commented Nov 5, 2026

Copy link
Copy Markdown
Author

All three are correct — fixed in 2d36be1.

  • Measurement-model mismatch: update_batch now compares observation_mtx and measurement_noise of every estimator against the reference and falls back to individual updates when they differ, instead of trusting the class check.
  • Overridden update: estimators whose class overrides BaseStateEstimator.update keep the individual path, so a subclass that refreshes noise or keeps its own bookkeeping still runs.
  • Zero observation matrix: _make_filters now sets observation_mtx = [I4 | 0], so the randomized equivalence tests produce a nonzero Kalman gain and actually exercise the batched correction and the Joseph covariance update.

Two tests were added for the new fallbacks (different noise, overridden update), and tests/utils is 216 passed, 1 skipped.

@rynwang

rynwang commented Nov 5, 2026

Copy link
Copy Markdown
Author

Pushed the follow-up for the Copilot review (2d36be1): model comparison before batching, a fallback for estimator classes that override update, and a nonzero observation matrix in the equivalence tests so the batched correction is actually exercised. CI is green — would you have a moment to take a look?

@AlexBodner

Copy link
Copy Markdown
Collaborator

Hello, thank you for the contribution! I ran it on DanceTrack and SportsMOT ground-truth boxes, IDs and boxes are identical to develop on every frame, and I got about +28% for SORT and +29% for ByteTrack, so the numbers hold up.

One thing I'd like to change is the naming. The batched update now has a different name at each level, see: KalmanFilter.update_batch and BaseStateEstimator.update_batch, but BaseTracker._update_matched for the tracklets. We already batch per-tracklet work as a static method on the tracklet class, OCSORTTracklet.apply_camera_motion_batch(tracklets, affine_mtx), so could this follow the same shape as BaseTracklet.update_batch(tracklets, bboxes)? Then it reads update_batch at every level.

A small note on the description: BoT-SORT and McByte can't use this because their update() recomputes each track's measurement noise from its box so the tracks don't share one model, so camera motion isn't the blocker here.
For OC-SORT, its not a direct application because it also plays with the kalman filter and one would have to separate it, so that is fine as another PR.
Other than that minor details its looking good!

The batched per-tracklet update lived on BaseTracker as the private
_update_matched, while the levels below it expose update_batch. Move it to
BaseTracklet as a static method shaped like OCSORTTracklet.apply_camera_motion_batch,
so SORT and ByteTrack call `TrackletClass.update_batch(tracklets, bboxes)` and the
name reads the same at every level.
@rynwang

rynwang commented Nov 19, 2026

Copy link
Copy Markdown
Author

Thanks for the independent run — good to see the ~+28%/+29% reproduces on your side.

Renamed as you suggested in 0724c86: the batched per-tracklet update is now BaseTracklet.update_batch(tracklets, bboxes), shaped like OCSORTTracklet.apply_camera_motion_batch, and SORT / ByteTrack call SORTTracklet.update_batch(...) / ByteTrackTracklet.update_batch(...). The private BaseTracker._update_matched is gone, so the name is update_batch at all three levels.

Also corrected the description: BoT-SORT and McByte are excluded because update() recomputes each track's measurement noise from its box (so the tracklets don't share one model — which the batch path now detects and falls back on), not because of camera motion. OC-SORT is left for a separate PR as you said.

Tests: tests/utils + tests/core 1162 passed, 4 skipped, with one pre-existing failure (test_botsort_reid needs the optional reid package, not installed here).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants