Skip to content

fix(sharding): keep whole-shard reads in the buffer's own memory - #4669

Merged
d-v-b merged 6 commits into
zarr-developers:mainfrom
d-v-b:fix/sharding-bulk-read-device-memory
Dec 4, 2026
Merged

d-v-b merged 6 commits into
zarr-developers:mainfrom
d-v-b:fix/sharding-bulk-read-device-memory

Conversation

@d-v-b

@d-v-b d-v-b commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

🤖 AI text below 🤖

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.

Fixes #4654.

Cause and fix

ShardingCodec._decode_full_shard_bulk_if_uncompressed, the fast path for reading a whole uncompressed shard, read the shard with as_numpy_array(). Under zarr.config.enable_gpu() that copies the shard to host memory, and the next step assigns each NumPy chunk into a CuPy output array, which CuPy refuses. Only the fused pipeline's synchronous partial-decode path reaches this function, so BatchedCodecPipeline and compressed shards were unaffected. The fast path arrived with #3885, so 3.3.0 through 3.4.2 are affected.

The fast path now uses as_array_like(), as BytesCodec._decode_sync does, so the payloads stay in the buffer's own memory.

The fast path also had its own copy of BytesCodec's stored-byte-order logic, without the structured-dtype branch, and declined structured shards for that reason. That logic is now one helper, BytesCodec._stored_dtype, used by both paths, and the structured-dtype exclusion is gone.

GPU CI did not catch this because its only sharded test uses the default pipeline and compressed shards.

Tests and measurements
  • tests/test_buffer.py::test_read_sharded_array_into_gpu_memory (GPU only) reads a sharded array into CuPy under both pipelines, with and without compression. The fused, uncompressed case is the issue's reproduction.
  • test_bulk_decode_declines_structured_dtype pinned the removed exclusion. It is replaced by test_bulk_decode_reads_stored_byte_order, which checks that plain and structured shards decode correctly in both byte orders.
  • No GPU was available to the agent. It reproduced the issue's exact error with a CPU stand-in: a NumPy subclass as the device array, with buffer classes registered as the default the way enable_gpu() does, and an NDBuffer.__setitem__ that rejects plain host arrays as CuPy does. With the fix, both pipelines read plain, big-endian and compressed shards correctly. The new GPU test has since run on real CuPy in upstream's GPU workflow (job py=3.12, head 281d66f), and all four cases passed.
  • Full test suite on the fix: 13,529 passed, 1,322 skipped, 9 xfailed. ruff and mypy are clean.
  • Timing of full reads under the fused pipeline, main vs fix, interleaved runs:
Shards main fix
1-D, 1000 chunks of 10 18.6 ms 18.5 ms
2-D, 64 chunks of 64×64 8.3 ms 8.4 ms
structured, 100 chunks 4.8 ms (per-chunk path) 2.7 ms (fast path)

The agent first tried decoding each chunk through BytesCodec._decode_sync. That cost up to 50% on shards of many small chunks, so it dropped that approach.

Adversarial review

Round 1 (a fresh reviewer given only the diff and the issue) found nothing serious:

  • Minor, unverified, not new: on GPU with a non-native stored byte order, the fast path now views the payload as, for example, >i4 and relies on CuPy's cast, exactly as BytesCodec._decode_sync already does on the per-chunk path. The new GPU test covers only native byte order. Left as is, since both paths now behave the same.
  • Minor, not new: with index_location="start", payloads of 8-byte dtypes start at offsets that are 4 mod 8, which could be misaligned for CUDA kernels. The per-chunk path takes the same zero-copy slices. Left as is.
  • Nit: only the fused, uncompressed case of the GPU test reaches the fixed code; the other three cases are general GPU coverage. The reviewer confirmed the test fails without the fix in the stand-in.
  • Nit: no changelog fragment yet. Added in 6688923, numbered for this PR afterwards.

The reviewer found the fast path and the per-chunk path byte-identical on CPU across plain, mixed-endian, nested and datetime struct dtypes, both endians, C and F order, index at start and end, morton and colexicographic write orders, and 1-D to 3-D shards.

Round 2 (a second fresh reviewer, on the pushed diff) found nothing serious:

  • Minor: the fragment carried the number of the fork PR this branch was first opened as, which issue_format would render as a link to an unrelated upstream PR. Fixed by renaming it to this PR's number (4b4cb64).
  • Nit: the property test test_bulk_shard_decode_equals_general_decode never drew a structured dtype, though structured dtypes now take the fast path. Fixed in 661f488: it draws a mixed-endian integer struct (59 of 100 examples), and it fails on the pre-fix code.
  • Nit: the fragment said structured dtypes take the fast path without naming the pipeline. Fixed in 661f488: it now says FusedCodecPipeline.
  • Nit, older than this PR: the fast path gates on isinstance(codec, BytesCodec), so a BytesCodec subclass that overrides _decode_sync would be bypassed. No such subclass exists in the tree. Left as is.

The second reviewer compared fused and batched reads on 416 configurations (312 on the fast path) with zero mismatches, and confirmed that edge shards, nested sharding, sparse shards and the async path all decline the fast path.

Two rounds in a row found nothing serious, so the review loop stopped.

🤖 Generated with Claude Code

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#4654

Assisted-by: ClaudeCode:claude-opus-5-5
…y 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
Assisted-by: ClaudeCode:claude-opus-5-5
@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.00%. Comparing base (5d8689b) to head (b1653f6).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4669      +/-   ##
==========================================
- Coverage   95.00%   95.00%   -0.01%     
==========================================
  Files          96       96              
  Lines       14115    14110       -5     
==========================================
- Hits        13410    13405       -5     
  Misses        705      705              
Files with missing lines Coverage Δ
src/zarr/codecs/bytes.py 99.38% <100.00%> (+<0.01%) ⬆️
src/zarr/codecs/sharding.py 95.74% <100.00%> (-0.05%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@codspeed

codspeed Bot commented Nov 29, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 113 untouched benchmarks
⏩ 37 skipped benchmarks1


Comparing d-v-b:fix/sharding-bulk-read-device-memory (4b4cb64) with main (593d394)2

Open in CodSpeed

Footnotes

  1. 37 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on main (d06ed58) during the generation of this report, so 593d394 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@d-v-b
d-v-b merged commit 7d30080 into zarr-developers:main Dec 4, 2026
44 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

benchmark Code will be benchmarked in a CI job.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FusedCodecPipeline fails to read uncompressed shards into GPU memory

1 participant