|
| 1 | +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# See file LICENSE for terms. |
| 3 | + |
| 4 | +import cupy |
| 5 | +import numpy |
| 6 | +import zarr |
| 7 | + |
| 8 | +import kvikio |
| 9 | +import kvikio.zarr |
| 10 | + |
| 11 | + |
| 12 | +def main(path): |
| 13 | + a = cupy.arange(20) |
| 14 | + |
| 15 | + # Let's use KvikIO's convenience function `open_cupy_array()` to create |
| 16 | + # a new Zarr file on disk. Its semantic is the same as `zarr.open_array()` |
| 17 | + # but uses a GDS file store, nvCOMP compression, and CuPy arrays. |
| 18 | + z = kvikio.zarr.open_cupy_array(store=path, mode="w", shape=(20,), chunks=(5,)) |
| 19 | + |
| 20 | + # `z` is a regular Zarr Array that we can write to as usual |
| 21 | + z[0:10] = numpy.arange(0, 10) |
| 22 | + # but it also support direct reads and writes of CuPy arrays |
| 23 | + z[10:20] = numpy.arange(10, 20) |
| 24 | + |
| 25 | + # Reading `z` returns a CuPy array |
| 26 | + assert isinstance(z[:], cupy.ndarray) |
| 27 | + assert (a == z[:]).all() |
| 28 | + |
| 29 | + # By default, `open_cupy_array()` uses nvCOMP's `lz4` GPU compression, which is |
| 30 | + # compatible with NumCodecs's `lz4` CPU compression (CPU). Normally, it is not |
| 31 | + # possible to change which decompressor to use when reading a Zarr file. The |
| 32 | + # decompressor specified in the Zarr file's metadata is always used. However, |
| 33 | + # `open_cupy_array()` makes it possible to overwrite the metadata on-the-fly |
| 34 | + # without having to modify the Zarr file on disk. In fact, the Zarr file written |
| 35 | + # above appears, in the metadata, as if it was written by NumCodecs's `lz4` CPU |
| 36 | + # compression. Thus, we can open the file using Zarr's regular API and the CPU. |
| 37 | + z = zarr.open_array(path) |
| 38 | + # `z` is now read as a regular NumPy array |
| 39 | + assert isinstance(z[:], numpy.ndarray) |
| 40 | + assert (a.get() == z[:]).all() |
| 41 | + # and we can write to is as usual |
| 42 | + z[:] = numpy.arange(20, 40) |
| 43 | + |
| 44 | + # Let's read the Zarr file back into a CuPy array |
| 45 | + z = kvikio.zarr.open_cupy_array(store=path, mode="r") |
| 46 | + assert isinstance(z[:], cupy.ndarray) |
| 47 | + assert (cupy.arange(20, 40) == z[:]).all() |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + main("/tmp/zarr-cupy-nvcomp") |
0 commit comments