Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions extension_backends/extension_codegen_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,13 @@ def codegen_loops(self):
code.splice(self.reduction_suffix)
return code

def define_kernel(self, wrapper, src_code, kernel_name):
if src_code in wrapper.src_to_kernel:
kernel_name = wrapper.src_to_kernel[src_code]
else:
wrapper.src_to_kernel[src_code] = kernel_name
wrapper.define_kernel(kernel_name, src_code, cuda=False)

def codegen_kernel(self, wrapper):
arg_defs, call_args, arg_types = self.args.cpp_argdefs()
arg_defs = ",\n".ljust(25).join(arg_defs)
Expand All @@ -116,7 +123,7 @@ def codegen_kernel(self, wrapper):
if not V.graph.cpp_wrapper:
codecache_def.writeline("''')")

wrapper.define_kernel(kernel_name, codecache_def.getvalue(), cuda=False)
self.define_kernel(wrapper, codecache_def.getvalue(), kernel_name)
# generate the code to call this
wrapper.generate_kernel_call(kernel_name, call_args, cuda=False)
print(code.getvalue())
Expand Down Expand Up @@ -193,8 +200,8 @@ def codegen_nodes(self, nodes):
nodes, key=lambda x: int(x.is_reduction())
).group

ex_kernel = ExtensionKernel()
for node in nodes:
ex_kernel = ExtensionKernel()
vars, reduction_vars = ex_kernel.set_ranges(group, reduction_group)
with ex_kernel:
node.run(vars, reduction_vars)
Expand Down
16 changes: 12 additions & 4 deletions extension_backends/llvm_codegen_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
from torch._inductor.utils import IndentedBuffer
import sympy

cexpr = cpp.CppPrinter().doprint

tile_size = 16 # FIXME. hard coded
tile_row = 4 # FIXME. hard coded
tile_col = 4 # FIXME. hard coded
Expand Down Expand Up @@ -295,6 +293,13 @@ def codegen_loops(self):
code.writeline(f"ret void")
return code

def define_kernel(self, wrapper, src_code, kernel_name):
if src_code in wrapper.src_to_kernel:
kernel_name = wrapper.src_to_kernel[src_code]
else:
wrapper.src_to_kernel[src_code] = kernel_name
wrapper.define_kernel(kernel_name, src_code, cuda=False)

def codegen_kernel(self, wrapper):
arg_defs, call_args = self.args.llvm_argdefs()
arg_defs = ",\n".ljust(25).join(arg_defs)
Expand Down Expand Up @@ -322,12 +327,15 @@ def codegen_kernel(self, wrapper):

codecache_def = IndentedBuffer()
if not V.graph.cpp_wrapper:
codecache_def.writeline("async_compile.cpp('''")
codecache_def.writeline("custom_async_compile.llvm('''")
codecache_def.splice(code)
if not V.graph.cpp_wrapper:
codecache_def.writeline("''')")

wrapper.define_kernel(kernel_name, codecache_def.getvalue(), cuda=False)
wrapper.add_import_once(f'\nfrom extension_codecache import CustomAsyncCompile')
wrapper.add_import_once(f'\ncustom_async_compile = CustomAsyncCompile()')

self.define_kernel(wrapper, codecache_def.getvalue(), kernel_name)
# generate the code to call this
wrapper.generate_kernel_call(kernel_name, call_args, cuda=False)
print(code.getvalue())
Expand Down
83 changes: 83 additions & 0 deletions extension_codecache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import functools
import getpass
import tempfile
import os
import re
import shlex
import subprocess

import torch
from torch._inductor.codecache import AsyncCompile, code_hash, get_path, get_lock_dir, get_hash, write, write_atomic

from concurrent.futures import Future

LOCK_TIMEOUT = 600
TORCHSIM_DUMP_PATH = os.environ.get('TORCHSIM_DUMP_PATH',
default = f"{tempfile.gettempdir()}/torchinductor_{getpass.getuser()}")
OutputPath = ''

def llvm_compile_command(input, output):
return re.sub(
r"[ \n]+",
" ",
f"""
llc -march=riscv64 -mattr=+m,+f,+d,+a,+c,+v -O2 {input} -o {output}
""",
).strip()

class LLVMCodeCache:
cache = dict()
clear = staticmethod(cache.clear) # Todo: Cache

@staticmethod
def _load_library(path):
pass

@classmethod
def load(cls, source_code):
global TORCHSIM_DUMP_PATH
write_path = os.path.join(TORCHSIM_DUMP_PATH, "tmp")
key, input_path = write(source_code, "ll", specified_dir=write_path)
output_path = input_path[:-2] + "s"

cmd = shlex.split(
llvm_compile_command(input_path, output_path)
)

from filelock import FileLock
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(cmd)
except subprocess.CalledProcessError as e:
assert(0) # Todo: make LLVMCompileError
else:
pass
return output_path

class CustomAsyncCompile(AsyncCompile):
def llvm(self, source_code):
def task():
global OutputPath
OutputPath = LLVMCodeCache.load(source_code)
return
future = self.submit(task)

def dummy_simulator(*args, **kwargs):
future.result()
os.system('echo "Running dummy simulator!"')
global OutputPath
print("OUTPUT PATH > ", OutputPath)
try:
with open(OutputPath, 'r') as file:
file_contents = file.read()

print("Assembly > ")
print(file_contents)
except FileNotFoundError:
print(f'{OutputPath} not found.')
except Exception as e:
print(f"Error while reading {OutputPath}.")
return dummy_simulator