|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from collections.abc import Awaitable |
| 5 | +from dataclasses import dataclass |
| 6 | +from functools import cached_property |
| 7 | +from typing import TYPE_CHECKING |
| 8 | + |
| 9 | +import numpy as np |
| 10 | + |
| 11 | +from zarr.abc.codec import BytesBytesCodec |
| 12 | +from zarr.core.common import JSON, parse_named_configuration |
| 13 | +from zarr.registry import register_codec |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + from collections.abc import Generator, Iterable |
| 17 | + from typing import Any, Self |
| 18 | + |
| 19 | + from zarr.core.array_spec import ArraySpec |
| 20 | + from zarr.core.buffer import Buffer |
| 21 | + |
| 22 | +try: |
| 23 | + import cupy as cp |
| 24 | +except ImportError: |
| 25 | + cp = None |
| 26 | + |
| 27 | +try: |
| 28 | + from nvidia import nvcomp |
| 29 | +except ImportError: |
| 30 | + nvcomp = None |
| 31 | + |
| 32 | + |
| 33 | +class AsyncCUDAEvent(Awaitable[None]): |
| 34 | + """An awaitable wrapper around a CuPy CUDA event for asynchronous waiting.""" |
| 35 | + |
| 36 | + def __init__( |
| 37 | + self, event: cp.cuda.Event, initial_delay: float = 0.001, max_delay: float = 0.1 |
| 38 | + ) -> None: |
| 39 | + """ |
| 40 | + Initialize the async CUDA event. |
| 41 | +
|
| 42 | + Args: |
| 43 | + event (cp.cuda.Event): The CuPy CUDA event to wait on. |
| 44 | + initial_delay (float): Initial polling delay in seconds (default: 0.001s). |
| 45 | + max_delay (float): Maximum polling delay in seconds (default: 0.1s). |
| 46 | + """ |
| 47 | + self.event = event |
| 48 | + self.initial_delay = initial_delay |
| 49 | + self.max_delay = max_delay |
| 50 | + |
| 51 | + def __await__(self) -> Generator[Any, None, None]: |
| 52 | + """Makes the event awaitable by yielding control until the event is complete.""" |
| 53 | + return self._wait().__await__() |
| 54 | + |
| 55 | + async def _wait(self) -> None: |
| 56 | + """Polls the CUDA event asynchronously with exponential backoff until it completes.""" |
| 57 | + delay = self.initial_delay |
| 58 | + while not self.event.query(): # `query()` returns True if the event is complete |
| 59 | + await asyncio.sleep(delay) # Yield control to other async tasks |
| 60 | + delay = min(delay * 2, self.max_delay) # Exponential backoff |
| 61 | + |
| 62 | + |
| 63 | +def parse_zstd_level(data: JSON) -> int: |
| 64 | + if isinstance(data, int): |
| 65 | + if data >= 23: |
| 66 | + raise ValueError(f"Value must be less than or equal to 22. Got {data} instead.") |
| 67 | + return data |
| 68 | + raise TypeError(f"Got value with type {type(data)}, but expected an int.") |
| 69 | + |
| 70 | + |
| 71 | +def parse_checksum(data: JSON) -> bool: |
| 72 | + if isinstance(data, bool): |
| 73 | + return data |
| 74 | + raise TypeError(f"Expected bool. Got {type(data)}.") |
| 75 | + |
| 76 | + |
| 77 | +@dataclass(frozen=True) |
| 78 | +class NvcompZstdCodec(BytesBytesCodec): |
| 79 | + is_fixed_size = True |
| 80 | + |
| 81 | + level: int = 0 |
| 82 | + checksum: bool = False |
| 83 | + |
| 84 | + def __init__(self, *, level: int = 0, checksum: bool = False) -> None: |
| 85 | + # TODO: Set CUDA device appropriately here and also set CUDA stream |
| 86 | + |
| 87 | + level_parsed = parse_zstd_level(level) |
| 88 | + checksum_parsed = parse_checksum(checksum) |
| 89 | + |
| 90 | + object.__setattr__(self, "level", level_parsed) |
| 91 | + object.__setattr__(self, "checksum", checksum_parsed) |
| 92 | + |
| 93 | + @classmethod |
| 94 | + def from_dict(cls, data: dict[str, JSON]) -> Self: |
| 95 | + _, configuration_parsed = parse_named_configuration(data, "zstd") |
| 96 | + return cls(**configuration_parsed) # type: ignore[arg-type] |
| 97 | + |
| 98 | + def to_dict(self) -> dict[str, JSON]: |
| 99 | + return { |
| 100 | + "name": "zstd", |
| 101 | + "configuration": {"level": self.level, "checksum": self.checksum}, |
| 102 | + } |
| 103 | + |
| 104 | + @cached_property |
| 105 | + def _zstd_codec(self) -> nvcomp.Codec: |
| 106 | + # config_dict = {algorithm = "Zstd", "level": self.level, "checksum": self.checksum} |
| 107 | + # return Zstd.from_config(config_dict) |
| 108 | + device = cp.cuda.Device() # Select the current default device |
| 109 | + stream = cp.cuda.get_current_stream() # Use the current default stream |
| 110 | + return nvcomp.Codec( |
| 111 | + algorithm="Zstd", |
| 112 | + bitstream_kind=nvcomp.BitstreamKind.RAW, |
| 113 | + device_id=device.id, |
| 114 | + cuda_stream=stream.ptr, |
| 115 | + ) |
| 116 | + |
| 117 | + async def _convert_to_nvcomp_arrays( |
| 118 | + self, |
| 119 | + chunks_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], |
| 120 | + ) -> tuple[list[nvcomp.Array], list[int]]: |
| 121 | + none_indices = [i for i, (b, _) in enumerate(chunks_and_specs) if b is None] |
| 122 | + filtered_inputs = [b.as_array_like() for b, _ in chunks_and_specs if b is not None] |
| 123 | + # TODO: add CUDA stream here |
| 124 | + return nvcomp.as_arrays(filtered_inputs), none_indices |
| 125 | + |
| 126 | + async def _convert_from_nvcomp_arrays( |
| 127 | + self, |
| 128 | + arrays: Iterable[nvcomp.Array], |
| 129 | + chunks_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], |
| 130 | + ) -> Iterable[Buffer | None]: |
| 131 | + return [ |
| 132 | + spec.prototype.buffer.from_array_like(cp.asarray(a, dtype=np.dtype("b"))) if a else None |
| 133 | + for a, (_, spec) in zip(arrays, chunks_and_specs, strict=True) |
| 134 | + ] |
| 135 | + |
| 136 | + async def decode( |
| 137 | + self, |
| 138 | + chunks_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], |
| 139 | + ) -> Iterable[Buffer | None]: |
| 140 | + """Decodes a batch of chunks. |
| 141 | + Chunks can be None in which case they are ignored by the codec. |
| 142 | +
|
| 143 | + Parameters |
| 144 | + ---------- |
| 145 | + chunks_and_specs : Iterable[tuple[Buffer | None, ArraySpec]] |
| 146 | + Ordered set of encoded chunks with their accompanying chunk spec. |
| 147 | +
|
| 148 | + Returns |
| 149 | + ------- |
| 150 | + Iterable[Buffer | None] |
| 151 | + """ |
| 152 | + chunks_and_specs = list(chunks_and_specs) |
| 153 | + |
| 154 | + # Convert to nvcomp arrays |
| 155 | + filtered_inputs, none_indices = await self._convert_to_nvcomp_arrays(chunks_and_specs) |
| 156 | + |
| 157 | + outputs = self._zstd_codec.decode(filtered_inputs) if len(filtered_inputs) > 0 else [] |
| 158 | + for index in none_indices: |
| 159 | + outputs.insert(index, None) |
| 160 | + |
| 161 | + return await self._convert_from_nvcomp_arrays(outputs, chunks_and_specs) |
| 162 | + |
| 163 | + async def encode( |
| 164 | + self, |
| 165 | + chunks_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], |
| 166 | + ) -> Iterable[Buffer | None]: |
| 167 | + """Encodes a batch of chunks. |
| 168 | + Chunks can be None in which case they are ignored by the codec. |
| 169 | +
|
| 170 | + Parameters |
| 171 | + ---------- |
| 172 | + chunks_and_specs : Iterable[tuple[Buffer | None, ArraySpec]] |
| 173 | + Ordered set of to-be-encoded chunks with their accompanying chunk spec. |
| 174 | +
|
| 175 | + Returns |
| 176 | + ------- |
| 177 | + Iterable[Buffer | None] |
| 178 | + """ |
| 179 | + # TODO: Make this actually async |
| 180 | + chunks_and_specs = list(chunks_and_specs) |
| 181 | + |
| 182 | + # Convert to nvcomp arrays |
| 183 | + filtered_inputs, none_indices = await self._convert_to_nvcomp_arrays(chunks_and_specs) |
| 184 | + |
| 185 | + outputs = self._zstd_codec.encode(filtered_inputs) if len(filtered_inputs) > 0 else [] |
| 186 | + for index in none_indices: |
| 187 | + outputs.insert(index, None) |
| 188 | + |
| 189 | + return await self._convert_from_nvcomp_arrays(outputs, chunks_and_specs) |
| 190 | + |
| 191 | + def compute_encoded_size(self, _input_byte_length: int, _chunk_spec: ArraySpec) -> int: |
| 192 | + raise NotImplementedError |
| 193 | + |
| 194 | + |
| 195 | +register_codec("zstd", NvcompZstdCodec) |
0 commit comments