"""Check the native provider without requiring Sentence Transformers.""" from __future__ import annotations from pathlib import Path import pytest import torch import torch.nn.functional as F from kernels import get_local_kernel @pytest.fixture(scope="module") def kernel(): return get_local_kernel(Path(__file__).resolve().parents[1]) def reference(a, b, am, bm, pairwise): values = torch.einsum("bsh,bth->bst" if pairwise else "ash,bth->abst", a, b) if bm is not None: valid = bm[:, None, :] if pairwise else bm[None, :, None, :] values = values.masked_fill(~valid, torch.finfo(values.dtype).min) scores = values.max(-1).values.float() if am is not None: scores = scores * (am if pairwise else am[:, None, :]) scores = scores.sum(-1) if bm is not None: scores = scores.masked_fill(~bm.any(-1), -1e9) return scores @pytest.mark.parametrize("pairwise", [False, True]) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64]) @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required") def test_masked_scores_and_gradients(kernel, pairwise, dtype, monkeypatch): if dtype != torch.float64: if not kernel.layers._HAS_TRITON: pytest.skip("Triton is required") def unexpected_reference(*args, **kwargs): pytest.fail("Expected the Triton provider, got reference scoring") monkeypatch.setattr(kernel.layers, "_reference", unexpected_reference) torch.manual_seed(313) a = F.normalize(torch.randn(3, 17, 64, device="cuda"), dim=-1).to(dtype).requires_grad_() b = F.normalize(torch.randn(3, 37, 64, device="cuda"), dim=-1).to(dtype).requires_grad_() am = torch.ones(a.shape[:2], dtype=torch.bool, device="cuda") bm = torch.ones(b.shape[:2], dtype=torch.bool, device="cuda") am[0] = False am[:, 2::5] = False bm[1] = False bm[:, 3::7] = False operation = kernel.layers.MaxSimPairwise() if pairwise else kernel.layers.MaxSim() expected = ( reference(a.float(), b.float(), am, bm, pairwise) if dtype in { torch.float16, torch.bfloat16, } else reference(a, b, am, bm, pairwise) ) observed = operation(a, b, am, bm) torch.testing.assert_close(observed, expected, atol=0.005, rtol=0.005) weights = torch.randn_like(observed) expected_grads = torch.autograd.grad(expected, (a, b), weights) observed_grads = torch.autograd.grad(observed, (a, b), weights) for actual, target in zip(observed_grads, expected_grads): error = (actual.float() - target.float()).norm() / target.float().norm().clamp_min(1e-9) assert error.item() < 0.03 @pytest.mark.parametrize("pairwise", [False, True]) def test_reference_contract(kernel, pairwise): a = torch.randn(3, 17, 64, requires_grad=True) b = torch.randn(3, 37, 64, requires_grad=True) am = torch.rand(3, 17) bm = torch.rand(3, 37) > 0.3 operation = kernel.layers.MaxSimPairwise() if pairwise else kernel.layers.MaxSim() expected = reference(a, b, am, bm, pairwise) torch.testing.assert_close(operation(a, b, am, bm), expected) compiled = torch.compile(operation, backend="eager", fullgraph=True) torch.testing.assert_close(compiled(a, b, am, bm), expected) empty = operation(a, b[:, :0], am, bm[:, :0]) assert (empty == -1e9).all() torch.autograd.grad(empty.sum(), (a, b))