|
| 1 | +# Copyright 2025 Advanced Micro Devices, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License v2.0 with LLVM Exceptions. |
| 4 | +# See https://llvm.org/LICENSE.txt for license information. |
| 5 | +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | + |
| 7 | +from typing import Callable |
| 8 | +import unittest |
| 9 | +import torch |
| 10 | + |
| 11 | +from parameterized import parameterized |
| 12 | + |
| 13 | +from sharktank import ops |
| 14 | +from sharktank.ops.sharded_impls import zeros_replicated |
| 15 | +from sharktank.types import DefaultPrimitiveTensor |
| 16 | +from sharktank.ops.default_impls import abs_default, cos_default, zeros_default |
| 17 | +from sharktank.types.tensors import InferenceTensor, ReplicatedTensor |
| 18 | +from sharktank.utils.testing import assert_tensor_close |
| 19 | + |
| 20 | + |
| 21 | +class DispatchTest(unittest.TestCase): |
| 22 | + def setUp(self): |
| 23 | + ops._registry._test_enable_last_op_dispatch(True) |
| 24 | + |
| 25 | + def tearDown(self): |
| 26 | + ops._registry._test_enable_last_op_dispatch(False) |
| 27 | + |
| 28 | + def make_tensor(self, shards: int) -> InferenceTensor: |
| 29 | + tensor = torch.tensor([1.0, 2.0, 3.0]) |
| 30 | + if shards == 1: |
| 31 | + return DefaultPrimitiveTensor(data=tensor) |
| 32 | + else: |
| 33 | + return ReplicatedTensor(ts=tensor, shard_count=shards) |
| 34 | + |
| 35 | + @parameterized.expand( |
| 36 | + [ |
| 37 | + (None, zeros_default), |
| 38 | + ((2, 3), zeros_replicated._unwrapped), |
| 39 | + ] |
| 40 | + ) |
| 41 | + def test_non_trivially_replicable_op( |
| 42 | + self, devices: tuple[int, ...] | None, expected_dispatch: Callable |
| 43 | + ): |
| 44 | + ops.zeros(1, devices=devices) |
| 45 | + |
| 46 | + last_dispatch_after_zeros = ops._registry._test_get_last_op_dispatch() |
| 47 | + self.assertIs(last_dispatch_after_zeros, expected_dispatch) |
| 48 | + |
| 49 | + @parameterized.expand([(1,), (2,)]) |
| 50 | + def test_trivially_replicable_op(self, shard_count: int): |
| 51 | + self.make_tensor(shard_count).abs() |
| 52 | + |
| 53 | + last_dispatch = ops._registry._test_get_last_op_dispatch() |
| 54 | + self.assertIs(last_dispatch, abs_default) |
| 55 | + |
| 56 | + @parameterized.expand([(1,), (2,)]) |
| 57 | + def test_multiple_dispatch(self, shard_count: int): |
| 58 | + tensor = self.make_tensor(shard_count) |
| 59 | + |
| 60 | + tensor.abs() |
| 61 | + last_dispatch_after_abs = ops._registry._test_get_last_op_dispatch() |
| 62 | + self.assertIs(last_dispatch_after_abs, abs_default) |
| 63 | + |
| 64 | + tensor.cos() |
| 65 | + last_dispatch_after_cos = ops._registry._test_get_last_op_dispatch() |
| 66 | + self.assertIs(last_dispatch_after_cos, cos_default) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + unittest.main() |
0 commit comments