From 68e5f08a60a95900d3408ebdaf6f959c5a02d81d Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 19:27:25 +0100 Subject: [PATCH 1/5] fix(sharding): keep whole-shard reads in the buffer's own memory The fused pipeline's fast path for reading a whole uncompressed shard copied the shard to host memory with `as_numpy_array()`, then assigned each chunk into the output buffer. Under `zarr.config.enable_gpu()` the output is a CuPy array, which refuses host arrays, so the read failed. The fast path now uses `as_array_like()`, as `BytesCodec` does. The stored-byte-order view dtype is now computed by one helper, `BytesCodec._stored_dtype`, shared by the per-chunk and fast paths. It handles structured data types, so the fast path no longer has to decline them. Closes zarr-developers/zarr-python#4654 Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/codecs/bytes.py | 32 ++++++++++-------- src/zarr/codecs/sharding.py | 34 ++++++------------- tests/test_buffer.py | 34 +++++++++++++++++++ tests/test_codecs/test_sharding_unit.py | 44 ++++++++++++++----------- 4 files changed, 87 insertions(+), 57 deletions(-) diff --git a/src/zarr/codecs/bytes.py b/src/zarr/codecs/bytes.py index 9ebcaa4c02..c32206f32b 100644 --- a/src/zarr/codecs/bytes.py +++ b/src/zarr/codecs/bytes.py @@ -21,6 +21,7 @@ from zarr.abc.store import ByteGetter from zarr.core.array_spec import ArraySpec from zarr.core.buffer import Buffer, NDBuffer + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType from zarr.core.indexing import Selector, SelectorTuple @@ -100,25 +101,30 @@ def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: ) return self + def _stored_dtype(self, dtype: ZDType[TBaseDType, TBaseScalar]) -> np.dtype[Any]: + """The NumPy data type to view stored bytes with. + + The byte order of the stored data is set by this codec's `endian` + configuration; the byte order of the decoded array is set by the array's + data type. The two are independent: the raw bytes are viewed with a dtype + in the stored byte order, then converted to the declared dtype if needed. + """ + if isinstance(dtype, HasEndianness): + return replace(dtype, endianness=self.endian).to_native_dtype() # type: ignore[call-arg] + native = dtype.to_native_dtype() + if isinstance(dtype, Struct) and self.endian is not None: + # Per the struct data type spec, all multi-byte fields are stored in the + # byte order configured on this codec. + return native.newbyteorder(self.endian) + return native + def _decode_sync( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> NDBuffer: - endian_str = self.endian dtype = chunk_spec.dtype.to_native_dtype() - # The byte order of the stored data is set by this codec's `endian` - # configuration; the byte order of the decoded array is set by the array's - # data type. The two are independent: the raw bytes are viewed with a dtype - # in the stored byte order, then converted to the declared dtype if needed. - if isinstance(chunk_spec.dtype, HasEndianness): - view_dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] - elif isinstance(chunk_spec.dtype, Struct) and endian_str is not None: - # Per the struct data type spec, all multi-byte fields are stored in the - # byte order configured on this codec. - view_dtype = dtype.newbyteorder(endian_str) - else: - view_dtype = dtype + view_dtype = self._stored_dtype(chunk_spec.dtype) as_array_like = chunk_bytes.as_array_like() chunk_array = chunk_spec.prototype.nd_buffer.from_ndarray_like( as_array_like.view(dtype=view_dtype) # type: ignore[attr-defined] diff --git a/src/zarr/codecs/sharding.py b/src/zarr/codecs/sharding.py index d4ccf71cb9..f1823f533d 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -52,9 +52,7 @@ product, ) from zarr.core.config import config as zarr_config -from zarr.core.dtype.common import HasEndianness from zarr.core.dtype.npy.int import UInt64 -from zarr.core.dtype.npy.structured import Struct from zarr.core.indexing import ( BasicIndexer, ChunkProjection, @@ -1187,8 +1185,6 @@ def _decode_full_shard_bulk_if_uncompressed( dtype/endian view with no reordering. A trailing crc32c is NOT accepted (the bulk path can't verify per-chunk checksums, so crc shards keep the per-chunk path's corruption detection); - - the data type is not structured (the byte-order handling below has no - `Struct` branch); - `indexer` is an identity full-shard read (`_is_identity_full_read`); - the stored index is dense (every chunk present, equal fixed length, exactly tiling the data section) so the data section is a regular @@ -1197,7 +1193,8 @@ def _decode_full_shard_bulk_if_uncompressed( Chunk positions are read from the stored index, so this is correct for any `subchunk_write_order` (morton / lexicographic / colexicographic / unordered). The on-disk byte order is taken from the BytesCodec's - `endian`, so big- and little-endian shards both decode correctly. + `endian` (`BytesCodec._stored_dtype`), so big- and little-endian shards, + structured ones included, decode as they do on the per-chunk path. """ # --- gate on a trivial, fixed-size inner codec chain --- if not self._inner_codecs_fixed_size: @@ -1212,12 +1209,6 @@ def _decode_full_shard_bulk_if_uncompressed( return None ab_codec = self.codecs[0] - # The byte-order handling below lacks the structured-dtype branch of - # `BytesCodec._decode_sync` (which applies `newbyteorder` to multi-byte - # struct fields), so structured dtypes must take the per-chunk path. - if isinstance(shard_spec.dtype, Struct): - return None - chunks_per_shard = self._get_chunks_per_shard(shard_spec) chunk_spec = self._get_chunk_spec(shard_spec) n_chunks = product(chunks_per_shard) @@ -1257,21 +1248,16 @@ def _decode_full_shard_bulk_if_uncompressed( # a dense, crc-free, fixed-size layout the payload length is exactly the # encoded item-bytes of one chunk. native_dtype = shard_spec.dtype.to_native_dtype() - raw = shard_bytes.as_numpy_array().view(np.uint8) + # `as_array_like`, not `as_numpy_array`: the payloads must stay in the + # buffer's own memory (a CuPy array under `zarr.config.enable_gpu()`), or + # assigning them into a device `out` below fails. + raw = shard_bytes.as_array_like() payload = chunk_byte_length cs = self.chunk_shape - # On-disk byte order is carried by the BytesCodec's `endian`, NOT by the - # data type (zarr v3). Build the read-view dtype from the codec's endian - # exactly as BytesCodec._decode_sync does, so a big-endian shard read on a - # little-endian host (or vice versa) is interpreted correctly. Assigning - # into the native-dtype `out` then performs any needed byteswap. `endian` - # is now a plain Literal['little', 'big'] | None string (no longer an enum). - endian_str = ab_codec.endian - if isinstance(chunk_spec.dtype, HasEndianness): - stored_dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] - else: - stored_dtype = chunk_spec.dtype.to_native_dtype() + # data type (zarr v3). Assigning the stored-order view into the + # native-dtype `out` performs any needed byteswap. + stored_dtype = ab_codec._stored_dtype(chunk_spec.dtype) offsets = index.offsets_and_lengths[..., 0].reshape(-1) # localized coords, C-order coords_c = list(np.ndindex(chunks_per_shard)) @@ -1280,7 +1266,7 @@ def _decode_full_shard_bulk_if_uncompressed( ) for flat, coord in enumerate(coords_c): start = int(offsets[flat]) - chunk = raw[start : start + payload].view(stored_dtype).reshape(cs) + chunk = raw[start : start + payload].view(stored_dtype).reshape(cs) # type: ignore[attr-defined] sel = tuple(slice(c * s, c * s + s) for c, s in zip(coord, cs, strict=True)) out[sel] = chunk return out diff --git a/tests/test_buffer.py b/tests/test_buffer.py index 307abfe499..037cca3d6e 100644 --- a/tests/test_buffer.py +++ b/tests/test_buffer.py @@ -179,6 +179,40 @@ async def test_sharding_use_of_gpu_prototype() -> None: assert cp.array_equal(expect, got) +@gpu_test +@pytest.mark.filterwarnings( + "ignore:Creating a zarr.buffer.gpu.Buffer with an array that does not support:zarr.errors.ZarrUserWarning" +) +@pytest.mark.parametrize( + "pipeline", + [ + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", + ], +) +@pytest.mark.parametrize("compressors", [None, "auto"]) +def test_read_sharded_array_into_gpu_memory( + pipeline: str, compressors: Literal["auto"] | None +) -> None: + """Both codec pipelines read sharded arrays, compressed or not, into CuPy arrays. + + The uncompressed case takes the sharding codec's whole-shard fast path, which + once copied each shard to host memory and then failed to assign it into the + device output (zarr-developers/zarr-python#4654). + """ + store = MemoryStore() + z = zarr.create_array( + store, shape=(100,), chunks=(10,), shards=(50,), dtype="int32", compressors=compressors + ) + z[:] = np.arange(100, dtype="int32") + + with zarr.config.enable_gpu(), zarr.config.set({"codec_pipeline.path": pipeline}): + got = zarr.open_array(store, mode="r")[:] + + assert isinstance(got, cp.ndarray) + assert cp.array_equal(got, cp.arange(100, dtype="int32")) + + def test_numpy_buffer_prototype() -> None: buffer = cpu.buffer_prototype.buffer.create_zero_length() ndbuffer = cpu.buffer_prototype.nd_buffer.create(shape=(1, 2), dtype=np.dtype("int64")) diff --git a/tests/test_codecs/test_sharding_unit.py b/tests/test_codecs/test_sharding_unit.py index 978f7882f4..f27e0cd49a 100644 --- a/tests/test_codecs/test_sharding_unit.py +++ b/tests/test_codecs/test_sharding_unit.py @@ -1070,29 +1070,33 @@ def _spec_for(data: np.ndarray[Any, np.dtype[Any]]) -> ArraySpec: ) -def test_bulk_decode_declines_structured_dtype() -> None: - """The bulk path has no structured-dtype byte-order handling (the `Struct` - branch of `BytesCodec._decode_sync`), so it must decline structured specs. - The plain-dtype control on an identically constructed blob proves the - decline comes from the dtype gate, not from a malformed blob.""" - codec = ShardingCodec(chunk_shape=(2,), codecs=[BytesCodec(endian="little")]) - - # control: same construction with a plain dtype engages the bulk path - plain = np.arange(4, dtype=" None: + """The bulk path views each payload with `BytesCodec._stored_dtype`, the same + data type the per-chunk path uses, so plain and structured shards decode + correctly whichever byte order the codec stored them in.""" + codec = ShardingCodec(chunk_shape=(2,), codecs=[BytesCodec(endian=endian)]) + data = np.zeros(4, dtype=dtype) + if dtype.names is None: + data[:] = np.arange(4) + else: + data["a"] = np.arange(4) + data["b"] = np.arange(4) * 0.5 + stored = data.astype(dtype.newbyteorder(endian)) - struct_data = np.zeros(4, dtype=np.dtype([("a", " Date: Sun, 29 Nov 2026 19:33:29 +0100 Subject: [PATCH 2/5] docs(changes): add fragment for the whole-shard device read fix Assisted-by: ClaudeCode:claude-opus-5-5 --- changes/471.bugfix.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changes/471.bugfix.md diff --git a/changes/471.bugfix.md b/changes/471.bugfix.md new file mode 100644 index 0000000000..3238d7f459 --- /dev/null +++ b/changes/471.bugfix.md @@ -0,0 +1,3 @@ +Reading an uncompressed sharded array into GPU memory with `FusedCodecPipeline` +no longer raises `ValueError: non-scalar numpy.ndarray cannot be used for fill`. +Structured data types now also take the fast path for whole uncompressed shards. From 661f4884764f571abc3a34bb1d8a978e6122f12a Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 19:40:31 +0100 Subject: [PATCH 3/5] test(sharding): draw structured data types in the bulk-decode property test The whole-shard fast path now takes structured data types, so its equivalence test with the per-chunk path draws a mixed-endian struct. The changelog fragment now says the structured fast path applies to FusedCodecPipeline only. Assisted-by: ClaudeCode:claude-opus-5-5 --- changes/471.bugfix.md | 3 ++- tests/test_fastpath_equivalence.py | 20 ++++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/changes/471.bugfix.md b/changes/471.bugfix.md index 3238d7f459..8cc20a4fa8 100644 --- a/changes/471.bugfix.md +++ b/changes/471.bugfix.md @@ -1,3 +1,4 @@ Reading an uncompressed sharded array into GPU memory with `FusedCodecPipeline` no longer raises `ValueError: non-scalar numpy.ndarray cannot be used for fill`. -Structured data types now also take the fast path for whole uncompressed shards. +Under `FusedCodecPipeline`, whole uncompressed shards with structured data types +now also take the fast path. diff --git a/tests/test_fastpath_equivalence.py b/tests/test_fastpath_equivalence.py index 9a2f782d13..b5014fd071 100644 --- a/tests/test_fastpath_equivalence.py +++ b/tests/test_fastpath_equivalence.py @@ -37,9 +37,17 @@ from zarr.storage import MemoryStore _DTYPES = st.sampled_from(["uint8", "int16", "float32"]) +# The whole-shard bulk decode also takes structured data types. Integer fields +# only: structured arrays compare field-wise with `==`, so NaN would never match. +_BULK_DTYPES = st.one_of( + _DTYPES.map(np.dtype), + st.just(np.dtype([("a", "u2"), ("c", "u1")])), +) -def _spec(shape: tuple[int, ...], dtype: str, *, write_empty_chunks: bool = True) -> ArraySpec: +def _spec( + shape: tuple[int, ...], dtype: str | np.dtype[Any], *, write_empty_chunks: bool = True +) -> ArraySpec: zdtype = get_data_type_from_native_dtype(np.dtype(dtype)) return ArraySpec( shape=shape, @@ -110,8 +118,7 @@ def _shard_cases(draw: st.DrawFn) -> dict[str, Any]: chunk_shape = tuple(draw(st.integers(1, 4)) for _ in range(ndim)) grid = tuple(draw(st.integers(1, 3)) for _ in range(ndim)) shard_shape = tuple(c * g for c, g in zip(chunk_shape, grid, strict=True)) - dtype = draw(_DTYPES) - data = draw(npst.arrays(dtype=np.dtype(dtype), shape=shard_shape)) + data = draw(npst.arrays(dtype=draw(_BULK_DTYPES), shape=shard_shape)) return { "chunk_shape": chunk_shape, "shard_shape": shard_shape, @@ -128,15 +135,16 @@ def _shard_cases(draw: st.DrawFn) -> dict[str, Any]: @given(case=_shard_cases()) def test_bulk_shard_decode_equals_general_decode(case: dict[str, Any]) -> None: """For dense fixed-size uncompressed shards, the vectorized bulk decode must - reproduce the general per-chunk decode exactly, whatever the endianness, - subchunk write order, or index location.""" + reproduce the general per-chunk decode exactly, whatever the data type + (structured ones included), endianness, subchunk write order, or index + location.""" codec = ShardingCodec( chunk_shape=case["chunk_shape"], codecs=[BytesCodec(endian=case["endian"])], index_location=case["index_location"], subchunk_write_order=case["subchunk_write_order"], ) - spec = _spec(case["shard_shape"], str(case["data"].dtype), write_empty_chunks=True) + spec = _spec(case["shard_shape"], case["data"].dtype, write_empty_chunks=True) blob = codec._encode_sync(CPUNDBuffer.from_numpy_array(case["data"]), spec) assert blob is not None # write_empty_chunks=True -> dense, never elided From 4b4cb6454a9fe007b51381b02ebefa10404922ca Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 21:38:32 +0100 Subject: [PATCH 4/5] docs(changes): number the fragment for the upstream PR Assisted-by: ClaudeCode:claude-opus-5-5 --- changes/{471.bugfix.md => 4669.bugfix.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changes/{471.bugfix.md => 4669.bugfix.md} (100%) diff --git a/changes/471.bugfix.md b/changes/4669.bugfix.md similarity index 100% rename from changes/471.bugfix.md rename to changes/4669.bugfix.md From 5d8689ba93a88bdb49226ad1d0c8ac4fec5fa236 Mon Sep 17 00:00:00 2001 From: Davis Bennett Date: Fri, 4 Dec 2026 13:55:17 +0100 Subject: [PATCH 5/5] chore(mypy): remove the no-op strict = false override (#4697) * chore(mypy): remove the no-op strict = false override mypy applies `strict` only when it is true, so `strict = false` in a per-module override is ignored. The 14 entries listed there (modules and globs) were already checked strictly. Remove the block, and reword the TODO on the `ignore_errors` list that pointed at it. Assisted-by: ClaudeCode:claude-opus-5-5 * test(fsspec): take test_fsspec off the mypy ignore list Narrow the subgroup returned by `AsyncGroup.getitem` to `AsyncGroup` before calling `group_keys`, which was the module's only mypy error, and remove `tests.test_store.test_fsspec` from the `ignore_errors` list so the module's own code is type-checked like the rest of the tests. Assisted-by: ClaudeCode:claude-opus-5-5 * test(v2): ignore numcodecs' Pickle deprecation warning in pickle tests numcodecs main now warns that its Pickle codec is deprecated whenever one is created, and the suite turns warnings into errors, so the pickle decode-gate tests in test_v2.py fail in the upstream-dependencies job. Those tests create Pickle codecs on purpose, so ignore that warning for them. Released numcodecs doesn't warn, so the filter ignores the warning rather than requiring it. Assisted-by: ClaudeCode:claude-opus-5-5 * test(fsspec): use get_group instead of narrowing getitem's result `AsyncGroup.get_group` returns an `AsyncGroup` and raises if the member is an array, so the test needs no isinstance assert to type-check. Assisted-by: ClaudeCode:claude-opus-5-5 * test(v2): match the Pickle deprecation comment to upstream #4680 Assisted-by: ClaudeCode:claude-opus-5-5 --- pyproject.toml | 23 +---------------------- tests/test_store/test_fsspec.py | 2 +- 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 97901a73df..36ca94ab62 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -373,30 +373,9 @@ strict = true warn_unreachable = true enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool", "truthy-iterable"] +# TODO: fix the type errors in these modules and remove them from this list [[tool.mypy.overrides]] module = [ - "tests.package_with_entrypoint.*", - "zarr.testing.stateful", - "tests.test_codecs.test_transpose", - "tests.test_config", - "tests.test_store.test_zip", - "tests.test_store.test_local", - "tests.test_store.test_memory", - "tests.test_codecs.test_codecs", - "tests.test_metadata.*", - "tests.test_store.test_core", - "tests.test_store.test_logging", - "tests.test_store.test_object", - "tests.test_store.test_stateful", - "tests.test_store.test_wrapper", -] -strict = false - -# TODO: Move the next modules up to the strict = false section -# and fix the errors -[[tool.mypy.overrides]] -module = [ - "tests.test_store.test_fsspec", "tests.test_group", "tests.test_indexing", "tests.test_properties", diff --git a/tests/test_store/test_fsspec.py b/tests/test_store/test_fsspec.py index f26a6f316a..faea1caf0f 100644 --- a/tests/test_store/test_fsspec.py +++ b/tests/test_store/test_fsspec.py @@ -488,7 +488,7 @@ async def test_fsspec_store_list_nested_via_reference_filesystem(path: str) -> N ] group = await zarr.api.asynchronous.open_group(store, mode="r") - subgroup = await group.getitem("a") + subgroup = await group.get_group("a") assert [name async for name in subgroup.group_keys()] == ["b"]