Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/474.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Reading or writing a sharded array with a buffer prototype other than the one `zarr.config` names no longer fails, and a Zarr format 2 array decodes into the requested prototype's buffer kind. The codec pipelines now hand each codec its input in the buffer kind its chunk spec names and convert a `Buffer` or `NDBuffer` of another kind that a codec returns, so codecs that build their buffers from `zarr.config` keep working.
12 changes: 12 additions & 0 deletions docs/user-guide/extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ Custom codecs should also implement the following methods:
- `evolve_from_array_spec` (optional), which can be useful for automatically filling in
codec configuration metadata from the array metadata.

A codec receives the chunk's buffer kind (host or GPU memory, for instance) in
`chunk_spec.prototype`, and should build the buffers it returns from that prototype
(`chunk_spec.prototype.buffer` and `chunk_spec.prototype.nd_buffer`), not from
[`zarr.config`][]: a read or write may ask for a different kind than the one configured.
The codec pipelines hand each codec its input as the kind its `chunk_spec.prototype`
names, and convert a `Buffer` or `NDBuffer` of another kind that a codec returns,
which copies the data when it moves between host and device memory. A cross-kind
`NDBuffer` conversion goes through `as_numpy_array` and `from_numpy_array`, so a
custom array buffer class must support both.
Codecs should return `Buffer` and `NDBuffer` instances; any other value is passed on
unchanged.

To use custom codecs in Zarr, they need to be registered using the
[entrypoint mechanism](https://packaging.python.org/en/latest/specifications/entry-points/).
Commonly, entrypoints are declared in the `pyproject.toml` of your package under the
Expand Down
3 changes: 1 addition & 2 deletions src/zarr/codecs/_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from zarr.abc.codec import ArrayBytesCodec
from zarr.core.config import config
from zarr.errors import PickleCodecDisabledError
from zarr.registry import get_ndbuffer_class

if TYPE_CHECKING:
from zarr.abc.numcodec import Numcodec
Expand Down Expand Up @@ -94,7 +93,7 @@ def _decode_sync(
chunk = chunk.reshape(-1, order="A")
chunk = chunk.reshape(chunk_spec.shape, order=chunk_spec.order)

return get_ndbuffer_class().from_ndarray_like(chunk)
return chunk_spec.prototype.nd_buffer.from_ndarray_like(chunk)

def _encode_sync(
self,
Expand Down
46 changes: 27 additions & 19 deletions src/zarr/codecs/sharding.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@
Buffer,
BufferPrototype,
NDBuffer,
default_buffer_prototype,
numpy_buffer_prototype,
)
from zarr.core.buffer.core import _as_prototype_buffer
from zarr.core.chunk_grids import ChunkGrid
from zarr.core.chunk_utils import (
ChunkTransform,
Expand Down Expand Up @@ -73,7 +73,7 @@
RegularChunkGridMetadata,
parse_codecs,
)
from zarr.registry import get_ndbuffer_class, get_pipeline_class
from zarr.registry import get_pipeline_class
from zarr.storage._common import StorePath
from zarr.storage._utils import _normalize_byte_range_index

Expand Down Expand Up @@ -153,6 +153,10 @@ class _ShardingByteGetter(ByteGetter):
synchronous codec pipeline takes its sync fast path on inner chunks
instead of scheduling one coroutine per chunk; the async `get` simply
delegates to `get_sync`.

`prototype` is not used: the buffers are slices of the shard, in the buffer
kind it was read or encoded with, and the codec chains convert their input
to the kind their chunk spec names (see `_as_prototype_buffer`).
"""

shard_dict: ShardMapping
Expand All @@ -161,11 +165,6 @@ class _ShardingByteGetter(ByteGetter):
def get_sync(
self, prototype: BufferPrototype | None = None, byte_range: ByteRequest | None = None
) -> Buffer | None:
if prototype is not None and prototype != default_buffer_prototype():
raise ValueError(
"Non-default buffer prototypes are not supported within shards. "
f"Got {prototype}, expected {default_buffer_prototype()}."
)
value = self.shard_dict.get(self.chunk_coords)
if value is None:
return None
Expand Down Expand Up @@ -344,10 +343,8 @@ async def from_bytes(

@classmethod
def create_empty(
cls, chunks_per_shard: tuple[int, ...], buffer_prototype: BufferPrototype | None = None
cls, chunks_per_shard: tuple[int, ...], buffer_prototype: BufferPrototype
) -> _ShardReader:
if buffer_prototype is None:
buffer_prototype = default_buffer_prototype()
index = _ShardIndex.create_empty(chunks_per_shard)
obj = cls()
obj.buf = buffer_prototype.buffer.create_zero_length()
Expand Down Expand Up @@ -655,7 +652,9 @@ def _validate_inner_codecs(self, dtype: ZDType[TBaseDType, TBaseScalar]) -> None
dtype=dtype,
fill_value=dtype.default_scalar(),
config=ArrayConfig.from_dict({}),
prototype=default_buffer_prototype(),
# Validation builds no buffers, so any prototype will do; a fixed one
# keeps validation from reading `zarr.config`.
prototype=numpy_buffer_prototype(),
)
for codec in self.codecs:
codec.validate(
Expand Down Expand Up @@ -706,7 +705,7 @@ def _encode_shard_index_sync(self, index: _ShardIndex) -> Buffer:
"""Encode shard index synchronously using ChunkTransform."""
index_transform = self._get_index_chunk_transform(index.chunks_per_shard)
index_spec = self._get_index_chunk_spec(index.chunks_per_shard)
index_nd = get_ndbuffer_class().from_numpy_array(index.offsets_and_lengths)
index_nd = index_spec.prototype.nd_buffer.from_numpy_array(index.offsets_and_lengths)
result: Buffer | None = index_transform.encode_chunk(index_nd, index_spec)
if result is None:
raise RuntimeError("Encoding the shard index produced no bytes.")
Expand Down Expand Up @@ -841,7 +840,7 @@ def _encode_sync(
return self._encode_shard_dict_sync(
shard_builder,
chunks_per_shard=chunks_per_shard,
buffer_prototype=default_buffer_prototype(),
buffer_prototype=shard_spec.prototype,
)

def _encode_partial_sync(
Expand Down Expand Up @@ -943,7 +942,7 @@ def _encode_partial_sync(
blob = self._encode_shard_dict_sync(
shard_dict,
chunks_per_shard=chunks_per_shard,
buffer_prototype=default_buffer_prototype(),
buffer_prototype=shard_spec.prototype,
)
if blob is None:
byte_setter.delete_sync()
Expand Down Expand Up @@ -1008,6 +1007,8 @@ def _assemble_shard(
"encoded shard index size does not match _shard_index_size; "
"variable-size index codecs are not supported"
)
# The index is encoded in host memory (see `_get_index_chunk_spec`).
index_bytes = _as_prototype_buffer(index_bytes, buffer_prototype)
if self.index_location == "start":
buffers.insert(0, index_bytes)
else:
Expand Down Expand Up @@ -1410,7 +1411,7 @@ async def _encode_single(
return await self._encode_shard_dict(
shard_builder,
chunks_per_shard=chunks_per_shard,
buffer_prototype=default_buffer_prototype(),
buffer_prototype=shard_spec.prototype,
)

async def _encode_partial_single(
Expand All @@ -1434,7 +1435,7 @@ async def _encode_partial_single(
chunks_per_shard=chunks_per_shard,
)
if shard_reader is None:
shard_reader = _ShardReader.create_empty(chunks_per_shard)
shard_reader = _ShardReader.create_empty(chunks_per_shard, chunk_spec.prototype)
# Use vectorized lookup for better performance. The lexicographic
# coordinate array and keys are cached, so neither is rebuilt on
# every write.
Expand All @@ -1456,7 +1457,7 @@ async def _encode_partial_single(
buf = await self._encode_shard_dict(
shard_dict,
chunks_per_shard=chunks_per_shard,
buffer_prototype=default_buffer_prototype(),
buffer_prototype=shard_spec.prototype,
)

if buf is None:
Expand Down Expand Up @@ -1602,7 +1603,9 @@ async def _encode_shard_index(self, index: _ShardIndex) -> Buffer:
.encode(
[
(
get_ndbuffer_class().from_numpy_array(index.offsets_and_lengths),
numpy_buffer_prototype().nd_buffer.from_numpy_array(
index.offsets_and_lengths
),
self._get_index_chunk_spec(index.chunks_per_shard),
)
]
Expand Down Expand Up @@ -1647,7 +1650,12 @@ def _get_index_chunk_spec(self, chunks_per_shard: tuple[int, ...]) -> ArraySpec:
config=ArrayConfig(
order="C", write_empty_chunks=False
), # Note: this is hard-coded for simplicity -- it is not surfaced into user code,
prototype=default_buffer_prototype(),
# The index lives in host memory whatever prototype the shard data uses:
# it is a few bytes per chunk, and it is consumed as a NumPy array
# (`_ShardIndex.offsets_and_lengths`). The index codec chain moves index
# bytes read with the shard's prototype to the host, and
# `_assemble_shard` converts the encoded index to the shard's prototype.
prototype=numpy_buffer_prototype(),
)

def _get_chunk_spec(self, shard_spec: ArraySpec) -> ArraySpec:
Expand Down
43 changes: 43 additions & 0 deletions src/zarr/core/buffer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Protocol,
SupportsIndex,
cast,
overload,
runtime_checkable,
)

Expand Down Expand Up @@ -598,6 +599,48 @@ class BufferPrototype(NamedTuple):
nd_buffer: type[NDBuffer]


@overload
def _as_prototype_buffer(value: Buffer, prototype: BufferPrototype) -> Buffer: ...
@overload
def _as_prototype_buffer(value: None, prototype: BufferPrototype) -> None: ...
def _as_prototype_buffer(value: Buffer | None, prototype: BufferPrototype) -> Buffer | None:
"""Return a `Buffer` of another kind as a `prototype.buffer`; return anything else unchanged.

The codec pipelines pass each codec's input, and the chain's output, through
this (and `_as_prototype_nd_buffer`), so a codec that builds its buffers some
other way than from `chunk_spec.prototype`, for instance from `zarr.config`,
cannot hand a buffer of another kind (host or device memory) to the next
codec, the store, or the caller. A value that is not a `Buffer` at all, such
as `bytes` from a codec that predates the `Buffer` contract, is passed on
unchanged, as it was before these conversions existed.
"""
if not isinstance(value, Buffer) or isinstance(value, prototype.buffer):
return value
# Through host memory with `from_bytes`, not `from_buffer`: between host kinds
# this copies nothing (`as_buffer_like` is a view of host data), and a GPU
# kind's `from_bytes` copies to the device without the slow-path warning its
# `from_buffer` gives for host memory. Between two device kinds it copies
# through the host, which only a codec that ignores the prototype causes.
return prototype.buffer.from_bytes(value.as_buffer_like())


@overload
def _as_prototype_nd_buffer(value: NDBuffer, prototype: BufferPrototype) -> NDBuffer: ...
@overload
def _as_prototype_nd_buffer(value: None, prototype: BufferPrototype) -> None: ...
def _as_prototype_nd_buffer(value: NDBuffer | None, prototype: BufferPrototype) -> NDBuffer | None:
"""Return an `NDBuffer` of another kind as a `prototype.nd_buffer`; return anything else unchanged.

`NDBuffer` has no `from_buffer`; the conversion goes through a NumPy array in
host memory. A value that is not an `NDBuffer`, such as a raw NumPy array
from a codec that predates the `NDBuffer` contract, is passed on unchanged.
See `_as_prototype_buffer`.
"""
if not isinstance(value, NDBuffer) or isinstance(value, prototype.nd_buffer):
return value
return prototype.nd_buffer.from_numpy_array(value.as_numpy_array())


# The default buffer prototype used throughout the Zarr codebase.
def default_buffer_prototype() -> BufferPrototype:
from zarr.registry import (
Expand Down
41 changes: 30 additions & 11 deletions src/zarr/core/chunk_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import TYPE_CHECKING, Any, cast

from zarr.abc.codec import GetResult, SupportsSyncCodec, _codec_supports_sync
from zarr.core.buffer.core import _as_prototype_buffer, _as_prototype_nd_buffer
from zarr.core.indexing import is_scalar

if TYPE_CHECKING:
Expand Down Expand Up @@ -106,6 +107,9 @@ def scatter_chunk(
if selected is None:
out[out_selection] = fill_value_or_default(chunk_spec)
return GetResult(status="missing")
# A partial decode (`decode_partial`) returns the array-bytes codec's output
# directly, so convert it here like the chain runners convert each stage.
selected = _as_prototype_nd_buffer(selected, chunk_spec.prototype)
if drop_axes:
selected = selected.squeeze(axis=drop_axes)
out[out_selection] = selected
Expand Down Expand Up @@ -225,6 +229,11 @@ class ChunkTransform:

All codecs must implement `SupportsSyncCodec`. Construction will
raise `TypeError` if any codec does not.

Every codec gets its input as the buffer kind its own spec's prototype
names, and the chain's output is returned as the kind `chunk_spec.prototype`
names (see `_as_prototype_buffer`), so a codec that ignores the prototype
cannot mix buffer kinds in the chain.
"""

codecs: tuple[Codec, ...]
Expand Down Expand Up @@ -316,16 +325,20 @@ def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer:
"""
aa_specs, ab_spec = self._resolve_specs(chunk_spec)

data: Buffer = chunk_bytes
data = chunk_bytes
for bb_codec in reversed(self._bb_codecs):
data = bb_codec._decode_sync(data, ab_spec)
data = bb_codec._decode_sync(_as_prototype_buffer(data, ab_spec.prototype), ab_spec)

chunk_array: NDBuffer = self._ab_codec._decode_sync(data, ab_spec)
chunk_array = self._ab_codec._decode_sync(
_as_prototype_buffer(data, ab_spec.prototype), ab_spec
)

for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True):
chunk_array = aa_codec._decode_sync(chunk_array, aa_spec)
chunk_array = aa_codec._decode_sync(
_as_prototype_nd_buffer(chunk_array, aa_spec.prototype), aa_spec
)

return chunk_array
return _as_prototype_nd_buffer(chunk_array, chunk_spec.prototype)

def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None:
"""Encode a single chunk through the full codec chain, synchronously.
Expand All @@ -342,25 +355,31 @@ def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer |
"""
aa_specs, ab_spec = self._resolve_specs(chunk_spec)

aa_data: NDBuffer = chunk_array
aa_data = chunk_array
for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True):
aa_result = aa_codec._encode_sync(aa_data, aa_spec)
aa_result = aa_codec._encode_sync(
_as_prototype_nd_buffer(aa_data, aa_spec.prototype), aa_spec
)
if aa_result is None:
return None
aa_data = aa_result

ab_result = self._ab_codec._encode_sync(aa_data, ab_spec)
ab_result = self._ab_codec._encode_sync(
_as_prototype_nd_buffer(aa_data, ab_spec.prototype), ab_spec
)
if ab_result is None:
return None

bb_data: Buffer = ab_result
bb_data = ab_result
for bb_codec in self._bb_codecs:
bb_result = bb_codec._encode_sync(bb_data, ab_spec)
bb_result = bb_codec._encode_sync(
_as_prototype_buffer(bb_data, ab_spec.prototype), ab_spec
)
if bb_result is None:
return None
bb_data = bb_result

return bb_data
return _as_prototype_buffer(bb_data, chunk_spec.prototype)

def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int:
for codec in self.codecs:
Expand Down
Loading
Loading