|
| 1 | +# |
| 2 | +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +# |
| 5 | + |
| 6 | +""" |
| 7 | +On-disk header helpers for the cuvs-bench binary file format. |
| 8 | +
|
| 9 | +cuvs-bench inherits the big-ann-benchmarks binary layout: a small header |
| 10 | +listing ``n_rows`` and ``n_cols`` followed by a dense ``n_rows * n_cols`` |
| 11 | +array of the dtype implied by the file extension. Two layouts are supported: |
| 12 | +
|
| 13 | +- **Legacy**: ``[uint32 n_rows, uint32 n_cols, data ...]`` (8-byte header). |
| 14 | + This is what every existing ``.fbin`` / ``.ibin`` / ``.u8bin`` / ``.i8bin`` |
| 15 | + / ``.f16bin`` / ``.hbin`` / ``.u64bin`` file on disk uses today. |
| 16 | +
|
| 17 | +- **Extended**: ``[uint64 n_rows, uint64 n_cols, data ...]`` (16-byte header). |
| 18 | + For datasets whose ``n_rows`` or ``n_cols`` exceeds ``UINT32_MAX`` (~4.29B). |
| 19 | +
|
| 20 | +Detection is **size-based**: a well-formed cuvs-bench binary is exactly |
| 21 | +``header_bytes + n_rows * n_cols * itemsize`` bytes long. :func:`read_bin_header` reads the first 16 bytes |
| 22 | +of the file and: |
| 23 | +
|
| 24 | +1. Tries the legacy layout (first 8 bytes as two ``uint32``s, 8-byte |
| 25 | + header). The layout is accepted if ``8 + n_rows * n_cols * itemsize`` |
| 26 | + matches the on-disk file size. |
| 27 | +2. Otherwise tries the extended layout (first 16 bytes as two |
| 28 | + ``uint64``s, 16-byte header). Accepted if |
| 29 | + ``16 + n_rows * n_cols * itemsize`` matches the file size instead. |
| 30 | +3. If neither layout matches, raises ``ValueError`` -- the file is |
| 31 | + truncated, padded, or has a mismatched dtype extension. |
| 32 | +""" |
| 33 | + |
| 34 | +import os |
| 35 | +import struct |
| 36 | +from typing import BinaryIO, Tuple |
| 37 | + |
| 38 | +import numpy as np |
| 39 | + |
| 40 | +UINT32_MAX = (1 << 32) - 1 |
| 41 | + |
| 42 | +LEGACY_HEADER_BYTES = 8 |
| 43 | +EXTENDED_HEADER_BYTES = 16 |
| 44 | + |
| 45 | + |
| 46 | +def read_bin_header(path: str, itemsize: int) -> Tuple[int, int, int]: |
| 47 | + """Read the header of a cuvs-bench binary file. |
| 48 | +
|
| 49 | + Auto-detects the on-disk layout from the file size by checking which |
| 50 | + of the two layouts (legacy 8-byte uint32 header, extended 16-byte uint64 |
| 51 | + header) makes ``file_size == header_bytes + n_rows * n_cols * itemsize`` |
| 52 | + balance. |
| 53 | +
|
| 54 | + Parameters |
| 55 | + ---------- |
| 56 | + path : str |
| 57 | + Path to the binary file. |
| 58 | + itemsize : int |
| 59 | + Per-element size in bytes (e.g. ``4`` for ``float32``, ``1`` for |
| 60 | + ``int8``) used for the size-equation check. |
| 61 | +
|
| 62 | + Returns |
| 63 | + ------- |
| 64 | + (n_rows, n_cols, header_bytes) : Tuple[int, int, int] |
| 65 | + Row count, column count, and the number of bytes the header |
| 66 | + occupies on disk (``8`` for legacy, ``16`` for extended). |
| 67 | +
|
| 68 | + Raises |
| 69 | + ------ |
| 70 | + ValueError |
| 71 | + If neither the legacy nor the extended interpretation matches. |
| 72 | + FileNotFoundError |
| 73 | + If ``path`` does not exist. |
| 74 | + """ |
| 75 | + if itemsize < 1: |
| 76 | + raise ValueError( |
| 77 | + f"itemsize must be a positive integer, got {itemsize!r}" |
| 78 | + ) |
| 79 | + file_size = os.path.getsize(path) |
| 80 | + with open(path, "rb") as f: |
| 81 | + head = f.read(EXTENDED_HEADER_BYTES) |
| 82 | + |
| 83 | + if len(head) < LEGACY_HEADER_BYTES: |
| 84 | + raise ValueError( |
| 85 | + f"File too small to contain a valid header (expected at least " |
| 86 | + f"{LEGACY_HEADER_BYTES} bytes, got {len(head)}): {path}" |
| 87 | + ) |
| 88 | + |
| 89 | + n_rows_32, n_cols_32 = struct.unpack("<II", head[:LEGACY_HEADER_BYTES]) |
| 90 | + if file_size == LEGACY_HEADER_BYTES + n_rows_32 * n_cols_32 * itemsize: |
| 91 | + return int(n_rows_32), int(n_cols_32), LEGACY_HEADER_BYTES |
| 92 | + |
| 93 | + if len(head) == EXTENDED_HEADER_BYTES: |
| 94 | + n_rows_64, n_cols_64 = struct.unpack("<QQ", head) |
| 95 | + if ( |
| 96 | + file_size |
| 97 | + == EXTENDED_HEADER_BYTES + n_rows_64 * n_cols_64 * itemsize |
| 98 | + ): |
| 99 | + return int(n_rows_64), int(n_cols_64), EXTENDED_HEADER_BYTES |
| 100 | + |
| 101 | + raise ValueError( |
| 102 | + f"File size {file_size:,} bytes does not match either the legacy " |
| 103 | + f"(8-byte uint32) or extended (16-byte uint64) header layout for " |
| 104 | + f"itemsize={itemsize}: {path}. The file may be truncated, padded, " |
| 105 | + f"or have a mismatched dtype extension." |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +def write_bin_header( |
| 110 | + f: BinaryIO, |
| 111 | + n_rows: int, |
| 112 | + n_cols: int, |
| 113 | + *, |
| 114 | + size_dtype=np.uint32, |
| 115 | +) -> int: |
| 116 | + """Write the canonical cuvs-bench binary header at the current position. |
| 117 | +
|
| 118 | + The legacy 8-byte uint32 layout is used whenever both ``n_rows`` and |
| 119 | + ``n_cols`` fit in a ``uint32``. The 16-byte uint64 layout is used |
| 120 | + otherwise, or when explicitly requested via ``size_dtype=np.uint64``. |
| 121 | +
|
| 122 | + Parameters |
| 123 | + ---------- |
| 124 | + f : BinaryIO |
| 125 | + Open binary file handle, positioned where the header should go. |
| 126 | + n_rows, n_cols : int |
| 127 | + Header values to write. Must be non-negative. |
| 128 | + size_dtype : numpy dtype |
| 129 | + ``np.uint32`` for the legacy 8-byte header (default), or |
| 130 | + ``np.uint64`` to force the extended 16-byte header. |
| 131 | +
|
| 132 | + Returns |
| 133 | + ------- |
| 134 | + int |
| 135 | + Number of bytes written (``8`` for legacy, ``16`` for extended). |
| 136 | + """ |
| 137 | + if n_rows < 0 or n_cols < 0: |
| 138 | + raise ValueError( |
| 139 | + f"n_rows and n_cols must be non-negative, got ({n_rows}, {n_cols})" |
| 140 | + ) |
| 141 | + use_uint64 = ( |
| 142 | + np.dtype(size_dtype) == np.uint64 |
| 143 | + or n_rows > UINT32_MAX |
| 144 | + or n_cols > UINT32_MAX |
| 145 | + ) |
| 146 | + if use_uint64: |
| 147 | + f.write(struct.pack("<QQ", int(n_rows), int(n_cols))) |
| 148 | + return EXTENDED_HEADER_BYTES |
| 149 | + f.write(struct.pack("<II", int(n_rows), int(n_cols))) |
| 150 | + return LEGACY_HEADER_BYTES |
0 commit comments