Skip to content
12 changes: 8 additions & 4 deletions PyTorchSimFrontend/llvm_caller_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -49,15 +50,18 @@ 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)

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)
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand Down
273 changes: 211 additions & 62 deletions PyTorchSimFrontend/llvm_codegen_backend.py

Large diffs are not rendered by default.

62 changes: 37 additions & 25 deletions PyTorchSimFrontend/llvm_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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):
Expand All @@ -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()
Expand All @@ -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:
Expand Down Expand Up @@ -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]
Expand Down
6 changes: 4 additions & 2 deletions PyTorchSimFrontend/llvm_conv_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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],
Expand Down
75 changes: 55 additions & 20 deletions PyTorchSimFrontend/llvm_gemm_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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
Loading