Skip to content

perf(python): decode one window of a stored Scene - #23

Merged
xtk8532704 merged 4 commits into
mainfrom
perf/window-decode
Dec 1, 2026
Merged

xtk8532704 merged 4 commits into
mainfrom
perf/window-decode

Conversation

@Max-Bin

@Max-Bin Max-Bin commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

First part of #22 (window decode). The zstd question stays in the issue.

Problem

A reader that wants a short window of a stored Scene has to call from_proto on the whole message and then slice_time. from_proto decodes and validates every row first, so the cost follows the file, not the window. On 60-second Scenes with 11 cameras per row this is about 290 ms per read.

Change

T4Scene.from_proto(message, rows=(start, stop), current_index=k) decodes one window.

  • The result equals from_proto(message), then setting current_index, then slice_time(start, stop).
  • Numeric columns are decoded whole and cut by slice_time itself, so the offset handling is not duplicated.
  • Camera and LiDAR rows are decoded only inside the window.
  • String columns (track_ids) are read lazily in this mode; slicing gives the same lists as before.
  • validate=True validates the window only.
  • current_index is an index into the stored rows and defaults to the stored one. It needs rows.
  • A message with non-empty model_data is rejected in this mode, because slice_time needs the caller's callback for it.

Independent of rows, a camera calibration that repeats across rows is now decoded once and its read-only arrays are shared between the rows' Camera objects. Cameras that carry an image or annotations are decoded as before.

Validation

  • pytest t4scene/python/tests: 296 passed, 4 skipped. ruff format --check and ruff check are clean.
  • New tests/test_scene_window_decode.py checks that a window serializes to the same bytes as whole decode plus slice_time, that no camera outside the window is decoded, the shared calibration, the default and invalid current rows, the model_data rejection, and window-only validation.
  • On 60 stored Scenes (520–600 rows, 11 calibration-only cameras per row, 4–6 MB), 180 windows of 111 rows all serialize to the same bytes as whole decode plus slice_time. One process, median:
from_proto before after
whole Scene, validate=True 317 ms 286 ms
whole Scene, validate=False 94 ms 69 ms
111-row window, validate=True — 63 ms
111-row window, validate=False — 15 ms
1-row window, validate=False — 2.9 ms

The "before" and "after" columns come from two runs on the same node and the same Scenes.

Not in this PR

  • The C++ reader is unchanged.
  • Validation is still the largest cost of a whole decode (about 200 ms here, much of it contains_tensor walking the record tree once per validate). That can be a separate change.

🤖 Generated with Claude Code

from_proto(message, rows=(start, stop)) decodes the numeric columns, cuts
the window with slice_time, and decodes camera, LiDAR and string rows only
inside it. Decoding also shares the arrays of a camera calibration that
repeats across rows.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Max-Bin
Max-Bin requested a review from xtk8532704 December 1, 2026 08:31

@xtk8532704 xtk8532704 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.

Please check the packed offsets used by the requested window before slicing. This affects malformed stored input, and the check can stay local to the window.

)
if window:
start, stop = rows
scene = scene.slice_time(start, stop)

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.

With five boxes (one per frame), changing the stored box_offsets to [0, 1, 2, -3, -2, 5] makes rows=(3, 4) return box 2 with validate=True. Python interprets [-3:-2] relative to the end of the column. Rebasing turns the boundaries into [0, 1], so the final validator accepts the wrong annotation. Whole decode rejects the same message. Could you check the selected boundaries for range and ordering before using them as indices, including the nested polygon and signal offsets, and add a regression test? Checking just the boundaries used to extract the window preserves window-local validation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, reproduced: with box_offsets = [0, 1, 3, -5, -1, 12] on the fixture, rows=(3, 4) returned other rows' boxes and passed validation. Fixed in 2ff34fc.

  • The window decode now checks every boundary it indexes with before slice_time: the per-row box, cylinder, polygon and signal group offsets, and the nested polygon vertex and signal element offsets of the selected objects and groups.
  • Each must be an integer array of the right length, with the window's boundaries non-negative, non-decreasing and inside their column.
  • The check covers only the boundaries of the window, so validation stays local to it. It also runs with validate=False, because these values are used as indices.
  • Regression tests in test_scene_window_decode.py: eight malformed cases across the five offset columns (negative, decreasing, past the end), each with validate on and off. Each is rejected by the whole decode and by a window that uses the boundary, and a window that does not use it still decodes.

The 180 windows from 60 stored Scenes are still byte-identical to whole decode plus slice_time, and the 111-row window takes 17 ms (15 ms before, within run-to-run noise on a shared node).

A negative or decreasing stored offset inside the window indexed the column
from its end, and rebasing hid it from the window's validation. The window
decode now checks the boundaries it indexes with: per-row annotation and
signal offsets, and the nested polygon vertex and signal element offsets.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@xtk8532704 xtk8532704 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.

The original negative-offset case now raises ValueError, and all 55 window-decode and time-slice tests passed locally. I found two remaining cases in the new boundary check. Both can be fixed while keeping validation local to the window.

edges = np.asarray(offsets)
if edges.ndim != 1 or len(edges) != rows + 1 or edges.dtype.kind not in "iu":
raise ValueError(f"{name} must hold one integer boundary per row and a final one")
part = edges[start : stop + 1]

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.

Please normalize both row bounds with operator.index() after rejecting booleans, before doing arithmetic, and use those Python integers throughout the window path. On NumPy 2, a valid 127-frame Scene with one box per frame and rows=(np.int8(125), np.int8(127)) overflows stop + 1 to -128. The empty boundary slice then raises IndexError at part[0]. Whole decode followed by slice_time(*rows) returns frames 125 and 126. This case would make a useful regression test for equivalence with slice_time().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 15c5264. The bounds are now converted with operator.index() after the boolean check and used as Python integers on the whole window path. test_window_rows_may_be_small_numpy_integers compares np.int8 bounds with whole decode followed by slice_time(*rows).

raise ValueError(f"{name} must hold one integer boundary per row and a final one")
part = edges[start : stop + 1]
if np.ma.getmaskarray(offsets[start : stop + 1]).any() or (
part[0] < 0 or part[-1] > size or np.any(part[1:] < part[:-1])

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.

Please enforce the endpoint invariant when the selected rows reach either end of the packed column. On the five-frame fixture with 12 boxes, changing only the first box offset from 0 to 1 or only the final offset from 12 to 11 makes whole decode reject the message. In both cases rows=(0, 5), validate=True returns 11 boxes and silently drops one. When start == 0 the first boundary must be zero, and when stop == rows the final boundary must equal the packed column size. These checks only read endpoints already in the window.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 15c5264. When start == 0 the first boundary must be zero, and when stop is the row count the last one must equal the column length. The same rule applies to the nested polygon vertex and traffic light element offsets. test_window_at_an_end_of_the_scene_checks_that_end_of_the_column covers both ends for boxes and polygons, with validation on and off; a window away from that end still decodes.

@xtk8532704

Copy link
Copy Markdown
Contributor

Could we add a slice_model_data callback to T4Scene.from_proto(..., rows=(start, stop)) in this PR? In DiffusionPlanner2 we want to store a recording range once, alongside its model cache, and sample random 111-frame training windows from it. At this revision, any nonempty model_data makes from_proto raise before it decodes the window. The caller can already supply a slicer to scene.slice_time, but reaching that API requires decoding the full scene first.

Could the window decoder pass the model payload and the half-open row bounds in the stored range to the callback, and use its return value as the window's model_data (None to drop it)? The model adapter knows which entries are time-aligned or keyed by anchor. For anchor-keyed caches, it can capture the requested absolute current_index when it supplies the callback. Keeping the existing error when no callback is supplied would protect callers from silently reusing the whole range's cache.

A regression test could request rows=(10, 121), current_index=40 on a range with nonempty model_data, verify that the callback receives (10, 121), and check both the returned payload and the window-local current_index == 30 against slice_time. For performance, the callback should run on the window-decode path without constructing the full T4Scene. Selective disk reads are a separate follow-up since from_proto already receives a parsed protobuf.

Max-Bin and others added 2 commits December 1, 2026 21:51
…l_data callback

- Normalize the window bounds with operator.index so small NumPy integers
  cannot overflow.
- A window that reaches either end of a packed column requires that end's
  boundary to be zero or the column's length.
- from_proto(rows=...) takes the slice_model_data callback of slice_time for
  a nonempty model_data payload.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Max-Bin

Max-Bin commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Added in 15c5264: T4Scene.from_proto(message, rows=(start, stop), slice_model_data=callback).

  • The callback gets the decoded payload and the window's bounds in the stored rows, the same contract as slice_time. Its result becomes the window's model_data, and None drops it.
  • A nonempty payload without a callback still raises.
  • The full T4Scene is not built: sensor and string rows outside the window stay undecoded. The model_data payload itself is decoded whole before the callback runs, since its keys are opaque to the codec.
  • test_model_data_callback_cuts_the_payload_to_the_window checks the bounds the callback receives, the window-local current_index, and equality with slice_time.

I also merged main to resolve the CHANGELOG conflict.

@Max-Bin
Max-Bin requested a review from xtk8532704 December 1, 2026 12:55

@xtk8532704 xtk8532704 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.

Verified both fixes on 15c5264. The window ending at np.int8(127) matches whole decode followed by slicing, and malformed first or last offsets are rejected for boxes, polygon vertices, and traffic light elements. The local Python suite passed with 235 tests passed and 50 skipped.

@xtk8532704
xtk8532704 merged commit 5e1325b into main Dec 1, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants