[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M713Y1SCFZD889TQJ7B1DZQ6":3,"skill-same:01M713Y1SCFZD889TQJ7B1DZQ6":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":48,"ownerHtmlUrl":49,"ownerBlogUrl":50,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M713Y1SCFZD889TQJ7B1DZQ6","sedpack",null,"Creates, writes, inspects, and iterates multi-shard machine learning and side-channel analysis datasets using the sedpack library (sedpack.io). Use when creating a sedpack Dataset, defining Metadata, DatasetStructure, or Attribute schemas, writing examples with dataset.filler(), DatasetFiller, or dataset.write_multiprocessing(), iterating data for JAX, PyTorch, Keras, TensorFlow, or NumPy (as_numpy_iterator, as_numpy_iterator_concurrent, as_numpy_iterator_async, as_numpy_iterator_rust, as_numpy_iterator_rust_batched, as_tfdataset), filtering or balancing shards via custom_metadata, or converting raw datasets (HDF5, NPZ, traces) into sedpack format. Don't use for modifying sedpack's internal Rust or FlatBuffers compiler implementation unless high-level API semantics are needed.","google\u002Fsedpack","google","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1342004?v=4","01M698VYEFDM0VJBZDYYJ2T83S","Google","01M713XZW3CD7QEM3HKBVMM10X",39,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fsedpack\u002Fblob\u002Fmain\u002Fsrc\u002Fsedpack\u002F.agents\u002Fskills\u002Fsedpack\u002FSKILL.md",[],[5,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"write","learning","async","for","machine learning","tensorflow","as","library","data","High-Level API","shard","io","api","analysis","dataset","when","writing","pytorch","rust","2026-11-10 10:12:30",false,"---\nname: sedpack\ndescription: >-\n  Creates, writes, inspects, and iterates multi-shard machine learning and\n  side-channel analysis datasets using the sedpack library (sedpack.io). Use\n  when creating a sedpack Dataset, defining Metadata, DatasetStructure, or\n  Attribute schemas, writing examples with dataset.filler(), DatasetFiller,\n  or dataset.write_multiprocessing(), iterating data for JAX, PyTorch, Keras,\n  TensorFlow, or NumPy (as_numpy_iterator, as_numpy_iterator_concurrent,\n  as_numpy_iterator_async, as_numpy_iterator_rust,\n  as_numpy_iterator_rust_batched, as_tfdataset), filtering or balancing\n  shards via custom_metadata, or converting raw datasets (HDF5, NPZ, traces)\n  into sedpack format. Don't use for modifying sedpack's internal Rust or\n  FlatBuffers compiler implementation unless high-level API semantics are\n  needed.\nlicense: Apache-2.0\n---\n\n# Using `sedpack` (`sedpack.io`)\n\n`sedpack` stores and streams sharded datasets using a hierarchical metadata tree\n(`dataset_info.json` to `\u003Csplit>\u002Fshards_list.json` to shard files) backed by\nFlatBuffers (`\"fb\"`), NPZ (`\"npz\"`), or TFRecords (`\"tfrec\"`).\n\n## 1. Core Imports\n\nTop-level `import sedpack` only exposes `sedpack.__version__`. Import API\nclasses from `sedpack.io` and type\u002Fsplit constants from `sedpack.io.types`:\n\n```python\nimport itertools\nfrom pathlib import Path\nimport numpy as np\n\nfrom sedpack.io import (\n    Attribute, Dataset, DatasetFiller, DatasetStructure, Metadata,\n)\nfrom sedpack.io.errors import DatasetExistsError\nfrom sedpack.io.iteration import RustBatchedGenerator, RustGenerator\nfrom sedpack.io.shard_file_metadata import ShardInfo, ShardListInfo\nfrom sedpack.io.shard_info_iterator import CachedShardInfoIterator\nfrom sedpack.io.shard_info_iterator.balanced_iterator import (\n    BalancedShardInfoIterator,\n)\nfrom sedpack.io.types import (\n    HOLDOUT_SPLIT, TEST_SPLIT, TRAIN_SPLIT, BatchT, ExampleT, SplitT,\n)\n```\n\n## 2. Creating vs. Loading a Dataset\n\n-   **Create a new dataset**: Call\n    `Dataset.create(path=dataset_path, metadata=metadata, ...)`\n    -   Creates `dataset_path` and writes `dataset_info.json`.\n    -   Raises `DatasetExistsError` (a subclass of `FileExistsError`) if\n        `dataset_info.json` already exists at `dataset_path`.\n-   **Load an existing dataset (to read or append)**: Call\n    `dataset = Dataset(dataset_path)`\n    -   There is **no** `Dataset.load()` or `Dataset.open()` method. Always call\n        `Dataset(path)`.\n-   **Valid Splits (`SplitT`)**:\n    -   Strictly `\"train\"`, `\"test\"`, or `\"holdout\"` (`TRAIN_SPLIT`,\n        `TEST_SPLIT`, `HOLDOUT_SPLIT`).\n    -   **Gotcha**: Passing `\"val\"` or `\"validation\"` raises\n        `ValueError: Not a known split value`. In `sedpack`, use `\"test\"` for\n        validation during training and `\"holdout\"` for final evaluation.\n\n## 3. Defining the Schema (`Metadata`, `DatasetStructure`, `Attribute`)\n\n```python\nmetadata = Metadata(\n    description=\"AES power traces dataset\",\n    dataset_license=\"Apache-2.0\",\n    dataset_version=\"1.0.0\",\n    custom_metadata={\"capture_scope\": \"ChipWhisperer\"},\n)\n\ndataset_structure = DatasetStructure(\n    saved_data_description=[\n        Attribute(name=\"trace\", dtype=\"float32\", shape=(5000,)),\n        Attribute(name=\"plaintext\", dtype=\"uint8\", shape=(16,)),\n        Attribute(name=\"key_id\", dtype=\"int\", shape=()),\n        Attribute(name=\"label\", dtype=\"uint8\", shape=()),\n        Attribute(name=\"raw_packet\", dtype=\"bytes\", shape=()),\n        Attribute(name=\"fixed_nonce\", dtype=\"bytes\", shape=(12,)),\n        Attribute(name=\"notes\", dtype=\"str\", shape=()),\n    ],\n    compression=\"LZ4\",          # Default is \"GZIP\"; \"LZ4\" or \"ZSTD\" recommended for speed\n    examples_per_shard=256,     # Default is 256\n    shard_file_type=\"fb\",       # \"fb\" (default, fastest), \"npz\", or \"tfrec\"\n    hash_checksum_algorithms=(\"sha256\",),\n)\n\ndataset_path = Path(\"datasets\u002Faes_traces\")\ndataset = Dataset.create(\n    path=dataset_path,\n    metadata=metadata,\n    dataset_structure=dataset_structure,\n)\n```\n\n### `Attribute` `dtype` and `shape` Rules\n\n1.  **Positive dimensions only**: Every integer in `shape` must be **strictly\n    positive (`> 0`)**. Passing `(-1,)`, `(0,)`, or `(None,)` raises\n    `ValueError`.\n2.  **Use `shape=()` for scalars and variable-length types**:\n    -   NumPy scalar: `Attribute(name=\"label\", dtype=\"uint8\", shape=())`\n    -   Arbitrary 64-bit signed Python `int`:\n        `Attribute(name=\"index\", dtype=\"int\", shape=())`\n    -   UTF-8 variable-length string:\n        `Attribute(name=\"notes\", dtype=\"str\", shape=())`\n    -   Variable-length byte sequence:\n        `Attribute(name=\"raw_packet\", dtype=\"bytes\", shape=())`\n        (`has_variable_size() == True`)\n3.  **Fixed-size vs. variable-size `\"bytes\"`**:\n    -   `dtype=\"bytes\", shape=()`: Variable-length `bytes`.\n    -   `dtype=\"bytes\", shape=(N,)`: Fixed-length `N`-byte sequence\n        (`has_variable_size() == False`). On write, accepts\n        `bytes`\u002F`bytearray`\u002F`memoryview` of length `N` or a 1D integer array of\n        shape `(N,)` with values in `[0, 255]`. On read, always returns `bytes`\n        of length `N`.\n4.  **Supported `dtype` strings**:\n    -   Numeric\u002Fboolean arrays or scalars: `\"float16\"`, `\"float32\"`,\n        `\"float64\"`, `\"int8\"`, `\"uint8\"`, `\"int16\"`, `\"uint16\"`, `\"int32\"`,\n        `\"uint32\"`, `\"int64\"`, `\"uint64\"`, `\"bool\"`.\n    -   Special scalar\u002Fsequence types: `\"int\"` (`shape=()`), `\"str\"`\n        (`shape=()`), `\"bytes\"` (`shape=()` or `shape=(N,)`).\n\n### Format (`shard_file_type`) & Compression Compatibility Matrix\n\nSelecting an unsupported `(shard_file_type, compression)` pair raises an\n`AssertionError` or `ValueError`:\n\n| `shard_file_type` | Supported `compression` values | Key Notes |\n| :--- | :--- | :--- |\n| `\"fb\"` (FlatBuffers, default) | `\"\"`, `\"LZ4\"`, `\"ZSTD\"`, `\"GZIP\"`, `\"ZLIB\"`, `\"BZ2\"`, `\"LZMA\"` | **Recommended**. Rust iterators (`as_numpy_iterator_rust*`) support `\"\"`, `\"LZ4\"`, `\"ZSTD\"`, `\"GZIP\"`, `\"ZLIB\"` (do **not** use `\"BZ2\"` or `\"LZMA\"` with Rust iterators). Does **not** support `\"ZIP\"`. |\n| `\"npz\"` (NumPy Zip) | `\"\"`, `\"ZIP\"` | **Gotcha**: Default `compression=\"GZIP\"` fails with `shard_file_type=\"npz\"`. You **must** pass `compression=\"ZIP\"` or `compression=\"\"`. |\n| `\"tfrec\"` (TFRecord) | `\"\"`, `\"GZIP\"`, `\"ZLIB\"` | Requires `tensorflow` (`sedpack[tf]` extra). Note: `\"str\"` attributes are returned as UTF-8 `bytes` when read via `as_numpy_iterator*`. |\n\n## 4. Writing Examples to a Dataset\n\n### Strict `dtype` and `shape` Checking on Write\n\nFor `\"fb\"` shards, `write_example` enforces\n`np.can_cast(value, attribute.dtype, casting=\"safe\")` and exact `shape` equality\n(`np.asarray(value).shape == attribute.shape`).\n\n-   **Gotcha**: Passing a default NumPy `float64` array to a `\"float32\"`\n    attribute, or a Python\u002FNumPy `int64` to a `\"uint8\"`\u002F`\"int32\"` attribute,\n    raises `ValueError: Cannot cast value of dtype ...`.\n-   **Fix**: Explicitly cast values before writing (for example,\n    `trace.astype(np.float32)`, `np.asarray(label, dtype=np.uint8)`).\n\n### Pattern A: Standard Single-Coordinator Writing (`dataset.filler`)\n\nUse `with dataset.filler(concurrency=4) as dataset_filler:` to stream examples.\nFull shards are serialized, compressed, and hashed asynchronously in a\nbackground `ProcessPoolExecutor` with `max(1, concurrency)` workers.\n\n```python\ndef make_example(i: int) -> ExampleT:\n    return {\n        \"trace\": np.zeros((5000,), dtype=np.float32),\n        \"plaintext\": np.zeros((16,), dtype=np.uint8),\n        \"key_id\": i,\n        \"label\": np.asarray(i % 256, dtype=np.uint8),\n        \"raw_packet\": b\"variable_len_bytes\",\n        \"fixed_nonce\": b\"0123456789ab\",\n        \"notes\": f\"example_{i}\",\n    }\n\nwith dataset.filler(concurrency=4) as dataset_filler:\n    for i in range(500):\n        dataset_filler.write_example(\n            values=make_example(i),\n            split=TRAIN_SPLIT,\n            custom_metadata={\"device\": i % 2},  # Optional per-shard metadata\n        )\n```\n\n-   **Shard buffering & `custom_metadata` grouping**:\n    -   Examples with different `custom_metadata` (or `None`\u002F`{}` vs. non-empty\n        `custom_metadata`) are never mixed in the same shard.\n    -   Up to `max(1, concurrency)` open shards are buffered in memory\n        simultaneously across `(split, custom_metadata)` pairs using an LRU\n        policy. Grouping writes by `(split, custom_metadata)` avoids flushing\n        partially filled shards when writing many distinct `custom_metadata`\n        values.\n-   **Appending to an existing dataset**:\n    -   Load `dataset = Dataset(path)` and open another\n        `with dataset.filler() as filler:` block. Exiting the `with` block\n        merges the new shards into `\u003Csplit>\u002Fshards_list.json` and\n        `dataset_info.json`.\n-   **Updating `dataset.metadata` or `Attribute.custom_metadata`**:\n    -   `dataset.filler()` saves `dataset_info.json` on `__exit__`. If you\n        modify `dataset.metadata.custom_metadata` or\n        `dataset.dataset_structure.saved_data_description[i].custom_metadata`\n        *after* the `with dataset.filler():` block (for example, recording\n        global min\u002Fmax statistics), you **must** call `dataset.write_config()`\n        afterwards to persist those updates.\n-   **Converting existing NPZ, HDF5, or raw trace files**:\n    -   Stream records into `with dataset.filler(concurrency=4) as filler:` and\n        cast each array to the schema `dtype` (`np.asarray(x, dtype=...)`).\n    -   When reading `.npz`\u002F`.npy` files, pass `allow_pickle=False`\n        (`with np.load(npz_path, allow_pickle=False) as archive:`) to prevent\n        unsafe `pickle` deserialization. For HDF5 (`h5py.File(h5_path, \"r\")`),\n        slice rows incrementally rather than loading the entire file into RAM.\n\n### Pattern B: Built-In Multiprocessing (`dataset.write_multiprocessing`)\n\nWhen generating or converting examples is CPU-bound, use\n`dataset.write_multiprocessing`. Each worker automatically receives an isolated\n`DatasetFiller` with a unique `relative_path_from_split`.\n\n```python\ndef feed_worker(\n    dataset_filler: DatasetFiller,\n    worker_items: list[int],\n    *,\n    split: SplitT,\n) -> int:\n    # MUST enter the context manager inside feed_writer\n    with dataset_filler:\n        for item in worker_items:\n            dataset_filler.write_example(values=make_example(item), split=split)\n    return len(worker_items)\n\n# Spawn 2 workers (len(custom_arguments) determines the number of tasks)\ncounts = dataset.write_multiprocessing(\n    feed_writer=feed_worker,\n    custom_arguments=[([0, 1, 2],), ([3, 4, 5],)],\n    custom_kwarguments=[{\"split\": TRAIN_SPLIT}, {\"split\": TEST_SPLIT}],\n    consistency_check=True,\n    single_process=False,\n)\n```\n\n-   **Gotcha**: The first positional argument of `feed_writer` is **always**\n    `dataset_filler: DatasetFiller`, and `feed_writer` **must** use\n    `with dataset_filler:`.\n\n### Pattern C: Custom Multi-Worker \u002F Distributed Writing\n\nIf you manage your own multi-process or distributed workers:\n\n1.  Every worker must open `Dataset(dataset_path)` and construct `DatasetFiller`\n    with a **non-empty, mutually disjoint** `relative_path_from_split` (no\n    worker path may be a parent prefix of another; for example, use\n    `Path(\"worker_0\")`, `Path(\"worker_1\")`).\n2.  Each worker writes inside `with filler:` and returns\n    `filler.get_updated_infos()`.\n3.  After all workers finish, a single coordinator calls\n    `dataset.write_config(updated_infos=all_updated_infos)`.\n\n```python\n# Inside worker `worker_id`:\nworker_ds = Dataset(dataset_path)\nfiller = DatasetFiller(\n    dataset=worker_ds,\n    concurrency=2,\n    relative_path_from_split=Path(f\"worker_{worker_id}\"),\n)\nwith filler:\n    filler.write_example(values=make_example(worker_id), split=TRAIN_SPLIT)\nworker_infos: list[ShardListInfo] = filler.get_updated_infos()\n\n# On the coordinator after all workers complete:\ndataset.write_config(updated_infos=all_worker_infos)\n```\n\n> **Critical**: Never use default `relative_path_from_split=Path(\".\")` across\n> concurrent workers, even if workers write to different splits—exiting a root\n> `DatasetFiller` immediately writes `dataset_info.json` and overwrites other\n> splits.\n\n## 5. Reading & Iterating a Dataset\n\n### Critical Defaults Gotcha: `repeat=True` and `shuffle=1_000`\n\nEvery `dataset.as_*` iterator defaults to **`repeat=True` (infinite stream)**\nand **`shuffle=1_000`**:\n\n-   **For training**: Keep `repeat=True, shuffle=1_000` (or larger) and bound\n    epochs with `itertools.islice(it, steps_per_epoch)` or `steps_per_epoch` in\n    `model.fit`.\n-   **For evaluation, validation, testing, or single-pass statistics (such as\n    SNR or accuracy)**: You **must** pass **`repeat=False, shuffle=0`**.\n    Otherwise a `for batch in dataset.as_numpy_iterator...(split=...)` loop\n    runs forever.\n-   **Keyword-only `split`**: Always pass `split=` as a keyword argument\n    (`split=TRAIN_SPLIT`).\n\n### Choosing the Right Iterator\n\n| Method | Yields \u002F Returns | Formats | Record Transform Arg | When to Use |\n| :--- | :--- | :--- | :--- | :--- |\n| `as_numpy_iterator_rust_batched` | `Iterator[BatchT]` | `\"fb\"` (`\"\"`, `\"LZ4\"`, `\"ZSTD\"`, `\"GZIP\"`, `\"ZLIB\"`) | `process_batch` | **Best for JAX, PyTorch, Keras, and fast batched evaluation**. |\n| `as_numpy_iterator_rust` | `Iterator[ExampleT]` | `\"fb\"` (`\"\"`, `\"LZ4\"`, `\"ZSTD\"`, `\"GZIP\"`, `\"ZLIB\"`) | `process_record` | Fast unbatched iteration over `\"fb\"` shards. |\n| `as_tfdataset` | `tf.data.Dataset` | `\"tfrec\"`, `\"fb\"`, `\"npz\"` | `process_record` | TensorFlow \u002F `tf.data` pipelines. |\n| `as_numpy_iterator` | `Iterator[ExampleT]` | `\"fb\"`, `\"npz\"`, `\"tfrec\"` | `process_record` | Simple single-process iteration, debugging, or `\"npz\"`\u002F`\"tfrec\"` reading. |\n| `as_numpy_iterator_concurrent` | `Iterator[ExampleT]` | `\"fb\"`, `\"npz\"`, `\"tfrec\"` | `process_record` | Multi-worker Python unbatched iteration (supports `custom_metadata_type_limit`). |\n| `as_numpy_iterator_async` | `AsyncIterator[ExampleT]` | `\"fb\"`, `\"npz\"` | `process_record` | `asyncio` pipelines (`async for example in ...`). |\n\n### 1. Fast Batched Iteration (`as_numpy_iterator_rust_batched`)\n\n```python\n# Training (infinite shuffled stream of batches)\ntrain_batches = dataset.as_numpy_iterator_rust_batched(\n    split=TRAIN_SPLIT,\n    batch_size=64,\n    repeat=True,\n    shuffle=10_000,\n    process_batch=lambda b: (b[\"trace\"], b[\"label\"]),\n)\n\n# Single-pass evaluation (finite, deterministic order)\nfor batch in dataset.as_numpy_iterator_rust_batched(\n    split=HOLDOUT_SPLIT,\n    batch_size=64,\n    repeat=False,\n    shuffle=0,\n):\n    traces = batch[\"trace\"]          # np.ndarray of shape (64, 5000), dtype float32\n    labels = batch[\"label\"]          # np.ndarray of shape (64,), dtype uint8\n    packets = batch[\"raw_packet\"]    # list[bytes] of length 64\n    notes = batch[\"notes\"]           # list[str] of length 64\n    key_ids = batch[\"key_id\"]        # list[int] of length 64\n```\n\n-   **Always pass `batch_size` explicitly**: `as_numpy_iterator_rust_batched`\n    defaults to `batch_size=1` (unlike `as_tfdataset`, which defaults to\n    `batch_size=32`).\n-   **Batched value types (`BatchT`)**:\n    -   Numeric\u002Fboolean NumPy attributes have shape\n        `(batch_size, *attribute.shape)`.\n    -   `\"bytes\"`, `\"str\"`, and `\"int\"` attributes are returned as\n        `list[bytes]`, `list[str]`, and `list[int]` of length `batch_size`.\n-   **Trailing remainder batches**: When `repeat=False`, if the total number of\n    examples `N` is not divisible by `batch_size`, the trailing\n    `N % batch_size` examples are dropped by `as_numpy_iterator_rust_batched`.\n    To visit every single example when `N % batch_size != 0`, use unbatched\n    `as_numpy_iterator_rust(split=..., repeat=False, shuffle=0)`.\n\n### 2. Unbatched Iteration (`as_numpy_iterator_rust`, `as_numpy_iterator`, `as_numpy_iterator_concurrent`)\n\n```python\nfor example in dataset.as_numpy_iterator_rust(\n    split=TEST_SPLIT,\n    repeat=False,\n    shuffle=0,\n    process_record=None,\n):\n    trace = example[\"trace\"]  # np.ndarray of shape (5000,)\n    label = example[\"label\"]  # np.ndarray scalar of shape ()\n```\n\n-   **Pickleable `process_record` in `as_numpy_iterator_concurrent`**: When\n    `shuffle > 0`, `as_numpy_iterator_concurrent` executes `process_record`\n    inside `multiprocessing.Pool` workers, so `process_record` **must be a\n    top-level function or `functools.partial`** (not a `lambda` or local\n    closure).\n\n### 3. TensorFlow Dataset (`as_tfdataset`)\n\n```python\ntf_ds = dataset.as_tfdataset(\n    split=TRAIN_SPLIT,\n    batch_size=32,   # Pass batch_size=0 to disable batching\n    repeat=True,\n    shuffle=1_000,\n)\n# When reshaping or converting dictionaries to (x, y) tuples for Keras on \"fb\"\n# or \"npz\" datasets, apply .map() on the returned tf.data.Dataset rather than\n# changing structure inside process_record (which must match\n# saved_data_description):\ntf_ds = tf_ds.map(lambda ex: (ex[\"trace\"], ex[\"label\"]))\n```\n\n## 6. Inspecting Metadata, Filtering, Balancing, & Checking Integrity\n\n### Inspect Example & Shard Counts Without Reading Shards\n\n```python\ndataset = Dataset(dataset_path)\n\n# Check if split exists before indexing dataset.dataset_info.splits\nif TRAIN_SPLIT in dataset.dataset_info.splits:\n    split_meta = dataset.dataset_info.splits[TRAIN_SPLIT]\n    print(split_meta.number_of_examples, split_meta.number_of_shards)\n\n# Look up an Attribute schema by name\ntrace_attr = dataset.dataset_structure.attribute_by_name(\"trace\")\nprint(trace_attr.dtype, trace_attr.shape, trace_attr.custom_metadata)\n```\n\n### Filter or Limit Shards by `ShardInfo` Metadata\n\nAll `as_*` iterators accept `shard_filter: Callable[[ShardInfo], bool]` and\n`shards: int | None` (evaluated purely from `shards_list.json` without reading\nshard files):\n\n```python\ndevice_0_it = dataset.as_numpy_iterator_rust_batched(\n    split=TRAIN_SPLIT,\n    batch_size=32,\n    repeat=False,\n    shuffle=0,\n    shards=10,  # Optional: read at most the first 10 matching shards\n    shard_filter=lambda shard_info: shard_info.custom_metadata.get(\"device\") == 0,\n)\n```\n\n-   **Empty filter result**: If `shard_filter` matches zero shards (or the\n    split has zero shards), `as_numpy_iterator`, `as_numpy_iterator_rust`, and\n    `as_numpy_iterator_rust_batched` yield zero items, whereas\n    `as_numpy_iterator_concurrent`, `as_numpy_iterator_async`, `as_tfdataset`,\n    and `shard_paths_dataset` raise\n    `ValueError: The list of shards is empty. Try less restrictive filtering.`\n-   **Limiting shards per distinct `custom_metadata`**: `as_numpy_iterator`,\n    `as_numpy_iterator_concurrent`, and `as_tfdataset` also accept\n    `custom_metadata_type_limit=K` to read at most `K` shards for each unique\n    `ShardInfo.custom_metadata` dictionary.\n-   **Iterating shard metadata directly**: Use\n    `for shard_info in dataset.shard_info_iterator(TRAIN_SPLIT): ...` (pass\n    `None` to iterate across all present splits).\n\n### Balanced Iteration Across Shard Categories (`BalancedShardInfoIterator`)\n\nTo sample shards with equal (or custom-weighted) probability across metadata\nattributes regardless of shard count imbalance:\n\n```python\ndef by_device(shard_info: ShardInfo) -> int:\n    return shard_info.custom_metadata[\"device\"]\n\n# Optional custom weight per category:\n# by_device.weight = lambda shard_info: 3.0 if shard_info.custom_metadata[\"device\"] == 0 else 1.0\n\nbalanced_shards = BalancedShardInfoIterator(\n    dataset_path=dataset.path,\n    dataset_info=dataset.dataset_info,\n    split=TRAIN_SPLIT,\n    repeat=True,\n    shuffle=100,\n    balance_by=(by_device,),\n    shard_filter=None,\n)\n\n# Option A: Fast Rust batched iteration over balanced shards (\"fb\" format)\nwith RustBatchedGenerator(\n    dataset_path=dataset.path,\n    dataset_structure=dataset.dataset_structure,\n    shard_iterator=balanced_shards,\n    batch_size=64,\n    process_batch=None,\n    shuffle_buffer_size=1_000,\n) as rust_generator:\n    for batch in itertools.islice(rust_generator(), 100):\n        traces = batch[\"trace\"]\n\n# Option B: Python unbatched iteration over balanced shards (all formats)\nbalanced_examples = dataset.example_iterator_from_shard_iterator(\n    shard_iterator=balanced_shards,\n    process_record=None,\n    shuffle=1_000,\n)\nfor example in itertools.islice(balanced_examples, 100):\n    trace = example[\"trace\"]\n```\n\n### Verify Dataset Integrity (`dataset.check()`)\n\n```python\n# Validates dataset_info.json, all shards_list.json files, shard hashes, and example counts\ndataset.check(show_progressbar=False)\n\n# Get root dataset_info.json checksums (call after write_config)\nchecksums: tuple[str, ...] = dataset.current_metadata_checksums()\n```\n\n## 7. Quick Troubleshooting Table\n\n| Error \u002F Symptom | Cause | Solution |\n| :--- | :--- | :--- |\n| Evaluation loop hangs \u002F never finishes | Default `repeat=True` creates an infinite iterator | Pass `repeat=False, shuffle=0` to `dataset.as_*` |\n| `ValueError: Not a known split value` | Passed `\"val\"` or `\"validation\"` as `split` | Use `\"train\"`, `\"test\"` (`TEST_SPLIT`), or `\"holdout\"` (`HOLDOUT_SPLIT`) |\n| `ValueError: The list of shards is empty. Try less restrictive filtering.` | `shard_filter` matched zero shards or split has no shards | Relax `shard_filter` or check `split in dataset.dataset_info.splits` first |\n| `ValueError: Cannot cast value of dtype ...` | Passed `float64` to `\"float32\"` or `int64` to `\"uint8\"`\u002F`\"int32\"` in `\"fb\"` writer | Cast explicitly before `write_example`: `trace.astype(np.float32)` |\n| `ValueError: Shape requires positive values` | Used `shape=()` with `0` or `-1`, such as `(-1, 128)` or `(0,)` | Use `shape=()` for scalars\u002Fvariable-length `\"str\"`\u002F`\"bytes\"`, or fixed positive dimensions |\n| `AssertionError` when creating\u002Fwriting `\"npz\"` dataset | Default `compression=\"GZIP\"` is unsupported for `shard_file_type=\"npz\"` | Set `compression=\"ZIP\"` or `compression=\"\"` in `DatasetStructure` |\n| `TypeError: ... takes 1 positional argument` on `as_numpy_iterator*` | Passed `split` by position (`dataset.as_numpy_iterator(\"train\")`) | Pass `split` as a keyword argument (`dataset.as_numpy_iterator(split=\"train\")`) |\n| `TypeError: ... got an unexpected keyword argument 'process_record'` on `as_numpy_iterator_rust_batched` | `as_numpy_iterator_rust_batched` transforms batches, not individual records | Use `process_batch=...` instead of `process_record=...` |\n| Attribute `custom_metadata` changes lost after `with dataset.filler():` | `dataset.filler()` writes `dataset_info.json` upon exiting the `with` block | Call `dataset.write_config()` after mutating `dataset.metadata` or `Attribute.custom_metadata` |\n| `AttributeError: Can't pickle local object` in `as_numpy_iterator_concurrent` | Passed a `lambda` or closure as `process_record` while `shuffle > 0` | Define `process_record` as a top-level function or use `as_numpy_iterator_rust` |\n","# Using `sedpack` (`sedpack.io`)\n\n`sedpack` stores and streams sharded datasets using a hierarchical metadata tree\n(`dataset_info.json` to `\u003Csplit>\u002Fshards_list.json` to shard files) backed by\nFlatBuffers (`\"fb\"`), NPZ (`\"npz\"`), or TFRecords (`\"tfrec\"`).\n\n## 1. Core Imports\n\nTop-level `import sedpack` only exposes `sedpack.__version__`. Import API\nclasses from `sedpack.io` and type\u002Fsplit constants from `sedpack.io.types`:\n\n```python\nimport itertools\nfrom pathlib import Path\nimport numpy as np\n\nfrom sedpack.io import (\n    Attribute, Dataset, DatasetFiller, DatasetStructure, Metadata,\n)\nfrom sedpack.io.errors import DatasetExistsError\nfrom sedpack.io.iteration import RustBatchedGenerator, RustGenerator\nfrom sedpack.io.shard_file_metadata import ShardInfo, ShardListInfo\nfrom sedpack.io.shard_info_iterator import CachedShardInfoIterator\nfrom sedpack.io.shard_info_iterator.balanced_iterator import (\n    BalancedShardInfoIterator,\n)\nfrom sedpack.io.types import (\n    HOLDOUT_SPLIT, TEST_SPLIT, TRAIN_SPLIT, BatchT, ExampleT, SplitT,\n)\n```\n\n## 2. Creating vs. Loading a Dataset\n\n-   **Create a new dataset**: Call\n    `Dataset.create(path=dataset_path, metadata=metadata, ...)`\n    -   Creates `dataset_path` and writes `dataset_info.json`.\n    -   Raises `DatasetExistsError` (a subclass of `FileExistsError`) if\n        `dataset_info.json` already exists at `dataset_path`.\n-   **Load an existing dataset (to read or append)**: Call\n    `dataset = Dataset(dataset_path)`\n    -   There is **no** `Dataset.load()` or `Dataset.open()` method. Always call\n        `Dataset(path)`.\n-   **Valid Splits (`SplitT`)**:\n    -   Strictly `\"train\"`, `\"test\"`, or `\"holdout\"` (`TRAIN_SPLIT`,\n        `TEST_SPLIT`, `HOLDOUT_SPLIT`).\n    -   **Gotcha**: Passing `\"val\"` or `\"validation\"` raises\n        `ValueError: Not a known split value`. In `sedpack`, use `\"test\"` for\n        validation during training and `\"holdout\"` for final evaluation.\n\n## 3. Defining the Schema (`Metadata`, `DatasetStructure`, `Attribute`)\n\n```python\nmetadata = Metadata(\n    description=\"AES power traces dataset\",\n    dataset_license=\"Apache-2.0\",\n    dataset_version=\"1.0.0\",\n    custom_metadata={\"capture_scope\": \"ChipWhisperer\"},\n)\n\ndataset_structure = DatasetStructure(\n    saved_data_description=[\n        Attribute(name=\"trace\", dtype=\"float32\", shape=(5000,)),\n        Attribute(name=\"plaintext\", dtype=\"uint8\", shape=(16,)),\n        Attribute(name=\"key_id\", dtype=\"int\", shape=()),\n        Attribute(name=\"label\", dtype=\"uint8\", shape=()),\n        Attribute(name=\"raw_packet\", dtype=\"bytes\", shape=()),\n        Attribute(name=\"fixed_nonce\", dtype=\"bytes\", shape=(12,)),\n        Attribute(name=\"notes\", dtype=\"str\", shape=()),\n    ],\n    compression=\"LZ4\",          # Default is \"GZIP\"; \"LZ4\" or \"ZSTD\" recommended for speed\n    examples_per_shard=256,     # Default is 256\n    shard_file_type=\"fb\",       # \"fb\" (default, fastest), \"npz\", or \"tfrec\"\n    hash_checksum_algorithms=(\"sha256\",),\n)\n\ndataset_path = Path(\"datasets\u002Faes_traces\")\ndataset = Dataset.create(\n    path=dataset_path,\n    metadata=metadata,\n    dataset_structure=dataset_structure,\n)\n```\n\n### `Attribute` `dtype` and `shape` Rules\n\n1.  **Positive dimensions only**: Every integer in `shape` must be **strictly\n    positive (`> 0`)**. Passing `(-1,)`, `(0,)`, or `(None,)` raises\n    `ValueError`.\n2.  **Use `shape=()` for scalars and variable-length types**:\n    -   NumPy scalar: `Attribute(name=\"label\", dtype=\"uint8\", shape=())`\n    -   Arbitrary 64-bit signed Python `int`:\n        `Attribute(name=\"index\", dtype=\"int\", shape=())`\n    -   UTF-8 variable-length string:\n        `Attribute(name=\"notes\", dtype=\"str\", shape=())`\n    -   Variable-length byte sequence:\n        `Attribute(name=\"raw_packet\", dtype=\"bytes\", shape=())`\n        (`has_variable_size() == True`)\n3.  **Fixed-size vs. variable-size `\"bytes\"`**:\n    -   `dtype=\"bytes\", shape=()`: Variable-length `bytes`.\n    -   `dtype=\"bytes\", shape=(N,)`: Fixed-length `N`-byte sequence\n        (`has_variable_size() == False`). On write, accepts\n        `bytes`\u002F`bytearray`\u002F`memoryview` of length `N` or a 1D integer array of\n        shape `(N,)` with values in `[0, 255]`. On read, always returns `bytes`\n        of length `N`.\n4.  **Supported `dtype` strings**:\n    -   Numeric\u002Fboolean arrays or scalars: `\"float16\"`, `\"float32\"`,\n        `\"float64\"`, `\"int8\"`, `\"uint8\"`, `\"int16\"`, `\"uint16\"`, `\"int32\"`,\n        `\"uint32\"`, `\"int64\"`, `\"uint64\"`, `\"bool\"`.\n    -   Special scalar\u002Fsequence types: `\"int\"` (`shape=()`), `\"str\"`\n        (`shape=()`), `\"bytes\"` (`shape=()` or `shape=(N,)`).\n\n### Format (`shard_file_type`) & Compression Compatibility Matrix\n\nSelecting an unsupported `(shard_file_type, compression)` pair raises an\n`AssertionError` or `ValueError`:\n\n| `shard_file_type` | Supported `compression` values | Key Notes |\n| :--- | :--- | :--- |\n| `\"fb\"` (FlatBuffers, default) | `\"\"`, `\"LZ4\"`, `\"ZSTD\"`, `\"GZIP\"`, `\"ZLIB\"`, `\"BZ2\"`, `\"LZMA\"` | **Recommended**. Rust iterators (`as_numpy_iterator_rust*`) support `\"\"`, `\"LZ4\"`, `\"ZSTD\"`, `\"GZIP\"`, `\"ZLIB\"` (do **not** use `\"BZ2\"` or `\"LZMA\"` with Rust iterators). Does **not** support `\"ZIP\"`. |\n| `\"npz\"` (NumPy Zip) | `\"\"`, `\"ZIP\"` | **Gotcha**: Default `compression=\"GZIP\"` fails with `shard_file_type=\"npz\"`. You **must** pass `compression=\"ZIP\"` or `compression=\"\"`. |\n| `\"tfrec\"` (TFRecord) | `\"\"`, `\"GZIP\"`, `\"ZLIB\"` | Requires `tensorflow` (`sedpack[tf]` extra). Note: `\"str\"` attributes are returned as UTF-8 `bytes` when read via `as_numpy_iterator*`. |\n\n## 4. Writing Examples to a Dataset\n\n### Strict `dtype` and `shape` Checking on Write\n\nFor `\"fb\"` shards, `write_example` enforces\n`np.can_cast(value, attribute.dtype, casting=\"safe\")` and exact `shape` equality\n(`np.asarray(value).shape == attribute.shape`).\n\n-   **Gotcha**: Passing a default NumPy `float64` array to a `\"float32\"`\n    attribute, or a Python\u002FNumPy `int64` to a `\"uint8\"`\u002F`\"int32\"` attribute,\n    raises `ValueError: Cannot cast value of dtype ...`.\n-   **Fix**: Explicitly cast values before writing (for example,\n    `trace.astype(np.float32)`, `np.asarray(label, dtype=np.uint8)`).\n\n### Pattern A: Standard Single-Coordinator Writing (`dataset.filler`)\n\nUse `with dataset.filler(concurrency=4) as dataset_filler:` to stream examples.\nFull shards are serialized, compressed, and hashed asynchronously in a\nbackground `ProcessPoolExecutor` with `max(1, concurrency)` workers.\n\n```python\ndef make_example(i: int) -> ExampleT:\n    return {\n        \"trace\": np.zeros((5000,), dtype=np.float32),\n        \"plaintext\": np.zeros((16,), dtype=np.uint8),\n        \"key_id\": i,\n        \"label\": np.asarray(i % 256, dtype=np.uint8),\n        \"raw_packet\": b\"variable_len_bytes\",\n        \"fixed_nonce\": b\"0123456789ab\",\n        \"notes\": f\"example_{i}\",\n    }\n\nwith dataset.filler(concurrency=4) as dataset_filler:\n    for i in range(500):\n        dataset_filler.write_example(\n            values=make_example(i),\n            split=TRAIN_SPLIT,\n            custom_metadata={\"device\": i % 2},  # Optional per-shard metadata\n        )\n```\n\n-   **Shard buffering & `custom_metadata` grouping**:\n    -   Examples with different `custom_metadata` (or `None`\u002F`{}` vs. non-empty\n        `custom_metadata`) are never mixed in the same shard.\n    -   Up to `max(1, concurrency)` open shards are buffered in memory\n        simultaneously across `(split, custom_metadata)` pairs using an LRU\n        policy. Grouping writes by `(split, custom_metadata)` avoids flushing\n        partially filled shards when writing many distinct `custom_metadata`\n        values.\n-   **Appending to an existing dataset**:\n    -   Load `dataset = Dataset(path)` and open another\n        `with dataset.filler() as filler:` block. Exiting the `with` block\n        merges the new shards into `\u003Csplit>\u002Fshards_list.json` and\n        `dataset_info.json`.\n-   **Updating `dataset.metadata` or `Attribute.custom_metadata`**:\n    -   `dataset.filler()` saves `dataset_info.json` on `__exit__`. If you\n        modify `dataset.metadata.custom_metadata` or\n        `dataset.dataset_structure.saved_data_description[i].custom_metadata`\n        *after* the `with dataset.filler():` block (for example, recording\n        global min\u002Fmax statistics), you **must** call `dataset.write_config()`\n        afterwards to persist those updates.\n-   **Converting existing NPZ, HDF5, or raw trace files**:\n    -   Stream records into `with dataset.filler(concurrency=4) as filler:` and\n        cast each array to the schema `dtype` (`np.asarray(x, dtype=...)`).\n    -   When reading `.npz`\u002F`.npy` files, pass `allow_pickle=False`\n        (`with np.load(npz_path, allow_pickle=False) as archive:`) to prevent\n        unsafe `pickle` deserialization. For HDF5 (`h5py.File(h5_path, \"r\")`),\n        slice rows incrementally rather than loading the entire file into RAM.\n\n### Pattern B: Built-In Multiprocessing (`dataset.write_multiprocessing`)\n\nWhen generating or converting examples is CPU-bound, use\n`dataset.write_multiprocessing`. Each worker automatically receives an isolated\n`DatasetFiller` with a unique `relative_path_from_split`.\n\n```python\ndef feed_worker(\n    dataset_filler: DatasetFiller,\n    worker_items: list[int],\n    *,\n    split: SplitT,\n) -> int:\n    # MUST enter the context manager inside feed_writer\n    with dataset_filler:\n        for item in worker_items:\n            dataset_filler.write_example(values=make_example(item), split=split)\n    return len(worker_items)\n\n# Spawn 2 workers (len(custom_arguments) determines the number of tasks)\ncounts = dataset.write_multiprocessing(\n    feed_writer=feed_worker,\n    custom_arguments=[([0, 1, 2],), ([3, 4, 5],)],\n    custom_kwarguments=[{\"split\": TRAIN_SPLIT}, {\"split\": TEST_SPLIT}],\n    consistency_check=True,\n    single_process=False,\n)\n```\n\n-   **Gotcha**: The first positional argument of `feed_writer` is **always**\n    `dataset_filler: DatasetFiller`, and `feed_writer` **must** use\n    `with dataset_filler:`.\n\n### Pattern C: Custom Multi-Worker \u002F Distributed Writing\n\nIf you manage your own multi-process or distributed workers:\n\n1.  Every worker must open `Dataset(dataset_path)` and construct `DatasetFiller`\n    with a **non-empty, mutually disjoint** `relative_path_from_split` (no\n    worker path may be a parent prefix of another; for example, use\n    `Path(\"worker_0\")`, `Path(\"worker_1\")`).\n2.  Each worker writes inside `with filler:` and returns\n    `filler.get_updated_infos()`.\n3.  After all workers finish, a single coordinator calls\n    `dataset.write_config(updated_infos=all_updated_infos)`.\n\n```python\n# Inside worker `worker_id`:\nworker_ds = Dataset(dataset_path)\nfiller = DatasetFiller(\n    dataset=worker_ds,\n    concurrency=2,\n    relative_path_from_split=Path(f\"worker_{worker_id}\"),\n)\nwith filler:\n    filler.write_example(values=make_example(worker_id), split=TRAIN_SPLIT)\nworker_infos: list[ShardListInfo] = filler.get_updated_infos()\n\n# On the coordinator after all workers complete:\ndataset.write_config(updated_infos=all_worker_infos)\n```\n\n> **Critical**: Never use default `relative_path_from_split=Path(\".\")` across\n> concurrent workers, even if workers write to different splits—exiting a root\n> `DatasetFiller` immediately writes `dataset_info.json` and overwrites other\n> splits.\n\n## 5. Reading & Iterating a Dataset\n\n### Critical Defaults Gotcha: `repeat=True` and `shuffle=1_000`\n\nEvery `dataset.as_*` iterator defaults to **`repeat=True` (infinite stream)**\nand **`shuffle=1_000`**:\n\n-   **For training**: Keep `repeat=True, shuffle=1_000` (or larger) and bound\n    epochs with `itertools.islice(it, steps_per_epoch)` or `steps_per_epoch` in\n    `model.fit`.\n-   **For evaluation, validation, testing, or single-pass statistics (such as\n    SNR or accuracy)**: You **must** pass **`repeat=False, shuffle=0`**.\n    Otherwise a `for batch in dataset.as_numpy_iterator...(split=...)` loop\n    runs forever.\n-   **Keyword-only `split`**: Always pass `split=` as a keyword argument\n    (`split=TRAIN_SPLIT`).\n\n### Choosing the Right Iterator\n\n| Method | Yields \u002F Returns | Formats | Record Transform Arg | When to Use |\n| :--- | :--- | :--- | :--- | :--- |\n| `as_numpy_iterator_rust_batched` | `Iterator[BatchT]` | `\"fb\"` (`\"\"`, `\"LZ4\"`, `\"ZSTD\"`, `\"GZIP\"`, `\"ZLIB\"`) | `process_batch` | **Best for JAX, PyTorch, Keras, and fast batched evaluation**. |\n| `as_numpy_iterator_rust` | `Iterator[ExampleT]` | `\"fb\"` (`\"\"`, `\"LZ4\"`, `\"ZSTD\"`, `\"GZIP\"`, `\"ZLIB\"`) | `process_record` | Fast unbatched iteration over `\"fb\"` shards. |\n| `as_tfdataset` | `tf.data.Dataset` | `\"tfrec\"`, `\"fb\"`, `\"npz\"` | `process_record` | TensorFlow \u002F `tf.data` pipelines. |\n| `as_numpy_iterator` | `Iterator[ExampleT]` | `\"fb\"`, `\"npz\"`, `\"tfrec\"` | `process_record` | Simple single-process iteration, debugging, or `\"npz\"`\u002F`\"tfrec\"` reading. |\n| `as_numpy_iterator_concurrent` | `Iterator[ExampleT]` | `\"fb\"`, `\"npz\"`, `\"tfrec\"` | `process_record` | Multi-worker Python unbatched iteration (supports `custom_metadata_type_limit`). |\n| `as_numpy_iterator_async` | `AsyncIterator[ExampleT]` | `\"fb\"`, `\"npz\"` | `process_record` | `asyncio` pipelines (`async for example in ...`). |\n\n### 1. Fast Batched Iteration (`as_numpy_iterator_rust_batched`)\n\n```python\n# Training (infinite shuffled stream of batches)\ntrain_batches = dataset.as_numpy_iterator_rust_batched(\n    split=TRAIN_SPLIT,\n    batch_size=64,\n    repeat=True,\n    shuffle=10_000,\n    process_batch=lambda b: (b[\"trace\"], b[\"label\"]),\n)\n\n# Single-pass evaluation (finite, deterministic order)\nfor batch in dataset.as_numpy_iterator_rust_batched(\n    split=HOLDOUT_SPLIT,\n    batch_size=64,\n    repeat=False,\n    shuffle=0,\n):\n    traces = batch[\"trace\"]          # np.ndarray of shape (64, 5000), dtype float32\n    labels = batch[\"label\"]          # np.ndarray of shape (64,), dtype uint8\n    packets = batch[\"raw_packet\"]    # list[bytes] of length 64\n    notes = batch[\"notes\"]           # list[str] of length 64\n    key_ids = batch[\"key_id\"]        # list[int] of length 64\n```\n\n-   **Always pass `batch_size` explicitly**: `as_numpy_iterator_rust_batched`\n    defaults to `batch_size=1` (unlike `as_tfdataset`, which defaults to\n    `batch_size=32`).\n-   **Batched value types (`BatchT`)**:\n    -   Numeric\u002Fboolean NumPy attributes have shape\n        `(batch_size, *attribute.shape)`.\n    -   `\"bytes\"`, `\"str\"`, and `\"int\"` attributes are returned as\n        `list[bytes]`, `list[str]`, and `list[int]` of length `batch_size`.\n-   **Trailing remainder batches**: When `repeat=False`, if the total number of\n    examples `N` is not divisible by `batch_size`, the trailing\n    `N % batch_size` examples are dropped by `as_numpy_iterator_rust_batched`.\n    To visit every single example when `N % batch_size != 0`, use unbatched\n    `as_numpy_iterator_rust(split=..., repeat=False, shuffle=0)`.\n\n### 2. Unbatched Iteration (`as_numpy_iterator_rust`, `as_numpy_iterator`, `as_numpy_iterator_concurrent`)\n\n```python\nfor example in dataset.as_numpy_iterator_rust(\n    split=TEST_SPLIT,\n    repeat=False,\n    shuffle=0,\n    process_record=None,\n):\n    trace = example[\"trace\"]  # np.ndarray of shape (5000,)\n    label = example[\"label\"]  # np.ndarray scalar of shape ()\n```\n\n-   **Pickleable `process_record` in `as_numpy_iterator_concurrent`**: When\n    `shuffle > 0`, `as_numpy_iterator_concurrent` executes `process_record`\n    inside `multiprocessing.Pool` workers, so `process_record` **must be a\n    top-level function or `functools.partial`** (not a `lambda` or local\n    closure).\n\n### 3. TensorFlow Dataset (`as_tfdataset`)\n\n```python\ntf_ds = dataset.as_tfdataset(\n    split=TRAIN_SPLIT,\n    batch_size=32,   # Pass batch_size=0 to disable batching\n    repeat=True,\n    shuffle=1_000,\n)\n# When reshaping or converting dictionaries to (x, y) tuples for Keras on \"fb\"\n# or \"npz\" datasets, apply .map() on the returned tf.data.Dataset rather than\n# changing structure inside process_record (which must match\n# saved_data_description):\ntf_ds = tf_ds.map(lambda ex: (ex[\"trace\"], ex[\"label\"]))\n```\n\n## 6. Inspecting Metadata, Filtering, Balancing, & Checking Integrity\n\n### Inspect Example & Shard Counts Without Reading Shards\n\n```python\ndataset = Dataset(dataset_path)\n\n# Check if split exists before indexing dataset.dataset_info.splits\nif TRAIN_SPLIT in dataset.dataset_info.splits:\n    split_meta = dataset.dataset_info.splits[TRAIN_SPLIT]\n    print(split_meta.number_of_examples, split_meta.number_of_shards)\n\n# Look up an Attribute schema by name\ntrace_attr = dataset.dataset_structure.attribute_by_name(\"trace\")\nprint(trace_attr.dtype, trace_attr.shape, trace_attr.custom_metadata)\n```\n\n### Filter or Limit Shards by `ShardInfo` Metadata\n\nAll `as_*` iterators accept `shard_filter: Callable[[ShardInfo], bool]` and\n`shards: int | None` (evaluated purely from `shards_list.json` without reading\nshard files):\n\n```python\ndevice_0_it = dataset.as_numpy_iterator_rust_batched(\n    split=TRAIN_SPLIT,\n    batch_size=32,\n    repeat=False,\n    shuffle=0,\n    shards=10,  # Optional: read at most the first 10 matching shards\n    shard_filter=lambda shard_info: shard_info.custom_metadata.get(\"device\") == 0,\n)\n```\n\n-   **Empty filter result**: If `shard_filter` matches zero shards (or the\n    split has zero shards), `as_numpy_iterator`, `as_numpy_iterator_rust`, and\n    `as_numpy_iterator_rust_batched` yield zero items, whereas\n    `as_numpy_iterator_concurrent`, `as_numpy_iterator_async`, `as_tfdataset`,\n    and `shard_paths_dataset` raise\n    `ValueError: The list of shards is empty. Try less restrictive filtering.`\n-   **Limiting shards per distinct `custom_metadata`**: `as_numpy_iterator`,\n    `as_numpy_iterator_concurrent`, and `as_tfdataset` also accept\n    `custom_metadata_type_limit=K` to read at most `K` shards for each unique\n    `ShardInfo.custom_metadata` dictionary.\n-   **Iterating shard metadata directly**: Use\n    `for shard_info in dataset.shard_info_iterator(TRAIN_SPLIT): ...` (pass\n    `None` to iterate across all present splits).\n\n### Balanced Iteration Across Shard Categories (`BalancedShardInfoIterator`)\n\nTo sample shards with equal (or custom-weighted) probability across metadata\nattributes regardless of shard count imbalance:\n\n```python\ndef by_device(shard_info: ShardInfo) -> int:\n    return shard_info.custom_metadata[\"device\"]\n\n# Optional custom weight per category:\n# by_device.weight = lambda shard_info: 3.0 if shard_info.custom_metadata[\"device\"] == 0 else 1.0\n\nbalanced_shards = BalancedShardInfoIterator(\n    dataset_path=dataset.path,\n    dataset_info=dataset.dataset_info,\n    split=TRAIN_SPLIT,\n    repeat=True,\n    shuffle=100,\n    balance_by=(by_device,),\n    shard_filter=None,\n)\n\n# Option A: Fast Rust batched iteration over balanced shards (\"fb\" format)\nwith RustBatchedGenerator(\n    dataset_path=dataset.path,\n    dataset_structure=dataset.dataset_structure,\n    shard_iterator=balanced_shards,\n    batch_size=64,\n    process_batch=None,\n    shuffle_buffer_size=1_000,\n) as rust_generator:\n    for batch in itertools.islice(rust_generator(), 100):\n        traces = batch[\"trace\"]\n\n# Option B: Python unbatched iteration over balanced shards (all formats)\nbalanced_examples = dataset.example_iterator_from_shard_iterator(\n    shard_iterator=balanced_shards,\n    process_record=None,\n    shuffle=1_000,\n)\nfor example in itertools.islice(balanced_examples, 100):\n    trace = example[\"trace\"]\n```\n\n### Verify Dataset Integrity (`dataset.check()`)\n\n```python\n# Validates dataset_info.json, all shards_list.json files, shard hashes, and example counts\ndataset.check(show_progressbar=False)\n\n# Get root dataset_info.json checksums (call after write_config)\nchecksums: tuple[str, ...] = dataset.current_metadata_checksums()\n```\n\n## 7. Quick Troubleshooting Table\n\n| Error \u002F Symptom | Cause | Solution |\n| :--- | :--- | :--- |\n| Evaluation loop hangs \u002F never finishes | Default `repeat=True` creates an infinite iterator | Pass `repeat=False, shuffle=0` to `dataset.as_*` |\n| `ValueError: Not a known split value` | Passed `\"val\"` or `\"validation\"` as `split` | Use `\"train\"`, `\"test\"` (`TEST_SPLIT`), or `\"holdout\"` (`HOLDOUT_SPLIT`) |\n| `ValueError: The list of shards is empty. Try less restrictive filtering.` | `shard_filter` matched zero shards or split has no shards | Relax `shard_filter` or check `split in dataset.dataset_info.splits` first |\n| `ValueError: Cannot cast value of dtype ...` | Passed `float64` to `\"float32\"` or `int64` to `\"uint8\"`\u002F`\"int32\"` in `\"fb\"` writer | Cast explicitly before `write_example`: `trace.astype(np.float32)` |\n| `ValueError: Shape requires positive values` | Used `shape=()` with `0` or `-1`, such as `(-1, 128)` or `(0,)` | Use `shape=()` for scalars\u002Fvariable-length `\"str\"`\u002F`\"bytes\"`, or fixed positive dimensions |\n| `AssertionError` when creating\u002Fwriting `\"npz\"` dataset | Default `compression=\"GZIP\"` is unsupported for `shard_file_type=\"npz\"` | Set `compression=\"ZIP\"` or `compression=\"\"` in `DatasetStructure` |\n| `TypeError: ... takes 1 positional argument` on `as_numpy_iterator*` | Passed `split` by position (`dataset.as_numpy_iterator(\"train\")`) | Pass `split` as a keyword argument (`dataset.as_numpy_iterator(split=\"train\")`) |\n| `TypeError: ... got an unexpected keyword argument 'process_record'` on `as_numpy_iterator_rust_batched` | `as_numpy_iterator_rust_batched` transforms batches, not individual records | Use `process_batch=...` instead of `process_record=...` |\n| Attribute `custom_metadata` changes lost after `with dataset.filler():` | `dataset.filler()` writes `dataset_info.json` upon exiting the `with` block | Call `dataset.write_config()` after mutating `dataset.metadata` or `Attribute.custom_metadata` |\n| `AttributeError: Can't pickle local object` in `as_numpy_iterator_concurrent` | Passed a `lambda` or closure as `process_record` while `shuffle > 0` | Define `process_record` as a top-level function or use `as_numpy_iterator_rust` |\n",{"name":5,"license":15,"description":7},"main","0e8e3e22d04fc2206ef9986af44e13688999d578","src\u002Fsedpack\u002F.agents\u002Fskills\u002Fsedpack",14,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fsedpack","https:\u002F\u002Fgoogle.github.io\u002Fsedpack\u002F","https:\u002F\u002Fgithub.com\u002Fgoogle","https:\u002F\u002Fopensource.google\u002F","Google ❤️ Open Source","2026-11-15 01:40:31",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add google\u002Fsedpack --skill sedpack",{"tool":59,"command":60},"bunx","bunx skills add google\u002Fsedpack --skill sedpack",{"tool":62,"command":63},"pnpm","pnpm dlx skills add google\u002Fsedpack --skill sedpack","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fsedpack\u002Fblob\u002Fmain\u002Fsrc\u002Fsedpack\u002F.agents\u002Fskills\u002Fsedpack\u002FSKILL.md",true,[],[]]