ML Foundations
Preserve mask length when packing NumPy bits
Round-trip a binary mask without mistaking padding bits for original values.

Evidence and testing
Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.
Packed bytes do not retain the original bit count
A binary mask may contain a number of elements that is not divisible by eight. NumPy packbits pads the end with zeros to fill a byte. Unpacking that byte without a count returns those padding bits alongside the original values. [1, 2]
The packed byte alone therefore cannot distinguish a genuine trailing zero from a padding zero. Store the original number of mask elements as metadata when the exact length matters.
Round-trip a five-element mask
Run python examples/numpy_packbits_mask_roundtrip.py. The example packs five binary values into one byte using little bit order. Unpacking without a count returns eight values, including three zero padding bits. [1, 2]
Passing the original size as count restores exactly five values. The same bit order is specified in both operations, and an assertion checks equality with the source. The printed byte and arrays are the results of this particular fixture. [1, 2]
Executed with Python 3.12.14; stdout and checksum recorded in private evidence.
import numpy as np
mask = np.array([1, 0, 1, 1, 0], dtype=np.uint8)
packed = np.packbits(mask, bitorder="little")
full = np.unpackbits(packed, bitorder="little")
restored = np.unpackbits(packed, count=mask.size, bitorder="little")
assert np.array_equal(restored, mask)
assert full.size == 8 and restored.size == 5
print("packed bytes:", packed.tolist())
print("unpacked with padding:", full.tolist())
print("restored mask:", restored.tolist())
print("round trip matches:", np.array_equal(restored, mask))
Recorded output
packed bytes: [13] unpacked with padding: [1, 0, 1, 1, 0, 0, 0, 0] restored mask: [1, 0, 1, 1, 0] round trip matches: True
Record shape and bit order as well
For multidimensional masks, store the original shape and agree which axis was packed. Both functions default to flattening when axis is omitted. Unpacking supports count along the chosen axis, so use the original axis length and reshape only when that matches the saved layout. [1, 2]
Keep bitorder consistent between packing and unpacking. The example uses a one-dimensional binary uint8 array, and does not define an encoding for arbitrary integers or a file format. [1, 2]