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_timestamps sampling.
  • ▸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:

bash
python -c "import knonik_multidataloader; print('dataloader import OK')"

For framework="torch", install the PyTorch build that matches your CUDA runtime, for example:

bash
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):

bash
knonik login --product multidataloader

4. Single-Dataset Python Example

Use ShardedDataLoader when training from one KHLP manifest.

python
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 with BrokenProcessPool.

5. Multi-Dataset Python Example

Use MultiShardedDataLoader to mix several KHLP datasets at fixed weights.

python
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

KeyMeaning
weightsShare of each dataset in every batch, in the order of datasets.
dataset_cycleWhen 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_chunksEpoch 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:

python
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:

python
# 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:

python
# 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:

python
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.

FrameworkSettings
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:

python
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:

python
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_executionMeaning
threadedDefault. Ordered thread-pool augment. A good first choice.
inlineRuns augment in the batch assembly path. Useful for debugging.
processProcess-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:

python
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:

python
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
}
KeyMeaning
zerocopyEnable zero-copy batching.
zerocopy_frame_shapesRequired with zerocopy. {stream: [H, W, C]} for each RGB stream.
zerocopy_resizeOptional {stream: [H, W]} when mixed datasets record a stream at different resolutions.

Constraints:

  • ▸augment_fn is not supported with zerocopy=True. Apply the transform to the batched tensor in your training loop instead.
  • ▸pin_memory and ram_cache_bytes are 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.

bash
torchrun --standalone --nproc-per-node 8 train.py
python
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_size and num_decoders are 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

KeyMeaning
decode_modeUse "random_access".
hlp_manifestPath to hlp_manifest.json (produced by knonik pack). Required for ShardedDataLoader.
chunk_lenFrames per sample.
batch_sizeSamples per batch (per rank).
frameworkOutput array type: "numpy" or "torch".
fs_type"local".
fs_params{"root": "/"}.
base_seedSeed 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.

KeyDefaultMeaning
num_decoders4Decode parallelism. The main throughput setting.
hlps_in_flight4KHLP files read ahead at the same time.
prefetch_shards12How far ahead shards are read and decoded. Larger = more throughput and more memory.
precollate_batches2Ready-to-consume batches kept in the background queue. 0 disables.
augment_executionthreadedthreaded / inline / process.
augment_workersautoAugment worker count.
training_profileoffTrue 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

KeyMeaning
shuffle_modeSet "global_triplet" or "global_triplet_fast" for training (see section 10). The default keeps reads sequential and gives little batch diversity.
sampling_policyshard_uniform (default, single dataset) or episode_uniform.
strideFrame step between possible sample starts.
overlapAlternative to stride for window overlap.
allow_cross_shardAllow samples to span shard boundaries.
delta_timestampsPer-stream offsets in seconds around the anchor (section 6).
pad_missingClamp out-of-range delta_timestamps offsets instead of dropping samples.
fpsOverride the dataset FPS used to resolve delta_timestamps.

Diversity & memory - trade shuffle diversity against RAM.

KeyMeaning
planner_localityglobal → hlp_bounded → low_mem → ultra_low_mem. Further right uses less RAM, with slightly less batch diversity.
low_memoryCap memory use. Turn on if memory keeps growing.
ram_cache_bytesDecoded-data RAM cache budget. Speeds up epoch 2 onward.
mmap_cache_root / mmap_cache_bytesOptional disk-backed decoded cache that survives restarts, and its budget.

Run control & output

KeyMeaning
max_stepsBatches per epoch. Required, and equal on every rank, when training on more than one GPU.
pin_memoryTorch output only. Pin each batch for fast asynchronous GPU copies.

Zero-copy - see section 11.

Storage-aware reads

KeyDefaultMeaning
kdelta_direct_local_decodeFalseFaster sparse reads for datasets packed with training_compressed.

14. Worked Examples

Each example is a loader_cfg for the call in section 4:

python
loader = ShardedDataLoader(loader_cfg=<one of the dicts below>,
                           stream_cfg={}, dataset_name="my_dataset")

14.1 Minimal local run

python
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

python
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

python
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)

python
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

python
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

python
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:

python
loader = ShardedDataLoader(...)
try:
    for batch in loader:
        train_step(batch)
finally:
    loader.shutdown()

This stops the loader's worker processes and threads.