|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""`aten.linear.default` (fp32, no bias) export + golden for the WebGPU backend. |
| 8 | +
|
| 9 | +Exports single-op linear graphs through VulkanPartitioner and locks the |
| 10 | +delegation contract + an fp64 torch golden. The handler computes |
| 11 | +out[m,n] = sum_k x[m,k] * w[n,k] (weight is [N,K]); it picks a vec4-over-K |
| 12 | +kernel when K % 4 == 0 and a scalar tiled kernel otherwise, so the configs span |
| 13 | +both branches (plus a K==1 / non-multiple shape that exercises the bounds guard). |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import unittest |
| 19 | + |
| 20 | +import torch |
| 21 | + |
| 22 | +from executorch.backends.vulkan.partitioner.vulkan_partitioner import VulkanPartitioner |
| 23 | +from executorch.exir import to_edge_transform_and_lower |
| 24 | + |
| 25 | +# name -> (M, K, N). weight is [N, K]; output is [M, N]. |
| 26 | +CONFIGS = { |
| 27 | + "square": (64, 64, 64), # K % 4 == 0 -> vec4-over-K kernel |
| 28 | + "tall_vec4": (32, 128, 16), # K % 4 == 0 -> vec4 path, skinny N |
| 29 | + "scalar_k": (8, 7, 5), # K % 4 != 0 -> scalar tiled path + bounds guard |
| 30 | + "k1": (4, 1, 8), # K == 1 rank-1, scalar path |
| 31 | +} |
| 32 | + |
| 33 | + |
| 34 | +class LinearModule(torch.nn.Module): |
| 35 | + def __init__(self, weight: torch.Tensor) -> None: |
| 36 | + super().__init__() |
| 37 | + n, k = weight.shape |
| 38 | + self.linear = torch.nn.Linear(k, n, bias=False) |
| 39 | + with torch.no_grad(): |
| 40 | + self.linear.weight.copy_(weight) |
| 41 | + |
| 42 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 43 | + return self.linear(x) |
| 44 | + |
| 45 | + |
| 46 | +def _det_inputs(m: int, k: int, n: int): |
| 47 | + """Deterministic fp32 input [M,K] + weight [N,K] (fixed seed).""" |
| 48 | + g = torch.Generator().manual_seed(0) |
| 49 | + x = torch.randn(m, k, generator=g, dtype=torch.float32) |
| 50 | + w = torch.randn(n, k, generator=g, dtype=torch.float32) |
| 51 | + return x, w |
| 52 | + |
| 53 | + |
| 54 | +def _export(m: torch.nn.Module, x: torch.Tensor): |
| 55 | + ep = torch.export.export(m, (x,)) |
| 56 | + return to_edge_transform_and_lower( |
| 57 | + ep, partitioner=[VulkanPartitioner()] |
| 58 | + ).to_executorch() |
| 59 | + |
| 60 | + |
| 61 | +def _delegates(et) -> bool: |
| 62 | + return any( |
| 63 | + d.id == "VulkanBackend" |
| 64 | + for plan in et.executorch_program.execution_plan |
| 65 | + for d in plan.delegates |
| 66 | + ) |
| 67 | + |
| 68 | + |
| 69 | +class TestLinear(unittest.TestCase): |
| 70 | + def test_export_delegates(self) -> None: |
| 71 | + for name, (m, k, n) in CONFIGS.items(): |
| 72 | + with self.subTest(name=name): |
| 73 | + x, w = _det_inputs(m, k, n) |
| 74 | + et = _export(LinearModule(w).eval(), x) |
| 75 | + self.assertTrue( |
| 76 | + _delegates(et), f"Expected a VulkanBackend delegate (linear {name})" |
| 77 | + ) |
| 78 | + |
| 79 | + def test_golden_matches_fp64(self) -> None: |
| 80 | + # Golden must match the fp64 F.linear truth (weight [N,K], no bias). |
| 81 | + for name, (m, k, n) in CONFIGS.items(): |
| 82 | + with self.subTest(name=name): |
| 83 | + x, w = _det_inputs(m, k, n) |
| 84 | + got = LinearModule(w).eval()(x) |
| 85 | + golden = torch.nn.functional.linear(x.double(), w.double()) |
| 86 | + torch.testing.assert_close( |
| 87 | + got, golden.to(torch.float32), atol=1e-3, rtol=1e-3 |
| 88 | + ) |
| 89 | + |
| 90 | + |
| 91 | +def export_linear_model( |
| 92 | + pte_path: str, golden_path: str, input_path: str, config: str = "square" |
| 93 | +) -> None: |
| 94 | + """Write a linear .pte + torch fp64 golden (raw LE fp32) + raw LE fp32 input.""" |
| 95 | + m_dim, k, n = CONFIGS[config] |
| 96 | + x, w = _det_inputs(m_dim, k, n) |
| 97 | + model = LinearModule(w).eval() |
| 98 | + golden = ( |
| 99 | + torch.nn.functional.linear(x.double(), w.double()) |
| 100 | + .to(torch.float32) |
| 101 | + .numpy() |
| 102 | + .astype("<f4") |
| 103 | + ) |
| 104 | + et = _export(model, x) |
| 105 | + with open(pte_path, "wb") as f: |
| 106 | + f.write(et.buffer) |
| 107 | + golden.tofile(golden_path) |
| 108 | + x.numpy().astype("<f4").tofile(input_path) |
| 109 | + print( |
| 110 | + f"Exported {pte_path}; golden {golden_path} ({golden.size} floats); " |
| 111 | + f"input {input_path} ({x.numel()} floats)" |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +if __name__ == "__main__": |
| 116 | + unittest.main() |
0 commit comments