|
| 1 | +"""Regression tests for the single-buffer pattern in _try_nvcomp_from_device_bufs. |
| 2 | +
|
| 3 | +Issue #1659: ``_try_nvcomp_from_device_bufs`` used to allocate N separate |
| 4 | +``cupy.empty(tile_bytes)`` output buffers and run ``cupy.concatenate`` after |
| 5 | +the nvCOMP decompress kernel returned. That kept two copies of the |
| 6 | +decompressed data alive at once and ran a serial concat the other nvCOMP |
| 7 | +paths in this module already avoid. The fix matches the single-contiguous- |
| 8 | +buffer + pointer-offset pattern used by the deflate / LZW / host-buffer |
| 9 | +paths nearby. |
| 10 | +
|
| 11 | +These tests skip when CuPy + CUDA are not available. They also skip the |
| 12 | +end-to-end nvCOMP integration check when ``kvikio`` or the nvCOMP shared |
| 13 | +library are not installed, which is the common case on developer hosts; |
| 14 | +the unit-level checks (contract + memory guard) run regardless. |
| 15 | +""" |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import importlib.util |
| 19 | + |
| 20 | +import numpy as np |
| 21 | +import pytest |
| 22 | + |
| 23 | +from xrspatial.geotiff._gpu_decode import _try_nvcomp_from_device_bufs |
| 24 | + |
| 25 | + |
| 26 | +def _gpu_available() -> bool: |
| 27 | + if importlib.util.find_spec("cupy") is None: |
| 28 | + return False |
| 29 | + try: |
| 30 | + import cupy |
| 31 | + return bool(cupy.cuda.is_available()) |
| 32 | + except Exception: |
| 33 | + return False |
| 34 | + |
| 35 | + |
| 36 | +def _nvcomp_available() -> bool: |
| 37 | + from xrspatial.geotiff._gpu_decode import _get_nvcomp |
| 38 | + return _get_nvcomp() is not None |
| 39 | + |
| 40 | + |
| 41 | +@pytest.mark.skipif(not _gpu_available(), reason="cupy + CUDA required") |
| 42 | +def test_unsupported_codec_short_circuits_before_allocation(): |
| 43 | + """Non-ZSTD codecs must return None without allocating output buffers. |
| 44 | +
|
| 45 | + Pins the early-return contract that lets the caller pick a different |
| 46 | + decoder when nvCOMP cannot handle this codec. |
| 47 | + """ |
| 48 | + import cupy |
| 49 | + |
| 50 | + # Use Deflate (8), which is unsupported by this function (ZSTD only). |
| 51 | + d_tiles = [cupy.zeros(1024, dtype=cupy.uint8) for _ in range(4)] |
| 52 | + assert _try_nvcomp_from_device_bufs(d_tiles, 1024, 8) is None |
| 53 | + |
| 54 | + |
| 55 | +@pytest.mark.skipif(not _gpu_available(), reason="cupy + CUDA required") |
| 56 | +def test_no_nvcomp_lib_returns_none(monkeypatch): |
| 57 | + """When the nvCOMP library is missing, the function must return None. |
| 58 | +
|
| 59 | + The caller relies on this signal to fall back to the bytes-based decode |
| 60 | + path. Without it, callers would hit a ctypes ``getattr`` AttributeError |
| 61 | + deeper in the function. |
| 62 | + """ |
| 63 | + import cupy |
| 64 | + from xrspatial.geotiff import _gpu_decode |
| 65 | + |
| 66 | + monkeypatch.setattr(_gpu_decode, "_get_nvcomp", lambda: None) |
| 67 | + |
| 68 | + d_tiles = [cupy.zeros(1024, dtype=cupy.uint8)] |
| 69 | + assert _try_nvcomp_from_device_bufs(d_tiles, 1024, 50000) is None |
| 70 | + |
| 71 | + |
| 72 | +@pytest.mark.skipif(not _gpu_available(), reason="cupy + CUDA required") |
| 73 | +def test_memory_guard_runs_with_full_decomp_size(monkeypatch): |
| 74 | + """The single-buffer allocation must be size-checked before cupy.empty. |
| 75 | +
|
| 76 | + The new pattern allocates one contiguous ``n * tile_bytes`` buffer |
| 77 | + instead of N small buffers. The OOM guard is what tells the caller |
| 78 | + early that the decode will not fit on the device; a regression that |
| 79 | + removed the guard would surface as an opaque CUDA OOM instead. |
| 80 | + """ |
| 81 | + import cupy |
| 82 | + from xrspatial.geotiff import _gpu_decode |
| 83 | + |
| 84 | + seen = {"total_bytes": None, "what": None, "called": False} |
| 85 | + |
| 86 | + def fake_check(required_bytes, what="tile buffer"): |
| 87 | + seen["total_bytes"] = int(required_bytes) |
| 88 | + seen["what"] = what |
| 89 | + seen["called"] = True |
| 90 | + raise MemoryError("simulated OOM") |
| 91 | + |
| 92 | + # Pin _get_nvcomp to something truthy so the function does not bail |
| 93 | + # before reaching the allocation step. The fake check raises before |
| 94 | + # any nvCOMP call would happen, so the lib value never gets used. |
| 95 | + monkeypatch.setattr(_gpu_decode, "_get_nvcomp", lambda: object()) |
| 96 | + monkeypatch.setattr(_gpu_decode, "_check_gpu_memory", fake_check) |
| 97 | + |
| 98 | + n_tiles = 8 |
| 99 | + tile_bytes = 65536 |
| 100 | + d_tiles = [cupy.zeros(128, dtype=cupy.uint8) for _ in range(n_tiles)] |
| 101 | + |
| 102 | + with pytest.raises(MemoryError): |
| 103 | + _try_nvcomp_from_device_bufs(d_tiles, tile_bytes, 50000) |
| 104 | + |
| 105 | + assert seen["called"], "_check_gpu_memory was not called" |
| 106 | + expected_bytes = n_tiles * tile_bytes |
| 107 | + assert seen["total_bytes"] == expected_bytes, ( |
| 108 | + f"expected total {expected_bytes}, got {seen['total_bytes']}" |
| 109 | + ) |
| 110 | + assert "decompressed" in seen["what"] or "nvCOMP" in seen["what"], ( |
| 111 | + f"unhelpful 'what' label: {seen['what']!r}" |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +@pytest.mark.skipif( |
| 116 | + not _gpu_available() or not _nvcomp_available(), |
| 117 | + reason="cupy + CUDA + nvCOMP shared lib required", |
| 118 | +) |
| 119 | +def test_zstd_decompress_roundtrip_returns_single_contiguous_buffer(): |
| 120 | + """End-to-end: feed real ZSTD-compressed device buffers in, check the |
| 121 | + output is a single flat ``cupy.uint8`` array of length n*tile_bytes. |
| 122 | +
|
| 123 | + This test confirms the return contract that ``_apply_predictor_and_assemble`` |
| 124 | + depends on: ``out`` is the contiguous concatenation of the N decompressed |
| 125 | + tiles, not a list. The previous implementation returned the same shape but |
| 126 | + via ``cupy.concatenate``; the new one allocates the contig buffer up front |
| 127 | + and writes through per-tile pointers, so a regression that dropped the |
| 128 | + return value would surface here. |
| 129 | + """ |
| 130 | + import cupy |
| 131 | + import zstandard as zstd |
| 132 | + |
| 133 | + rng = np.random.default_rng(seed=1659) |
| 134 | + tile_bytes = 4096 |
| 135 | + n_tiles = 8 |
| 136 | + |
| 137 | + cctx = zstd.ZstdCompressor() |
| 138 | + host_tiles = [rng.integers(0, 256, size=tile_bytes, dtype=np.uint8) |
| 139 | + for _ in range(n_tiles)] |
| 140 | + compressed = [cctx.compress(t.tobytes()) for t in host_tiles] |
| 141 | + d_tiles = [cupy.asarray(np.frombuffer(c, dtype=np.uint8)) |
| 142 | + for c in compressed] |
| 143 | + |
| 144 | + result = _try_nvcomp_from_device_bufs(d_tiles, tile_bytes, 50000) |
| 145 | + |
| 146 | + # nvCOMP may be present but mis-configured on the host (e.g. driver |
| 147 | + # version mismatch); skip rather than fail in that case so the test is |
| 148 | + # informative when run on a real GDS rig. |
| 149 | + if result is None: |
| 150 | + pytest.skip("nvCOMP returned None; library may be unusable on this host") |
| 151 | + |
| 152 | + assert isinstance(result, cupy.ndarray) |
| 153 | + assert result.dtype == cupy.uint8 |
| 154 | + assert result.shape == (n_tiles * tile_bytes,) |
| 155 | + assert result.flags.c_contiguous |
| 156 | + |
| 157 | + # Decoded payload must match the original host tiles. The buffer is a |
| 158 | + # single flat array; tile i lives at offset i*tile_bytes. |
| 159 | + host_out = result.get() |
| 160 | + for i, expected in enumerate(host_tiles): |
| 161 | + decoded = host_out[i * tile_bytes:(i + 1) * tile_bytes] |
| 162 | + assert np.array_equal(decoded, expected), ( |
| 163 | + f"tile {i} decoded payload differs from input" |
| 164 | + ) |
| 165 | + |
| 166 | + |
| 167 | +@pytest.mark.skipif(not _gpu_available(), reason="cupy + CUDA required") |
| 168 | +def test_no_orphan_decomp_buffers_after_call(monkeypatch): |
| 169 | + """Earlier code held a Python list of N device buffers in scope |
| 170 | + alongside the concatenated result. The replacement allocates once |
| 171 | + and returns that one buffer. |
| 172 | +
|
| 173 | + The check here is structural rather than numerical: after a successful |
| 174 | + call the only cupy ndarray the caller receives is ``result`` itself, |
| 175 | + and inspecting it confirms ``result.size == n_tiles * tile_bytes``. |
| 176 | + """ |
| 177 | + import cupy |
| 178 | + from xrspatial.geotiff import _gpu_decode |
| 179 | + |
| 180 | + # Stub the nvCOMP entry points so the decompress "succeeds" without an |
| 181 | + # actual library. Force the function down the success branch, capture |
| 182 | + # the returned buffer, then verify shape + ownership. |
| 183 | + monkeypatch.setattr(_gpu_decode, "_get_nvcomp", |
| 184 | + lambda: _FakeNvcompLib()) |
| 185 | + |
| 186 | + n_tiles = 4 |
| 187 | + tile_bytes = 2048 |
| 188 | + d_tiles = [cupy.zeros(64, dtype=cupy.uint8) for _ in range(n_tiles)] |
| 189 | + result = _try_nvcomp_from_device_bufs(d_tiles, tile_bytes, 50000) |
| 190 | + |
| 191 | + # The fake lib reports success and zero-fills the output buffer; the |
| 192 | + # function returns the contiguous buffer as-is. |
| 193 | + assert result is not None |
| 194 | + assert isinstance(result, cupy.ndarray) |
| 195 | + assert result.size == n_tiles * tile_bytes |
| 196 | + assert result.flags.c_contiguous |
| 197 | + # The contract requires uint8 -- not a uint8 view of something else. |
| 198 | + assert result.dtype == cupy.uint8 |
| 199 | + |
| 200 | + |
| 201 | +class _FakeNvcompLib: |
| 202 | + """Stand-in for the nvCOMP CDLL handle used in tests. |
| 203 | +
|
| 204 | + The real function calls ``getattr(lib, fn_name)`` for two entry points |
| 205 | + and invokes each as a ctypes function. We expose those entry-point |
| 206 | + names as Python callables that pretend the work succeeded. |
| 207 | + """ |
| 208 | + |
| 209 | + def __getattr__(self, name): |
| 210 | + if name == 'nvcompBatchedZstdDecompressGetTempSizeAsync': |
| 211 | + return _fake_temp_size_fn |
| 212 | + if name == 'nvcompBatchedZstdDecompressAsync': |
| 213 | + return _fake_decompress_fn |
| 214 | + raise AttributeError(name) |
| 215 | + |
| 216 | + |
| 217 | +def _fake_temp_size_fn(n, tile_bytes, opts, p_temp_size, total): |
| 218 | + """Stub for nvcompBatchedZstdDecompressGetTempSizeAsync.""" |
| 219 | + # Write a tiny temp-size value into the caller's c_size_t. |
| 220 | + p_temp_size._obj.value = 1 |
| 221 | + return 0 |
| 222 | + |
| 223 | + |
| 224 | +def _fake_decompress_fn(*args): |
| 225 | + """Stub for nvcompBatchedZstdDecompressAsync. |
| 226 | +
|
| 227 | + The function's return-value test is ``s != 0``. We return 0 (success). |
| 228 | + The caller's d_statuses array is already zero from ``cupy.zeros``, so |
| 229 | + the post-decode any-nonzero check passes. |
| 230 | + """ |
| 231 | + return 0 |
0 commit comments