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
136 changes: 129 additions & 7 deletions PyTorchSimFrontend/extension_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <c10/core/Allocator.h>

#include <torch/csrc/Device.h>
#include <torch/csrc/inductor/inductor_ops.h>
#include <c10/core/impl/DeviceGuardImplInterface.h>
#include <c10/core/MemoryFormat.h>
#include <c10/macros/Macros.h>
Expand All @@ -12,6 +13,8 @@
#include <ATen/native/Resize.h>
#include <ATen/EmptyTensor.h>
#include <ATen/core/GeneratorForPrivateuseone.h>
#include <ATen/NativeFunctions.h>
#include <ATen/native/CPUFallback.h>

static uint64_t op_counter = 0;
static uint64_t last_saved_value = 0;
Expand All @@ -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::TensorImpl>(
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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

zero_inplace_batching_rule는 무엇인가요?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분은 커밋에서 지워야 할 것 같습니다.

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<at::MemoryFormat> 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,
Expand Down Expand Up @@ -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<c10::TensorImpl>(
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<at::ScalarType> dtype_opt, c10::optional<at::Layout> layout_opt, c10::optional<at::Device> device_opt, c10::optional<bool> pin_memory_opt) {
op_counter += 1;

Expand All @@ -143,13 +237,41 @@ at::Tensor custom_empty(c10::IntArrayRef size, c10::optional<at::ScalarType> 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
Expand Down
28 changes: 10 additions & 18 deletions PyTorchSimFrontend/llvm_caller_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get_argv_idx 및 get_argv_idx의 도입 배경과 동작 방식을 간단히 알려주세요

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

현재 spike를 실행시킬때 validation_wrapper.c 파일에 선언하는 array의 size와 parameter value들이 저장된 path를 command line argument로 넣어주고 있습니다. LLVM kernel caller code를 만들때 현재 몇번째 argument를 사용해야하는지에 대한 counter 함수입니다.
현재 사용한 argument의 개수를 LLVMKernelCallerCodeGen() 에서 멤버 변수로 가지고 있고 array의 크기 또는 file의 path가 필요한 코드 위치에서 해당 함수를 호출하면 현재 사용해야 하는 argv index를 반환하고 increment 합니다.

self.arg_use_count += 1
return self.arg_use_count-1

def write_header(self):
self.writeline('#include <stdio.h>')
Expand All @@ -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)
Expand All @@ -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}')
Expand Down Expand Up @@ -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)

Expand All @@ -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()
Expand Down
Loading