diff --git a/PyTorchSimFrontend/llvm_caller_codegen.py b/PyTorchSimFrontend/llvm_caller_codegen.py index e3e7385c9..64144e499 100644 --- a/PyTorchSimFrontend/llvm_caller_codegen.py +++ b/PyTorchSimFrontend/llvm_caller_codegen.py @@ -25,6 +25,7 @@ def __init__(self, validation, arg_attributes): self.n_arg = len(arg_attributes) self.arg_attributes = arg_attributes self.arg_use_count = 1 + self.load_args = {} def get_argv_idx(self): self.arg_use_count += 1 @@ -49,7 +50,9 @@ def is_out_arg(self, arg_name): def load_arg(self): for i, arg_name in enumerate(self.arg_attributes.keys()): if self.is_in_arg(arg_name): - self.writeline(f'if(load_arg({arg_name}, sizeof({arg_name}), argv[{self.get_argv_idx()}]) == -1){self.open_bracket}') + argv_idx = self.get_argv_idx() if arg_name not in self.load_args else self.load_args[arg_name] + self.load_args[arg_name] = argv_idx + self.writeline(f'if(load_arg({arg_name}, sizeof({arg_name}), argv[{argv_idx}]) == -1){self.open_bracket}') with self.code.indent(): self.writeline(f'return -1{self.ending}') self.writeline(self.closed_bracket) @@ -57,7 +60,8 @@ def load_arg(self): def dump_arg(self): for i, arg_name in enumerate(self.arg_attributes.keys()): if self.is_out_arg(arg_name): - self.writeline(f'if(dump_arg({arg_name}, sizeof({arg_name}), argv[{self.get_argv_idx()}]) == -1){self.open_bracket}') + argv_idx = self.get_argv_idx() if arg_name not in self.load_args else self.load_args[arg_name] + self.writeline(f'if(dump_arg({arg_name}, sizeof({arg_name}), argv[{argv_idx}]) == -1){self.open_bracket}') with self.code.indent(): self.writeline(f'return -1{self.ending}') self.writeline(self.closed_bracket) @@ -132,7 +136,7 @@ def generate_wrapper_file(self, path, name): self.write_header() self.generate_kernel_declare() - + if self.validation: self.generate_load_dump_fn() self.generate_main() @@ -154,7 +158,7 @@ def compile_wih_kernel(self, write_path, llvm_name, wrapper_name, binary_name): kernel_compile = f'clang -c --target="riscv64" -march=rv64gcv -O2 -nostdlib {kernel_path} -o {kernel_obj_path}' target = os.path.join(write_path, binary_name) - link = f'riscv64-unknown-elf-gcc -march=rv64gcv {main_obj_path} {kernel_obj_path} -o {target}' + link = f'riscv64-unknown-elf-gcc -march=rv64gcv {main_obj_path} {kernel_obj_path} -o {target} -lm' main_compile_cmd = shlex.split(main_compile) kernel_compile_cmd = shlex.split(kernel_compile) diff --git a/PyTorchSimFrontend/llvm_codegen_backend.py b/PyTorchSimFrontend/llvm_codegen_backend.py index 13ac9d5a7..eccbcd2ef 100644 --- a/PyTorchSimFrontend/llvm_codegen_backend.py +++ b/PyTorchSimFrontend/llvm_codegen_backend.py @@ -1,12 +1,17 @@ import dataclasses import contextlib import sympy +import itertools +import re +from functools import reduce +from operator import mul from typing import List from typing import Dict import torch +from torch._inductor import dependencies from torch._inductor.codegen import cpp, wrapper, common from torch._inductor.scheduler import BaseScheduling -from torch._inductor.virtualized import V +from torch._inductor.virtualized import V, _ops as ops from torch._inductor.utils import IndentedBuffer import extension_codecache @@ -38,6 +43,10 @@ def reduction_init(reduction_type, dtype): return "0.0" if reduction_type == "prod": return "1.0" + if reduction_type in {"max", "argmax"}: + return "0.0" + if reduction_type in {"min", "argmin"}: + return "0.0" raise AssertionError(reduction_type) def reduction_combine(reduction_type, var, next_value): @@ -76,9 +85,9 @@ def vector_reduction_combine(reduction_type, start_value, vector_value): def matrix_reduction_combine(reduction_type, start_value, vector_value, tile_row=64): if reduction_type == "sum": - return f"tail call float @llvm.vector.reduce.fadd.nxv2f32(float %{start_value}, <{tile_row} x float> %{vector_value})" + return f"fadd <{tile_row} x float> %{start_value}, %{vector_value}" if reduction_type == "prod": - return f"tail call float @llvm.vector.reduce.fmul.nxv2f32(float %{start_value}, <{tile_row} x float> %{vector_value})" + return f"fmul <{tile_row} x float> %{start_value}, %{vector_value}" if reduction_type == "xor_sum": raise NotImplementedError() # TODO: implement if reduction_type == "any": @@ -96,6 +105,8 @@ def matrix_partial_reduction_combine(reduction_type, vector_value, tile_row=64): return f"tail call float @llvm.vector.reduce.fadd.nxv2f32(float 0.0, <{tile_row} x float> %{vector_value})" if reduction_type == "prod": return f"tail call float @llvm.vector.reduce.fmul.nxv2f32(float 1.0, <{tile_row} x float> %{vector_value})" + if reduction_type in ("min", "max"): + return f"tail call float @llvm.vector.reduce.f{reduction_type}.nxv2f32(<{tile_row} x float> %{vector_value})" raise AssertionError(reduction_type) class ExtensionWrapperCodegen(wrapper.WrapperCodeGen): @@ -189,7 +200,19 @@ def truediv(operand1, operand2, tile_size=4): @staticmethod def constant(value, dtype, tile_size=4): - return repr(value) + return f'insertelement <1 x float> undef, float {value}, i32 0' + + @staticmethod + def exp(operand, tile_size=4): + return f'tail call <{tile_size} x float> @llvm.exp.f32(<{tile_size} x float> %{operand})' + + @staticmethod + def maximum(operand1, operand2, tile_size=4): + return f'tail call <{tile_size} x float> @llvm.maximum.f32(<{tile_size} x float> %{operand1}, <{tile_size} x float >%{operand2})' + + @staticmethod + def relu(x, tile_size=4): + return ops.maximum(x, ops.constant(0.0, torch.int32)) SYMPY_TO_LLVM = { sympy.core.mul.Mul: "mul", @@ -214,6 +237,7 @@ def __init__(self, args=None): self.loop_info = {} self.load_desc = {} self.store_desc = {} + self.tiling_indices = [0, 1] def get_constant_vector(self, expr): constant_vector = [int(expr.coeff(var)) for var in self.itervars] @@ -270,6 +294,64 @@ def depth_first_traverse(self, expr, buffer, cse): else: raise Exception() + def codegen_nodes(self, nodes, kernel_name): + _, (group, reduction_group) = max( + nodes, key=lambda x: int(x.is_reduction()) + ).group + + def select_tiling_indices(): + all_index = [] + for node in nodes: + rw = dependencies.extract_read_writes(node._body, *node._sizes) + all_index += [dep.index for dep in itertools.chain(rw.reads, rw.writes)] + contig_vars = set() + contig_vars_list = [] + non_contig_stride_const = set() + non_contig_stride_other = set() + for index in all_index: + for var in index.free_symbols: + if not re.search(r"^d\d+$", var.name): + continue + stride = cpp.stride_at(var, index) + if stride == 1: + contig_vars.add(int(var.name[1:])) + contig_vars_list.append(int(var.name[1:])) + elif all(s.name.startswith("s") for s in stride.free_symbols): + non_contig_stride_const.add(int(var.name[1:])) + else: + non_contig_stride_other.add(int(var.name[1:])) + contig_only = ( + contig_vars - non_contig_stride_const - non_contig_stride_other + ) + if len(contig_vars) == 0: + # no contiguous vars + return [len(self.itervars) - 1] + if contig_only: + return sorted(contig_only)[-1:] + contig_and_const_stride = ( + contig_vars & non_contig_stride_const + ) - non_contig_stride_other + contig_vars_sorted = sorted(contig_vars) + if ( + len(contig_vars_sorted) == 2 + and contig_vars_sorted[-1] in contig_and_const_stride + and contig_vars_sorted[-1] == len(self.itervars) - 1 + ): + return contig_vars_sorted + return sorted(contig_vars_sorted, key=contig_vars_list.count)[-1:] + + self.set_ranges(group, reduction_group) + self.tiling_indices = select_tiling_indices() + + with self as kernel: + for node in nodes: + vars, reduction_vars = kernel.set_ranges(group, reduction_group) + node.run(vars, reduction_vars) + + src_code = self.codegen_kernel(kernel_name=kernel_name) + self.meta_kernel() + return src_code + def load(self, name: str, index: sympy.Expr): index = self.rename_indexing(index) index = self.depth_first_traverse(index, self.loads, self.index_cse) @@ -536,6 +618,34 @@ def __init__(self): self.tile_col = 64 self.tile_size = self.tile_row * self.tile_col + def get_load_info(self, vec_len, cv): + tile_row = self.tile_row + tile_col = self.tile_col + if vec_len > 1: + stride = reduce(mul, cv, 1) + if len(cv) == 2 and cv[1] == 0: # if the tile is row major vector + vec_len, tile_col, stride = self.tile_row, 1, self.tile_row + elif len(cv) == 2 and cv[0] == 0: # if the tile is colum major vector + vec_len, tile_row, stride = self.tile_col, 1, 1 + elif len(cv) == 1: # if the tile is vector + stride = tile_row + elif vec_len == 1: # scalar + tile_row, tile_col, stride = 1, 1, 1 + return tile_row, tile_col, stride, vec_len + + def need_vec_transpose(self, index): + return ( + len(self.itervars) > 1 + and self.outer_idx is not None + and cpp.stride_at(self.itervars[self.outer_idx], index) == 1 + and index.has(self.itervars[self.tiling_idx]) + and not cpp.stride_at(self.itervars[self.tiling_idx], index).has( + self.itervars[self.tiling_idx] + ) + and not cpp.stride_at(self.itervars[self.tiling_idx], index).has( + self.itervars[self.outer_idx] + ) + ) def load(self, name: str, index: sympy.Expr): var = self.args.input(name) @@ -546,18 +656,18 @@ def load(self, name: str, index: sympy.Expr): index = self.rename_indexing(index) 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) - 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}" + new_index = self.depth_first_traverse(index, self.loads, self.index_cse) + vec_len = self.tile_size if not new_index.is_number else 1 + new_index = f"%{new_index}" if not new_index.is_number else new_index + line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 {new_index}" var = 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)" + tile_row, tile_col, stride, vec_len = self.get_load_info(vec_len, cv) + 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 {tile_row}, i32 {tile_col})" out_var = self.cse.generate(self.loads, line) - self.vec_len[out_var] = vec_len + if self.need_vec_transpose(index): + line = f"call <{vec_len} x {type_name}> @llvm.matrix.transpose.v{vec_len}f32.p0f32(<{vec_len} x {type_name}> %{out_var}, i32 {tile_row}, i32 {tile_col})" + out_var = self.cse.generate(self.loads, line) + self.tile_shape[out_var] = [tile_row, tile_col] return out_var def store(self, name: str, index: sympy.Expr, value, *args, **kwargs): @@ -569,13 +679,16 @@ def store(self, name: str, index: sympy.Expr, value, *args, **kwargs): index = self.rename_indexing(index) 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) - 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}" + new_index = self.depth_first_traverse(index, self.stores, self.index_cse) + vec_len = self.tile_size if not new_index.is_number else 1 + new_index = f"%{new_index}" if not new_index.is_number else new_index + line = f"getelementptr inbounds {type_name}, ptr %{var}, i64 {new_index}" var = self.cse.generate(self.stores, line) if (isinstance(value, list)): value = value[0] + if self.need_vec_transpose(index): + line = f"call <{vec_len} x {type_name}> @llvm.matrix.transpose.v{vec_len}f32.p0f32(<{vec_len} x {type_name}> %{value}, i32 {self.tile_row}, i32 {self.tile_col})" + value = self.cse.generate(self.stores, line) 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})" @@ -606,40 +719,56 @@ def reduction(self, dtype, src_dtype, reduction_type, value): # NOTE. To keep below line be under the compute, used store buffers temp = self.cse.generate(self.stores, line) - output = [] - for i in range(self.tile_col): - indexes = [f"i32 {i*self.tile_row+j}" for j in range(self.tile_row)] - line = f"shufflevector <{self.tile_size} x {type_name}> %{value}, <{self.tile_size} x {type_name}> undef, <{self.tile_row} x i32> <{comma.join(indexes)}>" - split_vector = self.cse.generate(self.stores, line) - output.append(self.cse.generate(self.stores, matrix_partial_reduction_combine(reduction_type, split_vector, self.tile_row))) - length = len(output) - size = 1 - while(len(output) > 1): - op1 = output.pop(0) - op2 = output.pop(0) - if size == 1: - line = f"insertelement <2 x {type_name}> undef, {type_name} %{op1}, i32 0" - temp_vec = self.cse.generate(self.stores, line) - line = f"insertelement <2 x {type_name}> %{temp_vec}, {type_name} %{op2}, i32 1" + if self.tiling_idx >= self.reduction_depth: # horizontal reduction + output = [] + for i in range(self.tile_col): + if self.tile_col != 1: + indexes = [f"i32 {i*self.tile_row+j}" for j in range(self.tile_row)] + line = f"shufflevector <{self.tile_size} x {type_name}> %{value}, <{self.tile_size} x {type_name}> undef, <{self.tile_row} x i32> <{comma.join(indexes)}>" + split_vector = self.cse.generate(self.stores, line) + reduced_vector = self.cse.generate(self.stores, matrix_partial_reduction_combine(reduction_type, split_vector, self.tile_row)) + else: + reduced_vector = self.cse.generate(self.stores, matrix_partial_reduction_combine(reduction_type, value, self.tile_row)) + output.append(reduced_vector) + length = len(output) + size = 1 + while(len(output) > 1): + op1 = output.pop(0) + op2 = output.pop(0) + if size == 1: + line = f"insertelement <2 x {type_name}> undef, {type_name} %{op1}, i32 0" + temp_vec = self.cse.generate(self.stores, line) + line = f"insertelement <2 x {type_name}> %{temp_vec}, {type_name} %{op2}, i32 1" + else: + indexes = [f"i32 {j}" for j in range(size * 2)] + line = f"shufflevector <{size} x {type_name}> %{op1}, <{size} x {type_name}> %{op2}, <{size * 2} x i32> <{comma.join(indexes)}>" + out = self.cse.generate(self.stores, line) + output.append(out) + if (len(output) == length / 2): + size *= 2 + length = len(output) + 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: - indexes = [f"i32 {j}" for j in range(size * 2)] - line = f"shufflevector <{size} x {type_name}> %{op1}, <{size} x {type_name}> %{op2}, <{size * 2} x i32> <{comma.join(indexes)}>" - out = self.cse.generate(self.stores, line) - output.append(out) - if (len(output) == length / 2): - size *= 2 - length = len(output) - 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}" + line = f"fadd <{self.tile_row} x {type_name}> %{temp}, %{output[0]}" + stored_vector = self.cse.generate(self.stores, line) else: - line = f"fadd <{self.tile_row} x {type_name}> %{temp}, %{output[0]}" - output = self.cse.generate(self.stores, line) + partial_value = temp + for i in range(self.tile_col): + if self.tile_col != 1: + indexes = [f"i32 {i*self.tile_row+j}" for j in range(self.tile_row)] + line = f"shufflevector <{self.tile_size} x {type_name}> %{value}, <{self.tile_size} x {type_name}> undef, <{self.tile_row} x i32> <{comma.join(indexes)}>" + split_vector = self.cse.generate(self.stores, line) + partial_value = self.cse.generate(self.stores, matrix_reduction_combine(reduction_type, partial_value, split_vector, self.tile_row)) + else: + partial_value = self.cse.generate(self.stores, matrix_reduction_combine(reduction_type, partial_value, value, self.tile_row)) + stored_vector = partial_value if (self.tile_col == 1): - line = f"store <{self.tile_col} x {type_name}> %{output}, ptr %{acc}, align {align}" + line = f"store <{self.tile_col} x {type_name}> %{stored_vector}, ptr %{acc}, align {align}" else: - line = f"store <{self.tile_row} x {type_name}> %{output}, ptr %{acc}, align {align}" + line = f"store <{self.tile_row} x {type_name}> %{stored_vector}, ptr %{acc}, align {align}" self.cse.generate(self.stores, line, assignment = False) self.reduction_cse.reduction_cache[reduction_key] = acc return acc @@ -700,26 +829,49 @@ def codegen_loops(self): def set_ranges(self, lengths, reduction_lengths): ret = super().set_ranges(lengths, reduction_lengths) + # do vertical reduction as the tail loop + if len(self.itervars) > 1: + if len(self.tiling_indices) == 1: + self.tiling_idx = self.tiling_indices[0] + self.outer_idx = None + else: + self.outer_idx, self.tiling_idx = ( + self.tiling_indices + if self.tiling_indices[1] < self.reduction_depth + else reversed(self.tiling_indices) + ) + else: + self.tiling_idx = self.tiling_indices[0] + self.outer_idx = None # FIXME. this doesn't look pretty... # We have to change this logic to configurable tile_size if len(self.itervars) == 1: - self.tile_row = self.tile_size + self.tile_row = min(self.tile_size, self.ranges[0]) self.tile_col = 1 + elif len(self.itervars) > 1: + self.tile_row = min(self.tile_row, self.ranges[0]) + self.tile_col = min(self.tile_col, self.ranges[1]) + self.tile_size = self.tile_row * self.tile_col return ret 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') + if self.tile_size != self.tile_row: + code.writeline(f'declare <{self.tile_row} x float> @llvm.matrix.column.major.load.v{self.tile_row}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 void @llvm.matrix.column.major.store.v1f32.p0f32(<1 x float>, ptr , i64, i1, i32, i32) #3') 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 <{self.tile_size} x float> @llvm.matrix.transpose.v{self.tile_size}f32.p0f32(<{self.tile_size} x float>, i32, i32) #2') code.writeline(f'declare float @llvm.vector.reduce.fadd.nxv2f32(float, <{self.tile_row} x float>)') + code.writeline(f'declare float @llvm.vector.reduce.fmax.nxv2f32(<{self.tile_row} x float>)') + code.writeline(f'declare <{self.tile_size} x float> @llvm.exp.f32(<{self.tile_size} x float>) #1') + code.writeline(f'declare <{self.tile_size} x float> @llvm.maximum.f32(<{self.tile_size} x float>, <{self.tile_size} x float>) #1') return code @@ -858,7 +1010,7 @@ class MatrixLoopLevel(LoopLevel): def lines(self, line, stride=1): loop_index = self.idx - self.stride = stride * self.tile_row + self.stride = stride * self.tile_row # FIXME: this stride is not correct (it should be stride of tile, not stride of scalar) @contextlib.contextmanager def ctx(): entry_label = f"entry{loop_index}" @@ -879,7 +1031,7 @@ def ctx(): yield line.writeline(f"br label %{for_inc_label}") line.writeline(f"\n{for_inc_label}:") - line.writeline(f"{index_next} = add nsw {self.INDEX_TYPE} {index}, {stride * self.tile_row}") + line.writeline(f"{index_next} = add nsw {self.INDEX_TYPE} {index}, {self.tile_row}") line.writeline(f"{cmp_var} = icmp eq {self.INDEX_TYPE} {index_next}, {self.size}") line.writeline(f"br i1 {cmp_var}, label %{for_end_label}, label %{for_body_label}") @@ -944,14 +1096,10 @@ def codegen_nodes(self, nodes): nodes, key=lambda x: int(x.is_reduction()) ).group ex_kernel = self.target_kernel() - with ex_kernel as kernel: - for node in nodes: - vars, reduction_vars = ex_kernel.set_ranges(group, reduction_group) - node.run(vars, reduction_vars) - kernel_name = f"extension_kernel" - src_code = ex_kernel.codegen_kernel(kernel_name=kernel_name) - ex_kernel.meta_kernel() + kernel_name = f"extension_kernel_{self.count}" + self.count += 1 + src_code = ex_kernel.codegen_nodes(nodes, kernel_name) self.define_kernel(src_code, kernel_name) ex_kernel.call_kernel(kernel_name) @@ -984,6 +1132,7 @@ def define_kernel(self, src_code, kernel_name): codecache_def.writeline("arg_attributes=arg_attributes)") wrapper.define_kernel(kernel_name, codecache_def.getvalue(), cuda=False) + return kernel_name class VectorizedLLVMScheduling(LLVMScheduling): target_kernel = VectorizedLLVMKernel @@ -1003,6 +1152,6 @@ def codegen_template(self, template_node, epilogue_nodes): with V.set_kernel_handler(kernel): node_schedule = [template_node, *epilogue_nodes] kernel.meta_kernel() - self.define_kernel(src_code, kernel.kernel_name) + kernel_name = self.define_kernel(src_code, kernel.kernel_name) self.define_function(kernel) - kernel.call_kernel() \ No newline at end of file + kernel.call_kernel(kernel_name) \ No newline at end of file diff --git a/PyTorchSimFrontend/llvm_common.py b/PyTorchSimFrontend/llvm_common.py index a541480a4..1c76b826e 100644 --- a/PyTorchSimFrontend/llvm_common.py +++ b/PyTorchSimFrontend/llvm_common.py @@ -65,7 +65,7 @@ def is_llvm_arg_in(value): def is_llvm_arg_out(value): return (LLVMKernelArgs.LLVM_ARGS_OUT & value) | (LLVMKernelArgs.LLVM_ARGS_INOUT & value) - def llvm_argdefs(self): + def llvm_argdefs(self, only_args=False): buffer_types = {x.get_name(): [x.get_dtype(), x.get_numel()] for x in V.graph.buffers} for name, val in V.graph.graph_inputs.items(): if isinstance(val, sympy.Expr): @@ -85,24 +85,28 @@ def llvm_argdefs(self): outer = inplaced.other_names[-1] inner = inplaced.inner_name arg_defs.append(f"ptr %{inner}") - call_args.append(outer) - arg_attributes[outer] = [self.LLVM_ARGS_INOUT] + buffer_types[outer] + if not only_args: + call_args.append(outer) + arg_attributes[outer] = [self.LLVM_ARGS_INOUT] + buffer_types[outer] for outer, inner in self.input_buffers.items(): if outer in self.inplace_buffers: continue arg_defs.append(f"ptr readonly %{inner}") - call_args.append(outer) - arg_attributes[outer] = [self.LLVM_ARGS_IN] + buffer_types[outer] + if not only_args: + call_args.append(outer) + arg_attributes[outer] = [self.LLVM_ARGS_IN] + buffer_types[outer] for outer, inner in self.output_buffers.items(): if outer in self.inplace_buffers or self._buffer_is_marked_removed(inner): continue arg_defs.append(f"ptr %{inner}") - call_args.append(outer) - arg_attributes[outer] = [self.LLVM_ARGS_OUT] + buffer_types[outer] + if not only_args: + call_args.append(outer) + arg_attributes[outer] = [self.LLVM_ARGS_OUT] + buffer_types[outer] for outer, inner in self.sizevars.items(): arg_defs.append(f"ptr readonly %{inner}") - call_args.append(outer) - arg_attributes[outer] = [self.LLVM_ARGS_VAR] + buffer_types[outer] + if not only_args: + call_args.append(outer) + arg_attributes[outer] = [self.LLVM_ARGS_VAR] + buffer_types[outer] return arg_defs, call_args, arg_attributes class BaseLLVMKernel(common.Kernel): @@ -121,7 +125,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 = {} + self.tile_shape = {} def load(self, name: str, index: sympy.Expr): raise NotImplementedError() @@ -136,24 +140,31 @@ 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: + if not args[0] in self.tile_shape or not args[1] in self.tile_shape: + return args, [1, 1] + tile_shape0 = self.tile_shape[args[0]] + tile_shape1 = self.tile_shape[args[1]] + vec_len0 = tile_shape0[0] * tile_shape0[1] + vec_len1 = tile_shape1[0] * tile_shape1[1] + if tile_shape0 != tile_shape1: temp = list(args) - if (vec_len0 > vec_len1): - assert(vec_len1 == 1) - indexes = [f"i32 0" for i in range(vec_len0)] + idx = 0 if tile_shape0[0] != tile_shape1[0] else 1 + if tile_shape0[idx] > tile_shape1[idx]: + if idx == 0: + indexes = [f"i32 {i%tile_shape1[idx-1]}" for i in range(vec_len0)] + else: + indexes = [f"i32 {i//tile_shape1[idx-1]}" 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)] + elif tile_shape0[idx] < tile_shape1[idx]: + if idx == 0: + indexes = [f"i32 {i%tile_shape0[idx-1]}" for i in range(vec_len1)] + else: + indexes = [f"i32 {i//tile_shape0[idx-1]}" 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) + return args, max(tile_shape0, tile_shape1) def __enter__(self): class CSEProxy: @@ -182,17 +193,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) + args, tile_shape = self.widening(args, buf_bounds) elif len(args) == 1: - vec_len = self.vec_len[args[0]] + tile_shape = self.tile_shape[args[0]] else: assert(0) # not implemented yet. + vec_len = tile_shape[0] * tile_shape[1] csevar = self.cse.generate( self.compute, getattr(parent_handler, name)(*args, tile_size=vec_len, **kwargs), # type: ignore[has-type] bounds=buf_bounds, ) - self.vec_len[csevar] = vec_len + self.tile_shape[csevar] = tile_shape 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 index deeae2d91..13fa40809 100644 --- a/PyTorchSimFrontend/llvm_conv_template.py +++ b/PyTorchSimFrontend/llvm_conv_template.py @@ -77,7 +77,7 @@ """ CONV2D_FUNC = r""" -def Conv2d({{ INPUT }}, {{ WEIGHT }}, {{ BIAS }}, {{ OUT }}): +def {{ FUNC_NAME }}({{ INPUT }}, {{ WEIGHT }}, {{ BIAS }}, {{ OUT }}): {{ INPUT }}_cpu = {{ INPUT }}.cpu() {{ WEIGHT }}_cpu = {{ WEIGHT }}.cpu() {{ BIAS }}_cpu = {{ BIAS }}.cpu() @@ -135,7 +135,8 @@ def __init__(self, input_nodes, layout, input_reorder=None, **kwargs): self.stride = kwargs["stride"] self.padding = kwargs["padding"] self.dilation = kwargs["dilation"] - self.function_name = "Conv2d" + weight_shape = [str(i) for i in input_nodes[1].layout.size] + self.function_name = "Conv2D_" + "_".join(weight_shape) self.gemm_args = ['input', 'weight', 'bias', 'output'] def render(self, @@ -191,6 +192,7 @@ def function_render(self, kernel_name, input_args): options = dict( KERNEL_NAME=kernel_name, + FUNC_NAME=self.function_name, INPUT=input_args[0], WEIGHT=input_args[1], BIAS=input_args[2], diff --git a/PyTorchSimFrontend/llvm_gemm_template.py b/PyTorchSimFrontend/llvm_gemm_template.py index fe58c8a2d..2eeb29cbb 100644 --- a/PyTorchSimFrontend/llvm_gemm_template.py +++ b/PyTorchSimFrontend/llvm_gemm_template.py @@ -4,20 +4,21 @@ from PyTorchSimFrontend.llvm_template import LLVMTemplateKernel from torch._inductor.ir import Buffer from torch._inductor.ir import IRNode +from torch._inductor.ir import ReinterpretView GEMM_TEMPLATE = r""" -@sram_accum = dso_local global [{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}] zeroinitializer, align 64 +@sram_accum = dso_local global [{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}] zeroinitializer, align 4 -define dso_local void @{{ KERNEL_NAME }}(ptr %X, ptr %Y, ptr %W) { +define dso_local void @{{ KERNEL_NAME }}{{kernel.def_kernel(inputs=[X, W, Bias], outputs=[Y], names_str="X, W, Bias, Y", input_reorder=input_reorder)}} { entry: br label %for.cond1.preheader for.cond1.preheader: %indvars.iv49 = phi i64 [ 0, %entry ], [ %indvars.iv.next50, %for.cond.cleanup3 ] - %0 = mul nuw nsw i64 %indvars.iv49, {{ K }} - %add.ptr = getelementptr inbounds {{ DATA_TYPE }}, ptr %X, i64 %0 - %1 = mul nuw nsw i64 %indvars.iv49, {{ N }} - %add.ptr20 = getelementptr inbounds {{ DATA_TYPE }}, ptr %W, i64 %1 + {% if X_transposed %}%add.ptr = getelementptr inbounds {{ DATA_TYPE }}, ptr %X, i64 %indvars.iv49{% else %}%0 = mul nuw nsw i64 %indvars.iv49, {{ K }} + %add.ptr = getelementptr inbounds {{ DATA_TYPE }}, ptr %X, i64 %0{% endif %} + {% if not X_transposed %}%1{% else %}%0{% endif %} = mul nuw nsw i64 %indvars.iv49, {{ N }} + %add.ptr20 = getelementptr inbounds {{ DATA_TYPE }}, ptr %Y, i64 {% if not X_transposed %}%1{% else %}%0{% endif %} br label %for.body4 for.cond.cleanup: @@ -31,27 +32,32 @@ for.body4: %indvars.iv47 = phi i64 [ 0, %for.cond1.preheader ], [ %indvars.iv.next48, %for.cond.cleanup7 ] 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.iv47 + {% if W_transposed%}{% if X_transposed %}%1{% else %}%2{% endif %} = mul nuw nsw i64 %indvars.iv47, {{ K }} + %invariant.gep = getelementptr inbounds {{ DATA_TYPE }}, ptr %W, i64 {% if X_transposed %}%1{% else %}%2{% endif %}{% else %}%invariant.gep = getelementptr inbounds {{ DATA_TYPE }}, ptr %W, i64 %indvars.iv47{% endif %} br label %for.body8 for.cond.cleanup7: %add.ptr22 = getelementptr inbounds {{ DATA_TYPE }}, ptr %add.ptr20, i64 %indvars.iv47 - {{ kernel.store_matrix(TILE_M, TILE_N, N, DATA_TYPE, DATA_STYPE, "%add.ptr22", "%call18", "W", DATA_SIZE) }} + {{ kernel.store_output(TILE_N, TILE_M, N, DATA_TYPE, DATA_STYPE, "%add.ptr22", "%call18", "Y", 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 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, K, DATA_TYPE, DATA_STYPE, "%add.ptr10", "X", DATA_SIZE)}} - %2 = mul nuw nsw i64 %indvars.iv, {{ N }} + {% if X_transposed%}{% if W_transposed %}%2{% else %}%1{% endif %} = mul nuw nsw i64 %indvars.iv, {{ M }}{% endif %} + %add.ptr10 = getelementptr inbounds {{ DATA_TYPE }}, ptr %add.ptr, i64 {% if X_transposed %}{% if W_transposed %}%2{% else %}%1{% endif %}{% else %}%indvars.iv{% endif %} + %call = {{ kernel.load_matrix(TILE_K, TILE_M, K, DATA_TYPE, DATA_STYPE, "%add.ptr10", "X", DATA_SIZE)}} + {% if W_transposed %}%gep = getelementptr inbounds {{ DATA_TYPE }}, ptr %invariant.gep, i64 %indvars.iv + %call16 = {{ kernel.load_matrix(TILE_K, TILE_N, K, DATA_TYPE, DATA_STYPE, "%gep", "W", DATA_SIZE)}}{% else %}%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, 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 + %call16 = {{ kernel.load_matrix(TILE_N, TILE_K, N, DATA_TYPE, DATA_STYPE, "%gep", "W", DATA_SIZE)}}{% endif %} + {% if W_transposed %}%trans0 = call <{{ TILE_K * TILE_N }} x {{ DATA_TYPE }}> @llvm.matrix.transpose.v{{ TILE_K*TILE_N }}{{ DATA_STYPE }}(<{{ TILE_N * TILE_K }} x {{ DATA_TYPE }}> %call16, i32 {{ TILE_K }}, i32 {{ TILE_N }}){% endif %} + {% if X_transposed %}%trans1 = call <{{ TILE_M * TILE_K }} x {{ DATA_TYPE }}> @llvm.matrix.transpose.v{{ TILE_M*TILE_K }}{{ DATA_STYPE }}(<{{ TILE_K * TILE_M }} x {{ DATA_TYPE }}> %call, i32 {{ TILE_K }}, i32 {{ TILE_M }}){% endif %} + %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_K * TILE_N}} x {{ DATA_TYPE }}> {% if W_transposed %}%trans0{% else %}%call16{% endif %}, <{{ TILE_M * TILE_K}} x {{ DATA_TYPE }}> {% if X_transposed %}%trans1{% else %}%call{% endif %}, i32 {{ TILE_N }}, i32 {{ TILE_K }}, i32 {{ TILE_M }}) + %tmp_acc = load <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}>, ptr @sram_accum, align 4 %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 + store <{{ TILE_M * TILE_N }} x {{ DATA_TYPE }}> %call18, ptr @sram_accum, align 4 %indvars.iv.next = add nuw nsw i64 %indvars.iv, {{ TILE_K }} %cmp6 = icmp ult i64 %indvars.iv, {{ K - TILE_K }} br i1 %cmp6, label %for.body8, label %for.cond.cleanup7 @@ -63,14 +69,30 @@ 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 <{{TILE_N}} x float> @llvm.matrix.column.major.load.v{{ TILE_N }}{{ DATA_STYPE }}.p0{{ DATA_STYPE }}(ptr , i64, i1, i32, i32) #2 +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_N*TILE_K }} x {{ DATA_TYPE }}>, <{{ TILE_K*TILE_M }} 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 +{% if W_transposed %} +declare <{{TILE_K * TILE_N}} x float> @llvm.matrix.transpose.v{{ TILE_K*TILE_N }}{{ DATA_STYPE }}( <{{ TILE_N*TILE_K }} x {{ DATA_TYPE }}>, i32, i32) #1 +{% endif %} +{% if X_transposed %} +declare <{{TILE_M * TILE_K}} x float> @llvm.matrix.transpose.v{{ TILE_M*TILE_K }}{{ DATA_STYPE }}( <{{ TILE_K*TILE_M }} x {{ DATA_TYPE }}>, i32, i32) #1 +{% endif %} """ class LLVMGemmTemplate(LLVMTemplate): def __init__(self, input_nodes, layout, input_reorder=None): super().__init__("kernel", input_nodes, layout, input_reorder) + def is_transposed(self, node): + if isinstance(node, ReinterpretView): + if node.layout.stride != node.data.layout.stride: + if node.layout.stride[-2] == node.data.layout.stride[-1] and node.layout.stride[-1] == node.data.layout.stride[-2]: + return True + else: + raise NotImplementedError("If the stride is not equal to the original stride, it should have been transposed.") + return False + def render(self, kernel: LLVMTemplateKernel, template_buffer_node = None, @@ -85,20 +107,33 @@ def render(self, Y = self.output_node Bias = None if len(self.input_nodes) == 2 else self.input_nodes[2] + TILE_M = min(16, X.get_size()[0]) # TODO:: This should be determined by the size of the SRAM + TILE_N = min(16, W.get_size()[1]) # FIXME: 16 is hard-coded + TILE_K = min(16, X.get_size()[1]) + + W_transposed = self.is_transposed(W) + X_transposed = self.is_transposed(X) + options = dict( KERNEL_NAME=self.name, kernel=kernel, M=X.get_size()[0], N=W.get_size()[1], K=X.get_size()[1], - TILE_M=16, - TILE_N=16, - TILE_K=16, + TILE_M=TILE_M, + TILE_N=TILE_N, + TILE_K=TILE_K, DATA_TYPE="float", DATA_STYPE="f32", DATA_SIZE=4, + X = X, + W = W, + Y = Y, + Bias = Bias, + W_transposed = W_transposed, + X_transposed = X_transposed, + input_reorder = self.input_reorder ) code = self._template_from_string(GEMM_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) return code \ No newline at end of file diff --git a/PyTorchSimFrontend/llvm_lowering.py b/PyTorchSimFrontend/llvm_lowering.py index ac4e4daf1..d2c042fbb 100644 --- a/PyTorchSimFrontend/llvm_lowering.py +++ b/PyTorchSimFrontend/llvm_lowering.py @@ -17,6 +17,12 @@ def tuned_mm(mat1, mat2, * ,layout=None): return llvm_template.generate().output_node() +def tuned_addmm(inp, mat1, mat2, *, alpha=1, beta=1, layout=None): + m, n, k, layout, mat1, mat2, inp_expanded = mm_args(mat1, mat2, inp, layout=layout) + llvm_template = LLVMGemmTemplate([mat1, mat2, inp_expanded], layout) # TODO: add alpha and beta + + return llvm_template.generate().output_node() + def conv_layout( x: TensorBox, weight: TensorBox, @@ -81,4 +87,5 @@ def convolution( return llvm_template.generate().output_node() lowerings.update({getattr(aten.mm, overload): tuned_mm for overload in aten.mm.overloads()}) +lowerings.update({getattr(aten.addmm, overload): tuned_addmm for overload in aten.addmm.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 115fd34d9..9fc05fc08 100644 --- a/PyTorchSimFrontend/llvm_template.py +++ b/PyTorchSimFrontend/llvm_template.py @@ -49,6 +49,19 @@ def store_matrix(self, row, col, stride, dtype, stype, ptr, vec, base_addr, data self.add_desc(False, base_addr, data_size, [col, 1], [row, col]) return f"call {code}" + def store_output(self, row, col, stride, dtype, stype, ptr, vec, base_addr, data_size): + code = "" + if len(self.args.input_buffers) > 2: + indexes = [f"i32 {i%row}" for i in range(row * col)] + mask = ", ".join(indexes) + code += f"%add.ptr23 = getelementptr inbounds {dtype}, ptr %Bias, i64 %indvars.iv47\n " + code += f"%call19 = " + self.load_matrix(1, row, 1, dtype, stype, "%add.ptr23", "Bias", data_size) + "\n " #FIXME: Hardcoded %call19 + code += f"%call20 = shufflevector <{row} x {dtype}> %call19, <{row} x {dtype}> undef, <{row*col} x i32> <{mask}>\n " + code += f"%call21 = fadd <{row*col} x {dtype}> %call18, %call20\n " + vec = "%call21" + code += self.store_matrix(row, col, stride, dtype, stype, ptr, vec, base_addr, data_size) + return code + def add_desc(self, is_load, base_addr, element_size, stride_list, tile_size): if is_load: key = f"load{len(self.load_desc)}" @@ -87,7 +100,7 @@ def meta_kernel(self): wrapper.add_import_once(f"store_tile_info = {self.store_desc}") wrapper.add_import_once(f"arg_attributes = {arg_attributes}") - def call_kernel(self): + def call_kernel(self, kernel_name): """ Generates code to call the kernel through V.graph.wrapper_code. used from within torch._inductor.wrapper.WrapperCodeGen @@ -95,7 +108,7 @@ def call_kernel(self): wrapper = V.graph.wrapper_code _, call_args, _ = self.args.python_argdefs() wrapper.generate_kernel_call( - self.kernel_name if self.kernel_caller_function is None else self.kernel_caller_function, + kernel_name if self.kernel_caller_function is None else self.kernel_caller_function, call_args, cuda=False, ) @@ -130,6 +143,9 @@ def def_kernel( self.named_nodes[name] = node self.args.output_buffers[node.get_name()] = name + arg_defs, *_ = self.args.llvm_argdefs(only_args=True) + return f"({', '.join(arg_defs)})" + def def_function(self): _, call_args, _ = self.args.python_argdefs() if self.kernel_function_render is not None: @@ -187,10 +203,10 @@ def make_kernel_render( epilogue_nodes: Optional[List[IRNode]] = None, ): kernel = LLVMTemplateKernel( - kernel_name="KERNEL_NAME", + kernel_name=kernel_hash_name, kernel_function_render=functools.partial( self.function_render, - kernel_name="KERNEL_NAME" + kernel_name=kernel_hash_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 diff --git a/Simulator/simulator.py b/Simulator/simulator.py index eb91a5672..861e258de 100644 --- a/Simulator/simulator.py +++ b/Simulator/simulator.py @@ -29,8 +29,7 @@ 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, dtype=TORCH_TO_NUMPY[arg.dtype]) - src_tensor = torch.from_numpy(np_array).view(dtype=arg.dtype) - src_tensor = src_tensor.reshape(arg.shape) + src_tensor = torch.as_strided(torch.from_numpy(np_array), arg.size(), arg.stride()) arg.copy_(src_tensor) def get_biggest_filename(self, path): @@ -81,7 +80,7 @@ def run_spike(self, args, arg_attributes, target_binary, intermediate_op=None): 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) @@ -100,9 +99,9 @@ class CycleSimulator(): def __init__(self) -> None: pass - def compile_and_simulate(self, target_binary): + def compile_and_simulate(self, target_binary, array_size): try: - gem5_cmd = [extension_codecache.GEM5_PATH, extension_codecache.GEM5_SCRIPT_PATH, target_binary] + gem5_cmd = [extension_codecache.GEM5_PATH, extension_codecache.GEM5_SCRIPT_PATH, "-c", target_binary, "-o", array_size] output = subprocess.check_output(gem5_cmd) except subprocess.CalledProcessError as e: print("Command failed with exit code", e.returncode) diff --git a/extension_codecache.py b/extension_codecache.py index 566e4504e..fa285cb4f 100644 --- a/extension_codecache.py +++ b/extension_codecache.py @@ -20,7 +20,7 @@ TORCHSIM_DUMP_FILE = int(os.environ.get('TORCHSIM_DUMP_FILE', default="True") == "True") TORCHSIM_VALIDATION_MODE = int(os.environ.get('TORCHSIM_VALIDATION_MODE', default="True") == "True") TORCHSIM_LLVM_PATH = os.environ.get('TORCHSIM_LLVM_PATH', default="/usr/bin") -TORCHSIM_DIR = os.environ.get('TORCHSIM_DIR', default='/workspace/TorchSim') +TORCHSIM_DIR = os.environ.get('TORCHSIM_DIR', default='/workspace/PyTorchSim') TORCHSIM_CUSTOM_PASS_PATH = os.environ.get('TORCHSIM_CUSTOM_PASS_PATH', default=f"{TORCHSIM_DIR}/GemminiLowerPass/build") TORCHSIM_BACKEND_CONFIG = os.environ.get('TORCHSIM_CONFIG', @@ -112,10 +112,13 @@ def load(cls, source_code, 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) + array_size = [] + for (arg_name, arg_attribute) in arg_attributes.items(): + array_size.append(str(arg_attribute[2])) # Run cyclesim cyclesim = CycleSimulator() - cycle_list = cyclesim.compile_and_simulate(os.path.join(write_path, cycle_binary_name)) + cycle_list = cyclesim.compile_and_simulate(os.path.join(write_path, cycle_binary_name), " ".join(array_size)) if TORCHSIM_DUMP_FILE: tile_graph_generator.dump_basic_block_graph(os.path.join(write_path, "basic_block.onnx")) @@ -131,7 +134,6 @@ def get_backend_command(model_path): class CustomAsyncCompile(AsyncCompile): def __init__(self): - self.key = None self.validation_wrapper_name = "validation_wrapper" self.validation_binary_name = "validation_binary" self.cycle_wrapper_name = "cycle_wrapper" @@ -139,31 +141,31 @@ def __init__(self): def llvm(self, source_code, arg_attributes={}, **kwargs): def task(): - self.key = LLVMCodeCache.load(source_code, + key = LLVMCodeCache.load(source_code, valdiation_wrapper_name=self.validation_binary_name, validation_binary_name=self.validation_binary_name, arg_attributes=arg_attributes, **kwargs) - return + return key future = self.submit(task) def dummy_simulator(*args, **kwargs): # Wait for compilation - future.result() + key = future.result() # Run simulator pass - result_path = os.path.join(TORCHSIM_DUMP_PATH, "tmp", hash_prefix(self.key)) + result_path = os.path.join(TORCHSIM_DUMP_PATH, "tmp", hash_prefix(key)) print("Running dummy simulator!") print("OUTPUT PATH > ", result_path) # Dump arguments and meta data dump_metadata(args, arg_attributes, result_path) if TORCHSIM_VALIDATION_MODE: - funcsim = FunctionalSimulator(result_path, self.key) + funcsim = FunctionalSimulator(result_path, 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') + assembly_path = os.path.join(result_path, f'{key}.s') try: with open(assembly_path, 'r') as file: file_contents = file.read() diff --git a/gem5_script/script.py b/gem5_script/script.py index e408e2828..6ee0dcde9 100644 --- a/gem5_script/script.py +++ b/gem5_script/script.py @@ -30,13 +30,28 @@ """ import sys - +import argparse import m5 from m5.objects import * from ctypes import cdll bin_path = sys.argv[1] +parser = argparse.ArgumentParser() +parser.add_argument( + "-c", + "--cmd", + default="", + help="The binary to run in syscall emulation mode.", +) +parser.add_argument( + "-o", + "--options", + default="", + help="""The options to pass to the binary, use + around the entire string""", +) +args = parser.parse_args() system = System() @@ -63,16 +78,12 @@ system.system_port = system.membus.cpu_side_ports thispath = os.path.dirname(os.path.realpath(__file__)) -binary = os.path.join( - thispath, - "../../../", - bin_path, -) +binary = args.cmd system.workload = SEWorkload.init_compatible(binary) process = Process() -process.cmd = [binary] +process.cmd = [binary] + args.options.split() system.cpu.workload = process system.cpu.createThreads()