diff --git a/PyTorchSimFrontend/extension_device.cpp b/PyTorchSimFrontend/extension_device.cpp index 531fcb01b..8453e8e51 100644 --- a/PyTorchSimFrontend/extension_device.cpp +++ b/PyTorchSimFrontend/extension_device.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -12,6 +13,8 @@ #include #include #include +#include +#include static uint64_t op_counter = 0; static uint64_t last_saved_value = 0; @@ -38,6 +41,48 @@ at::Tensor custom_mul_Tensor(const at::Tensor & self, const at::Tensor & other) return at::empty(self.sizes(), self.options()); } +at::Tensor _reinterpret_tensor( + const at::Tensor& self, + c10::IntArrayRef size, + c10::IntArrayRef stride, + int64_t offset_increment) { + at::Tensor self_ = at::detail::make_tensor( + c10::Storage(self.storage()), self.key_set(), self.dtype()); + auto* self_tmp_ = self_.unsafeGetTensorImpl(); + self_tmp_->set_storage_offset(self.storage_offset() + offset_increment); + self_tmp_->set_sizes_and_strides(size, stride); + return self_; +} + +at::Tensor& zero_inplace_batching_rule(at::Tensor &self) { + op_counter += 1; + // Since this custom device is just for testing, not bothering to implement kernels. + return self; +} + +const at::Tensor& custom_resize_(const at::Tensor& self, at::IntArrayRef size, + std::optional optional_memory_format) { + at::TensorImpl* tensor_impl = self.unsafeGetTensorImpl(); + tensor_impl->set_sizes_contiguous(size); + const auto itemsize = tensor_impl->dtype().itemsize(); + const auto offset = tensor_impl->storage_offset(); + const auto storage_size = at::detail::computeStorageNbytesContiguous(size, itemsize, offset); + // Dummy device is using cpu allocator, so here just call cpu + // function maybe_resize_storage_cpu in aten/src/ATen/native/Resize.h + // to get a sufficient memory space. + at::native::maybe_resize_storage_cpu(tensor_impl, storage_size); + if (optional_memory_format.has_value()) { + auto memory_format = + optional_memory_format.value(); + TORCH_CHECK( + memory_format != at::MemoryFormat::Preserve, + "Unsupported memory format", + memory_format); + tensor_impl->empty_tensor_restride(memory_format); + } + return self; +} + // basic dummy eq function: Only support CPU at::Tensor custom_to_device( const at::Tensor & self, @@ -102,21 +147,70 @@ at::Tensor & custom_fill__scalar(at::Tensor & self, const at::Scalar & value) { return self; } +at::Tensor unsafe_create_cpu_tensor_from_dummy_tensor(const at::Tensor& src) { + // TORCH_CHECK(src.device().type() == c10::DeviceType::PrivateUse1, + // "Only support dummy device."); + const auto& sizes_ = src.sizes(); + const auto& strides_ = src.strides(); + auto storage_offset_ = src.storage_offset(); + at::detail::check_size_nonnegative(sizes_); + + size_t size_bytes = at::detail::computeStorageNbytes(sizes_, strides_, + src.element_size(), + storage_offset_); + + at::DataPtr data_ptr = + c10::InefficientStdFunctionContext::makeDataPtr(src.storage().mutable_data_ptr().get(), + [](void*){}, at::kCPU); + + c10::Storage storage{c10::Storage::use_byte_size_t{}, size_bytes, std::move(data_ptr), + /*allocator=*/&global_custom_alloc, /*resizeable=*/false}; + + constexpr c10::DispatchKeySet cpu_ks(c10::DispatchKey::CPU); + at::Tensor tensor = at::detail::make_tensor( + std::move(storage), cpu_ks, src.dtype()); + + c10::TensorImpl* tensor_impl = tensor.unsafeGetTensorImpl(); + tensor_impl->set_sizes_and_strides(sizes_, strides_); + tensor_impl->set_storage_offset(storage_offset_); + return tensor; +} + // basic dummy copy_() function, so we can copy from the custom device to/from CPU at::Tensor custom__copy_from(const at::Tensor& self, const at::Tensor& dst, bool non_blocking) { - TORCH_CHECK(self.is_cpu() || self.device().type() == c10::DeviceType::PrivateUse1, "Dummy test only allows copy from cpu -> dummy device."); - TORCH_CHECK(dst.is_cpu() || dst.device().type() == c10::DeviceType::PrivateUse1, "Dummy test only allows copy from cpu -> dummy device."); + TORCH_CHECK( + self.is_cpu() || self.device().type() == c10::DeviceType::PrivateUse1, + "Dummy test only allows copy from cpu -> dummy device."); + TORCH_CHECK( + dst.is_cpu() || dst.device().type() == c10::DeviceType::PrivateUse1, + "Dummy test only allows copy from cpu -> dummy device."); // Some dummy asserts for the basic use case: inputs are the same size / dtype, all contiguous. TORCH_CHECK(self.sizes() == dst.sizes()); TORCH_CHECK(self.scalar_type() == dst.scalar_type()); - TORCH_CHECK(self.is_contiguous() && dst.is_contiguous()); - op_counter += 1; - std::memcpy(dst.storage().data_ptr().get(), self.storage().data_ptr().get(), self.storage().nbytes()); + if (self.is_contiguous() && dst.is_contiguous()) { + std::memcpy(dst.storage().data_ptr().get(), + self.storage().data_ptr().get(), + self.storage().nbytes()); + } else { + // Using cpu tensor to accomplishment stride copy. + at::Tensor cpu_self = unsafe_create_cpu_tensor_from_dummy_tensor(self); + at::Tensor cpu_dst = unsafe_create_cpu_tensor_from_dummy_tensor(dst); + cpu_dst.copy_(cpu_self); + } + return dst; } +at::Tensor custom__copy_from_and_resize(const at::Tensor& self, const at::Tensor& dst) { + return custom__copy_from(self, dst, false); +} + +at::Tensor& custom_abs_out(const at::Tensor& self, at::Tensor& out) { + return at::native::abs_out(self, out); +} + at::Tensor custom_empty_strided(c10::IntArrayRef size, c10::IntArrayRef stride, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, c10::optional pin_memory_opt) { op_counter += 1; @@ -143,13 +237,41 @@ at::Tensor custom_empty(c10::IntArrayRef size, c10::optional dty // This macro registers your kernels to the PyTorch Dispatcher. // More details on the dispatcher can be found at http://blog.ezyang.com/2020/09/lets-talk-about-the-pytorch-dispatcher/. TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) { - m.impl("add.Tensor", &custom_add_Tensor); - m.impl("mul.Tensor", &custom_mul_Tensor); m.impl("to.Device", &custom_to_device); m.impl("fill_.Scalar", &custom_fill__scalar); m.impl("_copy_from", &custom__copy_from); + m.impl("_copy_from_and_resize", &custom__copy_from_and_resize); m.impl("empty_strided", &custom_empty_strided); m.impl("empty.memory_format", &custom_empty); + m.impl("as_strided", at::native::as_strided_tensorimpl); +} + +TORCH_LIBRARY_FRAGMENT(aten, m) { + m.def( + "_reinterpret_tensor(Tensor self, int[] size, int[] stride, int offset_increment=0) -> Tensor", + torch::dispatch( + c10::DispatchKey::AutogradPrivateUse1, _reinterpret_tensor), + {at::Tag::pt2_compliant_tag}); +} + +void custom_cpu_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + at::native::cpu_fallback(op, stack); +} + +TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) { + m.impl("add.Tensor", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("add.out", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("abs.out", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("sub.Tensor", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("mul.Tensor", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("div.Tensor", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("pow.Tensor_Scalar", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("zero_", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("_foreach_add.List", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("index.Tensor", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("triu_indices", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("neg.out", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); + m.impl("sum.IntList_out", torch::CppFunction::makeFromBoxedFunction<&custom_cpu_fallback>()); } // This basic implementation doesn't bother dealing with different device indices diff --git a/PyTorchSimFrontend/llvm_caller_codegen.py b/PyTorchSimFrontend/llvm_caller_codegen.py index 5c6319982..e3e7385c9 100644 --- a/PyTorchSimFrontend/llvm_caller_codegen.py +++ b/PyTorchSimFrontend/llvm_caller_codegen.py @@ -24,6 +24,11 @@ def __init__(self, validation, arg_attributes): self.validation = validation self.n_arg = len(arg_attributes) self.arg_attributes = arg_attributes + self.arg_use_count = 1 + + def get_argv_idx(self): + self.arg_use_count += 1 + return self.arg_use_count-1 def write_header(self): self.writeline('#include ') @@ -42,29 +47,17 @@ def is_out_arg(self, arg_name): return LLVMKernelArgs.is_llvm_arg_out(value) def load_arg(self): - self.writeline(f'char file_name[256]{self.ending}') - self.writeline(f'char path[512]{self.ending}') - self.writeline(f'sprintf(file_name, "%d.raw", n_call){self.ending}') for i, arg_name in enumerate(self.arg_attributes.keys()): if self.is_in_arg(arg_name): - path = os.path.join(self.dump_path, f'arg{i}_1/') - self.writeline(f'strcpy(path, "{path}"){self.ending}') - self.writeline(f'strcat(path, file_name){self.ending}') - self.writeline(f'if(load_arg({arg_name}, sizeof({arg_name}), path) == -1){self.open_bracket}') + self.writeline(f'if(load_arg({arg_name}, sizeof({arg_name}), argv[{self.get_argv_idx()}]) == -1){self.open_bracket}') with self.code.indent(): self.writeline(f'return -1{self.ending}') self.writeline(self.closed_bracket) def dump_arg(self): - self.writeline(f'sprintf(file_name, "%d.raw", n_call){self.ending}') for i, arg_name in enumerate(self.arg_attributes.keys()): if self.is_out_arg(arg_name): - path = os.path.join(self.dump_path, f'{arg_name}/') - if not os.path.exists(path): - os.makedirs(path, exist_ok=True) - self.writeline(f'strcpy(path, "{path}"){self.ending}') - self.writeline(f'strcat(path, file_name){self.ending}') - self.writeline(f'if(dump_arg({arg_name}, sizeof({arg_name}), path) == -1){self.open_bracket}') + self.writeline(f'if(dump_arg({arg_name}, sizeof({arg_name}), argv[{self.get_argv_idx()}]) == -1){self.open_bracket}') with self.code.indent(): self.writeline(f'return -1{self.ending}') self.writeline(self.closed_bracket) @@ -79,7 +72,8 @@ def generate_kernel_declare(self): def generate_args_define(self): for arg_name, (_, arg_type, arg_shape) in self.arg_attributes.items(): - self.writeline(f'{cpp.DTYPE_TO_CPP[arg_type]} {arg_name}[{arg_shape}] __attribute__ ((aligned (4096))){self.ending}') + self.writeline(f'{cpp.DTYPE_TO_CPP[arg_type]} {arg_name}[atoi(argv[{self.get_argv_idx()}])] __attribute__ ((aligned (4096))){self.ending}') + self.writeline(self.newline) def generate_load_dump_fn(self): self.writeline(f'{self.newline}int load_arg(void *arg, int size, const char *path) {self.open_bracket}') @@ -116,10 +110,9 @@ def generate_load_dump_fn(self): def generate_main(self): self.writeline(f'{self.newline}int main(int argc, char *argv[]) {self.open_bracket}{self.newline}') - with self.code.indent(): + self.generate_args_define() if self.validation: - self.writeline(f'int n_call = atoi(argv[1]){self.ending}{self.newline}') self.load_arg() self.writeline(self.newline) @@ -139,7 +132,6 @@ def generate_wrapper_file(self, path, name): self.write_header() self.generate_kernel_declare() - self.generate_args_define() if self.validation: self.generate_load_dump_fn() diff --git a/PyTorchSimFrontend/llvm_codegen_backend.py b/PyTorchSimFrontend/llvm_codegen_backend.py index cd73e904a..13ac9d5a7 100644 --- a/PyTorchSimFrontend/llvm_codegen_backend.py +++ b/PyTorchSimFrontend/llvm_codegen_backend.py @@ -8,6 +8,7 @@ from torch._inductor.scheduler import BaseScheduling from torch._inductor.virtualized import V from torch._inductor.utils import IndentedBuffer +import extension_codecache from . import llvm_common from . import llvm_lowering @@ -101,6 +102,34 @@ class ExtensionWrapperCodegen(wrapper.WrapperCodeGen): def __init__(self): super().__init__() + def write_header(self): + self.header.splice( + f""" + from ctypes import c_void_p, c_long + import torch + import math + import random + import os + import tempfile + from math import inf, nan + from torch._inductor.hooks import run_intermediate_hooks + from torch._inductor.utils import maybe_profile + from torch._inductor.codegen.memory_planning import _align as align + + from torch import device, empty, empty_strided + from {extension_codecache.__name__} import CustomAsyncCompile + from torch._inductor.select_algorithm import extern_kernels + + aten = torch.ops.aten + inductor_ops = torch.ops.inductor + assert_size_stride = torch._C._dynamo.guards.assert_size_stride + alloc_from_pool = torch.ops.inductor._alloc_from_pool + reinterpret_tensor = torch.ops.aten._reinterpret_tensor + async_compile = CustomAsyncCompile() + + """ + ) + class ExtensionOverrides(common.OpOverrides): """Map element-wise ops to LLVM IR""" @@ -154,6 +183,14 @@ def mul(operand1, operand2, tile_size=4): def div(operand1, operand2, tile_size=4): return f'fdiv <{tile_size} x float> %{operand1}, %{operand2}' + @staticmethod + def truediv(operand1, operand2, tile_size=4): + return f'fdiv <{tile_size} x float> %{operand1}, %{operand2}' + + @staticmethod + def constant(value, dtype, tile_size=4): + return repr(value) + SYMPY_TO_LLVM = { sympy.core.mul.Mul: "mul", sympy.core.add.Add: "add", @@ -510,11 +547,18 @@ def load(self, name: str, index: sympy.Expr): cv = self.get_constant_vector(index) self.add_desc(True, name, align, cv, [self.tile_col, self.tile_row]) index = self.depth_first_traverse(index, self.loads, self.index_cse) - line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 %{index}" + vec_len = self.tile_size if not index.is_number else 1 + index = f"%{index}" if not index.is_number else index + line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 {index}" var = self.cse.generate(self.loads, line) - stride = self.ranges[-1] # stride is input row size - line = f"call <{self.tile_size} x {type_name}> @llvm.matrix.column.major.load.v{self.tile_size}f32.p0f32(ptr %{var}, i64 {stride}, i1 0, i32 {self.tile_row}, i32 {self.tile_col})" - return self.cse.generate(self.loads, line) + if vec_len > 1: + stride = self.ranges[-1] + line = f"call <{vec_len} x {type_name}> @llvm.matrix.column.major.load.v{vec_len}f32.p0f32(ptr %{var}, i64 {stride}, i1 0, i32 {self.tile_row}, i32 {self.tile_col})" + elif vec_len == 1: # scalar + line = f"call <{vec_len} x {type_name}> @llvm.matrix.column.major.load.v{vec_len}f32.p0f32(ptr %{var}, i64 1, i1 0, i32 1, i32 1)" + out_var = self.cse.generate(self.loads, line) + self.vec_len[out_var] = vec_len + return out_var def store(self, name: str, index: sympy.Expr, value, *args, **kwargs): var = self.args.output(name) @@ -526,12 +570,17 @@ def store(self, name: str, index: sympy.Expr, value, *args, **kwargs): cv = self.get_constant_vector(index) self.add_desc(False, name, align, cv, [self.tile_col, self.tile_row]) index = self.depth_first_traverse(index, self.stores, self.index_cse) - line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 %{index}" + vec_len = self.tile_size if not index.is_number else 1 + index = f"%{index}" if not index.is_number else index + line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 {index}" var = self.cse.generate(self.stores, line) - stride = self.ranges[-1] if (isinstance(value, list)): value = value[0] - line = f"call void @llvm.matrix.column.major.store.v{self.tile_size}f32.p0f32(<{self.tile_size} x {type_name}> %{value}, ptr %{var}, i64 {stride}, i1 0, i32 {self.tile_row}, i32 {self.tile_col})" + if vec_len > 1: + stride = self.ranges[-1] + line = f"call void @llvm.matrix.column.major.store.v{self.tile_size}f32.p0f32(<{self.tile_size} x {type_name}> %{value}, ptr %{var}, i64 {stride}, i1 0, i32 {self.tile_row}, i32 {self.tile_col})" + elif vec_len == 1: + line = f"call void @llvm.matrix.column.major.store.v1f32.p0f32(<1 x {type_name}> %{value}, ptr %{var}, i64 1, i1 0, i32 1, i32 1)" self.cse.generate(self.stores, line, assignment = False) def reduction(self, dtype, src_dtype, reduction_type, value): @@ -547,9 +596,13 @@ def reduction(self, dtype, src_dtype, reduction_type, value): type_name = llvm_common.DTYPE_TO_LLVM[dtype] align = llvm_common.DTYPE_SIZE[dtype] comma = ", " - array_line = [f"{type_name} {reduction_init(reduction_type, dtype)}" for _ in range(self.tile_row)] - self.reduction_prefix.writeline(f"store <{self.tile_row} x {type_name}> <{comma.join(array_line)}>, ptr %{acc}, align {align}") - line = f"load <{self.tile_row} x {type_name}>, ptr %{acc}, align {align}" + if (self.tile_col == 1): # if the tile is vector + self.reduction_prefix.writeline(f"store {type_name} {reduction_init(reduction_type, dtype)}, ptr %{acc}, align {align}") + line = f"load <{self.tile_col} x {type_name}>, ptr %{acc}, align {align}" + else: + array_line = [f"{type_name} {reduction_init(reduction_type, dtype)}" for _ in range(self.tile_row)] + self.reduction_prefix.writeline(f"store <{self.tile_row} x {type_name}> <{comma.join(array_line)}>, ptr %{acc}, align {align}") + line = f"load <{self.tile_row} x {type_name}>, ptr %{acc}, align {align}" # NOTE. To keep below line be under the compute, used store buffers temp = self.cse.generate(self.stores, line) @@ -576,9 +629,17 @@ def reduction(self, dtype, src_dtype, reduction_type, value): if (len(output) == length / 2): size *= 2 length = len(output) - line = f"fadd <{self.tile_row} x {type_name}> %{temp}, %{output[0]}" + if (self.tile_col == 1): + line = f"insertelement <{self.tile_col} x {type_name}> undef, {type_name} %{output[0]}, i32 0" + cast_vec = self.cse.generate(self.stores, line) + line = f"fadd <{self.tile_col} x {type_name}> %{temp}, %{cast_vec}" + else: + line = f"fadd <{self.tile_row} x {type_name}> %{temp}, %{output[0]}" output = self.cse.generate(self.stores, line) - line = f"store <{self.tile_row} x {type_name}> %{output}, ptr %{acc}, align {align}" + if (self.tile_col == 1): + line = f"store <{self.tile_col} x {type_name}> %{output}, ptr %{acc}, align {align}" + else: + line = f"store <{self.tile_row} x {type_name}> %{output}, ptr %{acc}, align {align}" self.cse.generate(self.stores, line, assignment = False) self.reduction_cse.reduction_cache[reduction_key] = acc return acc @@ -593,12 +654,21 @@ def store_reduction(self, name, index, value): cv = self.get_constant_vector(index) self.add_desc(False, name, align, cv, [1, self.tile_row]) index = self.depth_first_traverse(index, self.reduction_suffix, self.index_cse) - line = f"load <{self.tile_row} x {type_name}>, ptr %{value}, align {align}" + if (self.tile_col == 1): + line = f"load <{self.tile_col} x {type_name}>, ptr %{value}, align {align}" + else: + line = f"load <{self.tile_row} x {type_name}>, ptr %{value}, align {align}" value = self.reduction_cse.generate(self.reductions_suffix, line) - line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 %{index}" + if (self.tile_col == 1): + line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 0" + else: + line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 %{index}" var = self.cse.generate(self.reductions_suffix, line) stride = self.ranges[-1] - line = f"call void @llvm.matrix.column.major.store.v{self.tile_row}f32.p0f32(<{self.tile_row} x {type_name}> %{value}, ptr %{var}, i64 {stride}, i1 0, i32 {self.tile_row}, i32 1)" + if (self.tile_col == 1): + line = f"call void @llvm.matrix.column.major.store.v{self.tile_col}f32.p0f32(<{self.tile_col} x {type_name}> %{value}, ptr %{var}, i64 1, i1 0, i32 {self.tile_col}, i32 1)" + else: + line = f"call void @llvm.matrix.column.major.store.v{self.tile_row}f32.p0f32(<{self.tile_row} x {type_name}> %{value}, ptr %{var}, i64 {stride}, i1 0, i32 {self.tile_row}, i32 1)" self.cse.generate(self.reductions_suffix, line, assignment = False) def codegen_loops(self): @@ -642,8 +712,11 @@ def _codegen_kernel(self, arg_defs, kernel_name): code = super()._codegen_kernel(arg_defs, kernel_name) # Add llvm matrix intrinsics definition code.writeline(f'declare <{self.tile_size} x float> @llvm.matrix.column.major.load.v{self.tile_size}f32.p0f32(ptr , i64, i1, i32, i32) #2') + code.writeline(f'declare <1 x float> @llvm.matrix.column.major.load.v1f32.p0f32(ptr , i64, i1, i32, i32) #2') code.writeline(f'declare <{self.tile_size} x float> @llvm.matrix.multiply.v{self.tile_size}f32.v16f32.v16f32(<16 x float>, <16 x float>, i32, i32, i32) #1') code.writeline(f'declare void @llvm.matrix.column.major.store.v{self.tile_size}f32.p0f32(<{self.tile_size} x float>, ptr , i64, i1, i32, i32) #3') + if self.tile_col == 1: + code.writeline(f'declare void @llvm.matrix.column.major.store.v{self.tile_col}f32.p0f32(<{self.tile_col} x float>, ptr , i64, i1, i32, i32) #3') if self.tile_size != self.tile_row: code.writeline(f'declare void @llvm.matrix.column.major.store.v{self.tile_row}f32.p0f32(<{self.tile_row} x float>, ptr , i64, i1, i32, i32) #3') code.writeline(f'declare float @llvm.vector.reduce.fadd.nxv2f32(float, <{self.tile_row} x float>)') @@ -888,6 +961,12 @@ def codegen_sync(self): def flush(self): self._scheduling.flush() + def define_function(self, kernel): + code = kernel.def_function() + if code is not None: + wrapper = V.graph.wrapper_code + wrapper.header.writeline(code) + def define_kernel(self, src_code, kernel_name): wrapper = V.graph.wrapper_code if src_code in wrapper.src_to_kernel: @@ -925,4 +1004,5 @@ def codegen_template(self, template_node, epilogue_nodes): node_schedule = [template_node, *epilogue_nodes] kernel.meta_kernel() self.define_kernel(src_code, kernel.kernel_name) + self.define_function(kernel) kernel.call_kernel() \ No newline at end of file diff --git a/PyTorchSimFrontend/llvm_common.py b/PyTorchSimFrontend/llvm_common.py index 76bf8ffe7..a541480a4 100644 --- a/PyTorchSimFrontend/llvm_common.py +++ b/PyTorchSimFrontend/llvm_common.py @@ -121,6 +121,7 @@ def __init__(self, args=None): self.cse = common.CSE(self.newvar_prefix, self.suffix, self.name_prefix) self.vector_cse = common.CSE(self.newvar_prefix, self.suffix, self.vector_prefix) self.tile_size = None + self.vec_len = {} def load(self, name: str, index: sympy.Expr): raise NotImplementedError() @@ -134,6 +135,26 @@ def store(self, name, index, value, mode=None): def reduction(self, dtype, src_dtype, reduction_type, value): raise NotImplementedError() + def widening(self, args, buf_bounds): + if not args[0] in self.vec_len or not args[1] in self.vec_len: + return args, 1 + vec_len0 = self.vec_len[args[0]] + vec_len1 = self.vec_len[args[1]] + if vec_len0 != vec_len1: + temp = list(args) + if (vec_len0 > vec_len1): + assert(vec_len1 == 1) + indexes = [f"i32 0" for i in range(vec_len0)] + line = f"shufflevector <{vec_len1} x float> %{args[1]}, <{vec_len1} x float> undef, <{vec_len0} x i32> <{', '.join(indexes)}>" + temp[1] = self.cse.generate(self.compute, line, bounds=buf_bounds) + elif (vec_len0 < vec_len1): + assert(vec_len0 == 1) + indexes = [f"i32 0" for i in range(vec_len1)] + line = f"shufflevector <{vec_len0} x float> %{args[0]}, <{vec_len0} x float> undef, <{vec_len1} x i32> <{', '.join(indexes)}>" + temp[0] = self.cse.generate(self.compute, line, bounds=buf_bounds) + args = tuple(temp) + return args, max(vec_len0, vec_len1) + def __enter__(self): class CSEProxy: self.name = "CSEProxy" @@ -160,11 +181,18 @@ def inner(*args, **kwargs): ) vector_csevar.update_on_args(name, vector_args, kwargs) args = (args[0][1], args[1][1]) + if len(args) == 2: + args, vec_len = self.widening(args, buf_bounds) + elif len(args) == 1: + vec_len = self.vec_len[args[0]] + else: + assert(0) # not implemented yet. csevar = self.cse.generate( self.compute, - getattr(parent_handler, name)(*args, tile_size=self.tile_size, **kwargs), # type: ignore[has-type] + getattr(parent_handler, name)(*args, tile_size=vec_len, **kwargs), # type: ignore[has-type] bounds=buf_bounds, ) + self.vec_len[csevar] = vec_len csevar.update_on_args(name, args, kwargs) if vector_csevar is not None: return [vector_csevar, csevar] diff --git a/PyTorchSimFrontend/llvm_conv_template.py b/PyTorchSimFrontend/llvm_conv_template.py new file mode 100644 index 000000000..deeae2d91 --- /dev/null +++ b/PyTorchSimFrontend/llvm_conv_template.py @@ -0,0 +1,227 @@ +import os, math +from typing import List, Optional, cast +from PyTorchSimFrontend.llvm_common import LLVMKernelArgs +from PyTorchSimFrontend.llvm_template import LLVMTemplate +from PyTorchSimFrontend.llvm_template import LLVMTemplateKernel +from torch._inductor.ir import Buffer +from torch._inductor.ir import IRNode +from torch._inductor.codecache import get_hash + +CONV2D_TEMPLATE = r""" +@sram_accum = dso_local global [{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}] zeroinitializer, align 64 + +define dso_local void @{{ KERNEL_NAME }}(ptr %X, ptr %Y, ptr %B, ptr %W) { +entry: + br label %for.cond1.preheader + +for.cond1.preheader: + %indvars.iv59 = phi i64 [ 0, %entry ], [ %indvars.iv.next60, %for.cond.cleanup3 ] + %0 = mul nuw nsw i64 %indvars.iv59, {{ N }} + %add.ptr = getelementptr inbounds {{ DATA_TYPE }}, ptr %B, i64 %0 + %1 = mul nuw nsw i64 %indvars.iv59, {{ K }} + %add.ptr13 = getelementptr inbounds {{ DATA_TYPE }}, ptr %X, i64 %1 + %add.ptr27 = getelementptr inbounds {{ DATA_TYPE }}, ptr %W, i64 %0 + br label %for.body4 + +for.cond.cleanup: + ret void + +for.cond.cleanup3: + %indvars.iv.next60 = add nuw nsw i64 %indvars.iv59, {{ TILE_M }} + %cmp = icmp ult i64 %indvars.iv59, {{ M - TILE_M }} + br i1 %cmp, label %for.cond1.preheader, label %for.cond.cleanup + +for.body4: + %indvars.iv57 = phi i64 [ 0, %for.cond1.preheader ], [ %indvars.iv.next58, %for.cond.cleanup9 ] + %add.ptr6 = getelementptr inbounds {{ DATA_TYPE }}, ptr %add.ptr, i64 %indvars.iv57 + %call = {{ kernel.load_matrix(TILE_M, TILE_N, N, DATA_TYPE, DATA_STYPE, "%add.ptr6", "B", DATA_SIZE)}} + tail call void @llvm.memset.p0.i64(ptr @sram_accum, i8 0, i64 {{ TILE_M * TILE_N * DATA_SIZE }}, i1 false) + %invariant.gep = getelementptr inbounds {{ DATA_TYPE }}, ptr %Y, i64 %indvars.iv57 + br label %for.body10 + +for.cond.cleanup9: + %call24 = fadd <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }} > %call, %call18 + %add.ptr29 = getelementptr inbounds {{ DATA_TYPE }}, ptr %add.ptr27, i64 %indvars.iv57 + {{ kernel.store_matrix(TILE_M, TILE_N, N, DATA_TYPE, DATA_STYPE, "%add.ptr29", "%call24", "W", DATA_SIZE) }} + %indvars.iv.next58 = add nuw nsw i64 %indvars.iv57, {{ TILE_N }} + %cmp2 = icmp ult i64 %indvars.iv57, {{ N - TILE_N }} + br i1 %cmp2, label %for.body4, label %for.cond.cleanup3 + +for.body10: + %indvars.iv = phi i64 [ 0, %for.body4 ], [ %indvars.iv.next, %for.body10 ] + %add.ptr15 = getelementptr inbounds {{ DATA_TYPE }}, ptr %add.ptr13, i64 %indvars.iv + %call16 = {{ kernel.load_matrix(TILE_M, TILE_K, K, DATA_TYPE, DATA_STYPE, "%add.ptr15", "X", DATA_SIZE)}} + %2 = mul nuw nsw i64 %indvars.iv, {{ N }} + %gep = getelementptr inbounds {{ DATA_TYPE }}, ptr %invariant.gep, i64 %2 + %call22 = {{ kernel.load_matrix(TILE_K, TILE_N, N, DATA_TYPE, DATA_STYPE, "%gep", "Y", DATA_SIZE)}} + %call23 = call <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}> @llvm.matrix.multiply.v{{ TILE_M*TILE_K }}{{ DATA_STYPE }}.v{{ TILE_K*TILE_N }}{{ DATA_STYPE }}.v{{ TILE_M*TILE_N }}{{ DATA_STYPE }}(<{{ TILE_N * TILE_K}} x {{ DATA_TYPE }}> %call22, <{{ TILE_M * TILE_K}} x {{ DATA_TYPE }}> %call16, i32 {{ TILE_M }}, i32 {{ TILE_K }}, i32 {{ TILE_N }}) + + %tmp_acc = load <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}>, ptr @sram_accum, align 64 + %call18 = fadd <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }} > %call23, %tmp_acc + store <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}> %call18, ptr @sram_accum, align 64 + + %indvars.iv.next = add nuw nsw i64 %indvars.iv, {{ TILE_K }} + %cmp8 = icmp ult i64 %indvars.iv, {{ K - TILE_K }} + br i1 %cmp8, label %for.body10, label %for.cond.cleanup9 +} + +declare void @llvm.memset.p0.i64(ptr, i8, i64, i1) +{% if TILE_M == TILE_N %} +declare <{{TILE_M * TILE_K}} x float> @llvm.matrix.column.major.load.v{{ TILE_M * TILE_K }}{{ DATA_STYPE }}.p0{{ DATA_STYPE }}(ptr , i64, i1, i32, i32) #2 +{% else %} +declare <{{TILE_M * TILE_K}} x float> @llvm.matrix.column.major.load.v{{ TILE_M * TILE_K }}{{ DATA_STYPE }}.p0{{ DATA_STYPE }}(ptr , i64, i1, i32, i32) #2 +declare <{{TILE_N * TILE_K}} x float> @llvm.matrix.column.major.load.v{{ TILE_N * TILE_K }}{{ DATA_STYPE }}.p0{{ DATA_STYPE }}(ptr , i64, i1, i32, i32) #2 +{% endif %} +declare <{{TILE_M * TILE_N}} x float> @llvm.matrix.multiply.v{{ TILE_M*TILE_K }}{{ DATA_STYPE }}.v{{ TILE_K*TILE_N }}{{ DATA_STYPE }}.v{{ TILE_M*TILE_N }}{{ DATA_STYPE }}(<{{ TILE_M*TILE_K }} x {{ DATA_TYPE }}>, < {{ TILE_N*TILE_K }} x {{ DATA_TYPE }}>, i32, i32, i32) #1 +declare void @llvm.matrix.column.major.store.v{{ TILE_M * TILE_N }}{{ DATA_STYPE }}.p0{{ DATA_STYPE }}(<{{ TILE_M*TILE_N }} x {{ DATA_TYPE }}>, ptr , i64, i1, i32, i32) #3 +""" + +CONV2D_FUNC = r""" +def Conv2d({{ INPUT }}, {{ WEIGHT }}, {{ BIAS }}, {{ OUT }}): + {{ INPUT }}_cpu = {{ INPUT }}.cpu() + {{ WEIGHT }}_cpu = {{ WEIGHT }}.cpu() + {{ BIAS }}_cpu = {{ BIAS }}.cpu() + {{ OUT }}_cpu = {{ OUT }}.cpu() + + # Torch support NCHW, so we need to transpose for now + {{ INPUT }}_cpu = {{ INPUT }}_cpu.permute(0, 2, 3, 1) + {{ WEIGHT }}_cpu = {{ WEIGHT }}_cpu.permute(0, 2, 3, 1) + {{ OUT }}_cpu = {{ OUT }}_cpu.permute(0, 2, 3, 1) + {{ OUT }}_cpu.zero_() + + input_shape = {{ INPUT }}_cpu.shape + weight_shape = {{ WEIGHT }}_cpu.shape + output_shape = {{ OUT }}_cpu.shape + + input_pad_shape = (input_shape[0], input_shape[1]+2*{{ PADDING_H }}, input_shape[2]+2*{{ PADDING_W }}, input_shape[3]) + input_pad = torch.zeros(input_pad_shape) + + if {{ PADDING_H }} != 0 and {{ PADDING_W }} != 0: + input_pad[:, {{ PADDING_H }}:-{{ PADDING_H }}, {{ PADDING_W }}:-{{ PADDING_W }}, :] = {{ INPUT }}_cpu + elif {{ PADDING_H }} != 0: + input_pad[:, {{ PADDING_H }}:-{{ PADDING_H }}, :, :] = {{ INPUT }}_cpu + elif {{ PADDING_W }} != 0: + input_pad[:,:, {{ PADDING_W }}:-{{ PADDING_W }}, :] = {{ INPUT }}_cpu + else: + input_pad = {{ INPUT }}_cpu + + {% if VALIDATION_MODE %} + {% endif %} + + for kh in range(weight_shape[1]): + for kw in range(weight_shape[2]): + input_tile = input_pad[:, kh:input_pad_shape[1]-(weight_shape[1]-1)+kh, kw:input_pad_shape[2]-(weight_shape[2]-1)+kw, :] + input_tile = input_tile[:,::{{ STRIDE_H }},::{{ STRIDE_W }}, :] + kernel_tile = {{ WEIGHT }}_cpu[:, kh, kw, :].t() + input_tile = input_tile.reshape(-1, input_pad_shape[3]) + {% if VALIDATION_MODE %} + if kh == 0 and kw == 0: + {{ KERNEL_NAME }}(input_tile, kernel_tile, {{ OUT }}_cpu, {{ OUT }}_cpu, intermediate_op=0b01) + elif kh == weight_shape[1]-1 and kw == weight_shape[2]-1: + {{ KERNEL_NAME }}(input_tile, kernel_tile, {{ OUT }}_cpu, {{ OUT }}_cpu, intermediate_op=0b10) + else: + {{ KERNEL_NAME }}(input_tile, kernel_tile, {{ OUT }}_cpu, {{ OUT }}_cpu, intermediate_op=0b11) + {% else %} + {{ KERNEL_NAME }}(input_tile, kernel_tile, {{ OUT }}_cpu, {{ OUT }}_cpu) # input, weight, bias, out + {% endif %} + + {{ OUT }}_cpu = {{ OUT }}_cpu.permute(0, 3, 1, 2) + {{ OUT }}.copy_({{ OUT }}_cpu) +""" + +class LLVMConvTemplate(LLVMTemplate): + def __init__(self, input_nodes, layout, input_reorder=None, **kwargs): + super().__init__("kernel", input_nodes, layout, input_reorder) + self.stride = kwargs["stride"] + self.padding = kwargs["padding"] + self.dilation = kwargs["dilation"] + self.function_name = "Conv2d" + self.gemm_args = ['input', 'weight', 'bias', 'output'] + + def render(self, + kernel: LLVMTemplateKernel, + template_buffer_node = None, + epilogue_nodes: Optional[List[IRNode]] = None, + **kwargs): + if template_buffer_node is not None: + self.output_node = template_buffer_node + if epilogue_nodes is not None and len(epilogue_nodes) > 0: + self.output_nodes = cast(Buffer, epilogue_nodes[-1]) + + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + Bias = None if len(self.input_nodes) == 2 else self.input_nodes[2] + + input_h = X.get_size()[2] + input_w = X.get_size()[3] + kernel_h = W.get_size()[2] + kernel_w = W.get_size()[3] + i_c = X.get_size()[1] + o_c = W.get_size()[0] + + weight_shape = self.input_nodes[1].get_size() + i_tile_h = int((input_h + 2*self.padding[0] - (weight_shape[2]-1) - 1) / self.stride[0]) + 1 + i_tile_w = int((input_w + 2*self.padding[1] - (weight_shape[3]-1) - 1) / self.stride[1]) + 1 + + gemm_m = i_tile_h * i_tile_w + gemm_n = o_c + gemm_k = i_c + + options = dict( + KERNEL_NAME=self.name, + kernel=kernel, + M=gemm_m, + N=gemm_n, + K=gemm_k, + TILE_M=4, + TILE_N=4, + TILE_K=4, + DATA_TYPE="float", + DATA_STYPE="f32", + DATA_SIZE=4, + ) + code = self._template_from_string(CONV2D_TEMPLATE).render(**options) + kernel.add_loop_info([options["M"], options["N"], options["K"]], [options["TILE_M"], options["TILE_N"], options["TILE_K"]]) + kernel.def_kernel(inputs=[X, W, Bias], outputs=[Y], names_str="X, W, Bias, Y", input_reorder=self.input_reorder) + + self.hash_value = get_hash(code.strip()) + return code + + def function_render(self, kernel_name, input_args): + + options = dict( + KERNEL_NAME=kernel_name, + INPUT=input_args[0], + WEIGHT=input_args[1], + BIAS=input_args[2], + OUT=input_args[3], + STRIDE_H=self.stride[0], + STRIDE_W=self.stride[1], + PADDING_H=self.padding[0], + PADDING_W=self.padding[1], + DILATION_H=self.dilation[0], + DILATION_W=self.dilation[1], + VALIDATION_MODE=int(os.environ.get('TORCH_VALIDATION_MODE', default="True") == "True"), + HASH_VALUE=self.hash_value + ) + code = self._template_from_string(CONV2D_FUNC).render(**options) + return code + + def get_arg_attributes(self): + arg_attributes = {} + + input_shape = self.input_nodes[0].get_size() + weight_shape = self.input_nodes[1].get_size() + gemm_h = int((input_shape[2] + 2*self.padding[0] - (weight_shape[2]-1) - 1) / self.stride[0]) + 1 + gemm_w = int((input_shape[3] + 2*self.padding[1] - (weight_shape[3]-1) - 1) / self.stride[1]) + 1 + + gemm_input_shape = [input_shape[0],input_shape[1],gemm_h, gemm_w] + gemm_weight_shape = [weight_shape[0],weight_shape[1],1,1] + gemm_output_shape = [gemm_input_shape[2]*gemm_input_shape[3], gemm_weight_shape[0]] # Consider Batch size 1 + + arg_attributes[self.gemm_args[0]] = [LLVMKernelArgs.LLVM_ARGS_IN, self.input_nodes[0].layout.dtype, math.prod(gemm_input_shape)] + arg_attributes[self.gemm_args[1]] = [LLVMKernelArgs.LLVM_ARGS_IN, self.input_nodes[1].layout.dtype, math.prod(gemm_weight_shape)] + arg_attributes[self.gemm_args[2]] = [LLVMKernelArgs.LLVM_ARGS_IN, self.input_nodes[0].layout.dtype, math.prod(gemm_output_shape)] + arg_attributes[self.gemm_args[3]] = [LLVMKernelArgs.LLVM_ARGS_OUT, self.input_nodes[0].layout.dtype, math.prod(gemm_output_shape)] + + return arg_attributes \ No newline at end of file diff --git a/PyTorchSimFrontend/llvm_gemm_template.py b/PyTorchSimFrontend/llvm_gemm_template.py index 4ffb84bbb..fe58c8a2d 100644 --- a/PyTorchSimFrontend/llvm_gemm_template.py +++ b/PyTorchSimFrontend/llvm_gemm_template.py @@ -36,7 +36,7 @@ for.cond.cleanup7: %add.ptr22 = getelementptr inbounds {{ DATA_TYPE }}, ptr %add.ptr20, i64 %indvars.iv47 - {{ kernel.store_matrix(TILE_M, TILE_N, DATA_TYPE, DATA_STYPE, "%add.ptr22", "%call18", "W", DATA_SIZE) }} + {{ kernel.store_matrix(TILE_M, TILE_N, N, DATA_TYPE, DATA_STYPE, "%add.ptr22", "%call18", "W", DATA_SIZE) }} %indvars.iv.next48 = add nuw nsw i64 %indvars.iv47, {{ TILE_N }} %cmp2 = icmp ult i64 %indvars.iv47, {{ N - TILE_N }} br i1 %cmp2, label %for.body4, label %for.cond.cleanup3 @@ -44,11 +44,11 @@ for.body8: %indvars.iv = phi i64 [ 0, %for.body4 ], [ %indvars.iv.next, %for.body8 ] %add.ptr10 = getelementptr inbounds {{ DATA_TYPE }}, ptr %add.ptr, i64 %indvars.iv - %call = {{ kernel.load_matrix(TILE_M, TILE_K, DATA_TYPE, DATA_STYPE, "%add.ptr10", "X", DATA_SIZE)}} + %call = {{ kernel.load_matrix(TILE_M, TILE_K, K, DATA_TYPE, DATA_STYPE, "%add.ptr10", "X", DATA_SIZE)}} %2 = mul nuw nsw i64 %indvars.iv, {{ N }} %gep = getelementptr inbounds {{ DATA_TYPE }}, ptr %invariant.gep, i64 %2 - %call16 = {{ kernel.load_matrix(TILE_K, TILE_N, DATA_TYPE, DATA_STYPE, "%gep", "Y", DATA_SIZE)}} - %call17 = call <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}> @llvm.matrix.multiply.v{{ TILE_M*TILE_K }}{{ DATA_STYPE }}.v{{ TILE_K*TILE_N }}{{ DATA_STYPE }}.v{{ TILE_M*TILE_N }}{{ DATA_STYPE }}(<{{ TILE_M * TILE_K}} x {{ DATA_TYPE }}> %call, <{{ TILE_N * TILE_K}} x {{ DATA_TYPE }}> %call16, i32 {{ TILE_M }}, i32 {{ TILE_K }}, i32 {{ TILE_N }}) + %call16 = {{ kernel.load_matrix(TILE_K, TILE_N, N, DATA_TYPE, DATA_STYPE, "%gep", "Y", DATA_SIZE)}} + %call17 = call <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}> @llvm.matrix.multiply.v{{ TILE_M*TILE_K }}{{ DATA_STYPE }}.v{{ TILE_K*TILE_N }}{{ DATA_STYPE }}.v{{ TILE_M*TILE_N }}{{ DATA_STYPE }}(<{{ TILE_N * TILE_K}} x {{ DATA_TYPE }}> %call16, <{{ TILE_M * TILE_K}} x {{ DATA_TYPE }}> %call, i32 {{ TILE_M }}, i32 {{ TILE_K }}, i32 {{ TILE_N }}) %tmp_acc = load <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}>, ptr @sram_accum, align 64 %call18 = fadd <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }} > %call17, %tmp_acc store <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}> %call18, ptr @sram_accum, align 64 diff --git a/PyTorchSimFrontend/llvm_lowering.py b/PyTorchSimFrontend/llvm_lowering.py index c39b4c008..ac4e4daf1 100644 --- a/PyTorchSimFrontend/llvm_lowering.py +++ b/PyTorchSimFrontend/llvm_lowering.py @@ -1,7 +1,13 @@ +from typing import List, Optional, Sequence + import torch from torch._inductor.lowering import lowerings from torch._inductor.kernel.mm_common import mm_args +from torch._inductor import ir +from torch._inductor.virtualized import V +from torch._inductor.ir import TensorBox from PyTorchSimFrontend.llvm_gemm_template import LLVMGemmTemplate +from PyTorchSimFrontend.llvm_conv_template import LLVMConvTemplate aten = torch.ops.aten @@ -11,4 +17,68 @@ def tuned_mm(mat1, mat2, * ,layout=None): return llvm_template.generate().output_node() -lowerings.update({getattr(aten.mm, overload): tuned_mm for overload in aten.mm.overloads()}) \ No newline at end of file +def conv_layout( + x: TensorBox, + weight: TensorBox, + bias: Optional[TensorBox], + stride: Sequence[int], + padding: tuple[int, ...], + dilation: tuple[int, ...], + transposed: bool, + output_padding: tuple[int, ...], + groups: int, +) -> ir.Layout: + """Determine output layout for a convolution""" + with V.graph.fake_mode: + output = torch.ops.aten.convolution( + ir.ir_node_to_tensor(x, guard_shape=True), + ir.ir_node_to_tensor(weight, guard_shape=True), + ir.ir_node_to_tensor(bias, guard_shape=True), + stride, + tuple(V.graph.sizevars.size_hint(p) for p in padding), + dilation, + transposed, + tuple(V.graph.sizevars.size_hint(p) for p in output_padding), + groups, + ) + sizes = ir.convert_shape_to_inductor(output.size()) + stride = ir.convert_shape_to_inductor(output.stride()) + + return ir.FixedLayout( + x.get_device(), + x.get_dtype(), + sizes, + stride, + ) + +def convolution( + x: TensorBox, + weight: TensorBox, + bias: TensorBox, + stride: List[int], + padding: List[int], + dilation: List[int], + transposed: bool, + output_padding: List[int], + groups: int, +): + stride = tuple(stride) + padding = tuple(padding) + dilation = tuple(dilation) + output_padding = tuple(output_padding) + + kwargs = { + "stride": stride, + "padding": padding, + "dilation": dilation, + "transposed": transposed, + "output_padding": output_padding, + "groups": groups, + } + + layout = conv_layout(x, weight, None, **kwargs) + llvm_template = LLVMConvTemplate([x, weight, bias], layout, **kwargs) + return llvm_template.generate().output_node() + +lowerings.update({getattr(aten.mm, overload): tuned_mm for overload in aten.mm.overloads()}) +lowerings.update({getattr(aten.convolution, overload): convolution for overload in aten.convolution.overloads()}) \ No newline at end of file diff --git a/PyTorchSimFrontend/llvm_template.py b/PyTorchSimFrontend/llvm_template.py index 29ad7d113..115fd34d9 100644 --- a/PyTorchSimFrontend/llvm_template.py +++ b/PyTorchSimFrontend/llvm_template.py @@ -19,25 +19,31 @@ class LLVMTemplateKernel(Kernel): overrides = OpOverrides - def __init__(self, kernel_name) -> None: + def __init__(self, kernel_name, + kernel_caller_function=None, + kernel_function_render=None, + kernel_arg_attributes=None) -> None: super().__init__(LLVMKernelArgs()) self.kernel_name = kernel_name self.named_nodes = {} self.loop_info = {} self.load_desc = {} self.store_desc = {} + self.kernel_caller_function = kernel_caller_function + self.kernel_function_render = kernel_function_render + self.kernel_arg_attributes = kernel_arg_attributes - def load_matrix(self, row, col, dtype, stype, ptr, base_addr, data_size): + def load_matrix(self, row, col, stride, dtype, stype, ptr, base_addr, data_size): suffix = f"v{row*col}{stype}.p0{stype}" - argument = f"(ptr {ptr}, i64 {col}, i1 0, i32 {row}, i32 {col})" + argument = f"(ptr {ptr}, i64 {stride}, i1 0, i32 {row}, i32 {col})" code = f"<{row*col} x {dtype}> @llvm.matrix.column.major.load.{suffix} {argument}" self.add_desc(True, base_addr, data_size, [col, 1], [row, col]) return f"call {code}" - def store_matrix(self, row, col, dtype, stype, ptr, vec, base_addr, data_size): + def store_matrix(self, row, col, stride, dtype, stype, ptr, vec, base_addr, data_size): suffix = f"v{row*col}{stype}.p0{stype}" - argument = f"(<{row*col} x {dtype}> {vec}, ptr {ptr}, i64 {col}, i1 0, i32 {row}, i32 {col})" + argument = f"(<{row*col} x {dtype}> {vec}, ptr {ptr}, i64 {stride}, i1 0, i32 {row}, i32 {col})" code = f"void @llvm.matrix.column.major.store.{suffix} {argument}" self.add_desc(False, base_addr, data_size, [col, 1], [row, col]) @@ -69,7 +75,9 @@ def add_loop_info(self, mat_size, tile_size): def meta_kernel(self): wrapper = V.graph.wrapper_code - _, _, arg_attributes = self.args.llvm_argdefs() + arg_attributes = self.kernel_arg_attributes + if arg_attributes is None: + _, _, arg_attributes = self.args.llvm_argdefs() wrapper.add_import_once('\nprint(f\'Wrapper Codegen Path = {__file__}\')') wrapper.add_import_once(f'\nfrom extension_codecache import CustomAsyncCompile') wrapper.add_import_once(f'\ncustom_async_compile = CustomAsyncCompile()') @@ -87,7 +95,7 @@ def call_kernel(self): wrapper = V.graph.wrapper_code _, call_args, _ = self.args.python_argdefs() wrapper.generate_kernel_call( - self.kernel_name, + self.kernel_name if self.kernel_caller_function is None else self.kernel_caller_function, call_args, cuda=False, ) @@ -122,6 +130,11 @@ def def_kernel( self.named_nodes[name] = node self.args.output_buffers[node.get_name()] = name + def def_function(self): + _, call_args, _ = self.args.python_argdefs() + if self.kernel_function_render is not None: + return self.kernel_function_render(input_args=call_args) + class LLVMTemplateCaller(CUDATemplateCaller): def __str__(self): return f"LLVMTemplateCaller(source_file={self.bmreq.source_file})" @@ -152,7 +165,10 @@ def __init__(self, name, input_nodes, layout, input_reorder = None): def generate(self, **kwargs) -> ChoiceCaller: kernel_name = f"llvm_{self.name}" with patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)): - kernel = LLVMTemplateKernel(kernel_name=kernel_name) + kernel = LLVMTemplateKernel(kernel_name=kernel_name, + kernel_caller_function=self.function_name if hasattr(self, 'function_name') else None, + kernel_function_render=self.function_render if hasattr(self, 'function_render') else None, + kernel_arg_attributes=self.get_arg_attributes() if hasattr(self, 'get_arg_attributes') else None) code = self.render(kernel=kernel, **kwargs) kernel_hash_name = f"llvm_{self.name}_{next(self.index_counter)}" @@ -172,6 +188,12 @@ def make_kernel_render( ): kernel = LLVMTemplateKernel( kernel_name="KERNEL_NAME", + kernel_function_render=functools.partial( + self.function_render, + kernel_name="KERNEL_NAME" + ) if hasattr(self, 'function_render') else None, + kernel_caller_function=self.function_name if hasattr(self, 'function_name') else None, + kernel_arg_attributes=self.get_arg_attributes() if hasattr(self, 'get_arg_attributes') else None ) render = functools.partial( self.render, diff --git a/Simulator/simulator.py b/Simulator/simulator.py index c05351b0e..eb91a5672 100644 --- a/Simulator/simulator.py +++ b/Simulator/simulator.py @@ -8,24 +8,82 @@ from PyTorchSimFrontend.llvm_common import LLVMKernelArgs import extension_codecache +TORCH_TO_NUMPY = { + torch.float32: np.float32, + torch.float64: np.float64, + torch.int64: np.int64, + torch.int32: np.int32, + torch.int16: np.int16, + torch.int8: np.int8, + torch.uint8: np.uint8, + torch.bool: np.bool_, + torch.bfloat16: np.float16, +} + class FunctionalSimulator(): - def __init__(self, path, key, arg_attributes, args): + def __init__(self, path, key): self.path = path self.key = key - self.arg_attributes = arg_attributes - self.args = args - - def load_tensor(self, arg, arg_name, arg_attribute, n_call): - path = os.path.join(self.path, arg_name, f'{n_call}.raw') + def load_tensor(self, arg, arg_name, arg_attribute, path): + # path = os.path.join(dump_path, arg_name, f'{n_call}.raw') with open(path, 'rb') as f: - np_array = np.fromfile(f) + np_array = np.fromfile(f, dtype=TORCH_TO_NUMPY[arg.dtype]) src_tensor = torch.from_numpy(np_array).view(dtype=arg.dtype) src_tensor = src_tensor.reshape(arg.shape) arg.copy_(src_tensor) - def run_spike(self, n_call, target_binary): - run = f'spike --isa rv64gcv /workspace/riscv-pk/build/pk {target_binary} {n_call}' + def get_biggest_filename(self, path): + return len(os.listdir(path)) + + def write_arg(self, arg, path, name): + dump_path = os.path.join(path, name) + os.makedirs(dump_path, exist_ok=True) + index = self.get_biggest_filename(dump_path) + + if (isinstance(arg, torch.Tensor)): + data_path = os.path.join(dump_path, f'{index}.raw') + tensor = arg.cpu() + t_arr = tensor.numpy().flatten() + t_arr.tofile(data_path) + else: + assert(0) + return index + + def dump_args(self, args, arg_attributes, load_path, dump_path): + array_size = [] + file_path = [] + for (arg_name, arg_attribute), arg in zip(arg_attributes.items(), args): + array_size.append(arg_attribute[2]) + if LLVMKernelArgs.is_llvm_arg_in(arg_attribute[0]): + index = self.write_arg(arg, load_path, arg_name) + file_path.append(os.path.join(load_path, arg_name, f'{index}.raw')) + elif LLVMKernelArgs.is_llvm_arg_out(arg_attribute[0]): + path = os.path.join(dump_path, arg_name) + os.makedirs(path, exist_ok=True) + file_path.append(os.path.join(path, f'{self.get_biggest_filename(path)}.raw')) + return array_size, file_path + + def run_spike(self, args, arg_attributes, target_binary, intermediate_op=None): + load_path = self.path + dump_path = self.path + + if intermediate_op is not None: + os.makedirs(os.path.join(self.path, "intermediate"), exist_ok=True) + if intermediate_op & 0b10: # input comes from intermediate + load_path = os.path.join(self.path, "intermediate") + if intermediate_op & 0b01: # output dumps to intermediate + dump_path = os.path.join(self.path, "intermediate") + for name, attr in arg_attributes.items(): + if attr[0] == 2: + os.makedirs(os.path.join(dump_path, name), exist_ok=True) + + array_size, file_path = self.dump_args(args, arg_attributes, load_path, dump_path) + array_size_str = ' '.join(map(str, array_size)) + file_path_str = ' '.join(file_path) + + run = f'spike --isa rv64gcv /workspace/riscv-pk/build/pk {target_binary} {array_size_str} {file_path_str}' + print("Spike cmd > ", run) run_cmd = shlex.split(run) try: subprocess.check_call(run_cmd) @@ -34,9 +92,9 @@ def run_spike(self, n_call, target_binary): print("Error output:", e.output) assert(0) - for (arg_name, arg_attribute), arg in zip(self.arg_attributes.items(), self.args): + for (arg_name, arg_attribute), arg, path in zip(arg_attributes.items(), args, file_path): if LLVMKernelArgs.is_llvm_arg_out(arg_attribute[0]): - self.load_tensor(arg, arg_name, arg_attribute, n_call) + self.load_tensor(arg, arg_name, arg_attribute, path) class CycleSimulator(): def __init__(self) -> None: diff --git a/extension_codecache.py b/extension_codecache.py index cbc05a5fc..566e4504e 100644 --- a/extension_codecache.py +++ b/extension_codecache.py @@ -23,8 +23,8 @@ TORCHSIM_DIR = os.environ.get('TORCHSIM_DIR', default='/workspace/TorchSim') TORCHSIM_CUSTOM_PASS_PATH = os.environ.get('TORCHSIM_CUSTOM_PASS_PATH', default=f"{TORCHSIM_DIR}/GemminiLowerPass/build") -TORCHSIM_ONNXIM_CONFIG = os.environ.get('TORCHSIM_CONFIG', - default=f'{TORCHSIM_DIR}/ONNXim/configs/systolic_ws_8x8_c1_simple_noc.json') +TORCHSIM_BACKEND_CONFIG = os.environ.get('TORCHSIM_CONFIG', + default=f'{TORCHSIM_DIR}/PyTorchSimBackend/configs/systolic_ws_128x128_c4_simple_noc_tpuv4.json') GEM5_PATH = os.environ.get('GEM5_PATH', default = f"/workspace/gem5/build/RISCV/gem5.opt") GEM5_SCRIPT_PATH = os.environ.get('GEM5_SCRIPT_PATH', @@ -43,27 +43,6 @@ def dump_metadata(args, arg_attributes, path): file.write(f'{arg_name}=({arg_attribute[0]}, {arg.dtype}, {arg.shape})\n') return -def write_arg(arg, path, name): - dump_path = os.path.join(path, name) - os.makedirs(dump_path, exist_ok=True) - index = len(os.listdir(dump_path)) - - if (isinstance(arg, torch.Tensor)): - data_path = os.path.join(dump_path, f'{index}.raw') - tensor = arg.cpu() - t_arr = tensor.numpy().flatten() - t_arr.tofile(data_path) - else: - assert(0) - return index - -def dump_args(args, arg_attributes, path): - index = 0 - for (arg_name, arg_attribute), arg in zip(arg_attributes.items(), args): - if LLVMKernelArgs.is_llvm_arg_in(arg_attribute[0]): - index = write_arg(arg, path, arg_name) - return index - def llvm_compile_command(input, output): opt_output = f"{input[:-3]}_opt.ll" return [re.sub(r"[ \n]+", " ", @@ -105,50 +84,49 @@ def load(cls, source_code, lock_dir = get_lock_dir() lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT) with lock: - if not os.path.exists(output_path): - try: - subprocess.check_call(opt_cmd) - subprocess.check_call(llc_cmd) - except subprocess.CalledProcessError as e: - print("Command failed with exit code", e.returncode) - print("Error output:", e.output) - assert(0) # Todo: make LLVMCompileError - - # Launch tile graph generator - tile_graph_generator = riscv_parser() - tile_graph_generator.load_file(output_path, - loop_info=loop_info, - load_tile_info=load_tile_info, - store_tile_info=store_tile_info) - # Create code for sampling - tile_graph_generator.dump_sampling_code(output_path[:-2] + "_sample.s") - - # Generate LLVM kernel calller and binary for validation - if TORCHSIM_VALIDATION_MODE: - val_llvm_caller = LLVMKernelCallerCodeGen(TORCHSIM_VALIDATION_MODE, arg_attributes) - val_llvm_caller.generate_wrapper_file(write_path, validation_wrapper_name) - val_llvm_caller.compile_wih_kernel(write_path, key, validation_wrapper_name, validation_binary_name) - - # Generate LLVM kernel calller and binary for cycle calculation - cycle_llvm_caller = LLVMKernelCallerCodeGen(False, arg_attributes) - cycle_llvm_caller.generate_wrapper_file(write_path, cycle_wrapper_name) - cycle_llvm_caller.compile_wih_kernel(write_path, key + "_sample", cycle_wrapper_name, cycle_binary_name) - - # Run cyclesim - cyclesim = CycleSimulator() - cycle_list = cyclesim.compile_and_simulate(os.path.join(write_path, cycle_binary_name)) - - if TORCHSIM_DUMP_FILE: - tile_graph_generator.dump_basic_block_graph(os.path.join(write_path, "basic_block.onnx")) - tile_graph_generator.cycle_analysis(cycle_list=cycle_list, name=os.path.join(write_path, "tile_graph")) + # if not os.path.exists(output_path): + try: + subprocess.check_call(opt_cmd) + subprocess.check_call(llc_cmd) + except subprocess.CalledProcessError as e: + print("Command failed with exit code", e.returncode) + print("Error output:", e.output) + assert(0) # Todo: make LLVMCompileError + + # Launch tile graph generator + tile_graph_generator = riscv_parser() + tile_graph_generator.load_file(output_path, + loop_info=loop_info, + load_tile_info=load_tile_info, + store_tile_info=store_tile_info) + # Create code for sampling + tile_graph_generator.dump_sampling_code(output_path[:-2] + "_sample.s") + + # Generate LLVM kernel calller and binary for validation + if TORCHSIM_VALIDATION_MODE: + val_llvm_caller = LLVMKernelCallerCodeGen(TORCHSIM_VALIDATION_MODE, arg_attributes) + val_llvm_caller.generate_wrapper_file(write_path, validation_wrapper_name) + val_llvm_caller.compile_wih_kernel(write_path, key, validation_wrapper_name, validation_binary_name) + + # Generate LLVM kernel calller and binary for cycle calculation + cycle_llvm_caller = LLVMKernelCallerCodeGen(False, arg_attributes) + cycle_llvm_caller.generate_wrapper_file(write_path, cycle_wrapper_name) + cycle_llvm_caller.compile_wih_kernel(write_path, key + "_sample", cycle_wrapper_name, cycle_binary_name) + + # Run cyclesim + cyclesim = CycleSimulator() + cycle_list = cyclesim.compile_and_simulate(os.path.join(write_path, cycle_binary_name)) + + if TORCHSIM_DUMP_FILE: + tile_graph_generator.dump_basic_block_graph(os.path.join(write_path, "basic_block.onnx")) + tile_graph_generator.cycle_analysis(cycle_list=cycle_list, name=os.path.join(write_path, "tile_graph")) return key -def get_onnxim_command(model_path): - base_dir = os.path.join(TORCHSIM_DIR, "ONNXim") +def get_backend_command(model_path): + base_dir = os.path.join(TORCHSIM_DIR, "PyTorchSimBackend") bin = os.path.join(base_dir, "build/bin/Simulator") - config = os.path.join(base_dir, TORCHSIM_ONNXIM_CONFIG) - model_list = os.path.join(base_dir, "models_list.json") # TODO: file format will be changed - cmd = f"{bin} --config {config} --model {model_path} --models_list {model_list}" + config = os.path.join(base_dir, TORCHSIM_BACKEND_CONFIG) + cmd = f"{bin} --config {config} --models_list {model_path}" return cmd.strip() class CustomAsyncCompile(AsyncCompile): @@ -180,9 +158,10 @@ def dummy_simulator(*args, **kwargs): # Dump arguments and meta data dump_metadata(args, arg_attributes, result_path) if TORCHSIM_VALIDATION_MODE: - n_call = dump_args(args, arg_attributes, result_path) - funcsim = FunctionalSimulator(result_path, self.key, arg_attributes, args) - funcsim.run_spike(n_call, os.path.join(result_path, self.validation_binary_name)) + funcsim = FunctionalSimulator(result_path, self.key) + funcsim.run_spike(args, arg_attributes, + os.path.join(result_path, self.validation_binary_name), + kwargs['intermediate_op'] if 'intermediate_op' in kwargs else None) assembly_path = os.path.join(result_path, f'{self.key}.s') try: @@ -193,7 +172,8 @@ def dummy_simulator(*args, **kwargs): print(f'{assembly_path} not found.') except Exception as e: print(f"Error while reading.") - cmd = get_onnxim_command(result_path) + onnx_path = os.path.join(result_path, "tile_graph.onnx") + cmd = get_backend_command(onnx_path) try: subprocess.check_call(shlex.split(cmd)) diff --git a/test_extension_backend.py b/test_extension_backend.py index d543b9e95..d0df769cb 100644 --- a/test_extension_backend.py +++ b/test_extension_backend.py @@ -5,8 +5,10 @@ import time import contextlib import unittest +import numpy as np import torch +import torch.nn as nn import torch._dynamo import torch.utils.cpp_extension from torch._inductor import config @@ -151,7 +153,7 @@ def test_open_device_registration(self): def fn(a, b, c): return a * b + c - + def vectoradd(a, b): return a + b @@ -161,11 +163,83 @@ def reduce_sum(a, b): def custom_matmul(a, b): return torch.matmul(a, b) + def custom_conv2d(a, b): + i_c = a.shape[1] + o_c = b.shape[0] + conv2d = nn.Conv2d(i_c, o_c, b.shape[-1], stride=1, padding=0, dilation=1) + conv2d.weight = nn.Parameter(b) + + return conv2d(a) + metrics.reset() + # conv test + input_array = np.arange(1*8*64*64)*0.001 + conv_input = torch.tensor(input_array, dtype=torch.float32).view(1, 8, 64, 64).to(device=device) + kernel_array = np.arange(16*8*3*3)*0.001 + conv_kernel = torch.tensor(kernel_array, dtype=torch.float32).view(16, 8, 3, 3).to(device=device) + + opt_fn = torch.compile()(custom_conv2d) + res = opt_fn(conv_input, conv_kernel) + # self.assertEqual(ref, res.to(device="cpu")) + + out = custom_conv2d(conv_input.cpu(), conv_kernel.cpu()) + + print("Result > ", torch.allclose(res.cpu(), out, rtol=1, atol=1)) + print("Max diff > ", torch.max(torch.abs(res.cpu() - out))) + + # Backward Uni-Test (Single Perceptron) + def perceptron(a, b, c): + res = a * b + c + return res.sum() + + def weight_update(a, b, lr): + return a - b * lr + + x = torch.empty(64).to(device=device).fill_(1) + w = torch.empty(64).to(device=device).fill_(3) + target_y = torch.tensor(384, dtype=torch.float32).to(device=device) + b = torch.empty(64).to(device=device).fill_(0.1) + w.requires_grad = True + b.requires_grad = True + opt_mlp = torch.compile()(perceptron) + opt_w = torch.compile()(weight_update) + lr = torch.tensor(1e-3).to(device=device) # learning rate + for i in range(50): + y = opt_mlp(x, w, b) + loss = (target_y - y) ** 2 # TODO: Add loss function + # print(loss.cpu().item()) # check loss + # loss.to(device=device) + loss.backward() + with torch.no_grad(): + w.copy_(opt_w(w, w.grad, lr)) + b.copy_(opt_w(b, b.grad, lr)) + w.grad.zero_() + b.grad.zero_() + + # GEMM Backward TEST + torch.manual_seed(0) + input = torch.randn(64, 64) + weight = torch.randn(64, 64) + + x1 = input.to(device=device) + w1 = weight.to(device=device) + x2 = input.to("cpu") + w2 = weight.to("cpu") + self.assertTrue(x1.device == device) + self.assertTrue(w1.device == device) + self.assertTrue(x2.device == torch.device("cpu")) + self.assertTrue(w2.device == torch.device("cpu")) + w1.requires_grad = True opt_fn = torch.compile()(custom_matmul) - res = opt_fn(x, y) - self.assertEqual(ref, res.to(device="cpu")) - + res = opt_fn(x1, w1) + loss = torch.sum(res) + loss.backward() + print(w1.grad.cpu()) + w2.requires_grad = True + y = custom_matmul(x2, w2) + loss2 = torch.sum(y) + loss2.backward() + print(w2.grad.cpu()) if __name__ == "__main__": from torch._dynamo.test_case import run_tests