Knonik DataLoader
The Knonik dataloader streams training batches from the KHLP datasets that
knonik pack produces. It is a Python API: you build a loader, iterate it in
your training loop, and shut it down at the end.
1. What The Dataloader Does
- ▸Single datasets with
ShardedDataLoader. - ▸Weighted mixes of several datasets with
MultiShardedDataLoader. - ▸NumPy output for JAX / TensorFlow / framework-neutral pipelines, and Torch output for PyTorch.
- ▸LeRobot-style
delta_timestampssampling. - ▸Ordered threaded or process-based augment.
- ▸Background batch prefetch, zero-copy batching and decoded-data caches.
- ▸Global sampling across the whole dataset for training diversity.
- ▸Any number of GPUs on one machine, with each rank reading its own part of the data.
In Knonik Standard the loader reads datasets from local disk on one
machine. Cloud storage, multi-node training and hub:// dataset addresses are
coming with Knonik Hub. To train on data that lives in a bucket today, download
the packed dataset and point the loader at its local hlp_manifest.json.
2. Install
The dataloader ships in the Knonik wheel. See Overview → Install. Verify:
python -c "import knonik_multidataloader; print('dataloader import OK')"
For framework="torch", install the PyTorch build that matches your CUDA
runtime, for example:
python -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128
3. Log In
Log in once for the dataloader with your email and a CLI key from your dashboard (see Overview → Log In):
knonik login --product multidataloader
4. Single-Dataset Python Example
Use ShardedDataLoader when training from one KHLP manifest.
from knonik_multidataloader.api.sharded_dataloader import ShardedDataLoader
def main():
loader = ShardedDataLoader(
loader_cfg={
"decode_mode": "random_access",
"hlp_manifest": "/data/knonik_thread_velcro_hlp/hlp_manifest.json",
"chunk_len": 10,
"batch_size": 64,
"framework": "numpy",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet",
"num_decoders": 8,
},
stream_cfg={}, # empty means: auto-discover streams from the manifest
dataset_name="thread_velcro",
)
try:
for batch in loader:
# train(batch)
print(batch.keys())
break
finally:
loader.shutdown()
if __name__ == "__main__":
main()
Always use an
if __name__ == "__main__":guard. The loader decodes in worker processes, and those processes import your entry script. Without the guard, each worker would start a loader of its own. The symptom is a run that hangs or fails withBrokenProcessPool.
5. Multi-Dataset Python Example
Use MultiShardedDataLoader to mix several KHLP datasets at fixed weights.
from knonik_multidataloader.api.multi_sharded_dataloader import MultiShardedDataLoader
datasets = [
(
"thread_velcro",
{
"loader": {
"hlp_manifest": "/data/thread_velcro_hlp/hlp_manifest.json",
"fs_type": "local",
"fs_params": {"root": "/"},
},
"streams": {},
},
),
(
"bimanual_transfer",
{
"loader": {
"hlp_manifest": "/data/bimanual_transfer_hlp/hlp_manifest.json",
"fs_type": "local",
"fs_params": {"root": "/"},
},
"streams": {},
},
),
]
def main():
loader = MultiShardedDataLoader(
datasets=datasets,
weights=[0.7, 0.3],
loader_cfg={
"decode_mode": "random_access",
"chunk_len": 10,
"batch_size": 64,
"framework": "numpy",
"shuffle_mode": "global_triplet",
"num_decoders": 8,
},
)
try:
batch = next(iter(loader))
print(batch["_sample_dataset_names"][:8])
finally:
loader.shutdown()
if __name__ == "__main__":
main()
Multi-Dataset Epoch & Mixing Keys
| Key | Meaning |
|---|---|
weights | Share of each dataset in every batch, in the order of datasets. |
dataset_cycle | When enabled, smaller datasets cycle so the weights ratio holds across the whole epoch. Disable it for exhaust-and-renormalize, where the ratio drifts as datasets run dry. |
epoch_chunks | Epoch length. "largest" = one pass over the largest dataset; an integer = an explicit number of draws per epoch; None = drain to natural exhaustion (only useful with dataset_cycle disabled). |
6. Batch Shape
Each batch is a dictionary. Typical stream keys:
batch["rgb_cam_high"] # (B, T, H, W, 3)
batch["state"] # (B, T, state_dim)
batch["action"] # (B, T, action_dim)
How a batch is built
B is batch_size. Each sample starts at an anchor frame. The time
dimension T is set per stream by chunk_len and delta_timestamps.
Plain chunk_len. Every stream gets the same contiguous run of chunk_len
frames starting at the anchor:
# chunk_len=16 -> every stream has T=16
batch["rgb_cam_high"] # (B, 16, H, W, 3)
batch["state"] # (B, 16, state_dim)
batch["action"] # (B, 16, action_dim)
With delta_timestamps. Each stream you list samples frames at the given
offsets in seconds around the anchor, so its T is the number of offsets.
Unlisted streams keep the contiguous chunk_len window, so streams can have
different T in the same batch:
# chunk_len=16, fps=50
loader_cfg["delta_timestamps"] = {
"state": [-0.10, -0.05, 0.0, 0.05, 0.10], # 5 offsets -> T=5
"action": [i / 50 for i in range(16)], # 16 offsets -> T=16
}
# rgb_cam_high is not listed -> contiguous chunk_len window -> T=16
batch["state"] # (B, 5, state_dim)
batch["action"] # (B, 16, action_dim)
batch["rgb_cam_high"] # (B, 16, H, W, 3)
pad_missing=True clamps offsets that fall outside the episode to its
boundaries instead of dropping the sample; when padding happens the batch also
carries a <stream>_valid_mask so you can tell real frames from padded ones.
Offsets are turned into frames using the dataset's FPS from the manifest (set
with knonik pack --fps). Override it with the fps loader key if needed.
Metadata keys carried with every batch:
batch["_dataset_name"] # single-dataset name
batch["_dataset_names"] # dataset names represented in the batch
batch["_sample_dataset_names"] # one dataset name per sample
batch["_episode_ids"]
batch["_chunk_starts"]
batch["_stream_names"]
Numeric streams arrive as stored, not normalised. For the mean, std and percentiles to normalise them with, see Norms and Stats.
With framework="numpy", arrays are numpy.ndarray. With
framework="torch", arrays are CPU torch tensors; move them to the GPU in your
training loop.
7. Recommended Framework Modes
| Framework | Settings |
|---|---|
| JAX / TensorFlow / NumPy | "framework": "numpy" |
| PyTorch | "framework": "torch", "pin_memory": True (then .to(device, non_blocking=True)) |
8. Augment Functions
augment_fn runs per sample before collation.
NumPy example:
def augment_numpy(sample):
image = sample["streams"]["rgb_cam_high"]
sample = dict(sample)
streams = dict(sample["streams"])
streams["rgb_cam_high"] = image[..., ::-1, :]
sample["streams"] = streams
return sample
loader_cfg = {
"framework": "numpy",
"augment_fn": augment_numpy,
"augment_execution": "threaded",
"augment_workers": 4,
}
Torch example:
def augment_torch(sample):
image = sample["streams"]["rgb_cam_high"]
sample = dict(sample)
streams = dict(sample["streams"])
streams["rgb_cam_high"] = image.float()
sample["streams"] = streams
return sample
loader_cfg = {
"framework": "torch",
"augment_fn": augment_torch,
"augment_execution": "threaded",
"augment_workers": 4,
}
augment_execution | Meaning |
|---|---|
threaded | Default. Ordered thread-pool augment. A good first choice. |
inline | Runs augment in the batch assembly path. Useful for debugging. |
process | Process-pool augment. The function must be top-level and picklable. |
9. Ordered Batch Prefetch (precollate_batches)
precollate_batches keeps fully collated, ready-to-consume batches in a
background queue so your training step does not wait on batch assembly. It is
on by default with a depth of 2. Raise it when model steps are expensive;
set it to 0 to disable. Batch order is preserved exactly.
10. Shuffle Modes and Storage Profiles
The two training shuffle modes, global_triplet and global_triplet_fast,
work with every storage profile (compact_video and training_compressed).
For the same seed they produce the same samples; they differ only in speed,
which depends on your data and machine. Try both and keep the faster one.
For a dataset packed with training_compressed, also set
kdelta_direct_local_decode: True:
loader_cfg = {
"decode_mode": "random_access",
"hlp_manifest": "/datasets/my_dataset_compressed/hlp_manifest.json",
"chunk_len": 1,
"batch_size": 64,
"framework": "numpy",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet_fast", # or "global_triplet"
"kdelta_direct_local_decode": True,
"delta_timestamps": {
"rgb_cam_high": [0.0, 0.1, 0.2, 0.3],
"state": [0.0, 0.1, 0.2, 0.3],
"action": [0.0, 0.1, 0.2, 0.3],
},
"pad_missing": True,
}
11. Zero-Copy Batching
Zero-copy batching can roughly double loader throughput at the cost of more RAM. It is off by default. Turn it on and declare each RGB stream's frame shape:
loader_cfg = {
"decode_mode": "random_access",
"hlp_manifest": "/data/my_dataset_compressed/hlp_manifest.json",
"chunk_len": 4,
"batch_size": 64,
"framework": "torch",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet_fast",
"zerocopy": True,
"zerocopy_frame_shapes": {"rgb_cam_high": [480, 640, 3]}, # [H, W, C] per RGB stream
}
| Key | Meaning |
|---|---|
zerocopy | Enable zero-copy batching. |
zerocopy_frame_shapes | Required with zerocopy. {stream: [H, W, C]} for each RGB stream. |
zerocopy_resize | Optional {stream: [H, W]} when mixed datasets record a stream at different resolutions. |
Constraints:
- ▸
augment_fnis not supported withzerocopy=True. Apply the transform to the batched tensor in your training loop instead. - ▸
pin_memoryandram_cache_bytesare ignored under zero-copy.
12. Multiple GPUs On One Machine
Launch one process per GPU with torchrun. Each process builds its own loader
with the same config and base_seed; the loader detects its rank and reads
its own part of the dataset.
torchrun --standalone --nproc-per-node 8 train.py
import torch.distributed as dist
from knonik_multidataloader.api.sharded_dataloader import ShardedDataLoader
def main():
dist.init_process_group("nccl")
loader = ShardedDataLoader(
loader_cfg={
"decode_mode": "random_access",
"hlp_manifest": "/data/my_dataset_hlp/hlp_manifest.json",
"chunk_len": 16,
"batch_size": 32, # per rank
"framework": "torch",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet",
"base_seed": 0, # same on every rank
"max_steps": 2000, # same on every rank -- required with >1 rank
"num_decoders": 8, # per rank
},
stream_cfg={},
dataset_name="my_dataset",
)
try:
for epoch in range(10):
loader.set_epoch(epoch)
for batch in loader:
...
finally:
loader.shutdown()
dist.destroy_process_group()
if __name__ == "__main__":
main()
Things to know:
- ▸Set
max_steps, the same on every rank. It is required with more than one GPU; without it, ranks finish epochs at different steps and hang. - ▸
batch_sizeandnum_decodersare per rank. Split the machine's CPU cores between ranks. - ▸Call
set_epoch(epoch)at the start of each epoch. - ▸All ranks must be on one machine.
Resuming
loader.state_dict() returns a small dictionary you can save with your
checkpoint. Pass it to loader.load_state_dict(state) on a new loader with the
same config and base_seed to continue from the same point in the epoch.
13. Useful Loader Config Keys
Only decode_mode, hlp_manifest, chunk_len and batch_size are required.
Everything else has a sensible default.
Required / common
| Key | Meaning |
|---|---|
decode_mode | Use "random_access". |
hlp_manifest | Path to hlp_manifest.json (produced by knonik pack). Required for ShardedDataLoader. |
chunk_len | Frames per sample. |
batch_size | Samples per batch (per rank). |
framework | Output array type: "numpy" or "torch". |
fs_type | "local". |
fs_params | {"root": "/"}. |
base_seed | Seed for deterministic sampling and shuffles. |
Throughput - raise these when the GPU is waiting on input; lower them under
CPU or RAM pressure. For most runs num_decoders is the only one you touch.
| Key | Default | Meaning |
|---|---|---|
num_decoders | 4 | Decode parallelism. The main throughput setting. |
hlps_in_flight | 4 | KHLP files read ahead at the same time. |
prefetch_shards | 12 | How far ahead shards are read and decoded. Larger = more throughput and more memory. |
precollate_batches | 2 | Ready-to-consume batches kept in the background queue. 0 disables. |
augment_execution | threaded | threaded / inline / process. |
augment_workers | auto | Augment worker count. |
training_profile | off | True sizes num_decoders, prefetch_shards, ram_cache_bytes and augment_workers from this process's share of the machine's CPU cores and RAM (it accounts for several GPU ranks on one machine). Any of those keys you set yourself wins. |
Sampling & shape
| Key | Meaning |
|---|---|
shuffle_mode | Set "global_triplet" or "global_triplet_fast" for training (see section 10). The default keeps reads sequential and gives little batch diversity. |
sampling_policy | shard_uniform (default, single dataset) or episode_uniform. |
stride | Frame step between possible sample starts. |
overlap | Alternative to stride for window overlap. |
allow_cross_shard | Allow samples to span shard boundaries. |
delta_timestamps | Per-stream offsets in seconds around the anchor (section 6). |
pad_missing | Clamp out-of-range delta_timestamps offsets instead of dropping samples. |
fps | Override the dataset FPS used to resolve delta_timestamps. |
Diversity & memory - trade shuffle diversity against RAM.
| Key | Meaning |
|---|---|
planner_locality | global → hlp_bounded → low_mem → ultra_low_mem. Further right uses less RAM, with slightly less batch diversity. |
low_memory | Cap memory use. Turn on if memory keeps growing. |
ram_cache_bytes | Decoded-data RAM cache budget. Speeds up epoch 2 onward. |
mmap_cache_root / mmap_cache_bytes | Optional disk-backed decoded cache that survives restarts, and its budget. |
Run control & output
| Key | Meaning |
|---|---|
max_steps | Batches per epoch. Required, and equal on every rank, when training on more than one GPU. |
pin_memory | Torch output only. Pin each batch for fast asynchronous GPU copies. |
Zero-copy - see section 11.
Storage-aware reads
| Key | Default | Meaning |
|---|---|---|
kdelta_direct_local_decode | False | Faster sparse reads for datasets packed with training_compressed. |
14. Worked Examples
Each example is a loader_cfg for the call in
section 4:
loader = ShardedDataLoader(loader_cfg=<one of the dicts below>,
stream_cfg={}, dataset_name="my_dataset")
14.1 Minimal local run
loader_cfg = {
"decode_mode": "random_access",
"hlp_manifest": "/data/my_dataset_hlp/hlp_manifest.json",
"chunk_len": 16,
"batch_size": 8,
"framework": "numpy",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet",
}
14.2 Memory-constrained training
loader_cfg = {
"decode_mode": "random_access",
"hlp_manifest": "/data/my_dataset_hlp/hlp_manifest.json",
"chunk_len": 16,
"batch_size": 8,
"framework": "numpy",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet",
"planner_locality": "hlp_bounded",
"ram_cache_bytes": 0,
"prefetch_shards": 4,
"num_decoders": 4,
"hlps_in_flight": 2,
"low_memory": True,
}
14.3 High throughput on a big machine
loader_cfg = {
"decode_mode": "random_access",
"hlp_manifest": "/data/my_dataset_hlp/hlp_manifest.json",
"chunk_len": 16,
"batch_size": 32,
"framework": "torch",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet",
"planner_locality": "global",
"num_decoders": 16,
"hlps_in_flight": 8,
"prefetch_shards": 16,
"ram_cache_bytes": 32 << 30,
"precollate_batches": 3,
}
14.4 Single-frame samples (chunk_len=1)
loader_cfg = {
"decode_mode": "random_access",
"hlp_manifest": "/data/my_dataset_hlp/hlp_manifest.json",
"chunk_len": 1,
"batch_size": 64,
"framework": "numpy",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet",
"planner_locality": "low_mem",
"low_memory": True,
"ram_cache_bytes": 16 << 30,
}
14.5 LeRobot-style delta_timestamps
FPS = 50
CHUNK_LEN = 16
loader_cfg = {
"decode_mode": "random_access",
"hlp_manifest": "/data/my_dataset_hlp/hlp_manifest.json",
"chunk_len": CHUNK_LEN,
"batch_size": 8,
"framework": "numpy",
"fs_type": "local",
"fs_params": {"root": "/"},
"shuffle_mode": "global_triplet",
"delta_timestamps": {
"state": [-0.10, -0.05, 0.0, 0.05, 0.10],
"action": [i / FPS for i in range(CHUNK_LEN)],
},
"pad_missing": True,
}
14.6 Multi-dataset mixing
from knonik_multidataloader.api.multi_sharded_dataloader import MultiShardedDataLoader
datasets = [
("dataset_a", {"loader": {"hlp_manifest": "/data/a_hlp/hlp_manifest.json",
"fs_type": "local", "fs_params": {"root": "/"}},
"streams": {}}),
("dataset_b", {"loader": {"hlp_manifest": "/data/b_hlp/hlp_manifest.json",
"fs_type": "local", "fs_params": {"root": "/"}},
"streams": {}}),
]
def main():
loader = MultiShardedDataLoader(
datasets=datasets,
weights=[0.7, 0.3], # 70% A / 30% B
loader_cfg={
"decode_mode": "random_access",
"chunk_len": 16,
"batch_size": 8,
"framework": "numpy",
"shuffle_mode": "global_triplet",
"planner_locality": "hlp_bounded",
"num_decoders": 8,
"ram_cache_bytes": 16 << 30,
},
)
try:
for batch in loader:
# batch["_sample_dataset_names"] -> which dataset each sample came from
pass
finally:
loader.shutdown()
if __name__ == "__main__":
main()
15. Tuning By Symptom
GPU is waiting on input. In order: raise num_decoders (4 → 8 → 16);
raise prefetch_shards (12 → 16 or 24); add or grow ram_cache_bytes; try
zerocopy; try the other shuffle mode (section 10). If the dataset was packed
as compact_video and your sampling is very sparse, try repacking it with
--storage-profile training_compressed.
Memory too high, or it keeps growing. Lower ram_cache_bytes; lower
prefetch_shards (12 → 4-8); set low_memory: true; tighten
planner_locality (global → hlp_bounded → low_mem → ultra_low_mem);
lower num_decoders.
Batches look temporally correlated. Loosen planner_locality
(ultra_low_mem → low_mem → hlp_bounded → global).
The first batch is slow. That is warm-up, paid once per loader. On large datasets it can take seconds to tens of seconds.
The run hangs at start, or fails with BrokenProcessPool. Add the
if __name__ == "__main__": guard to your entry script (section 4).
Multi-GPU run hangs at an epoch boundary. Set max_steps to the same value
on every rank (section 12).
Throughput swings batch to batch. Grow ram_cache_bytes, increase
prefetch_shards, and check whether other jobs share the disk.
16. Shut Down Correctly
Always call shutdown() when the loader is no longer needed:
loader = ShardedDataLoader(...)
try:
for batch in loader:
train_step(batch)
finally:
loader.shutdown()
This stops the loader's worker processes and threads.