diff --git a/changes/4669.bugfix.md b/changes/4669.bugfix.md new file mode 100644 index 0000000000..8cc20a4fa8 --- /dev/null +++ b/changes/4669.bugfix.md @@ -0,0 +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`. +Under `FusedCodecPipeline`, whole uncompressed shards with structured data types +now also take the fast path. 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", "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