"""Check GPU dispatch decisions without allocating CUDA tensors.""" from __future__ import annotations import importlib.util from pathlib import Path import sys from types import SimpleNamespace import pytest import torch @pytest.fixture def adapter(): path = Path(__file__).resolve().parents[1] / "torch-ext/late_interaction_kernels/layers.py" spec = importlib.util.spec_from_file_location("lik_dispatch_probe.layers", path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module class CudaInput: def __init__(self, tensor): self.tensor = tensor self.device = torch.device("cuda:0") self.dtype = tensor.dtype def numel(self): return self.tensor.numel() def to(self, dtype): return self.tensor.to(dtype) @pytest.mark.parametrize("capability", [(7, 5), (8, 0), (8, 6), (9, 0)]) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32]) @pytest.mark.parametrize("pairwise", [False, True]) def test_dispatch_values_and_gradients(adapter, monkeypatch, capability, dtype, pairwise): monkeypatch.setattr(adapter, "_HAS_TRITON", True) devices = [] def get_capability(device): devices.append(device) return capability monkeypatch.setattr(torch.cuda, "get_device_capability", get_capability) target_dtype = torch.float16 if dtype == torch.float16 or capability[0] < 8 else torch.bfloat16 calls = [] def score(a, b, q_mask, d_mask, normalize): assert a.dtype == b.dtype == target_dtype assert normalize is False calls.append(True) return adapter._reference(a.float(), b.float(), q_mask, d_mask, pairwise) monkeypatch.setitem(sys.modules, "lik_dispatch_probe.autograd", SimpleNamespace(maxsim=score, maxsim_pairs=score)) torch.manual_seed(42) a = torch.randn(2, 3, 16, dtype=dtype, requires_grad=True) b = torch.randn(2, 5, 16, dtype=dtype, requires_grad=True) am = torch.tensor([[True, False, True], [True, True, True]]) bm = torch.ones(2, 5, dtype=torch.bool) bm[0, -1] = False operation = adapter.MaxSimPairwise() if pairwise else adapter.MaxSim() observed = operation(CudaInput(a), CudaInput(b), am, bm) expected = adapter._reference(a.to(target_dtype).float(), b.to(target_dtype).float(), am, bm, pairwise) torch.testing.assert_close(observed, expected) actual_gradients = torch.autograd.grad(observed.sum(), (a, b)) expected_gradients = torch.autograd.grad(expected.sum(), (a, b)) for actual, expected in zip(actual_gradients, expected_gradients): assert torch.isfinite(actual).all() and actual.abs().sum() > 0 torch.testing.assert_close(actual, expected) assert calls == [True] assert devices == ([] if dtype == torch.float16 else [torch.device("cuda:0")])