Dataloader
rerun.experimental.dataloader
PyTorch Datasets for training on data from the Rerun catalog.
IndexValue
module-attribute
IndexValue: TypeAlias = int | datetime64 | timedelta64
A concrete index value on a timeline.
A plain int for integer timelines, a datetime64[ns] for timestamp
timelines, and a timedelta64[ns] for duration timelines.
BlockShuffle
dataclass
Bases: ShuffleStrategy
Shuffle fetch-sized blocks of consecutive samples instead of individual samples.
Each block is one fetch's worth of consecutive, segment-local samples. The block order is
shuffled, but samples keep their natural order within a block, so every fetch still reads one
contiguous span: stored data is read about once per epoch instead of once per fetch, and decoders
reuse their cache across a block. Set buffer_size to decorrelate batches at emission time.
| PARAMETER | DESCRIPTION |
|---|---|
buffer_size
|
Size of the post-decode buffer that randomizes emission order
without changing the fetch order. Warning The buffer holds up to
TYPE:
|
min_fill
|
Samples buffered before emission starts. Defaults to
TYPE:
|
ColumnDecoder
Bases: ABC, Generic[_DecodedT_co]
Base class for column decoders.
Subclasses convert raw Arrow data into decoded values. The pipeline calls
decode
once per field with every requested sample of a fetch block, so decoders can
amortize work across samples (one vectorized gather for numeric data, one
codec pass per GOP for video). Decoders that only care about one sample at a
time can simply loop over the requests and decode each
FieldBatch.take_decode_rows window.
fill_latest_at
property
fill_latest_at: bool
Whether this column's prefetch read latest-at-fills empty grid slots.
True for stateless columns (images, scalars): each grid slot wants the
most recent value snapped from the real rows. Keyframe-aware fields use
exact queries covering the decode window, regardless of this value.
TimeAlignedSampling disables filling for all selected fields.
The read is partitioned by this flag so it stays a global query argument
per group rather than a per-column one.
decode
abstractmethod
def decode(
batch: FieldBatch, requests: Sequence[DecodeRequest]
) -> Sequence[_DecodedT_co | None]
Decode all requests against batch, returning one entry per request.
requests arrive in row order: grouped by segment, and ascending by
index value within a segment. Implementations may process them in any
internal order (e.g. grouped by GOP), but the result must align 1:1 with
the input: result[i] is requests[i]'s decoded value, or None to
signal data missing for that sample.
DataSource
dataclass
A dataset or filtered selection, optionally restricted to curated intervals.
| PARAMETER | DESCRIPTION |
|---|---|
dataset
|
The remote dataset or selection to read from.
TYPE:
|
segments
|
Optional segment IDs, intersected with any segment filter on the selection. |
curation
|
Optional curated intervals, intersected with the selected recordings and their timeline ranges.
TYPE:
|
filter_segments
def filter_segments(segment_ids: list[str]) -> DataSource
Return a new DataSource narrowed to segment_ids, preserving its contents and curation.
DataloaderMetrics
Live cumulative metrics for a Rerun dataset.
Access this object through dataset.metrics. Calling
summary returns
a flat dictionary of available derived metrics, suitable for experiment
trackers. The values are a best-effort aggregate of completed worker
measurements, not an atomic boundary with concurrently running workers.
DecodeRequest
dataclass
One sample's decode request within a field's batch.
The pipeline has already resolved the index-value window this sample needs into batch rows, so a decoder consumes row indices rather than searching for them.
decode_row_indices
instance-attribute
The batch rows holding all data needed to decode this sample.
For compressed video this includes the intermediate frames needed to decode the requested output, even when the field has no explicit window.
output_row_indices
instance-attribute
Physical batch rows whose decoded values form this request's output.
Always non-empty: preparation omits unresolved requests before invoking a decoder.
sample_position
instance-attribute
sample_position: int
Position where this request's result belongs in the decoded fetch block.
segment_id
instance-attribute
segment_id: str
Segment this sample comes from. Index values are only comparable within one segment.
starts_at_keyframe
instance-attribute
starts_at_keyframe: bool
Whether the window's first row is known to be a keyframe a decoder may start from.
True when the pipeline found a prior keyframe at the first decode row; false when no prior keyframe exists for the requested output.
Field
dataclass
Declarative spec for one field of a training sample.
Note
This API is provisional and will be improved, expect the surface to change.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
TYPE:
|
decode
|
A
TYPE:
|
select
|
Optional jq-like
TYPE:
|
window
|
Optional explicit offsets of the values to return relative to the
current index value. Integer timelines require integral index-step
offsets. Timestamp and duration timelines use seconds, which are
converted to nanoseconds internally.
Unlike An RGB compressed-video window yields a |
FieldBatch
One field's rows for a whole fetch block, across every segment it touches.
Holds the entire fetched window of the field's column, so a decoder can process every sample of the block in one vectorized pass instead of one call per sample. A shuffled sampler puts almost every sample in a different segment, so batching per segment would collapse to a single sample per call.
Rows are ordered by segment, and ascending by index value within a
segment, so a decoder walking requests in order walks the column forwards.
Index values are only comparable inside a segment, which is why locating a
sample's rows is the pipeline's job: see
DecodeRequest.
The rows are kept in the chunks they were fetched in. Read them with
rows or the take_*
methods, which copy at most the rows they return; reading
column copies the whole
field when it was fetched in several chunks.
column
property
column: Array
Every row as one contiguous array.
When the rows were fetched in several chunks, the first access concatenates them: a copy of the whole field that lives as long as the batch.
is_windowed
instance-attribute
is_windowed = is_windowed
Whether decoded outputs keep a leading time axis, including a one-value window.
select
instance-attribute
select = select
Selector applied by the take_* methods.
__init__
def __init__(
*,
column: Array | ChunkedArray,
select: Selector | None = None,
is_windowed: bool = False,
) -> None
Wrap one field's fetched rows.
| PARAMETER | DESCRIPTION |
|---|---|
column
|
A Rerun component column, with one outer Arrow list per timeline row.
TYPE:
|
select
|
Selector applied by the
TYPE:
|
is_windowed
|
Whether decoded outputs keep a leading time axis, including a one-value window.
TYPE:
|
rows
Rows [start, stop) as one array: zero-copy within a chunk, a copy of just these rows across chunks.
take_decode_rows
def take_decode_rows(request: DecodeRequest) -> Array
The request's decode rows, with select applied.
take_output_rows
def take_output_rows(request: DecodeRequest) -> Array
The rows requested for output, preserving repeats and applying select.
FixedRateSampling
dataclass
Sample a timestamp or duration timeline on a fixed grid at rate_hz samples per second.
Live grids start at each recording's first time that accommodates all field windows. Curated grids start at timeline zero. Spacing is rounded to nanoseconds. Samples use the latest available values at or before each requested time; field windows remain in seconds.
ImageDecoder
Bases: ColumnDecoder[Tensor]
Decode encoded-image blobs (JPEG/PNG) to [C, H, W] uint8 tensors.
fill_latest_at
property
fill_latest_at: bool
Whether this column's prefetch read latest-at-fills empty grid slots.
True for stateless columns (images, scalars): each grid slot wants the
most recent value snapped from the real rows. Keyframe-aware fields use
exact queries covering the decode window, regardless of this value.
TimeAlignedSampling disables filling for all selected fields.
The read is partitioned by this flag so it stays a global query argument
per group rather than a per-column one.
NoShuffle
dataclass
Bases: ShuffleStrategy
Natural order (segment by segment, along the timeline): maximal fetch locality, no randomness.
emission_buffer
def emission_buffer() -> ShuffleBuffer | None
The post-decode buffer samples are emitted through, or None to emit in fetch order.
Only BlockShuffle defines
one, because it is the only strategy whose fetch order stays deliberately
correlated: emission is where its batches get decorrelated.
SampleShuffle already
fetches a uniform permutation, so a buffer would add nothing, and
NoShuffle is a deterministic
baseline that a buffer would only contaminate.
NumericDecoder
Bases: ColumnDecoder[Tensor]
Decode Arrow numeric / list-of-numeric columns to tensors, one vectorized gather per batch.
Segment-blind: every request already carries its rows, so the gather runs across the whole fetch block at once rather than once per sample.
Windowed numeric lists require every resolved row to have the same width
and return [T, D] (including [T, 1] for scalar components); a window
with varying widths returns None.
Unwindowed variable-width fields return one tensor per sample and require a padding
or ragged-data collator for batching.
fill_latest_at
property
fill_latest_at: bool
Whether this column's prefetch read latest-at-fills empty grid slots.
True for stateless columns (images, scalars): each grid slot wants the
most recent value snapped from the real rows. Keyframe-aware fields use
exact queries covering the decode window, regardless of this value.
TimeAlignedSampling disables filling for all selected fields.
The read is partitioned by this flag so it stays a global query argument
per group rather than a per-column one.
PooledBatchCollator
Collate CPU sample dictionaries into lazily allocated reusable shared buffers.
Pass this collator as a PyTorch DataLoader's collate_fn to pool worker
output buffers. Pooling requires Linux, multiprocessing_context="spawn",
and PyTorch's file_descriptor sharing strategy. It uses private PyTorch
storage APIs. With num_workers=0, each leaf uses default_collate
without pooling, including on other platforms.
A slot is reusable only after the receiving process releases its storage, including tensor and NumPy views. If every cached slot is still retained, a fresh allocation keeps loading moving without overwriting live outputs. Pooled tensors must be cloned before passing them to another process. Keep source tensors alive until asynchronous device transfers complete.
Supports dense, non-quantized CPU tensors without gradients, NumPy arrays, numbers, and
Yuv420Frame inside nested dictionaries, lists, and tuples.
Samples in a batch must have matching ordered fields, structure, shapes,
dtypes, and metadata; missing values are not supported.
| PARAMETER | DESCRIPTION |
|---|---|
slots_per_field
|
Maximum number of cached shared buffers per tensor leaf, per worker.
TYPE:
|
max_pool_bytes
|
Maximum cached storage in bytes per worker, allocated on demand. This does not bound memory retained by consumers or fallback allocations when all cached buffers are busy. Shared memory must accommodate both cached and in-flight batches.
TYPE:
|
RerunIterableDataset
Bases: IterableDataset[DecodedSample]
Iterable dataset backed by a catalog server.
Fetches samples in blocks and yields them individually. The DataLoader
controls the training batch size independently.
The index list is partitioned across DDP ranks and DataLoader workers
internally. With shuffling enabled (default), the sample order is permuted
once per epoch before partitioning; call set_epoch to re-seed between
epochs. When a finite dataset is consumed to exhaustion under DDP,
wrap the training loop in DistributedDataParallel.join(): rank shards can
have different lengths, especially when incomplete samples are skipped
after sharding.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The dataset to read from (with optional segment filter).
TYPE:
|
index
|
Timeline to iterate (e.g.
TYPE:
|
fields
|
Sample fields, keyed by output name. |
timeline_sampling
|
TYPE:
|
fetch_block_size
|
Number of samples to fetch per block. Larger values amortize network overhead but use more memory. Defaults to 128.
TYPE:
|
shuffle_strategy
|
The
TYPE:
|
seed
|
Base shuffle seed. The epoch selects a reproducible order using
TYPE:
|
decode_threads
|
Fields to decode concurrently within each
TYPE:
|
max_consecutive_skipped_samples
|
Maximum number of consecutive incomplete samples to skip in each
iterator, independently for every rank and
TYPE:
|
metrics
property
metrics: DataloaderMetrics
Cumulative fetch and decode metrics aggregated across this dataset's workers.
__getstate__
Carry the parent's DDP rank into spawned workers, which have no process group of their own.
__iter__
def __iter__() -> Iterator[DecodedSample]
Yield individual samples as they are decoded.
The arrow fetch for block N+1 runs on a background thread while block N is being decoded, so samples stream out during decode. When the strategy defines an emission buffer, decoded samples pass through that buffer before being yielded.
__len__
def __len__() -> int
Candidate count across all workers, before missing samples are skipped.
from_curation
classmethod
def from_curation(
curation: Curation,
source: DataSource,
fields: dict[str, Field],
*,
timeline_sampling: TimeAlignedSampling
| FixedRateSampling
| None = None,
fetch_block_size: int = 128,
shuffle_strategy: ShuffleStrategy | None = None,
seed: int = 0,
decode_threads: int | None = None,
max_consecutive_skipped_samples: int
| None = _DEFAULT_MAX_CONSECUTIVE_SKIPPED_SAMPLES,
) -> RerunIterableDataset
Sample selected intervals with deterministic shuffling and rank/worker assignments.
Sampling determines candidate anchors without reading source fields. Field windows may extend beyond selected intervals. Fields and video keyframes are resolved at runtime; missing samples are skipped after shuffling without replacement. Reproducing assignments requires the same source contents, settings, epoch, and rank/worker counts.
set_epoch
def set_epoch(epoch: int) -> None
Set the epoch for shuffling (like DistributedSampler.set_epoch).
RerunMapDataset
Bases: Dataset[DecodedSample]
Map-style dataset backed by a catalog server.
Supports random access by global index, so it works with PyTorch's
sampler ecosystem (DistributedSampler, WeightedRandomSampler,
SubsetRandomSampler, ...). Shuffling and cross-worker partitioning
are driven by the DataLoader's sampler.
For streaming iteration with internal shuffling, use
RerunIterableDataset instead.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The dataset to read from (with optional segment filter).
TYPE:
|
index
|
Timeline column to use as the sample index (e.g.
TYPE:
|
fields
|
Sample fields, keyed by output name. |
timeline_sampling
|
TYPE:
|
decode_threads
|
Fields to decode concurrently within each
TYPE:
|
Examples:
dataset = RerunMapDataset(
source,
"frame_nr",
{"image": Field("/camera:Image:blob", decode=ImageDecoder())},
)
sampler = DistributedSampler(dataset)
loader = DataLoader(dataset, batch_size=8, sampler=sampler, num_workers=4)
for batch in loader:
...
metrics
property
metrics: DataloaderMetrics
Cumulative fetch and decode metrics aggregated across this dataset's workers.
__getitems__
Fetch multiple samples by global index, sharing queries where possible.
PyTorch's DataLoader calls this once per batch.
__getstate__
Keep the parent-owned metrics reader out of spawned workers.
from_curation
classmethod
def from_curation(
curation: Curation,
source: DataSource,
fields: dict[str, Field],
*,
timeline_sampling: TimeAlignedSampling
| FixedRateSampling
| None = None,
decode_threads: int | None = None,
) -> RerunMapDataset
Index candidates from selected intervals in canonical segment and timeline order.
Field windows may extend beyond selected intervals. Overlapping selections produce one candidate per anchor. Missing values remain in returned sample dictionaries; the DataLoader's sampler controls ordering and worker ownership. Fields and keyframes are resolved at runtime within the source selection.
SampleIndex
Pre-computed description of the complete sample space.
Maps every segment's positional indices to concrete index values, accounting for the timeline strategy (integer or fixed-rate grid). Small enough to hold in memory for any realistic dataset.
| PARAMETER | DESCRIPTION |
|---|---|
segments
|
Per-segment metadata (window-adjusted index range + sample count).
TYPE:
|
ns_per_sample
|
For
TYPE:
|
ns_dtype
|
Numpy dtype string used when materializing index values:
TYPE:
|
ns_dtype
property
ns_dtype: str | None
Numpy dtype for materialized index values, or None for integer indices.
ns_per_sample
property
ns_per_sample: int | None
Nanoseconds between grid points for fixed-rate sampling, or None.
segment_offsets
property
segment_offsets: ndarray
Cumulative offsets: segments[i] covers global indices [segment_offsets[i], segment_offsets[i + 1]).
segments
property
segments: list[SegmentMetadata]
Eligible ranges; a segment may have several disjoint ranges.
build
staticmethod
def build(
source: DataSource,
index: str,
fields: dict[str, Field],
*,
timeline_sampling: TimeAlignedSampling
| FixedRateSampling
| None = None,
) -> SampleIndex
Build a SampleIndex from lightweight metadata queries.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
Data source to build from.
TYPE:
|
index
|
Name of the index timeline column.
TYPE:
|
fields
|
Field definitions, used for window-trim calculation. |
timeline_sampling
|
TYPE:
|
from_curation
staticmethod
def from_curation(
curation: Curation,
fields: dict[str, Field],
*,
timeline_sampling: TimeAlignedSampling
| FixedRateSampling
| None = None,
) -> SampleIndex
Derive candidates from selected inclusive intervals without reading training fields.
Intervals select anchor timestamps; field windows may read outside them. Overlapping selections do not duplicate anchors.
global_to_local
def global_to_local(
idx: int,
) -> tuple[SegmentMetadata, IndexValue]
Map a global index [0, total_samples) to (segment, concrete_idx_value).
The returned index value is a plain int for integer timelines,
a datetime64[ns] for timestamp timelines, and a
timedelta64[ns] for duration timelines.
indices_in_range
Enumerate valid index values in [lo, hi].
For fixed-rate timelines the returned values walk down from hi
in ns_per_sample steps (so they remain on the grid as long as
hi is). For integer timelines, every value in [lo, hi] is
returned. Values are plain int (ns-since-epoch for timestamp
indices, ns count for duration indices); the caller casts the
aggregated set to the right numpy dtype.
offset_index
def offset_index(
index_value: IndexValue, offset: int | float
) -> IndexValue
Add an explicit field-window offset to an index value.
output_index_values
def output_index_values(
index_value: IndexValue, field: Field
) -> tuple[IndexValue, ...]
Concrete index values requested by a field, preserving its explicit offset order.
resolve_local_index
def resolve_local_index(
seg: SegmentMetadata, pos: int
) -> IndexValue
Convert a positional index within seg to a concrete index value.
pos is in [0, seg.num_samples). Returns datetime64[ns]
for timestamp timelines, timedelta64[ns] for duration
timelines, and a plain int for integer indices.
SampleShuffle
dataclass
Bases: ShuffleStrategy
Uniform per-sample shuffle: maximal decorrelation, minimal fetch locality.
Every fetch scatters across all segments; prefer
BlockShuffle when fetch
throughput is the bottleneck.
emission_buffer
def emission_buffer() -> ShuffleBuffer | None
The post-decode buffer samples are emitted through, or None to emit in fetch order.
Only BlockShuffle defines
one, because it is the only strategy whose fetch order stays deliberately
correlated: emission is where its batches get decorrelated.
SampleShuffle already
fetches a uniform permutation, so a buffer would add nothing, and
NoShuffle is a deterministic
baseline that a buffer would only contaminate.
SegmentMetadata
dataclass
One contiguous eligible grid range within a segment.
index_min
class-attribute
instance-attribute
index_min: int | None = None
Untrimmed recording minimum, or None when selected spans do not provide it.
ShuffleStrategy
Bases: ABC
Determines the order in which an epoch's samples are fetched.
See the training guide for the trade-offs.
emission_buffer
def emission_buffer() -> ShuffleBuffer | None
The post-decode buffer samples are emitted through, or None to emit in fetch order.
Only BlockShuffle defines
one, because it is the only strategy whose fetch order stays deliberately
correlated: emission is where its batches get decorrelated.
SampleShuffle already
fetches a uniform permutation, so a buffer would add nothing, and
NoShuffle is a deterministic
baseline that a buffer would only contaminate.
epoch_order
abstractmethod
def epoch_order(
sample_index: SampleIndex,
*,
fetch_block_size: int,
seed: int,
) -> tuple[ndarray, ndarray]
Return (indices, block_bounds) for one epoch: every global sample index once, in emission order.
block_bounds are cumulative end positions of blocks within indices;
each block must be a contiguous, segment-local span of the global index space.
TimeAlignedSampling
dataclass
Sample aligned fields on a shared integer frame grid using exact-index reads.
Data requirements:
- An integer timeline. The selected timeline uses integer frame numbers.
- Dense, zero-based indices. Every selected field (scalars, state, actions,
video) has one value or frame at each index
0, 1, 2, …, with no gaps or null values. - Known video keyframes. With
keyframe_interval=K, frames0, K, 2K, …are valid decode starting points; forK=10, frame 27 decodes from frame 20. - A shared frame-number reference. The same index refers to the same physical instant across fields. The declared keyframe schedule applies to every selected video and recording.
- Integer field-window offsets. Windows use whole-frame steps, such as
(-2, -1, 0).
Decode starts are calculated from the declared interval without an upfront keyframe scan.
Keyframe markers are fetched with the video data and checked at each expected decode start.
A missing or false marker leaves that sample's video field unresolved; live iterable datasets
apply their incomplete-sample skip policy, while map-dataset consumers receive None.
| PARAMETER | DESCRIPTION |
|---|---|
keyframe_interval
|
Positive number of frames between video keyframes.
TYPE:
|
Examples:
dataset = RerunIterableDataset(
source,
index="frame_nr",
fields=fields,
timeline_sampling=TimeAlignedSampling(keyframe_interval=10),
)
VideoFrameDecoder
Bases: ColumnDecoder[DecodedValue], Generic[_OutputFormatT]
Compressed video random access via keyframe-aware fetching.
The loader finds the preceding keyframe in the required sibling
is_keyframe component on the VideoStream archetype, derived from
Field.path (e.g. /cam:VideoStream:sample pairs with
/cam:VideoStream:is_keyframe). Populate these markers when logging or
with LazyChunkStream.collect(optimize=…).
When all selected fields share a dense, zero-based integer frame grid and
videos have regularly spaced keyframes, pass
timeline_sampling=TimeAlignedSampling(keyframe_interval=…) to the dataset to calculate
decode starts using the declared interval. See
TimeAlignedSampling for the data requirements.
Samples may be raw H.264 AVC1/AVCC (length-prefixed NAL units) or Annex B; the format is detected automatically per sample.
A batch's requests are grouped by GOP: each GOP's packets are extracted and fed through the codec once, and every requested frame is captured as it is emitted. A batch (or a later batch) whose window extends an earlier one reuses the open codec context and decodes only the new packets.
With output_format="rgb", a
Field.window returns one frame
per explicit offset as a [T, 3, H, W] tensor. With
output_format="yuv420p", it returns a Yuv420Frame whose Y and UV
planes remain in YUV form until collation and device transfer.
Returns None when the resolved window does not start with a decodable
keyframe, for example before the video's first frame or with incorrect
keyframe markers. Map-dataset consumers must handle None before
stacking.
fill_latest_at
property
fill_latest_at: bool
Whether this column's prefetch read latest-at-fills empty grid slots.
True for stateless columns (images, scalars): each grid slot wants the
most recent value snapped from the real rows. Keyframe-aware fields use
exact queries covering the decode window, regardless of this value.
TimeAlignedSampling disables filling for all selected fields.
The read is partitioned by this flag so it stays a global query argument
per group rather than a per-column one.
__getstate__
Drop native codec and conversion contexts, which cannot be pickled. Cache stats restart per process.
__init__
def __init__(
*,
codec: str = "h264",
max_decoder_sessions: int = 8,
thread_count: int = 1,
window_storage: Literal["copy", "view"] = "copy",
output_format: Literal["rgb", "yuv420p"] = "rgb",
) -> None
Construct a decoder for a compressed video column.
| PARAMETER | DESCRIPTION |
|---|---|
codec
|
Video codec of the encoded samples (e.g.
TYPE:
|
max_decoder_sessions
|
Upper bound on the number of live codec contexts kept in the LRU cache. Set to 0 to disable session reuse.
TYPE:
|
thread_count
|
FFmpeg decode thread count.
TYPE:
|
window_storage
|
How windowed outputs are materialized.
TYPE:
|
output_format
|
TYPE:
|
decode
def decode(
batch: FieldBatch, requests: Sequence[DecodeRequest]
) -> Sequence[Tensor | None]
def decode(
batch: FieldBatch, requests: Sequence[DecodeRequest]
) -> Sequence[Yuv420Frame | None]
def decode(
batch: FieldBatch, requests: Sequence[DecodeRequest]
) -> Sequence[DecodedValue | None]
def decode(
batch: FieldBatch, requests: Sequence[DecodeRequest]
) -> Sequence[DecodedValue | None]
Decode each request's frame or frame window, feeding every GOP once.
Yuv420Collator
Collate dataset mappings containing Yuv420Frame values.
Without device, YUV planes remain compact CPU uint8 tensors. This is
the intended configuration with DataLoader(num_workers>0,
pin_memory=True): convert each collated Yuv420Frame in the training
process using Yuv420Frame.to_rgb.
Examples:
Custom collation can handle each non-video field however the application requires:
def collate(samples):
return {
"video": Yuv420Frame.stack([sample["video"] for sample in samples]),
"state": custom_state_collation(samples),
}
The convenience collator applies PyTorch's default collation to non-video fields:
loader = DataLoader(dataset, collate_fn=Yuv420Collator(), pin_memory=True)
for batch in loader:
batch["video"] = batch["video"].to_rgb("cuda", dtype=torch.float16, non_blocking=True)
Yuv420Frame
dataclass
One frame, frame window, or collated batch in planar YUV420 form.
y has shape [..., 1, H, W] and uv has shape
[..., 2, ceil(H / 2), ceil(W / 2)]. Both tensors are uint8.
uv[..., 0, :, :] is U and uv[..., 1, :, :] is V. Leading
dimensions may contain time and, after collation, batch.
Use Yuv420Frame.stack inside a custom collate function, or the
convenience Yuv420Collator.
The standard PyTorch collator does not know how to stack the planes and
metadata.
pin_memory
def pin_memory() -> Yuv420Frame
Pin both planes so a DataLoader can transfer them asynchronously.
stack
classmethod
def stack(frames: Sequence[Yuv420Frame]) -> Yuv420Frame
Stack frames or windows along a new leading batch dimension.
This is the composable building block for application-specific collate functions. All inputs must have identical shapes and color metadata. Stacking materializes window views, so the returned batch no longer shares decoder frame-bank storage with its inputs.
to_rgb
def to_rgb(
device: device | str | None = None,
*,
dtype: dtype = float32,
normalize: bool = True,
non_blocking: bool = False,
color_space: Literal["bt601", "bt709", "bt2020"]
| None = None,
color_range: Literal["limited", "full"] | None = None,
) -> Tensor
Transfer and convert to a contiguous [..., 3, H, W] RGB tensor.
Conversion goes directly from CPU uint8 YUV into the requested
floating-point dtype on device, so an intermediate RGB uint8
allocation is not required. If normalize is true, output values are
in [0, 1]; otherwise they are in [0, 255].
Chroma is expanded with nearest-neighbor sampling to stay close to
FFmpeg's default rgb24 conversion. Conversion can still differ by a
few intensity levels because FFmpeg uses integer arithmetic.
color_space and color_range override the metadata carried by the
decoded frame. Unspecified metadata falls back to BT.601 limited range
with a warning, matching FFmpeg's conventional SD-video default.
tracing_scope
Open an OpenTelemetry span for the duration of a with block and propagate trace context into Rerun's Rust SDK.
Context-manager counterpart to with_tracing —
use it to scope arbitrary blocks of code without extracting them into a
function. Any Rust-side #[instrument] spans triggered from within will be
parented under this span in Jaeger.
No-op unless TELEMETRY_ENABLED=true and an OTLP endpoint is configured
(OTEL_EXPORTER_OTLP_TRACES_ENDPOINT or OTEL_EXPORTER_OTLP_ENDPOINT).
Examples:
for epoch in range(num_epochs):
with tracing_scope(f"epoch {epoch}"):
train_one_epoch(...)
with_tracing
Wrap a function in an OpenTelemetry span and propagate trace context into Rerun's Rust SDK.
When enabled, creates a span named name, injects the W3C traceparent header into
Rerun's shared ContextVar, and runs the wrapped function. Any Rust-side
#[instrument] spans triggered from within (e.g. catalog queries) will be
parented under this span in Jaeger.
For ad-hoc blocks that don't belong in a dedicated function, use
tracing_scope instead.
No-op unless TELEMETRY_ENABLED=true and an OTLP endpoint is configured
(OTEL_EXPORTER_OTLP_TRACES_ENDPOINT or OTEL_EXPORTER_OTLP_ENDPOINT).