|
| 1 | +import jax |
| 2 | +import torch |
| 3 | +import torchax |
| 4 | + |
| 5 | +from tpu_inference.lora.torch_lora_ops import bgmv_torch |
| 6 | + |
| 7 | + |
| 8 | +def test_bgmv_torch(): |
| 9 | + num_tokens = 16 |
| 10 | + hidden_size = 128 |
| 11 | + max_loras = 9 |
| 12 | + max_lora_rank = 8 |
| 13 | + |
| 14 | + with torchax.default_env(), jax.default_device(jax.devices("tpu")[0]): |
| 15 | + inputs = torch.rand(num_tokens, hidden_size, device='jax') |
| 16 | + loras = torch.rand(max_loras, |
| 17 | + 1, |
| 18 | + max_lora_rank, |
| 19 | + hidden_size, |
| 20 | + device='jax') |
| 21 | + idxs = torch.randint(0, max_loras, (num_tokens, ), device='jax') |
| 22 | + |
| 23 | + actual = bgmv_torch(inputs, loras, idxs) |
| 24 | + expected = _ref_bgmv_torch(inputs, loras, idxs) |
| 25 | + torch.testing.assert_close(actual, expected, atol=3e-2, rtol=1e-3) |
| 26 | + |
| 27 | + |
| 28 | +def _ref_bgmv_torch(inputs, loras, idxs): |
| 29 | + if len(loras.shape) == 4: |
| 30 | + loras = loras.squeeze(axis=1) |
| 31 | + |
| 32 | + # Another equivalent ref impl is as the 2 lines below. |
| 33 | + # selected_loras = loras[idxs] |
| 34 | + # return torch.einsum('td,tld->tl', inputs, selected_loras) |
| 35 | + num_tokens, _ = inputs.shape |
| 36 | + outputs = [] |
| 37 | + for i in range(num_tokens): |
| 38 | + input = inputs[i] # [hidden_size] |
| 39 | + lora = loras[idxs[i]] # [max_lora_rank, hidden_size] |
| 40 | + out = torch.matmul(lora, input) |
| 41 | + outputs.append(out) |
| 42 | + |
| 43 | + return torch.stack(outputs, axis=0) |
0 commit comments