|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +"""External kernel integration fro TIR""" |
| 18 | +import json |
| 19 | +import logging |
| 20 | +import tempfile |
| 21 | +from typing import Any, Dict, List, Tuple, Union |
| 22 | + |
| 23 | +from tvm import __version__ as tvm_version |
| 24 | +from tvm import tir |
| 25 | +from tvm.runtime import Module, load_module |
| 26 | + |
| 27 | + |
| 28 | +class BaseKernel: |
| 29 | + """Base class for external kernels.""" |
| 30 | + |
| 31 | + def compile_to_device_module( |
| 32 | + self, launch_args, *args, **kwargs |
| 33 | + ) -> Tuple[str, Module, List[Any]]: |
| 34 | + """Compile the kernel to a device module.""" |
| 35 | + raise NotImplementedError() |
| 36 | + |
| 37 | + def _format_tvm_module_metadata(self, kernel_name, arg_types, launch_param_tags): |
| 38 | + """Format the TVM module metadata.""" |
| 39 | + tvm_metadata = """{{ |
| 40 | + "tvm_version": "{version}", |
| 41 | + "func_info": {{ |
| 42 | + "{kernel_name}": {{ |
| 43 | + "name": "", |
| 44 | + "arg_types": {arg_types}, |
| 45 | + "launch_param_tags": {launch_param_tags} |
| 46 | + }} |
| 47 | + }} |
| 48 | + }}""".format_map( |
| 49 | + { |
| 50 | + "version": tvm_version, |
| 51 | + "kernel_name": kernel_name, |
| 52 | + "arg_types": json.dumps(arg_types), |
| 53 | + "launch_param_tags": json.dumps(launch_param_tags), |
| 54 | + } |
| 55 | + ) |
| 56 | + return tvm_metadata |
| 57 | + |
| 58 | + def _create_cuda_module(self, ptx, kernel_arg_types, launch_param_tags, kernel_name): |
| 59 | + """ |
| 60 | + Create a CUDA module from PTX and metadata. |
| 61 | +
|
| 62 | + Parameters |
| 63 | + ---------- |
| 64 | + ptx : str |
| 65 | + The PTX code of the kernel. |
| 66 | +
|
| 67 | + kernel_arg_types : List[str] |
| 68 | + The types of the kernel arguments. |
| 69 | +
|
| 70 | + launch_param_tags : List[str] |
| 71 | + The tags of the launch parameters. |
| 72 | +
|
| 73 | + kernel_name : str |
| 74 | + The name of the kernel. |
| 75 | +
|
| 76 | + Returns |
| 77 | + ------- |
| 78 | + kernel_module : Module |
| 79 | + The CUDA module. |
| 80 | + """ |
| 81 | + tvm_metadata = self._format_tvm_module_metadata( |
| 82 | + kernel_name, kernel_arg_types, launch_param_tags |
| 83 | + ) |
| 84 | + with tempfile.TemporaryDirectory() as temp_dir: |
| 85 | + ptx_path = f"{temp_dir}/{kernel_name}.ptx" |
| 86 | + with open(ptx_path, "w") as f: |
| 87 | + f.write(ptx) |
| 88 | + with open(f"{temp_dir}/{kernel_name}.tvm_meta.json", "w") as f: |
| 89 | + f.write(tvm_metadata) |
| 90 | + kernel_module = load_module(ptx_path) |
| 91 | + return kernel_module |
| 92 | + |
| 93 | + |
| 94 | +def call_kernel( |
| 95 | + kernel, |
| 96 | + launch_args: List[Union[int, tir.PrimExpr, List[Union[int, tir.PrimExpr]]]], |
| 97 | + *args: List[Any], |
| 98 | + **kwargs: Dict[str, Any], |
| 99 | +): |
| 100 | + """ |
| 101 | + Call an external kernel. |
| 102 | +
|
| 103 | + Parameters |
| 104 | + ---------- |
| 105 | + kernel : Any |
| 106 | + The external kernel to call. |
| 107 | +
|
| 108 | + launch_args : List[Union[int, tir.PrimExpr, List[Union[int, tir.PrimExpr]]]] |
| 109 | + The launch arguments. A list of integers for grid size, block size, and shared memory size. |
| 110 | + The actual requirements depend on the kernel. |
| 111 | +
|
| 112 | + args : List[tir.PrimExpr] |
| 113 | + The arguments to pass to the kernel. |
| 114 | +
|
| 115 | + kwargs : Dict[str, Any] |
| 116 | + Additional keyword arguments to pass to the kernel or compilation. |
| 117 | + """ |
| 118 | + from ..ir import module_get_attr, module_set_attr # pylint: disable=import-outside-toplevel |
| 119 | + from .ir import call_packed # pylint: disable=import-outside-toplevel |
| 120 | + |
| 121 | + kernel_type = f"{type(kernel).__module__}.{type(kernel).__qualname__}" |
| 122 | + if kernel_type == "triton.runtime.jit.JITFunction": |
| 123 | + from .triton import TritonKernel # pylint: disable=import-outside-toplevel |
| 124 | + |
| 125 | + kernel = TritonKernel(kernel) |
| 126 | + else: |
| 127 | + raise ValueError("Unsupported kernel type {}".format(kernel_type)) |
| 128 | + |
| 129 | + kernel_name, kernel_module, runtime_args = kernel.compile_to_device_module( |
| 130 | + launch_args, *args, **kwargs |
| 131 | + ) |
| 132 | + |
| 133 | + # Attach the kernel module to the current IRModule |
| 134 | + external_mods: List[Module] = module_get_attr("external_mods") or [] |
| 135 | + kernel_exists = any([mod.implements_function(kernel_name) for mod in external_mods]) |
| 136 | + if kernel_exists: |
| 137 | + logging.debug("Kernel %s already exists in the IRModule", kernel_name) |
| 138 | + else: |
| 139 | + external_mods.append(kernel_module) |
| 140 | + module_set_attr("external_mods", external_mods, True) |
| 141 | + return call_packed(kernel_name, *runtime_args) |
0 commit comments