|
| 1 | +import unittest |
| 2 | + |
| 3 | +# Copyright 2024 Advanced Micro Devices, Inc. |
| 4 | +# |
| 5 | +# Licensed under the Apache License v2.0 with LLVM Exceptions. |
| 6 | +# See https://llvm.org/LICENSE.txt for license information. |
| 7 | +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 8 | + |
| 9 | +from pathlib import Path |
| 10 | +import tempfile |
| 11 | +import torch |
| 12 | +from shark_turbine import aot |
| 13 | +from sharktank.models.punet.layers import Conv2DLayer |
| 14 | +from sharktank import ops |
| 15 | +from sharktank.types import ( |
| 16 | + Dataset, |
| 17 | + DefaultPrimitiveTensor, |
| 18 | + Theta, |
| 19 | + ShardedTensor, |
| 20 | + SplitPrimitiveTensor, |
| 21 | + unbox_tensor, |
| 22 | +) |
| 23 | +from sharktank.types.sharding import Conv2DSplitOutputChannelSharding |
| 24 | +import iree.runtime |
| 25 | +from typing import List, Optional |
| 26 | +import os |
| 27 | + |
| 28 | +vm_context: iree.runtime.VmContext = None |
| 29 | + |
| 30 | + |
| 31 | +def get_compiler_args(target_device_kind: str, shard_count: int) -> List[str]: |
| 32 | + result = [ |
| 33 | + f"--iree-hal-target-device={target_device_kind}[{i}]" |
| 34 | + for i in range(shard_count) |
| 35 | + ] |
| 36 | + return result |
| 37 | + |
| 38 | + |
| 39 | +def compile_iree_module( |
| 40 | + export_output: aot.ExportOutput, module_path: str, shard_count: int |
| 41 | +): |
| 42 | + export_output.session.set_flags( |
| 43 | + *get_compiler_args(target_device_kind="llvm-cpu", shard_count=shard_count) |
| 44 | + ) |
| 45 | + export_output.compile(save_to=module_path, target_backends=None) |
| 46 | + |
| 47 | + |
| 48 | +# TODO: improve IREE's Python API to be more concise in a multi-device context. |
| 49 | +# This run function should be way shorter. |
| 50 | +def run_iree_module( |
| 51 | + sharded_input_image: ShardedTensor, |
| 52 | + module_path: str, |
| 53 | + parameters_path: str, |
| 54 | +) -> ShardedTensor: |
| 55 | + shard_count = sharded_input_image.shard_count |
| 56 | + hal_driver = iree.runtime.get_driver("local-task") |
| 57 | + vm_instance = iree.runtime.VmInstance() |
| 58 | + available_devices = hal_driver.query_available_devices() |
| 59 | + # Use the same actual device for all devices. |
| 60 | + devices = [ |
| 61 | + hal_driver.create_device(available_devices[0]) for _ in range(shard_count) |
| 62 | + ] |
| 63 | + hal_module = iree.runtime.create_hal_module(instance=vm_instance, devices=devices) |
| 64 | + params_path = Path(parameters_path) |
| 65 | + # TODO: make IREE able to load the parameters from the top parameter file |
| 66 | + # without having to specify the parameter file for each shard separately. |
| 67 | + parameter_index = iree.runtime.ParameterIndex() |
| 68 | + for i in range(shard_count): |
| 69 | + parameter_index.load( |
| 70 | + file_path=str( |
| 71 | + Path(params_path).with_suffix(f".rank{i}{params_path.suffix}") |
| 72 | + ) |
| 73 | + ) |
| 74 | + parameter_provider = parameter_index.create_provider(scope="model") |
| 75 | + parameters_module = iree.runtime.create_io_parameters_module( |
| 76 | + vm_instance, parameter_provider |
| 77 | + ) |
| 78 | + |
| 79 | + vm_module = iree.runtime.VmModule.mmap(vm_instance, str(module_path)) |
| 80 | + |
| 81 | + # The context needs to be destroyed after the buffers, although |
| 82 | + # it is not associate with them on the API level. |
| 83 | + global vm_context |
| 84 | + vm_context = iree.runtime.VmContext( |
| 85 | + instance=vm_instance, modules=(hal_module, parameters_module, vm_module) |
| 86 | + ) |
| 87 | + module_input_args = [ |
| 88 | + iree.runtime.asdevicearray( |
| 89 | + devices[i], sharded_input_image.shards[i].as_torch().to("cpu").numpy() |
| 90 | + ) |
| 91 | + for i in range(shard_count) |
| 92 | + ] |
| 93 | + |
| 94 | + vm_function = vm_module.lookup_function("main") |
| 95 | + invoker = iree.runtime.FunctionInvoker( |
| 96 | + vm_context=vm_context, |
| 97 | + # TODO: rework iree.runtime.FunctionInvoker interface for multiple devices. |
| 98 | + # This works, but does not look right. |
| 99 | + device=devices[0], |
| 100 | + vm_function=vm_function, |
| 101 | + ) |
| 102 | + results = invoker(*module_input_args) |
| 103 | + shards = [torch.tensor(tensor.to_host()) for tensor in results] |
| 104 | + return SplitPrimitiveTensor(ts=shards, shard_dim=1) |
| 105 | + |
| 106 | + |
| 107 | +def run_test_sharded_conv2d_with_iree( |
| 108 | + mlir_path: Path, module_path: Path, parameters_path: Path, caching: bool |
| 109 | +): |
| 110 | + torch.set_default_dtype(torch.float32) |
| 111 | + torch.manual_seed(123456) |
| 112 | + batches = 2 |
| 113 | + in_channels = 6 |
| 114 | + out_channels = 8 |
| 115 | + height = 11 |
| 116 | + width = 13 |
| 117 | + kernel_height = 5 |
| 118 | + kernel_width = 5 |
| 119 | + shard_count = 2 |
| 120 | + unsharded_theta = Theta( |
| 121 | + { |
| 122 | + "weight": DefaultPrimitiveTensor( |
| 123 | + data=torch.rand( |
| 124 | + out_channels, |
| 125 | + in_channels, |
| 126 | + kernel_height, |
| 127 | + kernel_width, |
| 128 | + ) |
| 129 | + ), |
| 130 | + } |
| 131 | + ) |
| 132 | + unsharded_theta.rename_tensors_to_paths() |
| 133 | + |
| 134 | + if not caching or not os.path.exists(parameters_path): |
| 135 | + sharding_spec = Conv2DSplitOutputChannelSharding(shard_count=shard_count) |
| 136 | + sharded_theta = ops.reshard(unsharded_theta, sharding_spec) |
| 137 | + |
| 138 | + # Roundtrip the dataset, which anchors the tensors as parameters to be loaded |
| 139 | + # vs constants to be frozen (TODO: This is a bit wonky). |
| 140 | + sharded_dataset = Dataset({}, sharded_theta) |
| 141 | + sharded_dataset.save(parameters_path) |
| 142 | + |
| 143 | + sharded_dataset = Dataset.load(parameters_path) |
| 144 | + |
| 145 | + input_image = torch.rand( |
| 146 | + batches, |
| 147 | + in_channels, |
| 148 | + height, |
| 149 | + width, |
| 150 | + ) |
| 151 | + |
| 152 | + sharded_torch_module = Conv2DLayer(sharded_dataset.root_theta, padding=(0, 0)) |
| 153 | + sharded_input_image = ops.reshard_split(input_image, dim=1, count=shard_count) |
| 154 | + expected_result = sharded_torch_module(sharded_input_image) |
| 155 | + |
| 156 | + if not caching or not os.path.exists(module_path): |
| 157 | + exported_module = aot.export( |
| 158 | + sharded_torch_module, |
| 159 | + args=(sharded_input_image,), |
| 160 | + ) |
| 161 | + exported_module.save_mlir(mlir_path) |
| 162 | + |
| 163 | + compile_iree_module( |
| 164 | + export_output=exported_module, |
| 165 | + module_path=module_path, |
| 166 | + shard_count=shard_count, |
| 167 | + ) |
| 168 | + |
| 169 | + actual_result = run_iree_module( |
| 170 | + sharded_input_image=sharded_input_image, |
| 171 | + module_path=module_path, |
| 172 | + parameters_path=parameters_path, |
| 173 | + ) |
| 174 | + assert len(actual_result.shards) == len(expected_result.shards) |
| 175 | + assert actual_result.shard_dim == expected_result.shard_dim |
| 176 | + # TODO: reenable this check once numerical issues are resolved. |
| 177 | + # See https://github.com/iree-org/iree/issues/18283 |
| 178 | + # for actual_shard, expected_shard in zip( |
| 179 | + # actual_result.shards, expected_result.shards |
| 180 | + # ): |
| 181 | + # torch.testing.assert_close( |
| 182 | + # unbox_tensor(actual_shard), unbox_tensor(expected_shard) |
| 183 | + # ) |
| 184 | + |
| 185 | + |
| 186 | +def test_sharded_conv2d_with_iree( |
| 187 | + mlir_path: Optional[Path], |
| 188 | + module_path: Optional[Path], |
| 189 | + parameters_path: Optional[Path], |
| 190 | + caching: bool, |
| 191 | +): |
| 192 | + """Test sharding, exporting and running with IREE a 2D convolution layer.""" |
| 193 | + |
| 194 | + with tempfile.TemporaryDirectory( |
| 195 | + # TODO: verify hypothesis and remove ignore_cleanup_errors=True after a fix. |
| 196 | + # torch.export.export is spawning some processes that don't exit when the |
| 197 | + # function returns, this causes some objects to not get destroyed, which |
| 198 | + # in turn holds files params.rank0.irpa and params.rank1.irpa open. |
| 199 | + ignore_cleanup_errors=True |
| 200 | + ) as tmp_dir: |
| 201 | + mlir_path = Path(tmp_dir) / "model.mlir" if mlir_path is None else mlir_path |
| 202 | + module_path = ( |
| 203 | + Path(tmp_dir) / "module.vmfb" if module_path is None else module_path |
| 204 | + ) |
| 205 | + parameters_path = ( |
| 206 | + Path(tmp_dir) / "params.irpa" |
| 207 | + if parameters_path is None |
| 208 | + else parameters_path |
| 209 | + ) |
| 210 | + run_test_sharded_conv2d_with_iree( |
| 211 | + mlir_path, module_path, parameters_path, caching |
| 212 | + ) |
0 commit comments