diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/codegen.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..23a70d82e25e770021bcf1f66a6a10c9a10ae2ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/codegen.h @@ -0,0 +1,274 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +template +class PaddedBuffer; + +class TORCH_API CodeGen { + public: + class BufferArg; + class CallArg; + + template + CodeGen(StmtPtr stmt, Ts... ts) + : stmt_(std::move(stmt)), buffer_args_({BufferArg(ts)...}) {} + + CodeGen( + StmtPtr stmt, + std::vector buffer_args, + at::Device device = at::kCPU, + std::string kernel_func_name = "func"); + + virtual ~CodeGen() = default; + + StmtPtr stmt() const { + return stmt_; + } + + void set_stmt(StmtPtr s) { + stmt_ = std::move(s); + } + + void apply_mutator(IRMutator* mutator) { + stmt_ = stmt_->accept_mutator(mutator); + } + + void apply_visitor(IRVisitor* visitor) { + stmt_->accept(visitor); + } + + std::vector& buffer_args() { + return buffer_args_; + } + + const std::vector& buffer_args() const { + return buffer_args_; + } + + at::Device device() { + return device_; + } + + // This function returns the generated code as + // a string. + virtual std::string getCodeText( + const std::string& attr [[maybe_unused]] = "") { + return ""; + } + + // TODO: Figure out how to unify these call interfaces. + + /// Call a function with a vector of CallArgs, which are tagged + /// unions that properly type the arguments. + virtual void call(const std::vector& args) = 0; + + /// Call a function faster than a regular `call` by assuming that + /// the generated kernel already knows the type of the arguments, so + /// they can be type-punned with `void*`s. + virtual void call_raw(const std::vector& args) = 0; + + /// Call a function even faster than a regular call, by assuming + /// that the number of thread blocks can be derived from `numel` via + /// a simple division, rather than evaluating an expression. + virtual void call_with_numel(void** args, int64_t numel); + + virtual at::Tensor empty_strided( + c10::IntArrayRef size, + c10::IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt) { + return at::empty_strided( + size, stride, dtype_opt, layout_opt, device_opt, pin_memory_opt); + } + + const std::string& kernel_func_name() const { + return kernel_func_name_; + } + + void allocIntermediateBufs(); + + protected: + static void* argToPtr(const BufferArg& bufferArg, const CallArg& callArg); + + private: + StmtPtr stmt_; + std::vector buffer_args_; + at::Device device_ = at::kCPU; + std::string kernel_func_name_ = "func"; +}; + +class TORCH_API ExtCallMemoryReuse : public IRMutator { + static std::unordered_map makeExtCallFuncNameMap(); + static const std::unordered_map extCallFuncNameMap_; + + public: + explicit ExtCallMemoryReuse( + const std::vector& bufferArgs); + ~ExtCallMemoryReuse() override = default; + StmtPtr mutate(const ExternalCallPtr& v) override; + + private: + std::unordered_set bufferArgs_; +}; + +class CodeGen::BufferArg { + public: + BufferArg(const Tensor& tensor) : buf_(tensor.buf()) {} + BufferArg(const VarHandle& var) : var_(var.node()), isVar_(true) {} + BufferArg(const BufHandle& buf) : buf_(buf.node()) {} + BufferArg(BufPtr buf) : buf_(std::move(buf)) {} + + VarPtr var() const { + return isVar_ ? var_ : buf_->base_handle(); + } + + BufPtr buf() const { + return buf_; + } + + bool isVar() const { + return isVar_; + } + + Dtype dtype() const { + return isVar_ ? var_->dtype() : buf_->dtype(); + } + + private: + VarPtr var_ = nullptr; + BufPtr buf_ = nullptr; + bool isVar_ = false; +}; + +class CodeGen::CallArg { + public: + template + CallArg(const PaddedBuffer& buffer); + + template + CallArg(const std::vector& buffer) + : data_(const_cast(buffer.data())) {} + + CallArg(void* ptr) : data_(ptr) {} + +#define ARG_TYPE_CTOR(Type, Name) \ + CallArg(Type v) { \ + memcpy(buffer_, &v, sizeof(Type)); \ + data_ = (void*)buffer_; \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, ARG_TYPE_CTOR) +#undef ARG_TYPE_CTOR + + void* data() const { + return data_; + } + + CallArg(const CallArg& rhs) { + if (rhs.data_ == rhs.buffer_) { + memcpy(this->buffer_, rhs.buffer_, sizeof(rhs.buffer_)); + this->data_ = (void*)(this->buffer_); + } else { + this->data_ = rhs.data_; + } + } + + CallArg& operator=(const CallArg& rhs) { + if (this == &rhs) { + return *this; + } + if (rhs.data_ == rhs.buffer_) { + memcpy(this->buffer_, rhs.buffer_, sizeof(rhs.buffer_)); + this->data_ = (void*)(this->buffer_); + } else { + this->data_ = rhs.data_; + } + return *this; + } + +#define ARG_PTR_DEFINE(Type, Name) \ + Type* Name##Ptr() const { \ + TORCH_INTERNAL_ASSERT(data_ == (void*)buffer_); \ + return (Type*)data_; \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, ARG_PTR_DEFINE) +#undef ARG_PTR_DEFINE + + private: + void* data_; + // Regarding a scalar value, CallArg uses void**=&data_ to store it. But the + // bit width of a pointer is 32bit on a 32bit platform. It cannot store the + // scalar if the bit width of the scalar is larger than 32bit, such as double + // and long. Hence, we add 8 bytes buffer dedicated to storing the scalar + // value regardless its bit width is less or greater than 32bits. + char buffer_[8] = {0}; // 64bits +}; + +class RegisterCodeGenList { + public: + TORCH_API static RegisterCodeGenList& GetInstance(); + + using StmtFactoryMethod = std::function( + StmtPtr stmt, + const std::vector&, + at::Device device, + const std::string& kernel_func_name)>; + + TORCH_API StmtFactoryMethod FindStmtFactoryMethod(const std::string& name); + RegisterCodeGenList(const RegisterCodeGenList&) = delete; + RegisterCodeGenList& operator=(const RegisterCodeGenList&) = delete; + + private: + template + friend class RegisterCodeGen; + RegisterCodeGenList() = default; + TORCH_API void AddStmtFactoryMethod( + const std::string& name, + const StmtFactoryMethod& stmt_factory_method); + + std::unordered_map stmt_factory_methods_; +}; + +template +class RegisterCodeGen { + public: + explicit RegisterCodeGen(const std::string& name) { + RegisterCodeGenList& codegen_list = RegisterCodeGenList::GetInstance(); + codegen_list.AddStmtFactoryMethod( + name, + [](const StmtPtr& stmt, + const std::vector& params, + at::Device device, + const std::string& kernel_func_name) { + return std::make_unique( + stmt, params, device, kernel_func_name); + }); + } +}; + +TORCH_API std::unique_ptr CreateCodeGen( + const std::string& name, + StmtPtr stmt, + const std::vector& params, + at::Device device = at::kCPU, + const std::string& kernel_func_name = "func"); + +class TORCH_API GenericIntrinsicsExpander : public IRMutator { + protected: + ExprPtr mutate(const IntrinsicsPtr& v) override; +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..d00a933d67098f6dc70d676ba27f50c59c4cc920 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit::tensorexpr { + +class CppVarNameRewriter; + +// Generates C++ code from the IR. +// +// Vector operations are unrolled. +// For example: +// C[Ramp(0, 1, 3)] = A[Ramp(0, 2, 3)] + B[Ramp(0, 3, 3)]; +// is unrolled into: +// C[0] = A[0] + B[0]; +// C[1] = A[2] + B[3]; +// C[2] = A[4] + B[6]; +class TORCH_API CppPrinter : public IRPrinter { + public: + explicit CppPrinter(std::ostream* os); + ~CppPrinter() override; + + void printPrologue(); + + using IRPrinter::visit; + + // Binary expressions. + void visit(const ModPtr& /*v*/) override; + void visit(const MaxPtr& /*v*/) override; + void visit(const MinPtr& /*v*/) override; + + // Conditional expressions. + void visit(const CompareSelectPtr& /*v*/) override; + void visit(const IfThenElsePtr& /*v*/) override; + + // Tensor operations. + void visit(const AllocatePtr& /*v*/) override; + void visit(const FreePtr& /*v*/) override; + void visit(const LoadPtr& /*v*/) override; + void visit(const StorePtr& /*v*/) override; + + // Casts. + void visit(const CastPtr& /*v*/) override; + void visit(const BitCastPtr& /*v*/) override; + + // Calls. + void visit(const IntrinsicsPtr& /*v*/) override; + void visit(const ExternalCallPtr& /*v*/) override; + + // Vars. + void visit(const LetPtr& /*v*/) override; + void visit(const VarPtr& /*v*/) override; + + // Vector data types. + void visit(const RampPtr& /*v*/) override; + void visit(const BroadcastPtr& /*v*/) override; + + private: + int lane_; + std::unordered_map vector_vars_; +}; + +class TORCH_API CppCodeGen : public CodeGen { + public: + CppCodeGen( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::kCPU, + const std::string& kernel_func_name = "func"); + + ~CppCodeGen() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + + template + void operator()(const Ts&... ts) { + call(std::vector({CallArg(ts)...})); + } + + std::string getCodeText(const std::string& attr = "") override { + return oss_.str(); + } + + private: + void init(); + + std::ostream& os() { + return printer_->os(); + } + + std::ostringstream oss_; + std::unique_ptr printer_; + std::unique_ptr var_name_rewriter_; +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h new file mode 100644 index 0000000000000000000000000000000000000000..0d977fc7f1920907d1779793a6a2ef6884fe3c98 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::jit::tensorexpr { + +constexpr auto cpp_intrinsics_definition = R"( +namespace std { + +template , int> = 0> +T rsqrt(T v) { + return 1.0f / std::sqrt(v); +} + +template , int> = 0> +T frac(T v) { + T intpart; + return std::modf(v, &intpart); +} + +template +To bitcast(const From& v) { + assert(sizeof(To) == sizeof(From)); + To res; + std::memcpy(&res, &v, sizeof(From)); + return res; +} + +} // namespace std +)"; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..2c94659c6dab2386c8aaa140ca14bb70d4ca8f86 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h @@ -0,0 +1,291 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +// A class that analyzes the given program relevant for Cuda backends. +class CudaAnalysis : public IRVisitor { + public: + CudaAnalysis() { + gpu_block_extents_ = {alloc(1), alloc(1), alloc(1)}; + gpu_thread_extents_ = { + alloc(1), alloc(1), alloc(1)}; + } + bool is_buf_store_target(const BufPtr& buf) const { + return store_targets_.count(buf) > 0; + } + + const std::unordered_set& thread_local_bufs() const { + return thread_local_bufs_; + } + + const std::unordered_set& cross_block_bufs() const { + return cross_block_bufs_; + } + + const std::vector& gpu_block_extents() const { + return gpu_block_extents_; + } + + const std::vector& gpu_thread_extents() const { + return gpu_thread_extents_; + } + + private: + void visit(const StorePtr& v) override { + store_targets_.insert(v->buf()); + } + + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + void visit(const PlacementAllocatePtr& v) override; + void visit(const ForPtr& v) override; + + std::unordered_set store_targets_; + std::unordered_set thread_local_bufs_; + std::unordered_set cross_block_bufs_; + + std::vector gpu_block_extents_; + std::vector gpu_thread_extents_; +}; + +// An IRMutator that replaces binding loop options with Cuda metavars, and masks +// statements blocks which should execute with less reach than the launch +// parameter extent. +// +// We do this by segmenting each block into chunks which should have the same +// execution parameters, then if those params differ from the max mask each dim. +class GPUMetaVarRewriter : public IRMutator { + public: + explicit GPUMetaVarRewriter(const CudaAnalysis* cuda_analysis) + : cuda_analysis_(cuda_analysis) { + gpu_block_vars_ = { + alloc("blockIdx.x", kInt), + alloc("blockIdx.y", kInt), + alloc("blockIdx.z", kInt)}; + gpu_thread_vars_ = { + alloc("threadIdx.x", kInt), + alloc("threadIdx.y", kInt), + alloc("threadIdx.z", kInt)}; + + current_block_reach_ = { + alloc(1), alloc(1), alloc(1)}; + current_thread_reach_ = { + alloc(1), alloc(1), alloc(1)}; + } + + StmtPtr mutate(const ForPtr& v) override; + StmtPtr mutate(const BlockPtr& v) override; + + const std::vector& gpu_block_vars() const { + return gpu_block_vars_; + } + + const std::vector& gpu_thread_vars() const { + return gpu_thread_vars_; + } + + const std::vector& gpu_block_extents() const { + return cuda_analysis_->gpu_block_extents(); + } + + const std::vector& gpu_thread_extents() const { + return cuda_analysis_->gpu_thread_extents(); + } + + private: + // When processing a block, stores the contents of each sub-segment. + class Segment { + public: + void reset(bool mask) { + stmts_.clear(); + mask_ = mask; + } + + bool empty() const { + return stmts_.empty(); + } + + std::vector& stmts() { + return stmts_; + } + bool mask() { + return mask_; + } + + private: + std::vector stmts_; + bool mask_{true}; + }; + + // Returns true if the current execution scope is equivalent to the launch + // parameters. + bool isFullExtent(); + + std::vector gpu_block_vars_; + std::vector gpu_thread_vars_; + + std::vector current_block_reach_; + std::vector current_thread_reach_; + + const CudaAnalysis* cuda_analysis_; +}; + +// A class that overrides the underlying IRPrinter to produce Cuda C. +class CudaPrinter : public IRPrinter { + public: + explicit CudaPrinter( + std::ostream* os, + const CudaAnalysis* cuda_analysis, + bool has_random) + : IRPrinter(*os), cuda_analysis_(cuda_analysis) { + if (has_random) { + rand_func_ = alloc("rand", kHandle); + } + } + + void visit(const CastPtr& v) override; + void visit(const IntrinsicsPtr& v) override; + void visit(const ForPtr& v) override; + + void visit(const LoadPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const AtomicAddPtr& v) override; + void visit(const MaxPtr& v) override; + void visit(const MinPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + void visit(const LetPtr& v) override; + + void visit(const ExternalCallPtr& v) override; + + VarPtr rand_func() const { + return rand_func_; + } + + std::string dtypeToCppString(const Dtype& dtype) override; + + using IRPrinter::name_manager; + using IRPrinter::visit; + + private: + VarPtr rand_func_; + const CudaAnalysis* cuda_analysis_; + + void print_flat_alloc(const AllocatePtr& alloc); +}; + +// Construct Cuda C from the buffer and tensor input, and invoke the +// kernel when real arguments are provided. +class TORCH_CUDA_CU_API CudaCodeGen : public CodeGen { + public: + template + CudaCodeGen(StmtPtr stmt, Ts... ts) + : CodeGen( + stmt, + std::vector({BufferArg(ts)...}), + at::Device(at::kCUDA, at::cuda::current_device())) { + Initialize(); + } + + CudaCodeGen( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::Device(at::kCUDA, at::cuda::current_device()), + const std::string& kernel_func_name = "func") + : CodeGen(std::move(stmt), buffer_args, device, kernel_func_name) { + Initialize(); + } + + ~CudaCodeGen() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + void call_with_numel(void** args, int64_t numel) override; + + template + void operator()(const Ts&... ts) { + call(std::vector({CallArg(ts)...})); + } + + at::Tensor empty_strided( + c10::IntArrayRef size, + c10::IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt) override; + + const std::vector& gpu_block_extents() const { + return cuda_analysis_->gpu_block_extents(); + } + + const std::vector& gpu_thread_extents() const { + return cuda_analysis_->gpu_thread_extents(); + } + + std::string getCodeText(const std::string& attr = "") override { + return oss_.str(); + } + + private: + void Initialize(); + + void CompileToNVRTC(const std::string& code, const std::string& func_name); + + UniqueNameManager* name_manager() { + if (!printer_) { + throw std::runtime_error("Null IRPrinter is not expected"); + } + return printer_->name_manager(); + } + + std::ostream& os() { + return printer_->os(); + } + + std::ostringstream oss_; + std::unique_ptr printer_; + std::unique_ptr cuda_analysis_; + std::unique_ptr metavar_rewriter_; + std::unordered_set taken_func_names; + std::mutex eval_lock_; + CUfunction function_{nullptr}; + bool has_random_ = false; + int thread_block_size_ = -1; + + std::vector arg_pos_in_extents_; +#ifdef TORCH_ENABLE_LLVM + std::vector> block_extents_eval_; + std::vector> thread_extents_eval_; +#else + std::vector> block_extents_eval_; + std::vector> thread_extents_eval_; +#endif + + std::string GetUniqueFuncName(const std::string& func_prefix); +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h new file mode 100644 index 0000000000000000000000000000000000000000..d0ba0493e2eaf79e75179370279d05d37c7ab7e9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h @@ -0,0 +1,105 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::jit::tensorexpr { + +constexpr auto philox_random_string = R"( + +class Philox { +public: + __device__ inline Philox(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset) { + key.x = (unsigned int)seed; + key.y = (unsigned int)(seed >> 32); + counter = make_uint4(0, 0, 0, 0); + counter.z = (unsigned int)(subsequence); + counter.w = (unsigned int)(subsequence >> 32); + STATE = 0; + incr_n(offset / 4); + } + + __device__ inline unsigned long operator()() { + if(STATE == 0) { + uint4 counter_ = counter; + uint2 key_ = key; + for(int i = 0; i < 9; i++) { + counter_ = single_round(counter_, key_); + key_.x += (kPhilox10A); key_.y += (kPhilox10B); + } + output = single_round(counter_, key_); + incr(); + } + unsigned long ret; + switch(STATE) { + case 0: ret = output.x; break; + case 1: ret = output.y; break; + case 2: ret = output.z; break; + case 3: ret = output.w; break; + } + STATE = (STATE + 1) % 4; + return ret; + } + +private: + uint4 counter; + uint4 output; + uint2 key; + unsigned int STATE; + __device__ inline void incr_n(unsigned long long n) { + unsigned int nlo = (unsigned int)(n); + unsigned int nhi = (unsigned int)(n >> 32); + counter.x += nlo; + if (counter.x < nlo) + nhi++; + counter.y += nhi; + if (nhi <= counter.y) + return; + if (++counter.z) + return; + ++counter.w; + } + __device__ inline void incr() { + if (++counter.x) + return; + if (++counter.y) + return; + if (++counter.z) + return; + ++counter.w; + } + __device__ unsigned int mulhilo32(unsigned int a, unsigned int b, + unsigned int *result_high) { + *result_high = __umulhi(a, b); + return a*b; + } + + __device__ inline uint4 single_round(uint4 ctr, uint2 key) { + unsigned int hi0; + unsigned int hi1; + unsigned int lo0 = mulhilo32(kPhiloxSA, ctr.x, &hi0); + unsigned int lo1 = mulhilo32(kPhiloxSB, ctr.z, &hi1); + + uint4 ret = {hi1 ^ ctr.y ^ key.x, lo1, hi0 ^ ctr.w ^ key.y, lo0}; + return ret; + } + + static const unsigned long kPhilox10A = 0x9E3779B9; + static const unsigned long kPhilox10B = 0xBB67AE85; + static const unsigned long kPhiloxSA = 0xD2511F53; + static const unsigned long kPhiloxSB = 0xCD9E8D57; +}; + +// Inverse of 2^32. +#define M_RAN_INVM32 2.3283064e-10f +__device__ __inline__ float Uint32ToFloat(unsigned int x) { + return x * M_RAN_INVM32; +} + +)"; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h new file mode 100644 index 0000000000000000000000000000000000000000..bacdb882de08365383e5548ecdfd80f8253fa359 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h @@ -0,0 +1,330 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +class InterpValue { + public: + InterpValue() : dtype_(kInt) { + Intvalues.push_back(0); + } + + template + InterpValue(Dtype dtype, T v) : dtype_(dtype) { +#define TYPE_CASE(Type, Name) \ + if (dtype == k##Name) { \ + Name##values.push_back(v); \ + return; \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE) +#undef TYPE_CASE + throw unsupported_dtype(); + } + +#define VALUE_CTOR(Type, Name) \ + InterpValue(Type v) : dtype_(k##Name) { \ + Name##values.push_back(v); \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_CTOR) +#undef VALUE_CTOR + + explicit InterpValue(c10::quint8 v) : dtype_(kQUInt8) { + QUInt8values.emplace_back(v.val_); + } + + explicit InterpValue(c10::qint8 v) : dtype_(kQInt8) { + QInt8values.emplace_back(v.val_); + } + +#define VALUE_VEC_CTOR(Type, Name) \ + InterpValue(const std::vector& v) \ + : dtype_(Dtype(k##Name, v.size())), Name##values(v) {} + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_VEC_CTOR) + VALUE_VEC_CTOR(c10::quint8, QUInt8) + VALUE_VEC_CTOR(c10::qint8, QInt8) +#undef VALUE_VEC_CTOR + + template + T as() const; + + template + const std::vector& as_vec() const; + + int64_t intValue() const; + + Dtype dtype() const { + return dtype_; + } + + private: + Dtype dtype_; + +#define VALUE_STORAGE(Type, Name) std::vector Name##values; + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_STORAGE) + VALUE_STORAGE(c10::qint8, QInt8) + VALUE_STORAGE(c10::quint8, QUInt8) +#undef VALUE_STORAGE + void* ptr{nullptr}; +}; + +#define VALUE_AS_DISPATCH(Type, Name) \ + template <> \ + inline Type InterpValue::as() const { \ + if (dtype_ != k##Name) { \ + throw unsupported_dtype(); \ + } \ + return Name##values[0]; \ + } +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_AS_DISPATCH) +VALUE_AS_DISPATCH(c10::quint8, QUInt8) +VALUE_AS_DISPATCH(c10::qint8, QInt8) +#undef VALUE_AS_DISPATCH + +#define VALUE_AS_VEC_DISPATCH(Type, Name) \ + template <> \ + inline const std::vector& InterpValue::as_vec() const { \ + if (dtype_.scalar_type() != ScalarType::Name) { \ + throw unsupported_dtype(); \ + } \ + return Name##values; \ + } +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_AS_VEC_DISPATCH) +VALUE_AS_VEC_DISPATCH(c10::quint8, QUInt8) +VALUE_AS_VEC_DISPATCH(c10::qint8, QInt8) +#undef VALUE_AS_VEC_DISPATCH + +template +auto underlyingValue(Type x) { + return x; +} + +template <> +inline auto underlyingValue(c10::quint8 x) { + return x.val_; +} + +template <> +inline auto underlyingValue(c10::qint8 x) { + return x.val_; +} + +template +To raw_bitcast(const From& src) { + TORCH_CHECK(sizeof(To) == sizeof(From), "Invalid bitcast invocation"); + To storage; + std::memcpy(&storage, &src, sizeof(To)); + return storage; +} + +class SimpleIREvaluatorImpl; +class TORCH_API SimpleIREvaluator : public CodeGen { + public: + SimpleIREvaluator( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::kCPU, + const std::string& kernel_func_name = "func"); + + ~SimpleIREvaluator() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + + template + void operator()(const Ts&... ts) { + std::vector args({CallArg(ts)...}); + call(args); + } + + void bindVar(const VarPtr& v, const ExprPtr& e); + InterpValue value() const; + + private: + void bindArg(const BufferArg& buf, void* data); + void expand_intrinsics() { + GenericIntrinsicsExpander intrinsics_expander; + apply_mutator(&intrinsics_expander); + } + + std::unique_ptr impl_; +}; + +template +class ExprEval { + public: + using BufferArg = CodeGen::BufferArg; + using CallArg = CodeGen::CallArg; + + template + ExprEval(const ExprHandle& expr, Ts... ts) + : ExprEval(expr, {BufferArg(ts)...}) {} + + ExprEval(const ExprHandle& expr, const std::vector& buffer_args) + : dtype_(expr.dtype()) { + std::vector buffer_args_extended = buffer_args; + BufHandle ret_buf("ret_val", {1}, dtype_); + std::vector indices; + ExprHandle zero = IntImm::make(0); + indices.reserve(ret_buf.ndim()); + for (size_t i = 0; i < ret_buf.ndim(); i++) { + indices.push_back(zero); + } + StmtPtr store_stmt = Store::make(ret_buf, indices, expr); + buffer_args_extended.emplace_back(ret_buf); + codegen_.reset(new CodeGenType(store_stmt, buffer_args_extended)); + } + + template + void operator()(Ts... ts) { + call(ts...); + } + + void operator()(const std::vector& call_args) { + call(call_args); + } + + void bindVar(VarPtr v, ExprPtr e) { + codegen_->bindVar(v, e); + } + + void bindVar(const VarHandle& v, const ExprHandle& e) { + codegen_->bindVar(v.node(), e.node()); + } + + template + void call(Ts... ts) { + call({CallArg(ts)...}); + } + + void call(const std::vector& call_args) { + std::vector call_args_extended = call_args; + switch (dtype_.scalar_type()) { +#define TYPE_CASE(Type, Name) \ + case ScalarType::Name: { \ + std::vector ret_val_arg(1); \ + call_args_extended.emplace_back(ret_val_arg); \ + codegen_->call(call_args_extended); \ + ret_value_ = InterpValue(ret_val_arg[0]); \ + } break; + AT_FORALL_SCALAR_TYPES_AND2(Half, BFloat16, TYPE_CASE); + TYPE_CASE(c10::quint8, QUInt8); + TYPE_CASE(c10::qint8, QInt8); +#undef TYPE_CASE + case ScalarType::Bool: { + std::vector ret_val_arg(1); + call_args_extended.emplace_back(ret_val_arg.data()); + codegen_->call(call_args_extended); + ret_value_ = InterpValue((bool)ret_val_arg[0]); + } break; + default: + throw unsupported_dtype(); + } + } + + void call_raw(const std::vector& args) { + std::vector args_extended = args; + switch (dtype_.scalar_type()) { +#define TYPE_CASE(Type, Name) \ + case ScalarType::Name: { \ + std::vector ret_val_arg(1); \ + args_extended.push_back(ret_val_arg.data()); \ + codegen_->call_raw(args_extended); \ + ret_value_ = InterpValue(ret_val_arg[0]); \ + } break; + AT_FORALL_SCALAR_TYPES_AND2(Half, BFloat16, TYPE_CASE); + TYPE_CASE(c10::quint8, QUInt8); + TYPE_CASE(c10::qint8, QInt8); +#undef TYPE_CASE + case ScalarType::Bool: { + std::vector ret_val_arg(1); + args_extended.push_back(ret_val_arg.data()); + codegen_->call_raw(args_extended); + ret_value_ = InterpValue((bool)ret_val_arg[0]); + } break; + default: + throw unsupported_dtype(); + } + } + + template + T value(const std::vector& args) { + call_raw(args); + return ret_value_.as(); + } + + template + T value(Ts... ts) { + call(std::forward(ts)...); + return ret_value_.as(); + } + + Dtype dtype() { + return dtype_; + } + + private: + Dtype dtype_; + std::unique_ptr codegen_; + InterpValue ret_value_; +}; + +// Evaluates the given expression and returns an int64_t value if the result of +// the given expression is int64_t. +std::optional evalInt(ExprPtr e); + +// Substitutes the given vars with their corresponding expressions in the input +// expression. +inline ExprPtr Substitute(const ExprPtr& expr, const VarMapping& var_mapping) { + VarSubMutator var_sub(var_mapping); + return expr->accept_mutator(&var_sub); +} + +// Substitutes the given vars with their corresponding expressions in the input +// statement. +inline StmtPtr Substitute(const StmtPtr& stmt, const VarMapping& var_mapping) { + VarSubMutator var_sub(var_mapping); + return stmt->accept_mutator(&var_sub); +} + +// Creates a clone of the input expression and substitutes the given vars with +// their corresponding expressions in the clone. +// NOTE: This works because cloning reuses variables and does not create new +// ones, and `VarMapping` input has variables as the key. +inline ExprPtr SubstituteInClone( + const ExprPtr& expr, + const VarMapping& var_mapping) { + VarSubMutator var_sub(var_mapping); + return Expr::clone(expr)->accept_mutator(&var_sub); +} + +// Creates a clone of the input statement and substitutes the given vars with +// their corresponding expressions in the clone. +// NOTE: This works because cloning reuses variables and does not create new +// ones, and `VarMapping` input has variables as the key. +inline StmtPtr SubstituteInClone( + const StmtPtr& stmt, + const VarMapping& var_mapping) { + VarSubMutator var_sub(var_mapping); + return Stmt::clone(stmt)->accept_mutator(&var_sub); +} + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h new file mode 100644 index 0000000000000000000000000000000000000000..a131ec071c32c3a6731691fd1f2328559d10ab99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h @@ -0,0 +1,90 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +// Forward declarations of types + +namespace torch::jit::tensorexpr { +class Expr; +class Stmt; +} // namespace torch::jit::tensorexpr + +// Forward declarations of functions +namespace std { +TORCH_API std::string to_string( + const torch::jit::tensorexpr::ExprPtr& /*expr*/); +TORCH_API std::string to_string( + const torch::jit::tensorexpr::StmtPtr& /*stmt*/); +} // namespace std + +namespace torch::jit::tensorexpr { + +class unsupported_dtype : public std::runtime_error { + public: + explicit unsupported_dtype() : std::runtime_error("UNSUPPORTED DTYPE") {} + explicit unsupported_dtype(const std::string& err) + : std::runtime_error("UNSUPPORTED DTYPE: " + err) {} +}; + +class out_of_range_index : public std::runtime_error { + public: + explicit out_of_range_index() : std::runtime_error("OUT OF RANGE INDEX") {} + explicit out_of_range_index(const std::string& err) + : std::runtime_error("OUT OF RANGE INDEX: " + err) {} +}; + +class unimplemented_lowering : public std::runtime_error { + public: + explicit unimplemented_lowering() + : std::runtime_error("UNIMPLEMENTED LOWERING") {} + explicit unimplemented_lowering(const ExprPtr& expr) + : std::runtime_error("UNIMPLEMENTED LOWERING: " + std::to_string(expr)) {} + explicit unimplemented_lowering(const StmtPtr& stmt) + : std::runtime_error("UNIMPLEMENTED LOWERING: " + std::to_string(stmt)) {} +}; + +class malformed_input : public std::runtime_error { + public: + explicit malformed_input() : std::runtime_error("MALFORMED INPUT") {} + explicit malformed_input(const std::string& err) + : std::runtime_error("MALFORMED INPUT: " + err) {} + explicit malformed_input(const ExprPtr& expr) + : std::runtime_error("MALFORMED INPUT: " + std::to_string(expr)) {} + explicit malformed_input(const std::string& err, const ExprPtr& expr) + : std::runtime_error( + "MALFORMED INPUT: " + err + " - " + std::to_string(expr)) {} + explicit malformed_input(const StmtPtr& stmt) + : std::runtime_error("MALFORMED INPUT: " + std::to_string(stmt)) {} + explicit malformed_input(const std::string& err, const StmtPtr& stmt) + : std::runtime_error( + "MALFORMED INPUT: " + err + " - " + std::to_string(stmt)) {} +}; + +class malformed_ir : public std::runtime_error { + public: + explicit malformed_ir() : std::runtime_error("MALFORMED IR") {} + explicit malformed_ir(const std::string& err) + : std::runtime_error("MALFORMED IR: " + err) {} + explicit malformed_ir(const ExprPtr& expr) + : std::runtime_error("MALFORMED IR: " + std::to_string(expr)) {} + explicit malformed_ir(const std::string& err, const ExprPtr& expr) + : std::runtime_error( + "MALFORMED IR: " + err + " - " + std::to_string(expr)) {} + explicit malformed_ir(const StmtPtr& stmt) + : std::runtime_error("MALFORMED IR: " + std::to_string(stmt)) {} + explicit malformed_ir(const std::string& err, const StmtPtr& stmt) + : std::runtime_error( + "MALFORMED IR: " + err + " - " + std::to_string(stmt)) {} +}; + +TORCH_API std::string buildErrorMessage(const std::string& s = ""); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h new file mode 100644 index 0000000000000000000000000000000000000000..40ba9800b9ce9eb06ddcf9bbdc8384e6480dd2ec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h @@ -0,0 +1,498 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** + * This file implements the core classes for Tensor Expressions. + * + * The structure of the expressions is inspired by Halide/TVM IR. + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +enum IRNodeType { + kPrimitive, + kAdd, + kSub, + kMul, + kDiv, + kMod, + kMax, + kMin, + kAnd, + kOr, + kLshift, + kRshift, + kXor, + kCompareSelect, + kCast, + kBitCast, + kOther, +}; + +// The common base between all expression node. +class TORCH_API Expr : public std::enable_shared_from_this { + public: + explicit Expr(Dtype dtype, IRNodeType expr_type = kOther) + : dtype_(dtype), expr_type_(expr_type) {} + virtual ~Expr() = default; + Dtype dtype() const { + return dtype_; + } + virtual void accept(IRVisitor* visitor) = 0; + virtual ExprPtr accept_mutator(IRMutator* mutator) = 0; + + IRNodeType expr_type() const { + return expr_type_; + } + // Is this a fixed (constant) immediate value. + virtual bool isConstant() const { + return false; + } + + void set_dtype(Dtype dtype) { + dtype_ = dtype; + } + + /* + * Make a deep copy of the given expression. + * + * All sub-expressions inside the given expressions are also cloned. Note + * that the variables are not deep-copied since they are immutable. + */ + static ExprPtr clone(const ExprPtr& s); + + protected: + std::shared_ptr getptr() { + return shared_from_this(); + } + + private: + Dtype dtype_; + IRNodeType expr_type_; +}; + +// A CRTP pattern to accept visitors for children class, +// and dispatch back to the children. +template +class ExprNode : public Base { + public: + using ExprNodeBase = ExprNode; + void accept(IRVisitor* visitor) override { + visitor->visit(static_to(Base::getptr())); + } + ExprPtr accept_mutator(IRMutator* mutator) override; + // pass the constructor to the base class + using Base::Base; +}; + +// A wrapper object to the underlying ExprNode. +// Also serves the primary way to build and operate on other expressions. +class TORCH_API ExprHandle { + public: + ExprHandle() = default; + explicit ExprHandle(ExprPtr node) : base_expr_node_(std::move(node)) {} + + ExprPtr node() { + return base_expr_node_; + } + + ExprPtr node() const { + return base_expr_node_; + } + + bool empty() const { + return base_expr_node_ == nullptr; + } + +#define IMM_EXPR_DECLARE(Type, Name) ExprHandle(Type v); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_EXPR_DECLARE) +#undef IMM_EXPR_DECLARE + + template + NodePtr AsNode() { + return to(this->node()); + } + + template + NodePtr AsNode() const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + return const_cast(this)->AsNode(); + } + + Dtype dtype() const { + return node()->dtype(); + } + + // Handling the math operators. + ExprHandle operator+(const ExprHandle& other) const; + ExprHandle operator-(const ExprHandle& other) const; + ExprHandle operator*(const ExprHandle& other) const; + ExprHandle operator/(const ExprHandle& other) const; + ExprHandle operator%(const ExprHandle& other) const; + ExprHandle operator==(const ExprHandle& other) const; + ExprHandle operator!=(const ExprHandle& other) const; + ExprHandle operator>(const ExprHandle& other) const; + ExprHandle operator>=(const ExprHandle& other) const; + ExprHandle operator<(const ExprHandle& other) const; + ExprHandle operator<=(const ExprHandle& other) const; + ExprHandle operator&(const ExprHandle& other) const; + ExprHandle operator|(const ExprHandle& other) const; + ExprHandle operator&&(const ExprHandle& other) const; + ExprHandle operator||(const ExprHandle& other) const; + ExprHandle operator^(const ExprHandle& other) const; + ExprHandle operator<<(const ExprHandle& other) const; + ExprHandle operator>>(const ExprHandle& other) const; + + private: + ExprPtr base_expr_node_ = nullptr; +}; + +// The underlying representation node to a Var. +// Currently, each Var object represents a unique variable, even though the +// names might be the same. We should consider add a unique_name as well. +class TORCH_API Var : public ExprNode { + public: + static ExprHandle make(const std::string& name_hint, Dtype dtype) { + return ExprHandle(alloc(name_hint, dtype)); + } + static ExprHandle make(Dtype dtype) { + return ExprHandle(alloc("", dtype)); + } + + // TODO: unique_name + const std::string& name_hint() const { + return name_hint_; + } + + void set_name_hint(const std::string& name) { + name_hint_ = name; + } + + void set_name_hint(std::string&& name) { + name_hint_ = std::move(name); + } + + Var(std::string name_hint, Dtype dtype) + : ExprNodeBase(dtype, kPrimitive), name_hint_(std::move(name_hint)) {} + + private: + std::string name_hint_; +}; + +TORCH_API std::vector make_contiguous_strides( + const std::vector& dims); +TORCH_API std::vector make_channels_last_strides( + const std::vector& dims); + +class TORCH_API Buf : public ExprNode { + public: + static BufHandle make(const std::vector& dims, Dtype dtype); + + static BufHandle make( + const std::string& name_hint, + const std::vector& dims, + const std::vector& strides, + Dtype dtype); + + static BufHandle make( + const std::string& name_hint, + const std::vector& dims, + Dtype dtype, + std::optional initializer = std::nullopt, + const std::optional>& strides = std::nullopt, + std::optional qscale = std::nullopt, + std::optional qzero = std::nullopt); + + // TODO: unique_name + VarPtr base_handle() const { + return base_handle_; + } + void set_base_handle(VarPtr base_handle) { + base_handle_ = std::move(base_handle); + } + + const std::string& name_hint() const { + return base_handle_->name_hint(); + } + void set_name_hint(const std::string& name_hint) { + base_handle_->set_name_hint(name_hint); + } + + Buf(const std::string& name_hint, + const std::vector& dims, + Dtype dtype, + ExprPtr initializer = nullptr, + std::optional> strides = std::nullopt, + ExprPtr qscale = nullptr, + ExprPtr qzero = nullptr) + : Buf(alloc(name_hint, kHandle), + dims, + dtype, + std::move(initializer), + std::move(strides), + std::move(qscale), + std::move(qzero)) {} + + Buf(const VarPtr& var, + std::vector dims, + Dtype dtype, + ExprPtr initializer = nullptr, + std::optional> strides = std::nullopt, + ExprPtr qscale = nullptr, + ExprPtr qzero = nullptr); + + size_t ndim() const { + return dims_.size(); + } + ExprPtr dim(size_t index) const { + if (index >= ndim()) { + throw out_of_range_index(); + } + return dims_[index]; + } + std::vector dims() const { + return dims_; + } + void set_dims(std::vector dims) { + dims_ = std::move(dims); + } + + std::vector strides() const { + return strides_; + } + + void set_strides(std::vector strides) { + strides_ = std::move(strides); + } + + ExprPtr initializer() const { + return initializer_; + } + + ExprPtr qzero() const { + return qzero_; + } + + ExprPtr qscale() const { + return qscale_; + } + + void set_qzero(ExprPtr qzero) { + qzero_ = std::move(qzero); + } + + void set_qscale(ExprPtr qscale) { + qscale_ = std::move(qscale); + } + + bool hasConstantDims() const { + for (const auto& d : dims_) { + if (!d->isConstant()) { + return false; + } + } + return true; + } + + bool is_contiguous( + at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) const; + + // The channels-last 1d can benefit the performance of some operators like + // conv1d. But the MemoryFormat enum has not covered this layout yet. Hence, + // we abstract a dedicated function to check channels-last 1d contiguous. + // + // Channels-last 1d: + // dims: n c l + // strides(nlc): c*l 1 c + bool is_channels_last_1d_contiguous() const { + if (dims_.size() != 3) { + return false; + } + return is_stride_one(1) && is_cont_with(2, 1) && is_cont_with(0, 2); + } + + private: + bool is_cont_with(int cur_dim, int adjacent_dim) const; + bool is_stride_one(int cur_dim) const; + + VarPtr base_handle_; + std::vector dims_; + std::vector strides_; + ExprPtr initializer_; + // qscale_ and qzero_ are used only for quantized dtypes Bufs: kQUInt8, kQInt8 + ExprPtr qscale_; + ExprPtr qzero_; +}; + +class TORCH_API BufHandle : public ExprHandle { + public: + BufHandle( + const std::string& name_hint, + const std::vector& dims, + Dtype dtype) + : ExprHandle(Buf::make(name_hint, dims, dtype)) {} + + BufHandle( + const std::string& name_hint, + const std::vector& dims, + const std::vector& strides, + Dtype dtype) + : ExprHandle(Buf::make(name_hint, dims, strides, dtype)) {} + + BufHandle(const std::vector& dims, Dtype dtype) + : ExprHandle(Buf::make("_", dims, dtype)) {} + + explicit BufHandle(Dtype dtype) : ExprHandle(Buf::make("_", {}, dtype)) {} + + explicit BufHandle(BufPtr node) : ExprHandle(std::move(node)) {} + BufPtr node() const { + return static_to(ExprHandle::node()); + } + BufPtr node() { + return static_to(ExprHandle::node()); + } + + template + inline ExprHandle load(const Ts&... ts) const; + + template + inline ExprHandle load(const std::vector& args) const; + + inline ExprHandle load(const std::vector& args) const; + + StorePtr store(const std::vector& args, const ExprHandle& val) + const; + + bool operator==(const BufHandle& other) const { + return this->node() == other.node(); + } + bool operator!=(const BufHandle& other) const { + return !(*this == other); + } + + const std::string& name_hint() const { + return this->node()->name_hint(); + } + + bool empty() const { + return (this->node() == nullptr); + } + + size_t ndim() const { + return node()->ndim(); + } + + std::vector dims() const; + + ExprHandle dim(size_t index) const { + return ExprHandle(node()->dim(index)); + } + + bool is_contiguous( + at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) const { + return node()->is_contiguous(memory_format); + } + + bool is_channels_last_1d_contiguous() const { + return node()->is_channels_last_1d_contiguous(); + } +}; + +// An expression to construct the underlying variable node. +// Note: do not store any info here, since it is often possible to slice this +// object. For example: VarHandle x('x'); ExprHandle x2 = x; +class TORCH_API VarHandle : public ExprHandle { + public: + // Creates an empty VarHandle whose base Var is set to nullptr. + VarHandle() = default; + + explicit VarHandle(Dtype dtype) : ExprHandle(Var::make(dtype)) {} + + VarHandle(const std::string& name_hint, Dtype dtype) + : ExprHandle(Var::make(name_hint, dtype)) {} + + explicit VarHandle(VarPtr node) : ExprHandle(std::move(node)) {} + + VarPtr node() const { + return static_to(ExprHandle::node()); + } + bool operator==(const VarHandle& other) const { + return this->node() == other.node(); + } + bool operator!=(const VarHandle& other) const { + return !(*this == other); + } + + const std::string& name_hint() const { + return this->node()->name_hint(); + } + bool empty() const { + return (this->node() == nullptr); + } +}; + +template +ExprPtr ExprNode::accept_mutator(IRMutator* mutator) { + return mutator->mutate(static_to(Base::getptr())); +} + +inline bool same_node(const ExprHandle& expr1, const ExprHandle& expr2) { + return expr1.AsNode() == expr2.AsNode(); +} + +TORCH_API ExprHandle sin(const ExprHandle& v); +TORCH_API ExprHandle cos(const ExprHandle& v); +TORCH_API ExprHandle tan(const ExprHandle& v); +TORCH_API ExprHandle asin(const ExprHandle& v); +TORCH_API ExprHandle acos(const ExprHandle& v); +TORCH_API ExprHandle atan(const ExprHandle& v); +TORCH_API ExprHandle sinh(const ExprHandle& v); +TORCH_API ExprHandle cosh(const ExprHandle& v); +TORCH_API ExprHandle tanh(const ExprHandle& v); +TORCH_API ExprHandle sigmoid(const ExprHandle& v); +TORCH_API ExprHandle exp(const ExprHandle& v); +TORCH_API ExprHandle expm1(const ExprHandle& v); +TORCH_API ExprHandle abs(const ExprHandle& v); +TORCH_API ExprHandle log(const ExprHandle& v); +TORCH_API ExprHandle fast_tanh(const ExprHandle& v); +TORCH_API ExprHandle fast_sigmoid(const ExprHandle& v); +TORCH_API ExprHandle fast_log(const ExprHandle& v); +TORCH_API ExprHandle log_vml(const ExprHandle& v); +TORCH_API ExprHandle log2(const ExprHandle& v); +TORCH_API ExprHandle log10(const ExprHandle& v); +TORCH_API ExprHandle log1p(const ExprHandle& v); +TORCH_API ExprHandle erf(const ExprHandle& v); +TORCH_API ExprHandle erfc(const ExprHandle& v); +TORCH_API ExprHandle sqrt(const ExprHandle& v); +TORCH_API ExprHandle rsqrt(const ExprHandle& v); +TORCH_API ExprHandle ceil(const ExprHandle& v); +TORCH_API ExprHandle floor(const ExprHandle& v); +TORCH_API ExprHandle round(const ExprHandle& v); +TORCH_API ExprHandle trunc(const ExprHandle& v); +TORCH_API ExprHandle frac(const ExprHandle& v); +TORCH_API ExprHandle lgamma(const ExprHandle& v); +TORCH_API ExprHandle atan2(const ExprHandle& v1, const ExprHandle& v2); +TORCH_API ExprHandle pow(const ExprHandle& v1, const ExprHandle& v2); +TORCH_API ExprHandle fmod(const ExprHandle& v1, const ExprHandle& v2); +TORCH_API ExprHandle remainder(const ExprHandle& v1, const ExprHandle& v2); +TORCH_API ExprHandle isnan(const ExprHandle& v1); +TORCH_API ExprHandle Relu(const ExprHandle& v1); + +TORCH_API ExprHandle +ifThenElse(const ExprHandle& c, const ExprHandle& t, const ExprHandle& f); + +TORCH_API ExprHandle expr_to_vec(const ExprHandle& v, int lanes); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..9d2ff4b04b8c68e1d7c2071860c2c5938bed58ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h @@ -0,0 +1,116 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#define FOR_ALL_EXTERNAL_FUNCTIONS(_) \ + _(nnc_aten_adaptive_avg_pool2d) \ + _(nnc_aten_addmm) \ + _(nnc_aten_conv2d) \ + _(nnc_aten_conv1d) \ + _(nnc_aten_conv1d_out) \ + _(nnc_aten_dequantize) \ + _(nnc_aten_dequantize_out) \ + _(nnc_aten_embedding) \ + _(nnc_aten_matmul) \ + _(nnc_aten_mv) \ + _(nnc_aten_mm) \ + _(nnc_aten_mean) \ + _(nnc_aten_max_red) \ + _(nnc_aten_max_red_out) \ + _(nnc_aten_quantized_conv1d) \ + _(nnc_aten_quantized_conv1d_out) \ + _(nnc_aten_quantized_conv2d) \ + _(nnc_aten_quantized_conv2d_out) \ + _(nnc_aten_quantized_conv2d_relu) \ + _(nnc_aten_quantized_conv2d_relu_out) \ + _(nnc_aten_quantized_linear) \ + _(nnc_aten_quantized_linear_out) \ + _(nnc_aten_quantized_linear_relu) \ + _(nnc_aten_quantized_add) \ + _(nnc_aten_quantized_cat) \ + _(nnc_aten_quantized_mul) \ + _(nnc_aten_quantized_mul_out) \ + _(nnc_aten_quantized_mul_scalar) \ + _(nnc_aten_quantized_mul_scalar_out) \ + _(nnc_aten_quantized_relu) \ + _(nnc_aten_quantized_sigmoid) \ + _(nnc_aten_quantized_sigmoid_out) \ + _(nnc_aten_quantize_per_tensor) \ + _(nnc_aten_quantize_per_tensor_out) \ + _(nnc_aten_triangular_solve) \ + _(nnc_aten_upsample_nearest2d) \ + _(nnc_aten_upsample_nearest2d_out) \ + _(nnc_prepacked_conv2d_clamp_run) \ + _(nnc_prepacked_linear_clamp_run) + +#define DECLARE_EXTERNAL_FUNCTION(NAME) \ + TORCH_API void NAME( \ + int64_t bufs_num, \ + void** buf_data, \ + int64_t* buf_ranks, \ + int64_t* buf_dims, \ + int64_t* buf_strides, \ + int8_t* buf_dtypes, \ + int64_t args_num, \ + int64_t* extra_args); + +namespace torch::jit::tensorexpr { +struct QIData final { + double scale; + int64_t zero; + c10::ScalarType scalarType; +}; +std::vector constructTensors( + int64_t bufs_num, + void** buf_data, + int64_t* buf_ranks, + int64_t* buf_dims, + int64_t* buf_strides, + int8_t* buf_dtypes, + std::optional>> qdataArg = + std::nullopt); + +std::vector constructTensors2( + int64_t bufs_in_num, + void** buf_data, + int64_t* buf_ranks, + int64_t* buf_dims, + int64_t* buf_strides, + int8_t* buf_dtypes, + std::optional>> qdataArg = + std::nullopt, + size_t bufs_out_num = 0); + +#ifdef C10_MOBILE +extern "C" { +#endif +void DispatchParallel( + int8_t* func, + int64_t start, + int64_t stop, + int8_t* packed_data) noexcept; + +FOR_ALL_EXTERNAL_FUNCTIONS(DECLARE_EXTERNAL_FUNCTION) +#if AT_MKLDNN_ENABLED() +DECLARE_EXTERNAL_FUNCTION(nnc_mkldnn_prepacked_conv_run) +#endif + +TORCH_API void nnc_aten_free(size_t bufs_num, void** ptrs) noexcept; + +#ifdef C10_MOBILE +} // extern "C" +#endif + +} // namespace torch::jit::tensorexpr + +#undef DECLARE_EXTERNAL_FUNCTION + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h new file mode 100644 index 0000000000000000000000000000000000000000..0977fd06b09fa72ac98d15a01b71f5abd841af96 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +#ifdef C10_MOBILE +extern "C" { +#endif +void DispatchParallel( + int8_t* func, + int64_t start, + int64_t stop, + int8_t* packed_data) noexcept; + +TORCH_API void nnc_aten_free(size_t bufs_num, void** ptrs) noexcept; + +#ifdef C10_MOBILE +} // extern "C" +#endif + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..d638dfa5911bd01af113d94cba196825f61fc532 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h @@ -0,0 +1,62 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +// The external functions that could be called from NNC must have the same +// signature defined by `NNCExternalFunction`. +// +// Why this signature? +// It was picked for two reasons: 1) it should be generic enough to represent +// most of the ops we might want to call, 2) it should be possible to generate a +// code for this call in LLVM codegen. +// The first 5 parameters allow to pass any number of contiguous CPU tensors in +// case we need to run aten ops (TODO: support different devices). The first +// buffer in the array is assumed to be the output buffer. We couldn't use +// `at::Tensor` (or `c10::IValue`) type there directly as it would mean that +// we'd need to declare it in LLVM codegen in LLVM IR form, which would be very +// cumbersome and hard to maintain. Note that the dimensions of all tensors are +// concatenated into a single array buf_dims. We do not need to pass its length, +// since it can be deduced from total number of buffers and their ranks. +// +// The last 2 arguments allow to pass any non-tensor arguments encoded as an +// array of int64_t values. The way they are encoded is not specified and could +// be arbitrary - whatever the most convenient for the specific bridge function +// is. +// +// The bridge functions must not throw exceptions - properly propagating them +// from the generated code is too cumbersome, and thus all calls to functions +// that could throw must be wrapped with try-catch blocks. +using NNCExternalFunction = void (*)( + int64_t bufs_num, + void** buf_data, + int64_t* buf_ranks, + int64_t* buf_dims, + int64_t* buf_strides, + int8_t* buf_dtypes, + int64_t args_num, + int64_t* extra_args); + +// Return a global map "function-name" -> "function-pointer" for all registered +// in NNC external functions +TORCH_API std::unordered_map& +getNNCFunctionRegistry(); + +// To register a new external function in NNC one needs to create an instance of +// this struct +struct RegisterNNCExternalFunction { + RegisterNNCExternalFunction(const std::string& name, NNCExternalFunction fn) { + getNNCFunctionRegistry()[name] = fn; + } +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h new file mode 100644 index 0000000000000000000000000000000000000000..c58dff538fab2fc7aafd5c3cc4a361703c921fda --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h @@ -0,0 +1,130 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +namespace torch::jit::tensorexpr { + +template +using NodePtr = std::shared_ptr; + +template +NodePtr to(const NodePtr& x) { + return std::dynamic_pointer_cast(x); +} + +template +NodePtr static_to(NodePtr x) { + return std::static_pointer_cast(x); +} + +template +NodePtr alloc(Args&&... args) { + return std::make_shared(std::forward(args)...); +} + +class Buf; +class Expr; +class Stmt; +class Var; + +using BufPtr = NodePtr; +using ExprPtr = NodePtr; +using StmtPtr = NodePtr; +using VarPtr = NodePtr; + +class ExprHandle; +class VarHandle; +class BufHandle; + +class Add; +class And; +class BitCast; +class Broadcast; +class Cast; +class CompareSelect; +class Div; +class IfThenElse; +class Intrinsics; +class Let; +class Load; +class Lshift; +class Max; +class MaxTerm; +class Min; +class MinTerm; +class Mod; +class Mul; +class Or; +class Polynomial; +class Ramp; +class ReduceOp; +class RoundOff; +class Rshift; +class Store; +class Sub; +class Term; +class Xor; +using AddPtr = NodePtr; +using AndPtr = NodePtr; +using BitCastPtr = NodePtr; +using BroadcastPtr = NodePtr; +using CastPtr = NodePtr; +using CompareSelectPtr = NodePtr; +using DivPtr = NodePtr
; +using IfThenElsePtr = NodePtr; +using IntrinsicsPtr = NodePtr; +using LetPtr = NodePtr; +using LoadPtr = NodePtr; +using LshiftPtr = NodePtr; +using MaxPtr = NodePtr; +using MaxTermPtr = NodePtr; +using MinPtr = NodePtr; +using MinTermPtr = NodePtr; +using ModPtr = NodePtr; +using MulPtr = NodePtr; +using OrPtr = NodePtr; +using PolynomialPtr = NodePtr; +using RampPtr = NodePtr; +using ReduceOpPtr = NodePtr; +using RoundOffPtr = NodePtr; +using RshiftPtr = NodePtr; +using StorePtr = NodePtr; +using SubPtr = NodePtr; +using TermPtr = NodePtr; +using XorPtr = NodePtr; + +class Allocate; +class AtomicAdd; +class Block; +class Cond; +class ExternalCall; +class ExternalCallWithAlloc; +class For; +class Free; +class FreeExt; +class PlacementAllocate; +class SyncThreads; +using AllocatePtr = NodePtr; +using AtomicAddPtr = NodePtr; +using BlockPtr = NodePtr; +using CondPtr = NodePtr; +using ExternalCallPtr = NodePtr; +using ExternalCallWithAllocPtr = NodePtr; +using ForPtr = NodePtr; +using FreePtr = NodePtr; +using FreeExtPtr = NodePtr; +using PlacementAllocatePtr = NodePtr; +using SyncThreadsPtr = NodePtr; + +#define IMM_DECLARE(Type, Name) \ + class Name##Imm; \ + using Name##ImmPtr = NodePtr; +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_DECLARE) +#undef IMM_DECLARE + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h new file mode 100644 index 0000000000000000000000000000000000000000..27427893f3f71dad8da98a25080b7e17995a636c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h @@ -0,0 +1,116 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::tensorexpr { + +// Optimize aten::cat ops in the given subgraph. +// +// Moving users of cat to its inputs. +// Cat ops get lowered into multiple loops, one per input. When the result +// of cat is used by some other op, it results in a situation where inlining +// of cat does not happen. This in turn results in intermediate buffers +// being created for the result of cat, since it is not inlined. +// +// For example, consider the following graph: +// graph(%x : Float(10, strides=[1], device=cpu), +// %y : Float(20, strides=[1], device=cpu)): +// %dim : int = prim::Constant[value=0]() +// %xy_list : Tensor[] = prim::ListConstruct(%x, %y) +// %cat : Float(60, strides=[1], device=cpu) = aten::cat(%xy_list, %dim) +// %5 : Float(60, strides=[1], device=cpu) = aten::log(%cat) +// return (%5))IR"; +// +// This will get lowered into: +// Allocate(aten_cat); +// for (...) +// aten_cat[...] = x[...] +// for (...) +// aten_cat[...] = y[...] +// for (...) +// aten_log[...] = log(aten_cat[...]) +// Free(aten_cat); +// Note that aten_cat is not inlined into aten_log and it results in +// an intermediate buffer allocation as well. +// +// Optimization: +// We move the ops that use the result of `cat` into its inputs whenever +// possible. +// +// The graph above will be transformed to: +// graph(%x : Float(10, strides=[1], device=cpu), +// %y : Float(20, strides=[1], device=cpu)): +// %3 : int = prim::Constant[value=0]() +// %7 : Float(10, strides=[1], device=cpu) = aten::log(%x) +// %8 : Float(20, strides=[1], device=cpu) = aten::log(%y) +// %9 : Tensor[] = prim::ListConstruct(%7, %8) +// %10 : Float(60, strides=[1], device=cpu) = aten::cat(%9, %3) +// return (%10) +// +// This will get lowered into: +// for (...) +// aten_cat[...] = log(x[...]) +// for (...) +// aten_cat[...] = log(y[...]) +// aten_cat is the output buffer here. + +bool OptimizeCat(const std::shared_ptr& graph); + +TORCH_API void annotateInputShapes( + const std::shared_ptr& graph, + const std::vector>& example_inputs); +TORCH_API std::shared_ptr removeUnusedSelfArgument( + const std::shared_ptr& graph); +TORCH_API std::shared_ptr removeGraphOutput( + const std::shared_ptr& graph, + size_t idx); +TORCH_API std::shared_ptr replaceListOutputWithTuple( + const std::shared_ptr& graph); + +// Perform \p ITERS rounds of "trimming" for the given \p GRAPH. +// +// Trimming means that we try to remove a small portion of the graph while +// keeping it valid. This is useful for debugging when we try to find a minimal +// example reproducing the issue at hand. When ITERS is 0, the graph remains +// unchanged, when ITERS is a big number, the graph usually becomes empty. +TORCH_API std::shared_ptr trimGraph( + const std::shared_ptr& graph, + int64_t iters); + +// Scan all values in the given graph and replace each dimension with a size Xi +// present in \p SIZES with a symbolic shape Yi. Return a vector of symbol +// values [Y0, Y1, .., Yn]. +// +// For example: +// Input: +// graph(%x : Float(10, 20, 30, 40)): +// %y : Float(10, 20, 30, 40) = aten::relu(%x) +// return %y +// +// If we run makeShapesSymbolic(graph, {20, 40}), then we'll get: +// +// graph(%x : Float(10, SS(-3), 30, SS(-5))): +// %y : Float(10, SS(-3), 30, SS(-5)) = aten::relu(%x) +// return %y +// +// and get {-3, -5} as the return value. +TORCH_API std::vector makeShapesSymbolic( + std::shared_ptr& graph, + const std::vector& sizes); + +// Inspect the graph and report whether it can be converted to TE IR. +// TODO: add error reporting for graphs that can't be converted. +TORCH_API bool isGraphCompilable(const std::shared_ptr& graph); + +// Examine the graph and (hackily) fill in missing tensor type info, such as +// scalar type, device, and strides. Ideally, this should be done by a proper +// dtype/device/shape propagation passes, but until they are ready we can use +// this, not always correct, workaround pass. +TORCH_API void fixupMissingShapeInfo(const std::shared_ptr& graph); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h new file mode 100644 index 0000000000000000000000000000000000000000..2d14d0b6aba003711f461c265d7be59a11b661fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h @@ -0,0 +1,217 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +// Walk the Statement looking for Half size loads/stores. +class HalfChecker : public IRVisitor { + public: + HalfChecker(const std::vector& args) { + for (const auto& BA : args) { + hasHalf_ |= BA.dtype().scalar_type() == ScalarType::Half; + } + } + + bool hasHalf() const { + return hasHalf_; + } + + bool hasBFloat16() const { + return hasBFloat16_; + } + + void visit(const LoadPtr& v) override { + hasHalf_ |= v->dtype().scalar_type() == ScalarType::Half; + hasBFloat16_ |= v->dtype().scalar_type() == ScalarType::BFloat16; + IRVisitor::visit(v); + } + + void visit(const StorePtr& v) override { + hasHalf_ |= v->buf()->dtype().scalar_type() == ScalarType::Half; + hasBFloat16_ |= v->buf()->dtype().scalar_type() == ScalarType::BFloat16; + IRVisitor::visit(v); + } + + void visit(const HalfImmPtr& v) override { + hasHalf_ = true; + } + + void visit(const BFloat16ImmPtr& v) override { + hasBFloat16_ = true; + } + + void visit(const CastPtr& v) override { + hasHalf_ |= v->dtype().scalar_type() == ScalarType::Half; + hasBFloat16_ |= v->dtype().scalar_type() == ScalarType::BFloat16; + IRVisitor::visit(v); + } + + private: + bool hasHalf_{false}; + bool hasBFloat16_{false}; +}; + +class HalfRewriter : public IRMutator { + ExprPtr mutate(const LoadPtr& v) override { + ExprPtr child = IRMutator::mutate(v); + if (!isHalf(child)) { + return child; + } + + ExprPtr ret = alloc( + child->dtype().cloneWithScalarType(ScalarType::Float), child); + + inserted_half_casts_.insert(ret); + return ret; + } + + StmtPtr mutate(const StorePtr& v) override { + // Since mutation changes the `value()` expression in-place, we need to + // get the dtype of the `value()` before that is mutated. + auto newType = v->value()->dtype(); + ExprPtr new_val = v->value()->accept_mutator(this); + auto bufType = v->buf()->dtype(); + + if (isHalf(newType.scalar_type())) { + new_val = alloc(newType, new_val); + inserted_half_casts_.insert(new_val); + } + + // The scalar_type of value is not Half while the buf is Half + if (!isHalf(newType.scalar_type()) && isHalf(bufType.scalar_type())) { + new_val = alloc( + newType.cloneWithScalarType(bufType.scalar_type()), new_val); + inserted_half_casts_.insert(new_val); + } + + v->set_value(new_val); + return v; + } + + ExprPtr mutate(const HalfImmPtr& v) override { + return alloc(kFloat, v); + } + + ExprPtr mutate(const BFloat16ImmPtr& v) override { + return alloc(kFloat, v); + } + + ExprPtr mutate(const CastPtr& v) override { + ExprPtr child = v->src_value()->accept_mutator(this); + + // just don't allow half casts we didn't insert. + if (isHalf(v)) { + if (inserted_half_casts_.count(v) < 1) { + v->set_src_value(child); + v->set_dtype(v->dtype().cloneWithScalarType(c10::kFloat)); + return v; + } + } + + // Remove Half(Float()) and friends. + CastPtr cast_child = to(child); + if (cast_child) { + auto cast_to_double = v->dtype().scalar_type() == ScalarType::Double; + auto from_half = isHalf(cast_child->src_value()); + // Cannot simplify the double(float(half)) to double(half) as NNC does + // not support cast BF16 to double directly. + auto not_cast_half_to_doulbe = !(cast_to_double && from_half); + if (v->dtype().is_floating_point() && + cast_child->dtype().is_floating_point() && not_cast_half_to_doulbe) { + return alloc(v->dtype(), cast_child->src_value()); + } + } + + if (child == v->src_value()) { + return v; + } + + return alloc(v->dtype(), child); + } + + StmtPtr mutate(const LetPtr& v) override { + if (isHalf(v->var()->dtype().scalar_type())) { + VarPtr load_new_var = alloc(v->var()->name_hint(), kFloat); + ExprPtr new_value = alloc( + v->var()->dtype().cloneWithScalarType(ScalarType::Float), + v->value()->accept_mutator(this)); + var_map[v->var()] = load_new_var; + + return alloc(load_new_var, new_value); + } + + return IRMutator::mutate(v); + } + + ExprPtr mutate(const VarPtr& v) override { + auto it = var_map.find(v); + if (it != var_map.end()) { + return it->second; + } + + return v; + } + + template + ExprPtr mutateArithmetic(T v) { + IRMutator::mutate(v); + if (isHalf(v)) { + v->set_dtype(v->dtype().cloneWithScalarType(c10::kFloat)); + } + return v; + } + + ExprPtr mutate(const AddPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const SubPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const MulPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const DivPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const MaxPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const MinPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const CompareSelectPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const BroadcastPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const IfThenElsePtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const IntrinsicsPtr& v) override { + return mutateArithmetic(v); + } + + private: + static bool isHalf(ScalarType st) { + return st == ScalarType::Half || st == ScalarType::BFloat16; + } + + static bool isHalf(const ExprPtr& v) { + return isHalf(v->dtype().scalar_type()); + } + + std::unordered_set inserted_half_casts_; + std::unordered_map var_map; +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..4e683bd7d2b6bf8c75d66e9d96ebf5b8c5e44a9b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h @@ -0,0 +1,286 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +struct TORCH_API SimplifierHashType { + SimplifierHashType() = default; + explicit SimplifierHashType(size_t s) : _h(s) {} + + bool operator==(const SimplifierHashType& other) const; + bool operator!=(const SimplifierHashType& other) const; + bool operator<(const SimplifierHashType& other) const; + bool operator==(const size_t other) const; + bool operator!=(const size_t other) const; + + size_t _h{0}; +}; + +} // namespace torch::jit::tensorexpr + +namespace std { +template <> +struct hash { + size_t operator()(const torch::jit::tensorexpr::SimplifierHashType& k) const { + return k._h; + } +}; + +} // namespace std + +namespace torch::jit::tensorexpr { + +#define CACHE_GUARD() \ + if (cachedHash(v)) { \ + return; \ + } + +class Term; +class Polynomial; + +/* Expression hasher providing comparable values representing sub-exprs. + * Uses memoization to avoid excessive recursion. */ +class TORCH_API HashProvider : public IRVisitor { + public: + template + SimplifierHashType hash(T e) { + e->accept(this); + return hashOf(e); + } + + bool cachedHash(const ExprPtr& e) { + return exprToHash_.find(e) != exprToHash_.end(); + } + bool cachedHash(const StmtPtr& s) { + return stmtToHash_.find(s) != stmtToHash_.end(); + } + + void clearCache() { + exprToHash_.clear(); + stmtToHash_.clear(); + } + + void visit(const AddPtr& v) override; + void visit(const SubPtr& v) override; + void visit(const MulPtr& v) override; + void visit(const DivPtr& v) override; + void visit(const ModPtr& v) override; + void visit(const RoundOffPtr& v) override; + void visit(const MaxPtr& v) override; + void visit(const MinPtr& v) override; + void visit(const AndPtr& v) override; + void visit(const OrPtr& v) override; + void visit(const XorPtr& v) override; + void visit(const LshiftPtr& v) override; + void visit(const RshiftPtr& v) override; + void visit(const CompareSelectPtr& v) override; + +#define IMM_VISIT(Type, Name) \ + void visit(const Name##ImmPtr& v) override { \ + CACHE_GUARD(); \ + putHash(v, hash_combine(#Name, v->value())); \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_VISIT) +#undef IMM_VISIT + + void visit(const CastPtr& v) override; + void visit(const VarPtr& v) override; + void visit(const RampPtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const ForPtr& v) override; + void visit(const BroadcastPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const IntrinsicsPtr& v) override; + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + void visit(const CondPtr& v) override; + void visit(const TermPtr& v) override; + void visit(const PolynomialPtr& v) override; + void visit(const MaxTermPtr& v) override; + void visit(const MinTermPtr& v) override; + + template + SimplifierHashType hash_combine(const Types&... args) { + SimplifierHashType seed; + _hash_combine(seed, args...); + return seed; + } + + private: + SimplifierHashType hashOf(const ExprPtr& e) { + auto it = exprToHash_.find(e); + if (it != exprToHash_.end()) { + return it->second; + } + + // As a failsafe fall back to IRPrinter. + std::stringstream ss; + IRPrinter printer(ss); + e->accept(&printer); + SimplifierHashType hash = SimplifierHashType(te_hash(ss.str())); + putHash(e, hash); + + return hash; + } + + SimplifierHashType hashOf(const StmtPtr& s) { + auto it = stmtToHash_.find(s); + if (it != stmtToHash_.end()) { + return it->second; + } + + // As a failsafe fall back to IRPrinter. + std::stringstream ss; + IRPrinter printer(ss); + s->accept(&printer); + SimplifierHashType hash = SimplifierHashType(te_hash(ss.str())); + putHash(s, hash); + + return hash; + } + + // Hash funcs for various types, numbers are random. + template + void _hash_combine(SimplifierHashType& seed, const T& val) { + seed._h ^= te_hash(val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4); + } + + void _hash_combine(SimplifierHashType& seed, const char* val) { + seed._h ^= te_hash(val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4); + } + + // at:::Half doesn't have a prime_number_hash, so cast to short. + void _hash_combine(SimplifierHashType& seed, const at::Half& val) { + seed._h ^= + te_hash((uint16_t)val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4); + } + + void _hash_combine(SimplifierHashType& seed, const Dtype& val) { + seed._h ^= te_hash(val.ToCppString()) + 0x1f752c19 + (seed._h << 7) + + (seed._h >> 4); + } + + void _hash_combine(SimplifierHashType& seed, ExprPtr e) { + _hash_combine(seed, hash(std::move(e))); + } + + template + void _hash_combine( + SimplifierHashType& seed, + const T& val, + const Types&... args) { + _hash_combine(seed, val); + _hash_combine(seed, args...); + } + + void putHash(const ExprPtr& e, SimplifierHashType h) { + auto res = exprToHash_.emplace(e, h); + if (res.second == false) { + // This is always a logic bug since we should check the cache first. + throw std::runtime_error("hash collision"); + } + } + void putHash(const StmtPtr& s, SimplifierHashType h) { + auto res = stmtToHash_.emplace(s, h); + if (res.second == false) { + // This is always a logic bug since we should check the cache first. + throw std::runtime_error("hash collision"); + } + } + + std::unordered_map exprToHash_; + std::unordered_map stmtToHash_; + UniqueNameManager name_manager_; + + size_t te_hash(SimplifierHashType val) { + return val._h; + } + + size_t te_hash(int64_t val) { + // put the thing down. + size_t h = val ^ 0x647AA4D20C0B; + // bit flip it. + size_t h2 = ~h; + // and reverse byte order. + size_t h3 = 0; + for (unsigned int i = 0; i < 64; i += 8) { + h3 |= ((h2 >> i) & 0xFF) << (64 - i - 8); + } + return h3; + } + + size_t te_hash(int32_t val) { + int64_t v2 = val; + return te_hash(v2); + } + + size_t te_hash(uint32_t val) { + int64_t v2 = val; + return te_hash(v2); + } + + size_t te_hash(uint64_t val) { + int64_t v2 = val; + return te_hash(v2); + } + + size_t te_hash(int16_t val) { + int64_t v2 = val; + return te_hash(v2); + } + + size_t te_hash(std::string val) { + size_t hash{0}; + int64_t intval{0}; + int64_t s = val.size() - 1; + while (s >= 0) { + for (unsigned int i = 0; i < 8; ++i) { + if (s < 0) + break; + int64_t c = val[s]; + intval |= (c << (i * 8)); + + s--; + } + hash ^= te_hash(intval); + intval = 0; + } + + return hash; + } + + size_t te_hash(double d) { + int64_t* n = reinterpret_cast(&d); + return te_hash(*n); + } + + size_t te_hash(float d) { + int32_t* n = reinterpret_cast(&d); + return te_hash(*n); + } + + size_t te_hash(at::Half d) { + int16_t* n = reinterpret_cast(&d); + return te_hash(*n); + } + + size_t te_hash(at::BFloat16 d) { + int16_t* n = reinterpret_cast(&d); + return te_hash(*n); + } +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h new file mode 100644 index 0000000000000000000000000000000000000000..ba5b5ff6728bec6e50e9151c29a9e1d2885693e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef TORCH_ENABLE_LLVM +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +struct SymbolAddress { + const char* symbol; + void* address; + + SymbolAddress(const char* sym, void* addr) : symbol(sym), address(addr) {} +}; + +c10::ArrayRef getIntrinsicSymbols(); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch +#endif // TORCH_ENABLE_LLVM + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir.h new file mode 100644 index 0000000000000000000000000000000000000000..4ec8f9bbf8d3a9e71f90e1aa712e2d75f336fcab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir.h @@ -0,0 +1,921 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +enum CompareSelectOperation { + kEQ = 0, + kGT, + kGE, + kLT, + kLE, + kNE, +}; + +enum CompareSelectBias { + kUnbiased, + kLikely, + kUnlikely, +}; + +inline int getPrecedence(IRNodeType ty) { + // Match C++ operator precedence rules, since some pretty-print expressions to + // C++. SEE: https://en.cppreference.com/w/cpp/language/operator_precedence + switch (ty) { + case kPrimitive: + return 0; + case kCast: + case kBitCast: + return 2; + case kAdd: + case kSub: + return 6; + case kMul: + case kDiv: + case kMod: + return 5; + case kMax: + case kMin: + return 99; + case kAnd: + return 11; + case kOr: + return 13; + case kLshift: + case kRshift: + return 7; + case kXor: + return 12; + case kCompareSelect: + return 16; + default: + return 99; + } +} + +class TORCH_API Cast : public ExprNode { + public: + ExprPtr src_value() const { + return src_value_; + } + + void set_src_value(ExprPtr src_value) { + src_value_ = std::move(src_value); + } + + static ExprHandle make(Dtype dtype, const ExprHandle& src_value) { + return ExprHandle(alloc(dtype, src_value.node())); + } + Cast(Dtype dtype, ExprPtr src_value) + : ExprNodeBase(dtype, kCast), src_value_(std::move(src_value)) {} + + bool isConstant() const override { + return src_value_->isConstant(); + } + + private: + ExprPtr src_value_; +}; + +template +ExprHandle cast(const ExprHandle& src_value) { + return Cast::make(Dtype(ToDtype(), src_value.dtype().lanes()), src_value); +} + +// This is a bitwise cast, akin to bitcast in LLVM +class TORCH_API BitCast : public ExprNode { + public: + ExprPtr src_value() const { + return src_value_; + } + + void set_src_value(ExprPtr src_value) { + src_value_ = std::move(src_value); + } + + static ExprHandle make(Dtype dtype, const ExprHandle& src_value) { + return ExprHandle(alloc(dtype, src_value.node())); + } + BitCast(Dtype dtype, ExprPtr src_value) + : ExprNodeBase(dtype, kBitCast), src_value_(std::move(src_value)) { + TORCH_CHECK(src_value_->dtype().byte_size() == dtype.byte_size()); + } + + bool isConstant() const override { + return src_value_->isConstant(); + } + + private: + ExprPtr src_value_; +}; + +template +ExprHandle bitcast(const ExprHandle& src_value) { + return BitCast::make( + Dtype(ToDtype(), src_value.dtype().lanes()), src_value); +} + +// Represent the expression node for binary operators. +// A CRTP pattern to share common code among the operators. +template +class BinaryOpNode : public ExprNode { + public: + ExprPtr lhs() const { + return this->lhs_; + } + ExprPtr rhs() const { + return this->rhs_; + } + + void set_lhs(ExprPtr lhs) { + lhs_ = std::move(lhs); + } + + void set_rhs(ExprPtr rhs) { + rhs_ = std::move(rhs); + } + + static ExprHandle make(const ExprHandle& lhs, const ExprHandle& rhs) { + return ExprHandle(alloc(lhs.node(), rhs.node())); + } + + BinaryOpNode( + ExprPtr lhs_v, + ExprPtr rhs_v, + IRNodeType expr_type, + ScalarType ret_type = ScalarType::Undefined) + : ExprNode( + BinaryOpDtype(lhs_v->dtype(), rhs_v->dtype(), ret_type), + expr_type), + lhs_(CastIfNeeded(std::move(lhs_v), ExprNode::dtype())), + rhs_(CastIfNeeded(std::move(rhs_v), ExprNode::dtype())) {} + + private: + static ExprPtr CastIfNeeded(ExprPtr expr, Dtype dst_dtype) { + if (expr->dtype() == dst_dtype) { + return expr; + } + return Cast::make(dst_dtype, ExprHandle(std::move(expr))).node(); + } + + ExprPtr lhs_; + ExprPtr rhs_; +}; + +namespace detail { +template +void bin_op_deducer(BinaryOpNode); +bool bin_op_deducer(...); +} // namespace detail + +class TORCH_API Add : public BinaryOpNode { + public: + Add(ExprPtr lhs, ExprPtr rhs) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kAdd) {} +}; + +class TORCH_API Sub : public BinaryOpNode { + public: + Sub(ExprPtr lhs, ExprPtr rhs) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kSub) {} +}; + +class TORCH_API Mul : public BinaryOpNode { + public: + Mul(ExprPtr lhs, ExprPtr rhs) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kMul) {} +}; + +class TORCH_API Div : public BinaryOpNode
{ + public: + Div(ExprPtr lhs, ExprPtr rhs) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kDiv) {} +}; + +class TORCH_API Mod : public BinaryOpNode { + public: + Mod(ExprPtr lhs, ExprPtr rhs) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kMod) {} +}; + +template +class BitwiseOpNode : public BinaryOpNode { + public: + BitwiseOpNode(ExprPtr lhs, ExprPtr rhs, IRNodeType type) + : BinaryOpNode(std::move(lhs), std::move(rhs), type) {} + + static ExprHandle make(const ExprHandle& lhs, const ExprHandle& rhs) { + if (!lhs.dtype().is_integral()) { + throw unsupported_dtype(); + } + if (lhs.dtype() != rhs.dtype()) { + throw malformed_input("lhs/rhs dtype mismatch"); + } + return BinaryOpNode::make(lhs, rhs); + } +}; + +class TORCH_API And : public BitwiseOpNode { + public: + And(ExprPtr lhs, ExprPtr rhs) + : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kAnd) {} +}; + +class TORCH_API Or : public BitwiseOpNode { + public: + Or(ExprPtr lhs, ExprPtr rhs) + : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kOr) {} +}; + +class TORCH_API Xor : public BitwiseOpNode { + public: + Xor(ExprPtr lhs, ExprPtr rhs) + : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kXor) {} +}; + +class TORCH_API Lshift : public BitwiseOpNode { + public: + Lshift(ExprPtr lhs, ExprPtr rhs) + : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kLshift) {} +}; + +class TORCH_API Rshift : public BitwiseOpNode { + public: + Rshift(ExprPtr lhs, ExprPtr rhs) + : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kRshift) {} +}; + +// TODO: add TORCH_API +// Currently adding it results in a compilation error on Windows +class Max : public BinaryOpNode { + private: + bool propagate_nans_; + + public: + Max(ExprPtr lhs, ExprPtr rhs, bool propagate_nans) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kMax), + propagate_nans_(propagate_nans) {} + + bool propagate_nans() const { + return propagate_nans_; + } + + static ExprHandle make(const ExprHandle& lhs, const ExprHandle& rhs) = delete; + static ExprHandle make( + const ExprHandle& lhs, + const ExprHandle& rhs, + bool propagate_nans) { + return ExprHandle(alloc(lhs.node(), rhs.node(), propagate_nans)); + } +}; + +// TODO: add TORCH_API +// Currently adding it results in a compilation error on Windows +class Min : public BinaryOpNode { + private: + bool propagate_nans_; + + public: + Min(ExprPtr lhs, ExprPtr rhs, bool propagate_nans) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kMin), + propagate_nans_(propagate_nans) {} + + bool propagate_nans() const { + return propagate_nans_; + } + + static ExprHandle make(const ExprHandle& lhs, const ExprHandle& rhs) = delete; + static ExprHandle make( + const ExprHandle& lhs, + const ExprHandle& rhs, + bool propagate_nans) { + return ExprHandle(alloc(lhs.node(), rhs.node(), propagate_nans)); + } +}; + +// Encode typed immediate values e.g. IntImm, FloatImm. +#define IMM_DECLARE(Type, Name) \ + class TORCH_API Name##Imm : public ExprNode { \ + public: \ + Name##Imm(Type value) \ + : ExprNodeBase(k##Name, kPrimitive), value_(value) {} \ + bool isConstant() const override { \ + return true; \ + } \ + Type value() const { \ + return value_; \ + } \ + static ExprHandle make(Type value) { \ + return ExprHandle(alloc(value)); \ + } \ + \ + private: \ + Type value_; \ + }; +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_DECLARE) +#undef IMM_DECLARE + +// Get immediate by ScalarType. +template +ExprPtr getImmediateByType(ScalarType immType, T initialVal) { + switch (immType) { +#define TYPE_CASE(Type, Name) \ + case ScalarType::Name: \ + return alloc(Type(initialVal)); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE) +#undef TYPE_CASE + default: + throw unsupported_dtype(); + } + return nullptr; +} + +template +ExprPtr getImmediateByType(Dtype dtype, T initialVal) { + return getImmediateByType(dtype.scalar_type(), initialVal); +} + +template +ExprPtr immLike(const ExprPtr& e, T v) { + return getImmediateByType(e->dtype(), v); +} + +template +ExprPtr immLike(const ExprHandle& e, T v) { + return immLike(e.node(), v); +} + +inline std::optional intValue(const ExprPtr& e) { +#define TYPE_CASE(Type, Name) \ + if (auto v = to(e)) { \ + return v->value(); \ + } + AT_FORALL_INT_TYPES(TYPE_CASE); +#undef TYPE_CASE + return std::nullopt; +} + +inline std::optional intValue(const ExprHandle& e) { + return intValue(e.node()); +} + +template +T immediateAs(const ExprPtr& e) { +#define TYPE_CASE(Type, Name) \ + if (Name##ImmPtr imm = to(e)) { \ + return imm->value(); \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE) +#undef TYPE_CASE + throw unsupported_dtype(); + return 0; +} + +template +T immediateAs(const ExprHandle& e) { + return immediateAs(e.node()); +} + +template +bool immediateEquals(const ExprPtr& e, T val) { +#define TYPE_CASE(Type, Name) \ + if (Name##ImmPtr imm = to(e)) { \ + return imm->value() == val; \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE) +#undef TYPE_CASE + throw unsupported_dtype(); + return false; +} + +TORCH_API bool immediateIsNegative(const ExprPtr& e); + +TORCH_API bool immediateIsPositive(const ExprPtr& e); + +TORCH_API bool immediateIsZero(const ExprPtr& e); + +// Represents a ramp vector node: +// [base, base + 1 * stride, ... , base + (lanes - 1) * stride] +class TORCH_API Ramp : public ExprNode { + public: + ExprPtr base() const { + return base_; + } + ExprPtr stride() const { + return stride_; + } + + void set_base(ExprPtr base) { + base_ = std::move(base); + } + + void set_stride(ExprPtr stride) { + stride_ = std::move(stride); + } + + static ExprHandle make( + const ExprHandle& base, + const ExprHandle& stride, + int64_t lanes) { + if (stride.dtype() != base.dtype()) { + throw malformed_input("Bad stride in Ramp"); + } + return ExprHandle(alloc(base.node(), stride.node(), lanes)); + } + int64_t lanes() const { + return lanes_; + } + + Ramp(ExprPtr base, ExprPtr stride, int64_t lanes) + : ExprNodeBase(Dtype(base->dtype(), lanes)), + base_(std::move(base)), + stride_(std::move(stride)), + lanes_(lanes) {} + + private: + ExprPtr base_; + ExprPtr stride_; + int64_t lanes_; +}; + +class TORCH_API Load : public ExprNode { + public: + VarPtr base_handle() const { + return buf_->base_handle(); + } + std::vector indices() const { + return indices_; + } + ExprPtr flat_index() const { + TORCH_CHECK(indices_.size() == 1, "Indices haven't been flattened."); + return indices_[0]; + } + BufPtr buf() const { + return buf_; + } + + void set_buf(BufPtr buf) { + buf_ = std::move(buf); + } + + void set_indices(std::vector indices) { + indices_ = std::move(indices); + } + + static ExprHandle make( + Dtype dtype, + const BufHandle& buf, + const std::vector& indices); + static ExprHandle make( + const BufHandle& buf, + const std::vector& indices); + + Load(Dtype dtype, BufPtr base_handle, std::vector indices); + Load(const BufPtr& base_handle, const std::vector& indices); + + private: + BufPtr buf_; + std::vector indices_; +}; + +class TORCH_API Broadcast : public ExprNode { + public: + ExprPtr value() const { + return value_; + } + + void set_value(ExprPtr value) { + value_ = std::move(value); + } + + int64_t lanes() const { + return lanes_; + } + static ExprHandle make(const ExprHandle& value, int64_t lanes) { + return ExprHandle(alloc(value.node(), lanes)); + } + Broadcast(ExprPtr value, int64_t lanes) + : ExprNodeBase(Dtype(value->dtype(), lanes)), + value_(std::move(value)), + lanes_(lanes) {} + + private: + ExprPtr value_; + int64_t lanes_; +}; + +class TORCH_API IfThenElse : public ExprNode { + public: + ExprPtr condition() const { + return condition_; + } + + // Lazily evaluated only if condition is true + ExprPtr true_value() const { + return true_; + } + + // Lazily evaluated only if condition is false + ExprPtr false_value() const { + return false_; + } + + void set_condition(ExprPtr condition) { + condition_ = std::move(condition); + } + + void set_true_value(ExprPtr true_value) { + true_ = std::move(true_value); + } + + void set_false_value(ExprPtr false_value) { + false_ = std::move(false_value); + } + + static ExprHandle make( + const ExprHandle& c, + const ExprHandle& t, + const ExprHandle& f) { + if (!c.dtype().is_integral()) { + throw unsupported_dtype(); + } + if (c.dtype().lanes() != 1) { + throw unsupported_dtype(); + } + if (t.dtype() != f.dtype()) { + throw malformed_input("Bad dtype in IfThenElse"); + } + return ExprHandle(alloc(c.node(), t.node(), f.node())); + } + + IfThenElse(ExprPtr c, ExprPtr t, ExprPtr f) + : ExprNodeBase(t->dtype()), + condition_(std::move(c)), + true_(std::move(t)), + false_(std::move(f)) {} + + private: + ExprPtr condition_; + ExprPtr true_; + ExprPtr false_; +}; + +class TORCH_API CompareSelect : public ExprNode { + public: + CompareSelectOperation compare_select_op() const { + return compare_op_; + } + ExprPtr lhs() const { + return this->lhs_; + } + ExprPtr rhs() const { + return this->rhs_; + } + ExprPtr ret_val1() const { + return this->ret_val1_; + } + ExprPtr ret_val2() const { + return this->ret_val2_; + } + + void set_lhs(ExprPtr lhs) { + lhs_ = std::move(lhs); + } + + void set_rhs(ExprPtr rhs) { + rhs_ = std::move(rhs); + } + + void set_ret_val1(ExprPtr ret_val1) { + ret_val1_ = std::move(ret_val1); + } + + void set_ret_val2(ExprPtr ret_val2) { + ret_val2_ = std::move(ret_val2); + } + + CompareSelectBias bias() const { + return bias_; + } + + static ExprHandle make( + const ExprHandle& lhs, + const ExprHandle& rhs, + CompareSelectOperation cmp_op, + CompareSelectBias bias = kUnbiased) { + if (lhs.dtype() != rhs.dtype()) { + throw malformed_input("bad dtype in CompareSelect"); + } + return ExprHandle(alloc( + lhs.node(), + rhs.node(), + IntImm::make(1).node(), + IntImm::make(0).node(), + cmp_op, + bias)); + } + + static ExprHandle make( + const ExprHandle& lhs, + const ExprHandle& rhs, + const ExprHandle& ret_val1, + const ExprHandle& ret_val2, + CompareSelectOperation cmp_op, + CompareSelectBias bias = kUnbiased) { + if (lhs.dtype() != rhs.dtype() || ret_val1.dtype() != ret_val2.dtype()) { + throw malformed_input("bad dtype in CompareSelect"); + } + return ExprHandle(alloc( + lhs.node(), + rhs.node(), + ret_val1.node(), + ret_val2.node(), + cmp_op, + bias)); + } + + CompareSelect( + ExprPtr lhs, + ExprPtr rhs, + ExprPtr ret_val1, + ExprPtr ret_val2, + CompareSelectOperation cmp_op, + CompareSelectBias bias = kUnbiased) + : ExprNodeBase(ret_val1->dtype()), + lhs_(std::move(lhs)), + rhs_(std::move(rhs)), + ret_val1_(std::move(ret_val1)), + ret_val2_(std::move(ret_val2)), + compare_op_(cmp_op), + bias_(bias) {} + + CompareSelect( + ExprPtr lhs, + ExprPtr rhs, + CompareSelectOperation cmp_op, + CompareSelectBias bias = kUnbiased) + : ExprNodeBase(kInt), + lhs_(std::move(lhs)), + rhs_(std::move(rhs)), + ret_val1_(alloc(1)), + ret_val2_(alloc(0)), + compare_op_(cmp_op), + bias_(bias) {} + + private: + ExprPtr lhs_; + ExprPtr rhs_; + ExprPtr ret_val1_; + ExprPtr ret_val2_; + CompareSelectOperation compare_op_; + CompareSelectBias bias_; +}; + +enum IntrinsicsOp { + kSin, + kCos, + kTan, + kAsin, + kAcos, + kAtan, + kAtan2, + kSinh, + kCosh, + kTanh, + kSigmoid, + kExp, + kExpm1, + kAbs, + kLog, + kLog2, + kLog10, + kLog1p, + kErf, + kErfc, + kSqrt, + kRsqrt, + kPow, + kCeil, + kFloor, + kRound, + kTrunc, + kFmod, + kRemainder, + kLgamma, + kFrac, + kIsNan, + kRand, // We need more discussions on this. Should we consider stateful? + kMaxIntrinsicsOp, +}; + +class TORCH_API Intrinsics : public ExprNode { + public: + static ExprHandle make(IntrinsicsOp op_type, const ExprHandle& v1) { + return ExprHandle(alloc(op_type, v1.node())); + } + + static ExprHandle make( + IntrinsicsOp op_type, + const ExprHandle& v1, + const ExprHandle& v2) { + return ExprHandle(alloc(op_type, v1.node(), v2.node())); + } + + static ExprHandle make( + IntrinsicsOp op_type, + const std::vector& params) { + std::vector params_nodes(params.size()); + for (size_t i = 0; i < params.size(); i++) { + params_nodes[i] = params[i].node(); + } + return ExprHandle(alloc(op_type, params_nodes)); + } + + static ExprHandle make(IntrinsicsOp op_type, Dtype dtype) { + return ExprHandle(alloc(op_type, dtype)); + } + + IntrinsicsOp op_type() const { + return op_type_; + } + + std::string func_name() const { + switch (op_type()) { + case kSin: + return "sin"; + case kCos: + return "cos"; + case kTan: + return "tan"; + case kAsin: + return "asin"; + case kAcos: + return "acos"; + case kAtan: + return "atan"; + case kAtan2: + return "atan2"; + case kSinh: + return "sinh"; + case kCosh: + return "cosh"; + case kTanh: + return "tanh"; + case kSigmoid: + return "sigmoid"; + case kExp: + return "exp"; + case kAbs: + return "abs"; + case kLog: + return "log"; + case kLog2: + return "log2"; + case kLog10: + return "log10"; + case kLog1p: + return "log1p"; + case kErf: + return "erf"; + case kSqrt: + return "sqrt"; + case kRsqrt: + return "rsqrt"; + case kPow: + return "pow"; + case kCeil: + return "ceil"; + case kFloor: + return "floor"; + case kRound: + return "round"; + case kTrunc: + return "trunc"; + case kRand: + return "rand"; + case kFmod: + return "fmod"; + case kRemainder: + return "remainder"; + case kLgamma: + return "lgamma"; + case kExpm1: + return "expm1"; + case kErfc: + return "erfc"; + case kFrac: + return "frac"; + case kIsNan: + return "isnan"; + default: + throw std::runtime_error( + "invalid op_type: " + std::to_string(op_type())); + } + } + + Intrinsics(IntrinsicsOp op_type, Dtype dtype) + : ExprNodeBase(IntrinsicsDtype(op_type, dtype)), + params_({}), + op_type_(op_type) { + if (OpArgCount(op_type) != 0) { + throw malformed_input("bad arg count in Intrinsics"); + } + } + + Intrinsics(IntrinsicsOp op_type, ExprPtr v1) + : ExprNodeBase(IntrinsicsDtype(op_type, v1->dtype())), + params_({std::move(v1)}), + op_type_(op_type) { + if (OpArgCount(op_type) != 1) { + throw malformed_input("bad arg count in Intrinsics"); + } + } + + Intrinsics(IntrinsicsOp op_type, ExprPtr v1, ExprPtr v2) + : ExprNodeBase(IntrinsicsDtype(op_type, v1->dtype(), v2->dtype())), + params_({std::move(v1), std::move(v2)}), + op_type_(op_type) { + if (OpArgCount(op_type) != 2) { + throw malformed_input("bad arg count in Intrinsics"); + } + } + + Intrinsics(IntrinsicsOp op_type, const std::vector& params) + : ExprNodeBase(IntrinsicsDtype(op_type, params)), + params_(params), + op_type_(op_type) { + if (OpArgCount(op_type) != nparams()) { + throw malformed_input("bad arg count in Intrinsics"); + } + } + + Intrinsics(IntrinsicsOp op_type, Dtype dtype, std::vector params) + : ExprNodeBase(IntrinsicsDtype(op_type, dtype)), + params_(std::move(params)), + op_type_(op_type) { + if (OpArgCount(op_type) != nparams()) { + throw malformed_input("bad arg count in Intrinsics"); + } + } + + bool isPure() const { + return op_type_ != kRand; + } + + size_t nparams() const { + return params_.size(); + } + + ExprPtr param(size_t index) const { + return params_[index]; + } + const std::vector& params() const { + return params_; + } + + void set_params(std::vector params) { + params_ = std::move(params); + } + + static size_t OpArgCount(IntrinsicsOp op_type); + + private: + static Dtype IntrinsicsDtype(IntrinsicsOp op_type, Dtype dt1); + static Dtype IntrinsicsDtype(IntrinsicsOp op_type, Dtype dt1, Dtype dt2); + static Dtype IntrinsicsDtype( + IntrinsicsOp op_type, + const std::vector& params); + + std::vector params_; + IntrinsicsOp op_type_; +}; + +TORCH_API std::vector ExprHandleVectorToExprVector( + const std::vector& /*v*/); +TORCH_API std::vector ExprVectorToExprHandleVector( + const std::vector& /*v*/); +TORCH_API std::vector VarHandleVectorToVarVector( + const std::vector& /*v*/); +TORCH_API std::vector VarVectorToVarHandleVector( + const std::vector& /*v*/); +TORCH_API ExprPtr flatten_index( + const std::vector& dims, + const std::vector& indices, + const std::vector& strides); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_cloner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_cloner.h new file mode 100644 index 0000000000000000000000000000000000000000..9c337bb1b6fa633b28be70d7497cdd149a4c45aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_cloner.h @@ -0,0 +1,67 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +class TORCH_API IRCloner : public IRMutator { + public: + ~IRCloner() override = default; + ExprPtr mutate(const AddPtr& v) override; + ExprPtr mutate(const SubPtr& v) override; + ExprPtr mutate(const MulPtr& v) override; + ExprPtr mutate(const DivPtr& v) override; + ExprPtr mutate(const ModPtr& v) override; + ExprPtr mutate(const MaxPtr& v) override; + ExprPtr mutate(const MinPtr& v) override; + ExprPtr mutate(const AndPtr& v) override; + ExprPtr mutate(const OrPtr& v) override; + ExprPtr mutate(const XorPtr& v) override; + ExprPtr mutate(const LshiftPtr& v) override; + ExprPtr mutate(const RshiftPtr& v) override; + ExprPtr mutate(const CompareSelectPtr& v) override; +#define IMM_MUTATE_DECLARE(Type, Name) \ + ExprPtr mutate(const Name##ImmPtr& v) override; + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_MUTATE_DECLARE) +#undef IMM_MUTATE_DECLARE + ExprPtr mutate(const CastPtr& v) override; + ExprPtr mutate(const BitCastPtr& v) override; + ExprPtr mutate(const VarPtr& v) override; + ExprPtr mutate(const BufPtr& v) override; + ExprPtr mutate(const RampPtr& v) override; + ExprPtr mutate(const LoadPtr& v) override; + ExprPtr mutate(const BroadcastPtr& v) override; + ExprPtr mutate(const IfThenElsePtr& v) override; + ExprPtr mutate(const IntrinsicsPtr& v) override; + + ExprPtr mutate(const TermPtr& v) override; + ExprPtr mutate(const PolynomialPtr& v) override; + ExprPtr mutate(const RoundOffPtr& v) override; + ExprPtr mutate(const MaxTermPtr& v) override; + ExprPtr mutate(const MinTermPtr& v) override; + + ExprPtr mutate(const ReduceOpPtr& v) override; + + StmtPtr mutate(const ForPtr& v) override; + StmtPtr mutate(const BlockPtr& v) override; + StmtPtr mutate(const StorePtr& v) override; + StmtPtr mutate(const AtomicAddPtr& v) override; + StmtPtr mutate(const SyncThreadsPtr& v) override; + StmtPtr mutate(const ExternalCallPtr& v) override; + StmtPtr mutate(const ExternalCallWithAllocPtr& v) override; + + StmtPtr mutate(const AllocatePtr& v) override; + StmtPtr mutate(const FreePtr& v) override; + StmtPtr mutate(const LetPtr& v) override; + StmtPtr mutate(const CondPtr& v) override; +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h new file mode 100644 index 0000000000000000000000000000000000000000..826122019d43d9542f27cbe8337c513dc5c6884b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h @@ -0,0 +1,67 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::jit::tensorexpr { + +class TORCH_API IRMutator { + public: + virtual ~IRMutator() = default; + virtual ExprPtr mutate(const AddPtr& v); + virtual ExprPtr mutate(const SubPtr& v); + virtual ExprPtr mutate(const MulPtr& v); + virtual ExprPtr mutate(const DivPtr& v); + virtual ExprPtr mutate(const ModPtr& v); + virtual ExprPtr mutate(const MaxPtr& v); + virtual ExprPtr mutate(const MinPtr& v); + virtual ExprPtr mutate(const AndPtr& v); + virtual ExprPtr mutate(const OrPtr& v); + virtual ExprPtr mutate(const XorPtr& v); + virtual ExprPtr mutate(const LshiftPtr& v); + virtual ExprPtr mutate(const RshiftPtr& v); + virtual ExprPtr mutate(const CompareSelectPtr& v); +#define IMM_MUTATE_DECLARE(Type, Name) \ + virtual ExprPtr mutate(const Name##ImmPtr& v); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_MUTATE_DECLARE) +#undef IMM_MUTATE_DECLARE + virtual ExprPtr mutate(const CastPtr& v); + virtual ExprPtr mutate(const BitCastPtr& v); + virtual ExprPtr mutate(const VarPtr& v); + virtual ExprPtr mutate(const BufPtr& v); + virtual ExprPtr mutate(const RampPtr& v); + virtual ExprPtr mutate(const LoadPtr& v); + virtual ExprPtr mutate(const BroadcastPtr& v); + virtual ExprPtr mutate(const IfThenElsePtr& v); + virtual ExprPtr mutate(const IntrinsicsPtr& v); + + virtual ExprPtr mutate(const TermPtr& v); + virtual ExprPtr mutate(const PolynomialPtr& v); + virtual ExprPtr mutate(const RoundOffPtr& v); + virtual ExprPtr mutate(const MaxTermPtr& v); + virtual ExprPtr mutate(const MinTermPtr& v); + + virtual ExprPtr mutate(const ReduceOpPtr& v); + + virtual StmtPtr mutate(const ForPtr& v); + virtual StmtPtr mutate(const BlockPtr& v); + virtual StmtPtr mutate(const StorePtr& v); + virtual StmtPtr mutate(const AtomicAddPtr& v); + virtual StmtPtr mutate(const SyncThreadsPtr& v); + virtual StmtPtr mutate(const ExternalCallPtr& v); + virtual StmtPtr mutate(const ExternalCallWithAllocPtr& v); + + virtual StmtPtr mutate(const AllocatePtr& v); + virtual StmtPtr mutate(const FreePtr& v); + virtual StmtPtr mutate(const FreeExtPtr& v); + virtual StmtPtr mutate(const PlacementAllocatePtr& v); + virtual StmtPtr mutate(const LetPtr& v); + virtual StmtPtr mutate(const CondPtr& v); +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_printer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_printer.h new file mode 100644 index 0000000000000000000000000000000000000000..033244123919bc33842771e479c989221daf897b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_printer.h @@ -0,0 +1,137 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +class Tensor; + +class TORCH_API IRPrinter : public IRVisitor { + public: + explicit IRPrinter(std::ostream& os) : printer_os_(this, os) {} + + void print(ExprHandle /*expr*/); + void print(Expr& /*expr*/); + void print(Stmt& /*stmt*/); + void visit(const AddPtr& v) override; + void visit(const SubPtr& v) override; + void visit(const MulPtr& v) override; + void visit(const DivPtr& v) override; + void visit(const ModPtr& v) override; + void visit(const MaxPtr& v) override; + void visit(const MinPtr& v) override; + void visit(const AndPtr& v) override; + void visit(const OrPtr& v) override; + void visit(const XorPtr& v) override; + void visit(const LshiftPtr& v) override; + void visit(const RshiftPtr& v) override; + void visit(const CompareSelectPtr& v) override; +#define IMM_PRINT_VISIT(Type, Name) void visit(const Name##ImmPtr& v) override; + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_PRINT_VISIT) +#undef IMM_PRINT_VISIT + void visit(const CastPtr& v) override; + void visit(const BitCastPtr& v) override; + void visit(const VarPtr& v) override; + void visit(const BufPtr& v) override; + void visit(const RampPtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const BroadcastPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const IntrinsicsPtr& v) override; + void visit(const TermPtr& v) override; + void visit(const PolynomialPtr& v) override; + void visit(const RoundOffPtr& v) override; + void visit(const MaxTermPtr& v) override; + void visit(const MinTermPtr& v) override; + void visit(const ReduceOpPtr& v) override; + + void visit(const AtomicAddPtr& v) override; + void visit(const SyncThreadsPtr& v) override; + void visit(const ExternalCallPtr& v) override; + void visit(const ExternalCallWithAllocPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const ForPtr& v) override; + void visit(const CondPtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + void visit(const FreeExtPtr& v) override; + void visit(const PlacementAllocatePtr& v) override; + void visit(const LetPtr& v) override; + + // A child class may have a difference rule for generating dtype + // string, e.g. CUDA needs int64_t to be generated as long long. + virtual std::string dtypeToCppString(const Dtype& dtype); + + std::ostream& os() { + return printer_os_; + } + + class PrinterStream : public std::ostream { + public: + PrinterStream(IRPrinter* printer, std::ostream& os) + : std::ostream(os.rdbuf()), printer_(printer) { + initialize_imbue(); + } + + void initialize_imbue(); + + IRPrinter* printer() { + return printer_; + } + + private: + IRPrinter* printer_ = nullptr; + }; + + protected: + std::string to_string(CompareSelectOperation op); + + UniqueNameManager* name_manager() { + return &name_manager_; + } + void emitIndent(); + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + int indent_ = 0; + + private: + PrinterStream printer_os_; + UniqueNameManager name_manager_; +}; + +TORCH_API std::ostream& operator<<(std::ostream& stream, const Expr& /*expr*/); +TORCH_API std::ostream& operator<<( + std::ostream& stream, + const ExprHandle& /*expr*/); +TORCH_API std::ostream& operator<<(std::ostream& stream, const Stmt& /*stmt*/); +TORCH_API std::ostream& operator<<(std::ostream& stream, const Tensor& /*t*/); + +TORCH_API void print(const ExprPtr& expr); +TORCH_API void print(const StmtPtr& stmt); +TORCH_API void print(const Tensor& t); + +} // namespace torch::jit::tensorexpr + +namespace std { + +using torch::jit::tensorexpr::Expr; +using torch::jit::tensorexpr::ExprPtr; +using torch::jit::tensorexpr::Stmt; +using torch::jit::tensorexpr::StmtPtr; +using torch::jit::tensorexpr::Tensor; + +TORCH_API std::string to_string(const ExprPtr& expr); +TORCH_API std::string to_string(const StmtPtr& stmt); +TORCH_API std::string to_string(const Tensor& t); +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..62310b4e42739135e835a886dd69daec18fe7f75 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h @@ -0,0 +1,551 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +/* IR Simplification + * + * Simplifies expressions in two stages: + * 1. Recursively traverse the map combining similar operations into Terms + * (interacted via Multiplication) and Polynomials (interacted via Addition). We + * reorder the components of each Term or Polynomial into a consistent order to + * allow combination or cancelling of like terms. + * 2. Once the format of the tree is minimal, expand each Term into a sequence + * of Muls, and each Polynomial into a sequence of Ads. + */ + +namespace torch::jit::tensorexpr { + +// A bunch of helpers for determine the Dtype of the output of a multi argument +// Term or Polynomial. +template +Dtype promoteTypesVec(const ExprPtr& s, const std::vector& v) { + Dtype t = s->dtype(); + bool first = true; + + for (const auto& e : v) { + if (first) { + t = Dtype(t.scalar_type(), e->dtype().lanes()); + first = false; + } + t = promoteTypes(t, e->dtype()); + } + return t; +} + +template +Dtype promoteTypesVec(const std::vector& v) { + if (v.empty()) { + throw malformed_input("empty list of types"); + } + + Dtype t = v[0]->dtype(); + for (const auto& e : v) { + t = promoteTypes(t, e->dtype()); + } + return t; +} + +template +Dtype promoteTypesMap( + const ExprPtr& s, + std::unordered_map& m) { + Dtype t = s->dtype(); + bool first = true; + for (auto& e : m) { + if (first) { + t = Dtype(t.scalar_type(), e.second->dtype().lanes()); + first = false; + } + t = promoteTypes(t, e.second->dtype()); + } + return t; +} + +template +Dtype promoteTypesVar(ExprType e) { + return e->dtype(); +} + +template +Dtype promoteTypesVar(ExprType e, Args... es) { + Dtype lhs = e->dtype(); + Dtype rhs = promoteTypesVar(es...); + if (e->isConstant()) { + lhs = Dtype(lhs.scalar_type(), rhs.lanes()); + } + + return promoteTypes(lhs, rhs); +} + +// Uses the evaluator to fold an Expression with constant terms. +// E.g. evaluateOp(Add(3, 4)) => 7. +// Expr v must not have any unbound Vars. +inline ExprPtr evaluateOp(const ExprPtr& v) { + ExprHandle handle(v); + ExprEval eval(handle); + + switch (v->dtype().scalar_type()) { +#define TYPE_CASE(Type, Name) \ + case ScalarType::Name: { \ + Type val = eval.value(); \ + return getImmediateByType(v->dtype().scalar_type(), val); \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE) +#undef TYPE_CASE + default: + LOG(FATAL) << "Unsupported datatype: " << v->dtype(); + return nullptr; + } + return nullptr; +} + +// A Term represents a grouping of Exprs through multiplication. +// E.g. product(scalar, *variables). +class Term : public ExprNode { + public: + template + Term(HashProvider& hasher, ExprPtr s, Args... ts) + : ExprNodeBase(promoteTypesVar(s, ts...)), scalar_(s), hasher_(hasher) { + CHECK(s->isConstant()); + addComponent(ts...); + sort(); + } + + Term(HashProvider& hasher, ExprPtr s, std::vector v) + : ExprNodeBase(promoteTypesVec(s, v)), + variables_(std::move(v)), + scalar_(std::move(s)), + hasher_(hasher) { + sort(); + } + + // Convenience constructor from a map of hash -> var, used when merging Terms. + Term( + HashProvider& hasher, + const ExprPtr& s, + std::unordered_map varmap) + : ExprNodeBase(promoteTypesMap(s, varmap)), scalar_(s), hasher_(hasher) { + for (auto& p : varmap) { + addComponent(p.second); + } + sort(); + } + + ExprPtr scalar() const { + return scalar_; + } + const std::vector& variables() const { + return variables_; + } + HashProvider& hasher() const { + return hasher_; + } + + // Produce a hash of just the variable components of this term, to determine + // if it can be combined with another term. + SimplifierHashType hashVars() const; + + private: + std::vector variables_; + ExprPtr scalar_; + HashProvider& hasher_; + + void addComponent() {} + void addComponent(ExprPtr e) { + variables_.push_back(std::move(e)); + } + template + void addComponent(ExprPtr e, Es&&... es) { + addComponent(std::move(e)); + addComponent(std::forward(es)...); + } + + // Sort by hash to normalize order of components. + void sort(); +}; + +// Polynomial represents a grouping of Exprs by addition. +// E.g. sum(*variables, scalar). +// This would better be called Expression, but, naming conflict... +class Polynomial : public ExprNode { + public: + template + Polynomial(HashProvider& hasher, ExprPtr s, Args... ts) + : ExprNodeBase(promoteTypesVar(s, ts...)), scalar_(s), hasher_(hasher) { + CHECK(s->isConstant()); + addTerm(ts...); + sort(); + } + + Polynomial(HashProvider& hasher, const ExprPtr& s, std::vector v) + : ExprNodeBase(promoteTypesVec(s, v)), + variables_(std::move(v)), + scalar_(s), + hasher_(hasher) { + sort(); + } + + // Helper constructor for list of terms with no scalar component. + Polynomial(HashProvider& hasher, std::vector terms) + : ExprNodeBase(promoteTypesVec(terms)), + variables_(std::move(terms)), + scalar_(getImmediateByType(dtype(), 0)), + hasher_(hasher) { + sort(); + } + + // Convenience constructor for map of hash -> var, used when merging + // Polynomials. + Polynomial( + HashProvider& hasher, + const ExprPtr& s, + std::unordered_map varmap) + : ExprNodeBase(promoteTypesMap(s, varmap)), scalar_(s), hasher_(hasher) { + for (auto& p : varmap) { + addTerm(p.second); + } + sort(); + } + + ExprPtr scalar() const { + return scalar_; + } + const std::vector& variables() const { + return variables_; + } + HashProvider& hasher() const { + return hasher_; + } + + SimplifierHashType hashVars() const; + + private: + std::vector variables_; + ExprPtr scalar_; + HashProvider& hasher_; + + void addTerm(TermPtr t) { + variables_.push_back(std::move(t)); + } + template + void addTerm(TermPtr t, Ts&&... ts) { + addTerm(std::move(t)); + addTerm(std::forward(ts)...); + } + + // Sort by hash to normalize order of terms. + void sort(); +}; + +class RoundOff : public BinaryOpNode { + public: + RoundOff(ExprPtr lhs, ExprPtr rhs) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kOther) {} +}; + +class MaxTerm : public ExprNode { + public: + template + MaxTerm(HashProvider& hasher, ExprPtr s, bool p, Args... ts) + : ExprNodeBase(s ? promoteTypesVar(s, ts...) : promoteTypesVar(ts...)), + scalar_(s), + hasher_(hasher), + propagate_nans_(p) { + addComponent(ts...); + uniquefy(); + } + + MaxTerm( + HashProvider& hasher, + const ExprPtr& s, + bool p, + std::vector v) + : ExprNodeBase(s ? promoteTypesVec(s, v) : promoteTypesVec(v)), + variables_(std::move(v)), + scalar_(s), + hasher_(hasher), + propagate_nans_(p) { + uniquefy(); + } + + bool propagate_nans() const { + return propagate_nans_; + } + + ExprPtr scalar() const { + return scalar_; + } + const std::vector& variables() const { + return variables_; + } + HashProvider& hasher() const { + return hasher_; + } + + private: + std::vector variables_; + ExprPtr scalar_; + HashProvider& hasher_; + bool propagate_nans_; + + void addComponent() {} + void addComponent(ExprPtr e) { + variables_.push_back(std::move(e)); + } + template + void addComponent(ExprPtr e, Es&&... es) { + addComponent(std::move(e)); + addComponent(std::forward(es)...); + } + + // Uniquefy the terms using their hash. + void uniquefy(); +}; + +class MinTerm : public ExprNode { + public: + template + MinTerm(HashProvider& hasher, ExprPtr s, bool p, Args... ts) + : ExprNodeBase(s ? promoteTypesVar(s, ts...) : promoteTypesVar(ts...)), + scalar_(s), + hasher_(hasher), + propagate_nans_(p) { + addComponent(ts...); + uniquefy(); + } + + MinTerm( + HashProvider& hasher, + const ExprPtr& s, + bool p, + std::vector v) + : ExprNodeBase(s ? promoteTypesVec(s, v) : promoteTypesVec(v)), + variables_(std::move(v)), + scalar_(s), + hasher_(hasher), + propagate_nans_(p) { + uniquefy(); + } + + bool propagate_nans() const { + return propagate_nans_; + } + + ExprPtr scalar() const { + return scalar_; + } + const std::vector& variables() const { + return variables_; + } + HashProvider& hasher() const { + return hasher_; + } + + private: + std::vector variables_; + ExprPtr scalar_; + HashProvider& hasher_; + bool propagate_nans_; + + void addComponent() {} + void addComponent(ExprPtr e) { + variables_.push_back(std::move(e)); + } + template + void addComponent(ExprPtr e, Es&&... es) { + addComponent(std::move(e)); + addComponent(std::forward(es)...); + } + + // Uniquefy the terms using their hash. + void uniquefy(); +}; + +// Context-sensitive IR simplification +using VarBoundInfo = std::unordered_map; + +class TORCH_API SimplifierUnderContext : public IRMutator { + public: + ~SimplifierUnderContext() override = default; + // Add boundary info for index variables in for-loops + StmtPtr mutate(const ForPtr& v) override; + + ExprPtr mutate(const DivPtr& v) override; + ExprPtr mutate(const ModPtr& v) override; + ExprPtr mutate(const CompareSelectPtr& v) override; + ExprPtr mutate(const IfThenElsePtr& v) override; + + protected: + bool getLoopBoundInfo(const ExprPtr& expr, analysis::Bound* loop_bound_info); + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + HashProvider hasher_; + VarBoundInfo var_bound_info_; +}; + +// Stmt simplification should occur in both modes. +class TORCH_API PolynomialBase : public IRMutator { + public: + ~PolynomialBase() override = default; + + StmtPtr mutate(const BlockPtr& v) override; + + StmtPtr mutate(const CondPtr& v) override; + + StmtPtr mutate(const ForPtr& v) override; + + // Trivially factorize terms by GCD of scalar components. + TermPtr factorizePolynomial(const PolynomialPtr& poly); + + HashProvider& hasher() { + return hasher_; + } + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + HashProvider hasher_; +}; + +// Simplify the IR by combining arithmetic expressions over common terms. +class TORCH_API PolynomialTransformer : public PolynomialBase { + public: + using PolynomialBase::mutate; + // Inserts term into the provided map, in the case of a hash collision + // combines the term with the existing and updates the map. + void addOrUpdateTerm( + std::unordered_map& varmap, + const TermPtr& term); + + // Add Polynomial expressions, combining Terms representing the same + // variables. + ExprPtr addPolynomials(const PolynomialPtr& lhs, const PolynomialPtr& rhs); + + // Insert a new Term into the provided polynomial. If the new term has + // common variables to an existing term it is combined. + ExprPtr insertTerm(const PolynomialPtr& poly, const TermPtr& term); + + // Merge and simplify addition. + ExprPtr mutate(const AddPtr& v) override; + + // Subtract one term from another, cancelling if necessary. + ExprPtr subTerms(const TermPtr& lhs, TermPtr rhs, bool negated); + + // Subtract the RHS Polynomial from the LHS Polynomial, cancelling out where + // possible. + ExprPtr subPolynomials(const PolynomialPtr& lhs, const PolynomialPtr& rhs); + + // Merge and simplify subtraction. + ExprPtr mutate(const SubPtr& v) override; + + // Multiply two terms together, usually creating a new term with the variable + // lists concatenated. + TermPtr mulTerms(const TermPtr& lhs, const TermPtr& rhs); + + // Multiply a Polynomial by a Term. + ExprPtr polyByTerm(const PolynomialPtr& poly, const TermPtr& term); + + // Match a rounding pattern and create a RoundOff if found. + ExprPtr isRoundOff(const ExprPtr& lhs, const ExprPtr& rhs); + + // Inserts a new component into a term, simplifying if possible. + ExprPtr insertIntoTerm(const TermPtr& term, const ExprPtr& expr); + + // Merge and simplify multiplication. + ExprPtr mutate(const MulPtr& v) override; + + ExprPtr mutate(const DivPtr& v) override; + + ExprPtr mutate(const ModPtr& v) override; + + ExprPtr mutate(const AndPtr& v) override; + + ExprPtr mutate(const XorPtr& v) override; + + ExprPtr mutate(const LshiftPtr& v) override; + + ExprPtr mutate(const RshiftPtr& v) override; + + ExprPtr mutate(const MaxPtr& v) override; + + ExprPtr mutate(const MinPtr& v) override; + + ExprPtr mutate(const CompareSelectPtr& v) override; + + ExprPtr mutate(const IntrinsicsPtr& v) override; + + ExprPtr mutate(const CastPtr& v) override; + + ExprPtr mutate(const IfThenElsePtr& v) override; + + static ExprPtr simplify(ExprPtr e); + static ExprHandle simplify(const ExprHandle& e); + static StmtPtr simplify(StmtPtr e); +}; + +// Expands Terms and Polynomial expressions into primitive operations. +// Does some simple factorization and reordering. +class TORCH_API TermExpander : public PolynomialBase { + PolynomialTransformer* simplifier_; + std::set eliminated_allocations_; + + public: + using PolynomialBase::mutate; + TermExpander(PolynomialTransformer* simplifier) : simplifier_(simplifier) {} + bool check_safe() { + return eliminated_allocations_.empty(); + } + + // Expand Terms out to a series of Muls. + ExprPtr mutate(const TermPtr& v) override; + + // Expand Polynomials out to a series of Adds. + ExprPtr mutate(const PolynomialPtr& v) override; + + // Expand MaxTerms to a series of Max ops. + ExprPtr mutate(const MaxTermPtr& v) override; + + // Expand MinTerms to a series of Min ops. + ExprPtr mutate(const MinTermPtr& v) override; + + // Expand RoundOff to it's component: Mul(Div(lhs, rhs), rhs). + ExprPtr mutate(const RoundOffPtr& v) override; + + // Eliminate zero length allocations. + StmtPtr mutate(const AllocatePtr& v) override; + StmtPtr mutate(const FreePtr& v) override; + + // Override to enable condition fusing. + BlockPtr fuseConditions(BlockPtr v); + StmtPtr fuseSyncThreads(BlockPtr block); + StmtPtr mutate(const BlockPtr& v) override; +}; + +class TORCH_API IRSimplifier { + public: + static StmtPtr simplify(StmtPtr s); + static ExprPtr simplify(ExprPtr e); + static ExprHandle simplify(const ExprHandle& e) { + return ExprHandle(simplify(e.node())); + } +}; + +// Flattens the buf and performs the simplifier on the flattened dims. +ExprPtr buf_flat_size(const BufPtr& v); +// Returns true if expressions A and B can be simplified to an equal expression. +TORCH_API bool exprEquals(const ExprPtr& A, const ExprPtr& B); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h new file mode 100644 index 0000000000000000000000000000000000000000..bd88ed8314ae8b5c971815348aaffc8218a8f62f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h @@ -0,0 +1,59 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit::tensorexpr { + +class Expr; +class ExprHandle; +class Mod; +class And; +class Or; +class Xor; +class Lshift; +class Rshift; +class CompareSelect; +class Ramp; +class Load; +class IfThenElse; +class Intrinsics; + +class Stmt; +class ExternalCall; +class Store; +class For; +class Block; + +class TORCH_API IRVerifier : public IRVisitor { + public: + IRVerifier() = default; + + void visit(const ModPtr& v) override; + void visit(const AndPtr& v) override; + void visit(const OrPtr& v) override; + void visit(const XorPtr& v) override; + void visit(const LshiftPtr& v) override; + void visit(const RshiftPtr& v) override; + void visit(const CompareSelectPtr& v) override; + void visit(const RampPtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const IntrinsicsPtr& v) override; + + void visit(const ExternalCallPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const ForPtr& v) override; + void visit(const BlockPtr& v) override; +}; + +TORCH_API void verify(const StmtPtr& /*s*/); +TORCH_API void verify(const ExprPtr& /*e*/); +TORCH_API void verify(const ExprHandle& /*e*/); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_visitor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_visitor.h new file mode 100644 index 0000000000000000000000000000000000000000..d93ef37828c62407dbd27ff43a4fab3ffcf465e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_visitor.h @@ -0,0 +1,65 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::jit::tensorexpr { + +class TORCH_API IRVisitor { + public: + virtual ~IRVisitor() = default; + virtual void visit(const AddPtr& v); + virtual void visit(const SubPtr& v); + virtual void visit(const MulPtr& v); + virtual void visit(const DivPtr& v); + virtual void visit(const ModPtr& v); + virtual void visit(const MaxPtr& v); + virtual void visit(const MinPtr& v); + virtual void visit(const AndPtr& v); + virtual void visit(const OrPtr& v); + virtual void visit(const XorPtr& v); + virtual void visit(const LshiftPtr& v); + virtual void visit(const RshiftPtr& v); + virtual void visit(const CompareSelectPtr& v); + +#define IMM_PRINT_VISIT(Type, Name) virtual void visit(const Name##ImmPtr& v); + + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_PRINT_VISIT) +#undef IMM_PRINT_VISIT + + virtual void visit(const CastPtr& v); + virtual void visit(const BitCastPtr& v); + virtual void visit(const VarPtr& v); + virtual void visit(const BufPtr& v); + virtual void visit(const RampPtr& v); + virtual void visit(const LoadPtr& v); + virtual void visit(const ForPtr& v); + virtual void visit(const BlockPtr& v); + virtual void visit(const StorePtr& v); + virtual void visit(const BroadcastPtr& v); + virtual void visit(const IfThenElsePtr& v); + virtual void visit(const IntrinsicsPtr& v); + virtual void visit(const AllocatePtr& v); + virtual void visit(const FreePtr& v); + virtual void visit(const FreeExtPtr& v); + virtual void visit(const PlacementAllocatePtr& v); + virtual void visit(const LetPtr& v); + virtual void visit(const CondPtr& v); + virtual void visit(const TermPtr& v); + virtual void visit(const PolynomialPtr& v); + virtual void visit(const RoundOffPtr& v); + virtual void visit(const MaxTermPtr& v); + virtual void visit(const MinTermPtr& v); + virtual void visit(const ReduceOpPtr& v); + virtual void visit(const AtomicAddPtr& v); + virtual void visit(const SyncThreadsPtr& v); + virtual void visit(const ExternalCallPtr& v); + virtual void visit(const ExternalCallWithAllocPtr& v); +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b40b542412a76cdc7161b6a3f4bc97f83bf04d79 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/kernel.h @@ -0,0 +1,383 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +struct SmallSizeTPairHash { + public: + std::size_t operator()(const std::pair& x) const { + // hashing input index and then dim index + return x.first * 128 + x.second; + } +}; + +// Returns true if the TE fuser supports this conv2d. +bool conv2dIsSupportedJit(const Node* node); +// Returns true if the TE fuser supports this conv2d with mkldnn prepacked conv. +bool mkldnnPrepackedConvIsSupportedJit(const Node* node); +// Returns true if the TE _convolution node is Conv2d. +bool isConv2d(const Node* node); +// Returns true if the TE fuser supports this matmul. +bool matmulIsSupported(const Node* node); +template +inline std::vector bufferSizes(const T& t) { + std::vector sizes; + for (size_t i = 0; i < t->ndim(); i++) { + sizes.push_back(*intValue(t->dim(i))); + } + return sizes; +} + +// Get the dimensions of a value. +std::vector valueShape(const ArgValue& v); + +// If v is a tensor, broadcast it to match the shape of axes, or return +// directly if v is a constant. +ExprHandle tensorOrConstant( + const ArgValue& v, + const std::vector& axes); + +int64_t normalizeAndCheckIndex(int64_t idx, int64_t list_size); + +ExprHandle broadcast(const BufHandle& b, const std::vector& axes); + +ExprHandle constant(const ArgValue& v); + +std::vector computeIndicesToBroadcast( + const std::vector& outputAxes, + const std::vector& inputSizes); + +inline std::string getArgValueName(const ArgValue& a) { + if (std::holds_alternative(a)) { + return "BufHandle"; + } else if (std::holds_alternative(a)) { + return "VarHandle"; + } else if (std::holds_alternative(a)) { + return "double"; + } else if (std::holds_alternative(a)) { + return "int64_t"; + } else if (std::holds_alternative(a)) { + return "bool"; + } else if (std::holds_alternative(a)) { + return "BufList"; + } else if (std::holds_alternative(a)) { + return "DoubleList"; + } else if (std::holds_alternative(a)) { + return "IntList"; + } else if (std::holds_alternative(a)) { + return "None"; + } else { + throw std::runtime_error("ArgValue type not handled in string conversion"); + } +} + +template +std::vector convertVecArgValue(const std::vector& v) { + std::vector res; + for (auto& x : v) { + auto val = std::get_if(&x); + if (val) { + res.push_back(*val); + } else { + throw std::runtime_error( + "vector type not homogeneous - found " + getArgValueName(x) + + ", expected " + getArgValueName(v[0])); + } + } + return res; +} + +class TORCH_API TensorExprKernel { + struct ConstantDescr { + BufPtr buf; + // Only one of ptr and node is used at a time + // 1) ptr for the constant tensors + // 2) node for the constant custom class objects + void* ptr = nullptr; + Node* node = nullptr; + }; + + public: + // Constructor Params: + // * subgraph + // - the graph that needs to be compiled. + // * kernel_func_name + // - the name that should be used for the generated kernel. + // * custom_lowerings + // - map that represents custom lowering definitions for a set of ops. + // * symbolic_shape_inputs + // - a list of symbolic graph inputs that represent the symbolic dims of + // the input tensors. + // * pre_alloc + // - a flag to control pre-allocation of buffers. + explicit TensorExprKernel( + const std::shared_ptr& subgraph, + std::string kernel_func_name, + std::unordered_map custom_lowerings = + {}, + std::vector symbolic_shape_inputs = {}, + bool pre_alloc = false, + std::unordered_map< + const torch::jit::Value*, + std::vector> symbolic_strides = {}); + + explicit TensorExprKernel( + const std::shared_ptr& subgraph, + std::unordered_map custom_lowerings = + {}, + std::vector symbolic_shape_inputs = {}, + bool pre_alloc = false, + std::unordered_map< + const torch::jit::Value*, + std::vector> symbolic_strides = {}) + : TensorExprKernel( + subgraph, + SubgraphUtils::generateNameForGraph(subgraph), + std::move(custom_lowerings), + std::move(symbolic_shape_inputs), + pre_alloc, + std::move(symbolic_strides)) {} + + void run(Stack& stack) const; + void runFast( + const std::vector& inputs, + const std::vector& outputs) const; + // Expected format of stack: + // ... + // i.e., output IValues must be below the input IValues in the stack. + void runWithAllocatedOutputs(Stack& stack) const; + + void fallback(Stack& stack) const { + InterpreterState(code_).run(stack); + } + void recompile(); + + StmtPtr getCodeGenStmt(); + + std::string getCodeText(const std::string& attr = "") { + return codegen_->getCodeText(attr); + } + + const std::shared_ptr graph() { + return graph_; + } + + const std::vector& getConstantDescriptors() const { + return constants_; + } + + const std::vector& getBufferArgs() const { + return bufferArgs_; + } + + const std::string& getKernelName() const { + return (codegen_ ? codegen_->kernel_func_name() : kernel_func_name_); + } + + const std::vector& getSymbolicShapeInputs() const { + return symbolic_shape_inputs_; + } + + private: + enum BackendType { + kUninitialized, + kSimpleIREval, + kLLVMCodeGen, + kCudaCodeGen, + kBlockCodeGen, + }; + + enum MemoryLayoutPolicy { + kContiguous, + kChannelsLastNdContiguous, + }; + + void compile(); + void genInputDebugNames(); + void runKernel(Stack& stack) const; + + std::vector sizesForValue(const torch::jit::Value* v); + + // These functions broadcast shape and also store a `hasBroadcast_` variable. + std::vector broadcastShapesMut( + const std::vector& a, + const std::vector& b); + std::vector broadcastShapesMut( + std::vector> shapes); + + ArgValue toArg(const torch::jit::Value* v) const; + ExprHandle constant(const torch::jit::Value* v); + + Tensor computeValue(const torch::jit::Value* v); + + void bindConstant(const torch::jit::Value* v); + + StmtPtr transformLoops(BackendType backendType, StmtPtr st); + + std::string getCodeGenName(BackendType backendType); + + void getStaticOutputSizesAndStrides( + const at::ArrayRef& inputs, + std::vector>* static_sizes, + std::vector>* static_strides) const; + + std::vector prepareRunArgs( + const at::ArrayRef& inputs, + std::vector& outputs) const; + BackendType inferBackendTypeFromDevice(at::Device device); + + Tensor bindInput(const torch::jit::Value* input); + BlockPtr bindAllInputs(); + + // Deduce the memory layout policy to be propagated within + // NNC fusion group. The memory layout policy could be `kContiguous` + // or `kChannelsLastNdContiguous`. + // `kContiguous`: Always convert the non-contiguous input tensors and + // internal buffers to contiguous. + // `kChannelsLastNdContiguous`: Always convert the input tensors and + // internal buffers to channels-last contiguous. + // Currently, the rule is simple. + // If all the input and out tensors of NNC fusion group are channels-last + // contiguous, the policy is `kChannelsLastNdContiguous`. Otherwise, it + // is always `kContiguous`. + void deduceMemoryLayoutPolicy(); + + Tensor convertSymbolicOutputToCorrectStrides(torch::jit::Value* v); + Tensor convertStaticShapeOutputToCorrectStrides(torch::jit::Value* v); + Tensor convertSymbolicOutputToCorrectStrides( + const std::vector& sizes, + const std::vector& sorted_stride_indices_descending, + const std::vector& strides, + BufPtr& buf); + + NNCLoweringFunction getCustomLoweringFor(c10::Symbol op) const; + std::unordered_map getCustomLowerings() + const { + return custom_lowerings_; + } + + // Allocate memory for intermediate buffers at compile time. + // Specifically, we pre-allocate memory for intermediate buffers with static + // size and manage these buffers in the way we manage JIT constant tensors: + // push the buf args into the stack so NNC IR can access them at runtime. + std::vector preAllocIntermediateBufs( + const std::vector& interm_bufs); + + struct UnpackedTensorOptions { + std::optional dtype; + std::optional layout; + std::optional device; + std::optional pinned_memory; + + UnpackedTensorOptions(const c10::TensorOptions& opts) + : dtype(c10::optTypeMetaToScalarType(opts.dtype_opt())), + layout(opts.layout_opt()), + device(opts.device_opt()), + pinned_memory(opts.pinned_memory_opt()) {} + }; + + ExprHandle getVarForShape(const c10::ShapeSymbol& ss); + std::vector computeInputTensorDims( + const torch::jit::Value* input); + ExprHandle getStrideArg(size_t tensor_input, size_t stride_index); + std::vector sizesFromSymbolicShape( + const c10::SymbolicShape& shape); + std::vector getInputStrides( + const torch::jit::Value* input, + const std::vector& inputTensorDims); + std::vector& getSymbolicStrideDesc( + const torch::jit::Value* value); + + // Apply the optimizations to the graph owned by the current fusion group, + // like concatenation optimization, post-op fusion, and some other graph-level + // optimizations. + void optimizeOwningGraph(); + + int64_t nInputs_ = 0; + int64_t nOutputs_ = 0; + std::vector bufferArgs_; + std::vector> tensorOutputSizes_; + std::vector> tensorOutputStrides_; + std::vector tensorOutputStrideDesc_; + std::vector isOutputScalar_; + std::vector tensorOutputTensorOptions_; + std::unordered_set bufOutputs_; + std::unordered_set bufsToBeParallelized_; + std::unordered_map bufs_; + std::unordered_map scalars_; + std::unordered_map input_name_map_; + std::unique_ptr codegen_; + at::Device device_ = at::kCPU; + std::shared_ptr graph_; + Code code_; + bool allow_fallback_{false}; + bool use_fallback_{false}; + bool hasRandom_{false}; + bool hasBroadcast_{false}; + std::unordered_map> + known_sizes_; + + std::vector> tensorOutputSymbolicSizes_; + // A map from ShapeSymbol.value() to the corresponding Var. + std::unordered_map shapeSymbolToVar_; + std::unordered_map shapeSymbolInputPos_; + // List of values corresponding to the ShapeSymbols that are inputs to + // kernel being compiled. The order of these values correspond to the order + // of the symbolic inputs at the end of the list of inputs to the kernel. + std::vector symbolic_shape_inputs_; + bool has_symbolic_shapes_{false}; + + std::vector unpacked_constant_tensors_; + std::vector constants_; + + std::unordered_map custom_lowerings_; + StmtPtr stmt_ = nullptr; + bool pre_alloc_{false}; + std::string kernel_func_name_; + + // index of stack, stride index of tensor that will be appended as a codegen + // arg + std::vector> input_stride_args_; + // map from to stride as arg VarHandle + std::unordered_map, VarHandle, SmallSizeTPairHash> + strideArgToVar_; + std::unordered_map< + const torch::jit::Value*, + std::vector> + symbolic_strides_; + + // Memory layout to be propagated with fusion group + MemoryLayoutPolicy memory_layout_policy_ = MemoryLayoutPolicy::kContiguous; +}; + +TORCH_API int& getTECudaPointwiseLoopLevels(); +TORCH_API int& getTECudaPointwiseBlockCount(); +TORCH_API int& getTECudaPointwiseBlockSize(); +TORCH_API bool& getTEGenerateBlockCode(); +TORCH_API bool& getTEMustUseLLVMOnCPU(); +TORCH_API bool fallbackAllowed(); +TORCH_API bool setFallbackAllowed(bool value); +TORCH_API bool& getCatWoConditionals(); +TORCH_API bool& getOptConditionals(); + +TORCH_API std::optional pickDeviceType( + const at::ArrayRef& inputs); + +bool isContiguous( + const torch::jit::Value* v, + at::MemoryFormat memory_format = at::MemoryFormat::Contiguous); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..f253224710956595b35d147f0687e0763ee74fd1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h @@ -0,0 +1,148 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef TORCH_ENABLE_LLVM +#include + +#include +#include +#include + +#include + +#include +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +class LLVMCodeGenImpl; +class LLVMCodeGenCallee; + +class TORCH_API LLVMCodeGen : public CodeGen { + public: + explicit LLVMCodeGen( + StmtPtr stmt, + const std::vector& args, + at::Device device = at::kCPU, + const std::string& kernel_func_name = "func", + Dtype dtype = kInt, + std::optional triple = std::nullopt, + std::optional cpu = std::nullopt, + std::optional attrs = std::nullopt); + explicit LLVMCodeGen(StmtPtr stmt); + + LLVMCodeGen() = delete; + ~LLVMCodeGen() override; + + // Cleans up all the memory used during LLVM code generation pass except + // the generated kernel. After calling this method, users should not call + // methods like `getCodeText` that require the LLVMCodeGenImpl data. However, + // users can continue to call this kernel using `call` and `call_raw`. + void cleanup_memory(); + + TORCH_API void call(const std::vector& args) override; + TORCH_API void call_raw(const std::vector& args) override; + TORCH_API void call_with_numel(void** args, int64_t numel) override; + + at::Tensor empty_strided( + c10::IntArrayRef size, + c10::IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt) override; + + template + T value() { + return value(nullptr); + } + + template + T value(std::vector& args) { + return value(args.data()); + } + + template + T value(void** args) { + T (*fp)(void**) = (T(*)(void**))getKernelAddress(callee_.get()); + T rv = fp(args); + return rv; + } + + std::string getCodeText(const std::string& attr = "") override; + + private: + void* getKernelAddress(LLVMCodeGenCallee* callee); + + std::unique_ptr callee_; + std::unique_ptr impl_; +}; + +struct TORCH_API LLVMCodeGenBuilder { + using BufferArg = CodeGen::BufferArg; + + LLVMCodeGenBuilder(StmtPtr stmt, std::vector args) + : stmt_(stmt), args_(std::move(args)) {} + + LLVMCodeGenBuilder& device(at::Device device) { + device_ = device; + return *this; + } + + LLVMCodeGenBuilder& kernelFuncName(std::string name) { + kernelFuncName_ = std::move(name); + return *this; + } + + LLVMCodeGenBuilder& dtype(Dtype d) { + dtype_ = d; + return *this; + } + + LLVMCodeGenBuilder& triple(std::string triple) { + triple_ = std::move(triple); + return *this; + } + + LLVMCodeGenBuilder& cpu(std::string cpu) { + cpu_ = std::move(cpu); + return *this; + } + + LLVMCodeGenBuilder& attrs(std::string attrs) { + attrs_ = std::move(attrs); + return *this; + } + + std::unique_ptr build() { + return std::make_unique( + stmt_, args_, device_, kernelFuncName_, dtype_, triple_, cpu_, attrs_); + } + + private: + StmtPtr stmt_; + std::vector args_; + at::Device device_ = at::kCPU; + std::string kernelFuncName_ = "func"; + Dtype dtype_ = kInt; + std::optional triple_ = std::nullopt; + std::optional cpu_ = std::nullopt; + std::optional attrs_ = std::nullopt; +}; + +TORCH_API std::optional& LLVMTargetTriple(); +TORCH_API std::optional& LLVMTargetCPU(); +TORCH_API std::optional& LLVMTargetAttrs(); +TORCH_API bool& LLVMAOTWorkflow(); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch + +#endif // TORCH_ENABLE_LLVM + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h new file mode 100644 index 0000000000000000000000000000000000000000..deece5fe694540855646f8a33f723ed5babf5bbe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h @@ -0,0 +1,84 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef TORCH_ENABLE_LLVM +#include +#include +#include +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wsuggest-override") +#include +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wextra-semi") +#include +#include +#include +C10_DIAGNOSTIC_POP() + +#include +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +inline std::string formatError(llvm::Error&& err, const char* msg) { + static constexpr const char* defaultErrorMsg = + "Unexpected failure in LLVM JIT"; + std::string errorMsg(msg ? msg : defaultErrorMsg); + llvm::raw_string_ostream ss(errorMsg); + ss << ": " << err; + return ss.str(); +} + +template +T assertSuccess(llvm::Expected valOrErr, const char* msg = nullptr) { + TORCH_INTERNAL_ASSERT(valOrErr, formatError(valOrErr.takeError(), msg)); + return std::move(*valOrErr); +} + +inline void assertSuccess(llvm::Error err, const char* msg = nullptr) { + TORCH_INTERNAL_ASSERT(!err, formatError(std::move(err), msg)); +} + +} // namespace tensorexpr +} // namespace jit +} // namespace torch + +namespace llvm { +namespace orc { + +class PytorchLLVMJITImpl; + +class TORCH_API PytorchLLVMJIT { + public: + PytorchLLVMJIT( + std::optional triple, + std::optional cpu, + std::optional attrs); + ~PytorchLLVMJIT(); + + void addModule(std::unique_ptr M, std::unique_ptr C); + + JITSymbol findSymbol(const std::string Name); + + bool hasSymbol(const std::string& Name); + + TargetMachine& getTargetMachine(); + + const DataLayout& getDataLayout(); + + private: + // Use the PImpl idiom here to hide the no-rtti parts of the JIT structure. + std::unique_ptr impl_; +}; + +} // end namespace orc +} // end namespace llvm + +#endif // ENABLE LLVM + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h new file mode 100644 index 0000000000000000000000000000000000000000..fe3f27c0861dc6b643f5ffbd3cceb53517642cec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h @@ -0,0 +1,622 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { + +class Expr; +class Var; +class Buf; +class Tensor; +class Function; +class Stmt; +class For; +class Block; +class Store; +class Dtype; + +class TORCH_API LoopNest { + public: + // A constructor for building a LoopNest from a list of Tensors + LoopNest( + const std::vector& output_tensors, + const std::vector& tensors_to_compute); + + // A convenience constructor for the case when all tensors are output tensors + LoopNest(const std::vector& output_tensors); + + // A constructor for building a LoopNest from an Stmt and a list of output + // buffers. + LoopNest(StmtPtr stmt, std::unordered_set output_bufs); + + // A constructor for building a LoopNest from another loopnest. It clones the + // other loopnest's stmt. + LoopNest(const LoopNest& other); + + StmtPtr root_stmt() const { + return root_stmt_; + } + + std::vector getLoopStmtsFor(const Tensor& /*t*/) const; + std::vector getLoopStmtsFor(const BufPtr& /*buf*/) const; + std::vector getLoopStmtsFor(StmtPtr /*s*/) const; + StmtPtr getLoopBodyFor(const Tensor& /*t*/) const; + StmtPtr getLoopBodyFor(BufPtr /*buf*/) const; + + // Returns the For stmt indexed by 'indices' in the 'root' For stmt. + //'indices' indicates the path to the returned loop from 'root' in AST, e.g., + // + // root: for(int i...){ + // j_loop: for (int j...){ + // k1_loop: for (int k1...){ + // A[i, j, k1] = .... + // } + // B[i, j] = ... + // k2_loop: for (int k2...){ + // A[i, j, k2] = ... + // } + // } + // } + // + // the path from 'root' to 'j_loop' is [0] + // the path from 'root' to 'k1_loop' is [0, 0] + // the path from 'root' to 'k2_loop' is [0, 2] + ForPtr getLoopAt(ForPtr root, const std::vector& indices) const; + + // Returns the For stmt that is immediately enclosing the given stmt. + static ForPtr getParentLoop(const StmtPtr& st); + + // Returns the list of For stmts corresponding to the loopnest that is + // enclosing the given stmt. + static std::vector getEnclosingLoopNest(const StmtPtr& st); + + // Returns a list of all Stmts that write to the given buf. + std::vector getAllWritesToBuf(BufPtr /*buf*/) const; + + // The following methods return the For loops that contain writes to + // the given buf. + // + // For example, consider the following code: + // for i1 + // for j1 + // a[i1,j1] = + // for i2 + // for j2 + // for k2 + // a[i2,j2] = + // for j3 + // a[i2,j3] = + + // Returns a list of For loops which directly contain a Stmt that writes + // to buf. + // For the above example: + // getAllInnermostLoopsWritingToBuf(a) => {j1, k2, j3} + std::vector getAllInnermostLoopsWritingToBuf(BufPtr /*buf*/) const; + + // Returns a list of For loopnests which contain a Stmt that writes to + // the given buf. Each loopnest here is a vector For loops. + // For the above example: + // getAllLoopNestsWritingToBuf(a) => {{i1,j1}, {i2,j2,k2}, {i2,j3}} + std::vector> getAllLoopNestsWritingToBuf( + BufPtr /*buf*/) const; + + StmtPtr simplify(); + + // Sanitize variables and buffer names. + // The pass assigns predefined names for loop index variables + // (i,j,k,l,m,n,o,p,i1,j1,k1,...) and ensures these names are not conflicting + // anywhere. It also removes duplicates from other Buf nad Var names as well + // as replaces illegal characters in them with underscores. + // + // Note: since it's currently technically possible to use the same variable + // as index in two different loops, this transformation finds such cases and + // introduces new variables to avoid duplication. + static StmtPtr sanitizeNames(StmtPtr s); + + bool computeInline(const StmtPtr& s); + bool computeInline(const BufPtr& b); + void inlineIntermediateBufs(bool allow_duplicated_work); + + // Optimizes conditionals. + // + // Currently, only the following pattern of conditionals is optimized. + // This corresponds to the conditional format that is generated to handle + // `aten::cat` op. + // + // for (int i = 0; i < 20; i++) { + // A[i] = IfThenElse(i<5 ? 1 : 0, B[i], C[i-5]) + // } + // + // Constraints that must be satisfied for this optimization: + // * All conditions should be of the form "var < expr". + // * All conditions should have the same variable, say v. + // * The condition variable found should be the same as the inner-most + // loop variable. TODO: Remove this constraint. + // * If there are multiple stores that contain conditionals using the same + // loop variable, only the first conditional will be optimized. + // TODO: Remove this constraint. + bool optimizeConditionals(); + + // Splits the given loop into 2 nested loops with the given factor as the + // inner loop bound. If the factor does not evenly divide the loop bound, + // then the remaining iterations are extracted into a tail loop that is + // added after the given loop. + // + // For example, consider the following code: + // for (int i = 0; i < 100; ++i) { + // A[i] = + // } + // + // splitWithTail(i, 8, ...) will result in: + // for (int i_outer = 0; i_outer < 12; ++i_outer) { + // for (int i_inner = 0; i_inner < 8; ++i_inner) { + // A[i_outer * 8 + i_inner] = + // } + // } + // for (int i_tail = 0; i_tail < 4; ++i_tail) { + // A[i_tail + 96] = + // } + // + // The given loop will be transformed to the outer loop after splitting. + // So, the pointer to the input loop should be valid after splitting and + // will point to the outer loop. The `inner` and `tail` parameters will be + // set to point to the inner and tail loops that are generated. + static void splitWithTail( + const ForPtr& f, + int factor, + ForPtr* inner, + ForPtr* tail); + // A convenience wrapper when the caller does not need to access the + // split loops. + static void splitWithTail(const ForPtr& f, int factor); + + // Splits the given loop into 2 nested loops with the given factor as the + // inner loop bound. If the factor does not evenly divide the loop bound, + // then a conditional is inserted into the body to handle the remaining + // iterations appropriately. + // + // For example, consider the following code: + // for (int i = 0; i < 100; ++i) { + // A[i] = + // } + // + // splitWithMask(i, 8, ...) will result in: + // for (int i_outer = 0; i_outer < 13; ++i_outer) { + // for (int i_inner = 0; i_inner < 8; ++i_inner) { + // if (i_outer * 8 + i_inner < 100) { + // A[i_outer * 8 + i_inner] = + // } + // } + // } + // + // The given loop will be transformed to the outer loop after splitting. + // So, the pointer to the input loop should be valid after splitting and + // will point to the outer loop. The `inner` parameter will be set to point + // to the inner loop that is generated. + static void splitWithMask(const ForPtr& f, int factor, ForPtr* inner); + // A convenience wrapper when the caller does not need to access the + // split loops. + static void splitWithMask(const ForPtr& f, int factor); + + // The following methods support loop distribution. + // For example, consider the following code. This will be used to + // demonstrate the methods below. + // + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + + // This method distributes the given loop over its body by splitting + // after every given pivot stmt. + // + // NOTE: Pivot stmts that are not in the given loop's body will be ignored. + // + // For the above example: + // distributeLoop(S1, {S3, S5}) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoop( + const ForPtr& loop, + const std::unordered_set& pivots); + + // This method distributes the given loop over every stmt in its body. + // + // For the above example: + // distributeLoop(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // : for i + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoop(const ForPtr& loop); + // Same as above, but also distribute parent loops. + // Returns the result of distributing the outermost loop. + // + // For the above example: + // distributeLoopAndParents(S1) will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // : for m + // : for i + // S3: for j + // S4: A[i] = A[i] + + // : for m + // : for i + // S5: B[i] = A[i] + // : for m + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopAndParents(const ForPtr& loop); + + // This method distributes the given loop over its body by splitting + // after every For stmt in its body. + // + // For the above example: + // distributeLoopOverInnerLoops(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopOverInnerLoops(const ForPtr& loop); + // Same as above, but also distribute parent loops. + // Returns the result of distributing the outermost loop. + // + // For the above example: + // distributeLoopAndParentsOverInnerLoops(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for m + // : for i + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopAndParentsOverInnerLoops( + const ForPtr& loop); + + // This method performs loop fusion. + // For example, consider the following code. + // + // S1: for m + // S2: A[m] = 0 + // S3: for j + // S4: A[m] = A[m] + + // S5: for n + // S5: B[n] = A[n] + // S6: for k + // S7: B[n] = B[n] + + // + // fuseLoops({S1, S5}), will return the following loop: + // S1: for m + // S2: A[m] = 0 + // S3: for j + // S4: A[m] = A[m] + + // S5: B[m] = A[m] + // S6: for k + // S7: B[m] = B[m] + + // + // This transformation is unsafe as it simply add all loops into the body of + // the first loop for fusion without correctness checks. + // + // Below are the two requirements to apply unsafeFuseLoops: + // * All the loops have the same parent. + // * There are no statements between these loops in their parent body. + static bool unsafeFuseLoops(const std::vector& loops, ForPtr* fused); + + // Loop fusion is done only when all the conditions below are satisfied. + // * All the loops have the same parent. + // * There are no statements between these loops in their parent body. + // * The start bounds are the same for all loops. + // * The stop bounds are the same for all loops. + // * Fusing the loops does not violate or add any dependencies. + static bool fuseLoops(const std::vector& loops, ForPtr* fused); + + static void reorderAxis(const ForPtr& a, const ForPtr& b); + + // Reorder the given list of loops according to the permutation specified. + // Here `permutation[i]` represents the position of the loop in the input + // which will end up at position `i` after the reorder. + // + // For example, consider the following code: + // for p + // for q + // for r + // for s + // A[p,q,r,s] = + // + // reorder({p, q, r, s}, {2, 3, 0, 1}) will return the list of loops in the + // following form: + // for r + // for s + // for p + // for q + // A[p,q,r,s] = + static std::vector reorder( + const std::vector& loops, + const std::vector& permutation); + + // Tile takes a 2d domain (x, y) and splits it into small rectangular blocks + // each with shape (x_factor, y_factor). The traversal over the domain turns + // into an outer iteration over the blocks and an inner traversal over all + // points in the block. + // Note that if x dim % x_factor or y dim % y_factor does not equal to 0, the + // loop body will generate corresponding tailing loops. + // The transformation is in-place and returns 'xtail'. + // + // For example, consider the following code: + // for i: [0, 64) + // for j: [0, 64) + // for k: [0, 32) + // A[i, j] = B[i, k] + C[j, k] + // + // tile(i, j, 4, 8) will transform "i" for-stmt into the following nested + // loop: + // for i_outer: [0, 16) + // for j_outer: [0, 8) + // for i_inner: [0, 4) + // for j_inner: [0, 8) + // for k: [0, 32) + // A[i_outer * 4 + i_inner, j_outer * 8 + j_inner] = + // B[i_outer * 4 + i_inner, k] + C[j_outer * 8 + j_inner, k] + // + // tile(i, j, 4, 9) will transform "i" for-stmt into the following nested + // loop: + // for i_outer: [0, 16) + // for j_outer: [0, 7) + // for i_inner: [0, 4) + // for j_inner: [0, 9) + // for k: (0, 32) + // A[i_outer * 4 + i_inner, j_outer * 9 + j_inner] = + // B[i_outer * 4 + i_inner, k] + C[j_outer * 9 + j_inner, k] + // for j_tail: [0, 1) + // for i_inner: [0, 4) + // for k: (0, 32) + // A[i_outer * 4 + i_inner, 7 * 9 + j_tail] = + // B[i_outer * 4 + i_inner, k] + C[7 * 9 + j_tail, k] + ForPtr tile(const ForPtr& x, const ForPtr& y, int x_factor, int y_factor); + + // Returns true if the given loops are perfectly nested, i.e., every loop + // (except the innermost) should have exactly one statement in its body + // and that statement must be the next inner loop. + static bool areLoopsPerfectlyNested(const std::vector& loops); + + // Returns true if the given loop has a loop-carried dependence. + static bool hasLoopCarriedDependence(const ForPtr& loop); + + // Unrolls all the iterations of the given loop. + // Requires that the loop bounds are constant. + static void fullUnroll(const ForPtr& f, StmtPtr* unrolled); + static void fullUnroll(const ForPtr& f); + + // Unrolls the given loop for the specified factor. + // This does not require constant bounds for the loop being unrolled. + static void unroll(const ForPtr& f, int factor, ForPtr* tail); + static void unroll(const ForPtr& f, int factor); + + static bool normalize(const ForPtr& f); + static bool isNormalized(const ForPtr& f); + + static bool flatten(const std::vector& f, ForPtr* flattened); + static bool flatten(const std::vector& f); + + // Compresses the given buffer based on its use in the given Stmts. + // + // NOTE: This API assumes that there are no accesses to the given buffer + // outside the given statement. So, this should be called with the entire + // kernel statement to avoid incorrect buffer compressions. + // + // For example, given the input: + // + // for (int i = 0; i < 100; ++i) { + // for (int j = 0; j < 200; ++j) { + // A[i,j] = sin(i*j) + // } + // for (int j = 0; j < 199; ++j) { + // B[i,j] = A[i,j] + A[i, j+1] + // } + // } + // + // compressBuffer(A, ...) will compress buffer A from + // [100, 200] to [1, 200] and modify the code as follows: + // + // for (int i = 0; i < 100; ++i) { + // for (int j = 0; j < 200; ++j) { + // A[0,j] = sin(i*j) + // } + // for (int j = 0; j < 199; ++j) { + // B[i,j] = A[0,j] + A[0, j+1] + // } + // } + static void compressBuffer(const BufPtr& buf, const StmtPtr& stmt); + + // Compresses all buffers in the given statement. + // + // NOTE: This API assumes that there are no accesses to buffers outside + // the given statement. So, this should be called with the entire + // kernel statement to avoid incorrect buffer compressions. + // + // TODO: Add an IR verifier check to detect invalidly compressed buffers. + static void compressAllBuffers(const StmtPtr& stmt); + + // Get 'num' loops from the loopnest starting at 'f'. + static std::vector getLoopStmtsInLoopNest( + const ForPtr& f, + size_t num); + + // LoopOptions are propagated to tail. + static void sliceHead( + const ForPtr& f, + int factor, + ForPtr* head, + ForPtr* tail); + static void sliceHead(const ForPtr& f, int factor); + // LoopOptions are propagated to head. + static void sliceTail( + const ForPtr& f, + int factor, + ForPtr* head, + ForPtr* tail); + static void sliceTail(const ForPtr& f, int factor); + + using AccessResult = std::pair; + // Insert a cache for the consumer's usages of the buffer produced in + // consumer, and redirect reads and writes in the consumer to that cache. + // Returns a pair of the new cache buffer, and the new rewritten consumer. + static AccessResult cacheAccesses( + const BufPtr& producer, + const std::string& name, + const StmtPtr& consumer); + + // Insert a temporary computation of statement S in the scope of loop AT. + // S is assumed to be a Store or a Block containing a Store. Along with the + // computation itself, this transformation inserts Alloc/Free statements for + // the temporary buffer used in the computation. + static void computeAt(const StmtPtr& s, const ForPtr& at); + + // Rfactor a reduction axis into a normal axis. + // + // Requirements: + // * S is the reduction store + // * S is the only statement in the innermost loop + // * There is at least two reduction arguments in S + // * OUTER_REDUCTION_FOR loop corresponds to the outermost reduction variable + // used in the store and all other reduction variables are index variables of + // children loops of OUTER_REDUCTION_FOR + // * OUTER_REDUCTION_FOR is a perfect loop nest, i.e. it has only loops + // corresponding to the other reduction variables and the store, nested into + // each other + // + // What it does: + // * Introduce a new buffer with an extra dimension of a size equal to the + // span of the loop OUTER_REDUCTION_FOR (the new buffer is returned via + // RFAC_BUF_PTR) + // * Insert an initialization store for the new buffer in + // OUTER_REDUCTION_FOR before its nested loop + // * Replace the reduction store to the original buffer with the reduction + // store to the temp buffer, removing the index var of OUTER_REDUCTION_FOR + // from reduction arguments + // * Insert a final reduction store over the extra dimension of the new + // buffer to the original buffer + // * Returns TRUE if the transformation succeeded and FALSE otherwise + // + // Example: + // Original IR: + // S1: for i # normal axis + // S2: X[i] = 0 + // S3: for j # reduction axis + // S4: for k # reduction axis + // S5: X[i] = ReduceOp(X[i] + Y[i,j,k], reduce_axis={j,k}) + // + // After RFACTOR(S5, S3) + // S1: for i # normal axis + // S2: X[i] = 0 + // S3: for j # reduction axis for X, normal axis for X_rfac + // X_rfac[i,j] = 0 + // S4: for k # reduction axis + // X_rfac[i,j] = ReduceOp(X_rfac[i,j] + Y[i,j,k], reduce_axis={k}) + // X[i] = ReduceOp(X[i] + X_rfac[i,j], reduce_axis={j}) + static bool rfactor(const StmtPtr& s, const ForPtr& outer_reduction_for); + static bool rfactor( + const StmtPtr& s, + const ForPtr& outer_reduction_for, + BufPtr* rfac_buf_ptr); + + // Vectorize the given loop. This method requires that the given loop + // does not perform a reduction. + // It returns true if vectorization is successful and false otherwise. + static bool vectorize(const ForPtr& /*f*/); + + // Find the inner-most loops and vectorize them. Currently, this only works + // for the LLVM backend, when no reductions are involved. + void vectorizeInnerLoops(); + + void eliminateDeadStores(); + + void prepareForCodegen(); + + const std::unordered_set getInputBufs() const; + const std::unordered_set getOutputBufs() const { + return output_bufs_; + } + std::vector getIntermediateBufs() const; + + // Finds which is the outer For between a and b for loops. If neither of the 2 + // Fors is an ancestor of the other, it returns nullptr. + static ForPtr findOuterFor(ForPtr a, ForPtr b); + + private: + void initialize( + const std::vector& output_tensors, + const std::vector& tensors_to_compute); + + StmtPtr root_stmt_; + + std::unordered_set output_bufs_; +}; + +TORCH_API StmtPtr FlattenIndexes(const StmtPtr& s); + +// TODO: Revisit this once we decide on how dependencies analysis should look +// like. Maybe we would choose to use a different API and BufUse would be +// removed, or if we decide to keep it we need to properly document its API. +struct BufLoadOrStoreUse { + StmtPtr s; + bool isStore; +}; + +/* + * Returns a map ( Buf -> uses of this Buf), uses are represented as vectors of + * BufUse elements, which are StmtPtr and a bool isStore flag. The order of uses + * in the vectors reflects the order in which the uses appear in the given + * statement. + */ +std::unordered_map> findLoadOrStoreUses( + const StmtPtr& s); + +// replaces all invalid characters with underscore +TORCH_API std::string sanitizeName(const std::string& input_name); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h new file mode 100644 index 0000000000000000000000000000000000000000..674fd337b0ea8ceb9cb6d09f122489eaa56cdc30 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::jit::tensorexpr { + +// Applies a series of loop optimizations chosen randomly. This is only for +// testing purposes. This allows automatic stress testing of NNC loop +// transformations. +void loopnestRandomization(int64_t seed, LoopNest& l); +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h new file mode 100644 index 0000000000000000000000000000000000000000..79a75576d509dbe9b143daf2611cde26d7149d7d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// This file defines classes for registering standard lowerings from JIT to TE +// IR. +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +using ArgNone = std::monostate; +using BufList = std::vector; +using DoubleList = std::vector; +using IntList = std::vector; +using ArgValue = std::variant< + tensorexpr::BufHandle, + tensorexpr::VarHandle, + double, + int64_t, + bool, + BufList, + DoubleList, + IntList, + std::string, + ArgNone>; + +using NNCLoweringFunction = std::function&, + const std::vector&, + const std::vector&, + const std::optional&, + at::Device)>; + +TORCH_API FunctionSchemaMap& getNNCLoweringRegistry(); +TORCH_API NNCLoweringFunction getStandardLoweringFor(const std::string& op); + +struct RegisterNNCLoweringsFunction { + RegisterNNCLoweringsFunction( + const std::vector& schemas, + const NNCLoweringFunction& fn); +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h new file mode 100644 index 0000000000000000000000000000000000000000..8e5b9e292d862bf890e19729b0a4ba206d4a85bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h @@ -0,0 +1,414 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr::analysis { + +enum class AccessType { + Input, + Output, + Load, + Store, + Call, + AtomicAdd, + Alloc, + Free +}; +const char* AccessToString(AccessType a); + +class AccessInfo; +using DependencySet = std::unordered_set>; + +/* AccessInfo + * + * Represents a single bounded memory access to a buffer, for instance a Load or + * a Store. Holds information relating to the specific access and links to + * connected accesses in the dependency graph. + */ +class TORCH_API AccessInfo { + public: + AccessInfo( + size_t id, + AccessType type, + StmtPtr stmt, + VarPtr var, + IndexBounds bounds) + : id_(id), + type_(type), + stmt_(std::move(stmt)), + expr_(nullptr), + var_(std::move(var)), + bounds_(std::move(bounds)) {} + + AccessInfo( + size_t id, + AccessType type, + ExprPtr expr, + StmtPtr stmt, + VarPtr var, + IndexBounds bounds) + : id_(id), + type_(type), + stmt_(std::move(stmt)), + expr_(std::move(expr)), + var_(std::move(var)), + bounds_(std::move(bounds)) {} + + // Id is a unique int representing the order this access occurred in the + // graph. + size_t id() const { + return id_; + } + + // The type of the access (Load, Store, etc). + AccessType type() const { + return type_; + } + + // The enclosing Stmt this access represents. E.g. if this is a Store then + // Stmt is the Store itself, while if the access is caused by an Expr, this is + // the most immediate parent Stmt. + StmtPtr stmt() const { + return stmt_; + } + + // If the access is represented by an Expr (such as Load or Call) then this is + // it, otherwise it's nullptr. + ExprPtr expr() const { + return expr_; + } + + // The Var representing the underlying Buffer. + VarPtr var() const { + return var_; + } + + // A vector of Bounds representing the start and end expression for each + // dimension. + IndexBounds& bounds() { + return bounds_; + } + + // Each access that this depends upon, + // eg. if this is a Load, then it contains every Store that immediately + // contributes to a load of the bounds. + // or: if this is a Store, it contains all reads on the RHS of the Store. + const std::map>& dependencies() const { + return dependencies_; + } + + // Each access that depends on this one. + // ie. this access is present in the dependencies map of all accesses that are + // dependent. + std::map> dependents() const { + std::map> res; + for (const auto& kv : dependents_) { + res.emplace(kv.first, kv.second.lock()); + } + return res; + } + + // Returns the symbolic expression of the indices of this access. + std::vector getIndices() const; + + // Establishes a dependency or dependent relationship with another access. + void addDependency(const std::shared_ptr& write); + void addDependent(const std::shared_ptr& read); + + // helper for checking dependencies. + bool hasDependency(const std::shared_ptr& info) const; + + // Returns the set of all nodes that are direct (immediate) dependencies of + // this access. + DependencySet getDirectDependencies(); + // likewise, returns all nodes that directly depend on this one. + DependencySet getDirectDependents(); + + // Returns the full list of all nodes in the graph that this access depends + // on, and all nodes they depend on, and so forth, back to the inputs. + DependencySet getIndirectDependencies(); + // likewise, returns the full list of all nodes that depend on this node, and + // all nodes that depend on those nodes and so on down to the outputs. + DependencySet getIndirectDependents(); + + // Does this access represent a read of memory (Load, ReduceOp, Call, etc). + bool isRead() const; + // Does this access represent a write of memory (Store, etc). + bool isWrite() const; + + // Helpers for dumping accesses in various formats. + void print() const; + void dumpDOT(std::ostream& os) const; + const char* AccessTypeColour() const; + + private: + size_t id_; + AccessType type_; + StmtPtr stmt_; + ExprPtr expr_; + VarPtr var_; + IndexBounds bounds_; + + // Yes these should be sorted. + std::map> dependencies_; + std::map> dependents_; +}; + +using VarBoundMap = std::unordered_map; + +/* MemDependencyChecker analyses a IR fragment and builds a dependency graph of + * accesses contained within. + * + * It's possible to retrieve the entire graph in node-object form, or can be + * used as an oracle for answering dependency questions. e.g: + * + * analyzer.hasIndirectDependency(BufA, BufB); or, + * analyzer.hasDirectDependency(LoadA, StoreB); + */ +class TORCH_API MemDependencyChecker : public IRVisitor { + struct Scope; + + public: + MemDependencyChecker(); + MemDependencyChecker( + const std::unordered_set& inputs, + const std::unordered_set& outputs); + MemDependencyChecker( + const std::vector& inputs, + const std::vector& outputs); + + ~MemDependencyChecker() override = default; + + // Whether or not to allow loop execution order to influence dependency + // calculation. If the loop may later be parallelized you don't want this. + bool allowLoopExecutionOrderAnalysis(bool allow = true); + + // Dependency Checking API. + // The goal is to have enough overloads here so you don't really have to think + // about it. + + // Returns true if any read in A has a direct dependence on a write in B. + bool dependsDirectly(const StmtPtr& A, const StmtPtr& B); + bool dependsDirectly(const ExprPtr& A, const StmtPtr& B); + + // Returns true of the output depends directly on a write contained in B. + bool dependsDirectly(const BufPtr& output, const StmtPtr& B); + + // Returns true if a read in A depends directly on the provided input. + bool dependsDirectly(const StmtPtr& A, const BufPtr& input); + bool dependsDirectly(const ExprPtr& A, const BufPtr& input); + + // Outputs/inputs cannot depend directly. + + // Returns true if the access A has B as an immediate dependency. + bool dependsDirectly( + const std::shared_ptr& A, + const std::shared_ptr& B); + + // Returns true if any read in A has an ancestor write contained in B. + bool dependsIndirectly(const StmtPtr& A, const StmtPtr& B); + bool dependsIndirectly(const ExprPtr& A, const StmtPtr& B); + + // Returns true of the output depends indirectly on a write contained in B. + bool dependsIndirectly(const BufPtr& output, const StmtPtr& B); + + // Returns true if a read in A depends indirectly on the provided input. + bool dependsIndirectly(const StmtPtr& A, const BufPtr& input); + bool dependsIndirectly(const ExprPtr& A, const BufPtr& input); + + // returns true if the output uses any load of the input. + bool dependsIndirectly(const BufPtr& output, const BufPtr& input); + + // Returns true if the access A has a dependency chain to access B. + bool dependsIndirectly( + const std::shared_ptr& A, + const std::shared_ptr& B); + + // Returns the AccessInfo + std::shared_ptr accessFor(const StmtPtr& A) const; + std::shared_ptr accessFor(const ExprPtr& A) const; + + // Returns all AccessInfos. + std::unordered_set> accessesWithin( + const StmtPtr& A) const; + // TODO: this will return only the AccessInfo for A. It's included for + // completeness but be aware it won't return accesses used in the computation + // of A. + std::unordered_set> accessesWithin( + const ExprPtr& A) const; + + // Accesses relating to input and output buffers. + std::shared_ptr input(const BufPtr& B) const; + std::shared_ptr output(const BufPtr& B) const; + + // Returns the full history of reads and writes. + const std::vector>& getHistory() const; + + // Dumps the dependency graph in DOT format. + void dumpDAG(const std::string& filename) const; + + private: + // Node visitors. + void visit(const StorePtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const ForPtr& v) override; + void visit(const CondPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const CompareSelectPtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const LetPtr& v) override; + void visit(const AtomicAddPtr& v) override; + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + + using BoundRelationship = std::pair>; + + // An internal struct holding the accesses found within a scope Block. + struct Scope { + Scope(BlockPtr b, std::shared_ptr p) + : block(std::move(b)), parent(std::move(p)) {} + + BlockPtr block; + std::shared_ptr parent; + + std::unordered_map shadowedVarBounds; + std::unordered_set localVars; + + std::vector> accesses_; + + std::unordered_map> openWrites_; + }; + std::shared_ptr currentScope_; + + bool allowExecutionOrderAnalysis_{false}; + + std::unordered_multimap> stmtToAccess_; + std::unordered_multimap> exprToAccess_; + std::unordered_map>> + scopeToAccesses_; + + VarBoundMap knownVarBounds_; + + // Finds all accesses that are reads within the scope of v. + template + DependencySet getAllReadsWithin(const StmtOrExprPtr& v) { + DependencySet reads; + auto insertAllReads = [&](const auto& nodes) { + for (const auto& l : nodes) { + auto bound = exprToAccess_.equal_range(l); + for (auto it = bound.first; it != bound.second; ++it) { + if (it->second->isRead()) { + reads.insert(it->second); + } + } + } + }; + + // Look for and insert accesses belonging to all nodes that act like + // reads. + insertAllReads(NodeFinder::find(v)); + insertAllReads(NodeFinder::find(v)); + + return reads; + } + + // Finds all accesses that are writes within the scope of v. + // Writes cannot occur in Exprs, so this is a little simpler. + DependencySet getAllWritesWithin(const StmtPtr& v) { + DependencySet writes; + + // writes just Store currently. + auto stores = NodeFinder::find(v); + for (const auto& s : stores) { + auto bound = stmtToAccess_.equal_range(s); + for (auto it = bound.first; it != bound.second; ++it) { + if (it->second->isWrite()) { + writes.insert(it->second); + } + } + } + return writes; + } + + // Templated helpers to work on either Exprs or Stmts. + template + bool dependsDirectlyHelper(const StmtOrExprPtr& A, const StmtPtr& B) { + auto aReads = getAllReadsWithin(A); + auto bWrites = getAllWritesWithin(B); + + for (auto& read : aReads) { + for (auto& depPair : read->dependencies()) { + if (bWrites.count(depPair.second) != 0) { + return true; + } + } + } + + return false; + } + + template + bool dependsIndirectlyHelper(StmtOrExprPtr A, const StmtPtr& B) { + auto aReads = getAllReadsWithin(A); + auto bWrites = getAllWritesWithin(B); + + auto aDeps = getAllWriteDependencies(aReads); + + for (auto& dependency : aDeps) { + if (bWrites.count(dependency) != 0) { + return true; + } + } + + return false; + } + + DependencySet getAllWriteDependencies(const DependencySet& products); + + // Maps for inputs and outputs, since they aren't present directly in the IR. + std::unordered_map> inputs_; + std::unordered_map> outputs_; + std::unordered_map> intermediates_; + + // Inserts accesses for Buf's: specifically for inputs and outputs. + void insertBuffers( + std::unordered_map>& bufs, + AccessType type); + + // Update the write history with a new write, adding dependencies and closing + // any overlapped writes (if possible). + void updateWriteHistory( + std::list& writeHistory, + const std::shared_ptr& info, + size_t latestAccessToClose, + bool closeOverlapped = true, + bool insert = true); + + // Merge a child scope into a parent scope, adding dependencies for open + // writes in the parent to accesses in the child. + void mergeScope( + const std::shared_ptr& child, + const std::shared_ptr& parent, + bool closeOverlapped = true); + + // Binds symbolic vars in indices with the low and high bound for those vars. + std::vector getIndicesBounds(const std::vector& indices); + + size_t nextAccess_{0}; + StmtPtr lastStmt_{nullptr}; +}; + +} // namespace torch::jit::tensorexpr::analysis + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h new file mode 100644 index 0000000000000000000000000000000000000000..ca63d7b9be1773cec3ada78416bd2c865427722d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h @@ -0,0 +1,106 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit::tensorexpr { + +// An API to compute 2D depthwise convolutions with bias. +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + BufHandle bias, + int stride, + int pad, + int groups); + +// An API to compute 2D depthwise convolutions without bias. +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + int stride, + int pad, + int groups); + +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + BufHandle bias, + ExprHandle N, + ExprHandle C, + ExprHandle H, + ExprHandle W, + ExprHandle K, + ExprHandle CperG, + ExprHandle R, + ExprHandle S, + ExprHandle stride, + ExprHandle pad, + ExprHandle groups); + +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + ExprHandle N, + ExprHandle C, + ExprHandle H, + ExprHandle W, + ExprHandle K, + ExprHandle CperG, + ExprHandle R, + ExprHandle S, + ExprHandle stride, + ExprHandle pad, + ExprHandle groups); + +bool conv2dIsSupported( + const TensorInfo& input, + const TensorInfo& weight, + const TensorInfo& bias, + const std::vector& stride, + const std::vector& pad, + const std::vector& dilation, + int64_t groups); +bool mkldnnPrepackedConvIsSupported( + const TensorInfo& input, + const TensorInfo& weight, + const std::vector& stride, + const std::vector& pad, + const std::vector& dilation, + int64_t groups); +Tensor computeConv2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeConv1d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computePrepackedConv2dClampRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computePrepackedLinearClampRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeMkldnnPrepackedConvRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..1090455818d68d23348eb870b8930d1def34358b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::tensorexpr { + +Tensor computeMatmul( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeAddMM( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h new file mode 100644 index 0000000000000000000000000000000000000000..6a1f61a2fb09e0342292b72c2c23d3a801df3a10 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h @@ -0,0 +1,99 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit::tensorexpr { + +struct TensorInfo { + std::vector dims; + c10::ScalarType dtype; +}; +std::optional getTensorInfo(const BufHandle& b); + +int64_t normalizeAndCheckIndex(int64_t idx, int64_t list_size); + +// Convert boolean to integer, if needed. +ExprHandle boolToInteger(const ExprHandle& x); +ExprHandle promoteToDtype(ExprHandle e, ScalarType dt); +void promoteInputs( + std::vector& inputs, + const int typeConstraints = kAllTypes); +ExprHandle promoteIntegerToDefaultType(const ExprHandle& e); +ExprHandle promoteHalfToFloat(const ExprHandle& e); +ExprHandle demoteOutput( + const ExprHandle& e, + const std::optional type); + +std::vector broadcastShapes( + std::vector> shapes); +std::vector broadcastShapes( + const std::vector& a, + const std::vector& b); + +std::vector valueShape(const ArgValue& v); +ExprHandle tensorOrConstant( + const ArgValue& v, + const std::vector& axes); +ExprHandle scalarOrConstant(const ArgValue& v); +ExprHandle broadcast(const BufHandle& b, const std::vector& axes); +ExprHandle constant(const ArgValue& v); + +ExprHandle clamp( + const ExprHandle& cmin, + const ExprHandle& cmax, + const ExprHandle& input); + +Tensor computeChunk( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeTranspose( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeExpand( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeReshape( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeFlatten( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeCatWoConditionals( + const std::vector& inputs, + const std::vector& outputShape); +Tensor computeCat( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeEmbedding( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h new file mode 100644 index 0000000000000000000000000000000000000000..3d712cca1beae7547bd5f24f366f050d8783e5c5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::tensorexpr { + +Tensor computeBatchNorm( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h new file mode 100644 index 0000000000000000000000000000000000000000..8625cbf737729e3f33095526e2b712a3f35575c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h new file mode 100644 index 0000000000000000000000000000000000000000..cd8035fdaf773a5467a015e5113b8b5f4bd20fe8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h @@ -0,0 +1,87 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::tensorexpr { + +TORCH_API Tensor computeSign( + const std::vector& inputs, + const std::vector& outputShape, + const std::optional>& outputStrides = std::nullopt); + +Tensor computeOneOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& innerExpr, + const int checkParamTypes = kAllTypes); +Tensor computeTwoOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& + innerExpr); +Tensor computeTwoOperandWithAlpha( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& + innerExpr); +Tensor computeConditionWithTwoOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function< + ExprHandle(const ExprHandle&, const ExprHandle&, const ExprHandle&)>& + innerExpr); +Tensor computeThreeOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function< + ExprHandle(const ExprHandle&, const ExprHandle&, const ExprHandle&)>& + innerExpr, + bool promote_inputs = true); +Tensor computeFourOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& innerExpr); +Tensor computeNoop( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +Tensor computeScalar( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& + innerExpr); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h new file mode 100644 index 0000000000000000000000000000000000000000..9ebd11bc633c053ad5a3ff6df24f56f0f95bdc35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h @@ -0,0 +1,154 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::tensorexpr { + +TORCH_API ExprHandle quantizePerTensorQParamFromArg(ArgValue arg); + +TORCH_API double immQScale(const BufHandle& qx); + +TORCH_API int64_t immQZero(const BufHandle& qx); + +TORCH_API ScalarType immQDType(const BufHandle& qx); + +TORCH_API bool isQuantized(const BufHandle& qx); + +TORCH_API Tensor computeQuantizePerTensor( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizePerTensorExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv1d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv2dPrepack( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv2dRelu( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedLinear( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedLinearRelu( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedAdd( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +Tensor computeQuantizedAddExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedMul( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedMulScalar( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedCat( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedRelu( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeDequantize( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeDequantizeExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeUpsampleNearest2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeUpsampleNearest2dExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedSigmoidExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device /*unused*/); +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h new file mode 100644 index 0000000000000000000000000000000000000000..c9e3cb67920a3984118cea1c7ddb1837d4080cec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::tensorexpr { + +TORCH_API Tensor computeSum( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +TORCH_API Tensor computeMean( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +TORCH_API Tensor computeAdaptiveAvgPool2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeMax( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h new file mode 100644 index 0000000000000000000000000000000000000000..675a6c0bc795913bc588be6084aad749eb4bf153 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::tensorexpr { + +Tensor computeSoftmax( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + bool log_softmax); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h new file mode 100644 index 0000000000000000000000000000000000000000..9faee10a839d2b3aa0ecd62724dd899e2f9f284a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h @@ -0,0 +1,311 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::tensorexpr { + +using ParameterList = const std::vector; +using ReduceInteraction = std::function; + +// A Reducer is a user interface describing a particular reduction +// operation. It has three components: An initialization value, a way of +// interacting each value with the accumulation, and a method for obtaining the +// current value to be reduced. It is materialized into a ReduceOp when loop +// variables are known. +class TORCH_API Reducer { + public: + Reducer(ExprHandle init, ReduceInteraction& interaction) + : init_(init.node()), interaction_(interaction) {} + + template + Reducer(ExprHandle init, RI interaction) + : init_(init.node()), interaction_(std::move(interaction)) {} + + ExprPtr initializer() const { + return init_; + } + + ExprHandle operator()( + const BufHandle& result_buf, + ExprHandle body, + const std::vector& output, + const std::vector& inner) const; + + ReduceOpPtr operator()( + const BufPtr& result_buf, + ExprPtr body, + const std::vector& output, + const std::vector& inner) const; + + ExprHandle operator()( + const BufHandle& result_buf, + BufHandle acc_buf, + const ExprHandle& body, + const std::vector& output, + const std::vector& inner) const; + + // Polymorphic handling of Body functions with a variety of parameters. + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + return func(vars); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 1) { + throw malformed_input("mismatch between reduce body and arg size (1)"); + } + + return func(vars[0]); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 2) { + throw malformed_input("mismatch between reduce body and arg size (2)"); + } + return func(vars[0], vars[1]); + } + + static ExprHandle getReduceBody( + const std::function< + ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>& + func, + const std::vector& vars) { + if (vars.size() != 3) { + throw malformed_input("mismatch between reduce body and arg size (3)"); + } + return func(vars[0], vars[1], vars[2]); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 4) { + throw malformed_input("mismatch between reduce body and arg size (4)"); + } + return func(vars[0], vars[1], vars[2], vars[3]); + } + + // Completes the reduction operator by applying the interaction function to + // the accumulation and the body expression. + static ExprPtr complete( + const BufPtr& accumulator, + const ReduceInteraction& interaction, + ExprHandle body, + const std::vector& output_args, + const std::vector& reduce_args) { + ExprHandle accum = + ExprHandle(alloc(body.dtype(), accumulator, output_args)); + auto e = interaction(std::move(accum), std::move(body)); + return e.node(); + } + static ExprHandle complete( + const BufHandle& accumulator, + const ReduceInteraction& interaction, + ExprHandle body, + const std::vector& output_args, + const std::vector& reduce_args) { + ExprHandle accum = Load::make(body.dtype(), accumulator, output_args); + auto e = interaction(std::move(accum), std::move(body)); + return e; + } + + private: + ExprPtr init_; + ReduceInteraction interaction_; +}; + +// An expression representing a Reduction operation (e.g. Sum, Max) broken into +// it's component parts: initialization, accumulation var, acquisition of value +// to be reduced and interaction. +// +// This is intended to be expanded in the loopnest and not make it to codegen. +class TORCH_API ReduceOp : public ExprNode { + public: + ReduceOp( + const ExprPtr& body, + std::vector reduce_args, + Reducer reducer) + : ExprNodeBase(body->dtype()), + body_(body), + reduce_args_(std::move(reduce_args)), + reducer_(std::move(reducer)) { + result_buf_ = nullptr; + acc_buf_ = nullptr; + ri_operand_ = nullptr; + } + + ReduceOp( + const ExprPtr& body, + std::vector reduce_args, + BufPtr result_buf, + BufPtr acc_buf, + ExprPtr ri_operand, + Reducer reducer) + : ExprNodeBase(body->dtype()), + body_(body), + reduce_args_(std::move(reduce_args)), + result_buf_(std::move(result_buf)), + acc_buf_(std::move(acc_buf)), + ri_operand_(std::move(ri_operand)), + reducer_(std::move(reducer)) {} + + static ExprHandle make( + ExprHandle body, + const std::vector& reduce_args, + const Reducer& reducer); + + static ExprHandle make( + ExprHandle body, + const std::vector& reduce_args, + BufHandle result_buf, + BufHandle acc_buf, + ExprHandle ri_operand, + const Reducer& reducer); + + // return the body expression which obtains the value to be reduced. + ExprPtr body() const { + return body_; + } + + // Returns the original Reducer factory that can create ReduceOps. + const Reducer& reducer() const { + return reducer_; + } + + // returns variables associated with the axes of reduction. + const std::vector& reduce_args() const { + return reduce_args_; + } + + void setAccBuf(BufHandle acc_buf) { + acc_buf_ = acc_buf.node(); + } + BufPtr getAccBuf() { + return acc_buf_; + } + + void setResultBuf(BufHandle buf) { + result_buf_ = buf.node(); + } + BufPtr getResultBuf() { + return result_buf_; + } + + void setRiOperand(ExprHandle ri_operand) { + ri_operand_ = ri_operand.node(); + } + ExprPtr getRiOperand() { + return ri_operand_; + } + + private: + // body_ = reducer_->interaction_(result_buf_, ri_operand_) + ExprPtr body_; + std::vector reduce_args_; + + BufPtr result_buf_; + BufPtr acc_buf_; + ExprPtr ri_operand_; + + const Reducer reducer_; +}; + +class Sum : public Reducer { + public: + Sum() + : Reducer(ExprHandle(0), [](const ExprHandle& a, const ExprHandle& b) { + return a + b; + }) {} +}; + +inline ExprHandle maximumVal(ScalarType type) { + switch (type) { +#define MAX_BY_TYPE_CASE(Type, Name) \ + case ScalarType::Name: \ + return ExprHandle(std::numeric_limits::max()); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, MAX_BY_TYPE_CASE) +#undef MAX_BY_TYPE_CASE + default: + throw unsupported_dtype(); + } + return ExprHandle(); +} + +inline ExprHandle minimumVal(ScalarType type) { + switch (type) { +#define MAX_BY_TYPE_CASE(Type, Name) \ + case ScalarType::Name: \ + return ExprHandle(std::numeric_limits::min()); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, MAX_BY_TYPE_CASE) +#undef MAX_BY_TYPE_CASE + default: + throw unsupported_dtype(); + } +} + +class Maximum : public Reducer { + public: + // TODO possible to remove this arg by deferring the init value until we + // know the dtype of the body. + Maximum(Dtype dtype) + : Reducer( + minimumVal(dtype.scalar_type()), + [](const ExprHandle& a, const ExprHandle& b) { + return Max::make(a, b, true); + }) {} + Maximum(ExprHandle initializer) + : Reducer( + std::move(initializer), + [](const ExprHandle& a, const ExprHandle& b) { + return Max::make(a, b, true); + }) {} +}; + +class Minimum : public Reducer { + public: + Minimum(Dtype dtype) + : Reducer( + maximumVal(dtype.scalar_type()), + [](const ExprHandle& a, const ExprHandle& b) { + return Min::make(a, b, true); + }) {} + Minimum(const ExprHandle& initializer) + : Reducer(initializer, [](const ExprHandle& a, const ExprHandle& b) { + return Min::make(a, b, true); + }) {} +}; + +class ReductionExpander : public IRMutator { + public: + StmtPtr expand(const StmtPtr& s) { + return s->accept_mutator(this); + } + + ExprPtr mutate(const ReduceOpPtr& v) override { + return v->body(); + } +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h new file mode 100644 index 0000000000000000000000000000000000000000..29236965a87abe2217ca1727d52b2133227e7b77 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h @@ -0,0 +1,431 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { +namespace registerizer { + +/* The Registerizer performs scalar replacement by looking for common Stores and +Loads to a single item in a buffer and replacing them with a local temporary +scalar which is cheaper to write. + +For example it can replace: + +{ + A[0] = 0; + for(const auto x : c10::irange(10)) { + A[0] = (A[0]) + x; + } +} + +with: + +{ + int A_ = 0; + for(const auto x : c10::irange(10)) { + A_ = x + A_; + } + A[0] = A_; +} + +This is particularly useful on GPUs when parallelizing, since after replacing +loops with metavars we have a lot of accesses like this. */ + +class Scope; + +/* Holds analysis information about accesses to a specific range of a + buffer, including the number of loads and stores and the lowest common parent + Block. + */ +class AccessInfo { + public: + AccessInfo() = default; + AccessInfo( + SimplifierHashType h, + BufPtr b, + std::vector i, + size_t accessOrder) + : hash_(h), + buf_(std::move(b)), + indices_(std::move(i)), + store_cost_(alloc(0)), + load_cost_(alloc(0)), + accessOrder_(accessOrder) {} + + // Adds a Store to this access, which is in the provided scope. + void addStore(const StorePtr& store, const std::shared_ptr& scope); + + // Adds a Load to this access, which occurs in the usage Stmt in the provided + // scope. + void addLoad( + const LoadPtr& load, + const std::shared_ptr& scope, + const StmtPtr& usage); + + // Merge another AccessInfo into this one. + void merge(const std::shared_ptr& other); + + // Returns true if the other AccessInfo's bounds may overlap this one. + bool overlaps(const std::shared_ptr& other); + + // Returns true if the indices of this access depend on the provided Var. + bool dependsOnVar(const VarPtr& v); + + // Clone this AccessInfo, and set this as the new accesses' hiddenAccess. + static std::shared_ptr cloneWithHiddenInfo( + const std::shared_ptr& orig); + + // print for debugging. + void print() const; + + SimplifierHashType hash() const { + return hash_; + } + + BufPtr buf() const { + return buf_; + } + + const std::vector& indices() const { + return indices_; + } + + BlockPtr block() const { + return block_; + } + + void setEnclosingBlock(BlockPtr b) { + block_ = std::move(b); + } + + StmtPtr first_usage() const { + return first_usage_; + } + StmtPtr last_usage() const { + return last_usage_; + } + + void setUsageMarks(StmtPtr first, StmtPtr last) { + first_usage_ = std::move(first); + last_usage_ = std::move(last); + } + + bool firstUsageOverlapped() const { + return firstUsageOverlapped_; + } + + ExprPtr store_cost() const { + return store_cost_; + } + + ExprPtr load_cost() const { + return load_cost_; + } + + const std::vector& stores() const { + return stores_; + } + + const std::vector& loads() const { + return loads_; + } + + void hoistCosts(const ExprPtr& extent) { + store_cost_ = IRSimplifier::simplify(alloc(store_cost_, extent)); + load_cost_ = IRSimplifier::simplify(alloc(load_cost_, extent)); + } + + size_t conditionId() const { + return conditionId_; + } + + void setConditionId(size_t c) { + conditionId_ = c; + } + + size_t accessOrder() const { + return accessOrder_; + } + + std::shared_ptr hiddenAccess() const { + return hiddenAccess_; + } + + // Holds state relating to the scalar variable we will insert to replace some + // number of loads and stores. + struct ScalarReplacement { + VarPtr var{nullptr}; + BufPtr var_wrapper{nullptr}; + LetPtr initializer{nullptr}; + }; + + ScalarReplacement& replacement() { + return replacement_; + } + + private: + SimplifierHashType hash_; + BufPtr buf_; + std::vector indices_; + BlockPtr block_{nullptr}; + + StmtPtr first_usage_{nullptr}; + StmtPtr last_usage_{nullptr}; + + // Whether or not this access is overlapped in the first Stmt it appears. This + // means we cannot use it's first Store as the initializer. + bool firstUsageOverlapped_{false}; + + // The cost in real ops that this access represents, to enable + // filtering accesses that won't save any loads or stores. + ExprPtr store_cost_; + ExprPtr load_cost_; + + // The actual Stores and Loads which represent this access. + // Be careful with these, any mutator will invalidate these pointers. + std::vector stores_; + std::vector loads_; + + // An identifier representing the conditional block, if any, this access + // depends on. + size_t conditionId_{0}; + + // An identifier representing the order this access was first encountered, for + // sorting returned results. + size_t accessOrder_{0}; + + // Sometimes when traversing the tree we need to record what would happen if + // we hoisted an access, but sometimes it doesn't work out. This lets us + // "undo" some mutation and return to the internal hidden AccessInfo. + // It will be removed after any further additions to this AccessInfo. + std::shared_ptr hiddenAccess_; + + ScalarReplacement replacement_; +}; + +using AccessHashMap = + std::unordered_map>; + +// Represents a scope block and holds all accesses contained within it. +class Scope { + public: + Scope(BlockPtr b, std::shared_ptr parent, size_t conditionId = 0) + : block_(std::move(b)), + parent_(std::move(parent)), + conditionId_(conditionId) {} + + AccessHashMap& getAccessMapByBuf(const BufPtr& b); + + std::unordered_map& openAccesses() { + return openAccesses_; + } + + std::vector>& closedAccesses() { + return closedAccesses_; + } + + BlockPtr block() const { + return block_; + } + + std::shared_ptr parent() const { + return parent_; + } + + size_t conditionId() const { + return conditionId_; + } + + const std::unordered_set& localVars() const { + return localVars_; + } + void addLocalVar(VarPtr v) { + localVars_.insert(std::move(v)); + } + + void closeAccess(const std::shared_ptr& info); + + void filterClosed(); + + private: + // Map of map to access, narrowing by Buf then by hash(Buf+Indices). + // This allows us to find a candidate access easily, and also check for + // overlap with other accesses to the same buf. Buf -> + // Hash -> + // Access + std::unordered_map openAccesses_; + std::vector> closedAccesses_; + + // The Block object this scope represents. + BlockPtr block_; + + // The enclosing scope object. + std::shared_ptr parent_; + + // An identifier representing the condition block this scope depends on. + size_t conditionId_; + + // A set of variables local to this scope (e.g. loop vars). + std::unordered_set localVars_; +}; + +/* Analyzes the graph and collects accesses to the same symbolic tensor element + * which can be replaced by a single local scalar. + * + * This works by recursively walking the tree in postfix order, building sets of + * accesses to the same symbolic element by scope and then merging lower scopes + * into their enclosing scope. + * + * It is safe to move two accesses of the same Tensor element to a local scalar + * Var if between all usages of the element there are no other Loads or Stores + * that may refer to it. In the comments I refer to this as overlapping the + * access, or "cutting" the existing AccessInfo. In the case where a candidate + * for registerization is cut, it may be possible to finalize the access early + * by writing it back to the Tensor and then create a new scalar variable after + * the overlapping access is complete. We will attempt to do this when it saves + * memory accesses. + * + * There are a few cases that make this more challenging: + * + * - For: Loops change the number of real usages of a buffer by the loop + * extent, but only if we can pull the definition and finalization of the scalar + * variable out of the loop block. + * + * - Cond: Conditions complicate lifting scalars out of internal scopes. + * Generally we cannot lift an access outside of a conditional scope unless + * there is already a reference to that same access at the higher scope, since + * we don't know if the condition was guarding an array access not safe at the + * higher scope. In the comments I refer to this as the condition "hiding" the + * access, and the outer access "unhiding" it. + * + * - IfThenElse: Same situation as Cond, except since IfThenElse is an Expr + * rather than a Stmt we cannot insert the scalar definition or finalizer + * within the conditional scope. Accesses inside an IfThenElse can be safely + * combined with external accesses but cannot exist completely within. + * + * - Let: Accesses dependent on local variables via Let Stmts, or loop vars, + * cannot be raised outside of the scope of the dependent var. + */ +class TORCH_API RegisterizerAnalysis : public IRVisitor { + public: + RegisterizerAnalysis() + : currentScope_(std::make_shared(nullptr, nullptr, 0)) {} + ~RegisterizerAnalysis() override = default; + + void visit(const ForPtr& v) override; + + void visit(const CondPtr& v) override; + + void visit(const BlockPtr& v) override; + + void visit(const StorePtr& v) override; + + void visit(const LoadPtr& v) override; + + void visit(const IfThenElsePtr& v) override; + + void visit(const LetPtr& v) override; + +#define STMT_ON_STACK(Op) \ + void visit(const Op##Ptr& v) override { \ + stmtStack_.push_front(v); \ + IRVisitor::visit(v); \ + stmtStack_.pop_front(); \ + } + + STMT_ON_STACK(AtomicAdd) + STMT_ON_STACK(Allocate) + STMT_ON_STACK(Free) + +#undef STMT_ON_STACK + + std::vector> getCandidates(); + + private: + void mergeCurrentScopeIntoParent(); + void mergeHiddenScope(bool allowClosed); + void closeAccessIntoScope( + const std::shared_ptr& info, + const std::shared_ptr& scope); + + std::unordered_set exprConditionals_; + + // A stack of enclosing Stmts for tracking the usage Stmt of Loads. + std::deque stmtStack_; + + // The current scope being analyzed. + std::shared_ptr currentScope_; + + HashProvider hasher_; + + size_t conditionId_{0}; + size_t accessOrder_{0}; +}; + +/* Replaces each registerizable access with a Scalar variable, including + * definition, initializer and finalizer. + */ +class TORCH_API RegisterizerReplacer : public IRMutator { + public: + RegisterizerReplacer(std::vector>& vec) + : infoSet_(vec) { + buildReplacements(); + } + + ExprPtr mutate(const LoadPtr& v) override; + + StmtPtr mutate(const StorePtr& v) override; + + StmtPtr mutate(const BlockPtr& v) override; + + private: + struct ReplacerScope { + std::unordered_map>> + initializerPoints_; + std::unordered_map>> + finalizePoints_; + }; + + // Creates the various ReplacerScope objects and builds internal maps. + void buildReplacements(); + + // State relating to the accesses yet to be replaced. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + std::vector>& infoSet_; + std::unordered_map> storeToAccess_; + std::unordered_map> loadToAccess_; + std::unordered_map parentToAccesses_; + + // Holds the set of Stores that should be pulled into an initializer, so they + // can be eliminated. + std::set eliminatedIntializers_; + + // Tracks the number of times we've seen each buffer, so we can name the + // scalar Vars appropriately. + std::unordered_map bufferAccessCounts_; + unsigned int getBufferAccessCount(const BufPtr& b) { + return ++bufferAccessCounts_[b]; + } +}; +} // namespace registerizer + +// Apply scalar replacement to all accesses in s. +// To produce safe code, this must occur after handling parallelized axes and +// atomics. +TORCH_API StmtPtr registerize(StmtPtr s); + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/stmt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/stmt.h new file mode 100644 index 0000000000000000000000000000000000000000..331fc954825ce4d2416ec55877203891df1cee59 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/stmt.h @@ -0,0 +1,1017 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +// The common base between all statement node. +class TORCH_API Stmt : public std::enable_shared_from_this { + public: + Stmt() = default; + virtual ~Stmt() = default; + virtual void accept(IRVisitor* visitor) = 0; + virtual StmtPtr accept_mutator(IRMutator* mutator) = 0; + + StmtPtr get_parent() const { + return parent_ ? parent_->getptr() : nullptr; + } + + /* + * Make a deep copy of the given statement. + * + * All statements and expressions used in children of the statement are + * cloned. Note that the variables are not deep-copied since they are + * immutable. + */ + static StmtPtr clone(const StmtPtr& s); + + protected: + static void set_parent(const StmtPtr& s, Stmt* new_parent) { + s->parent_ = new_parent; + } + std::shared_ptr getptr() { + return shared_from_this(); + } + + private: + Stmt* parent_ = nullptr; +}; + +template +class StmtNode : public Stmt { + public: + using StmtNodeBase = StmtNode; + void accept(IRVisitor* visitor) override { + visitor->visit(static_to(getptr())); + } + StmtPtr accept_mutator(IRMutator* mutator) override; + friend Op; + + private: + StmtNode() = default; +}; + +template +StmtPtr StmtNode::accept_mutator(IRMutator* mutator) { + return mutator->mutate(static_to(getptr())); +} + +// Concrete Stmt classes +class TORCH_API Block : public StmtNode { + public: + static BlockPtr make(const std::vector& stmts) { + std::vector valid_stmts; + for (auto& stmt : stmts) { + if (!stmt) { + continue; + } + valid_stmts.push_back(stmt); + } + if (valid_stmts.empty()) { + return nullptr; + } + return alloc(valid_stmts); + } + + size_t nstmts() const { + return stmts_.size(); + } + bool empty() const { + return stmts_.empty(); + } + + void prepend_stmt(const StmtPtr& s) { + if (s->get_parent()) { + throw malformed_input("Block prepend Stmt with existing parent", s); + } + + stmts_.push_front(s); + set_parent(s, this); + } + void append_stmt(const StmtPtr& s) { + if (s->get_parent()) { + throw malformed_input("Block append Stmt with existing parent", s); + } + + stmts_.push_back(s); + set_parent(s, this); + } + + void insert_stmt_before(const StmtPtr& s, const StmtPtr& before) { + if (s->get_parent()) { + throw malformed_input("Block append Stmt with existing parent", s); + } + + auto pos = std::find(stmts_.begin(), stmts_.end(), before); + if (pos == stmts_.end()) { + throw malformed_input( + "Inserting after statement that is not in block", s); + } + + stmts_.insert(pos, s); + set_parent(s, this); + } + + void insert_stmt_after(const StmtPtr& s, const StmtPtr& after) { + if (s->get_parent()) { + throw malformed_input("Block append Stmt with existing parent", s); + } + + auto pos = std::find(stmts_.begin(), stmts_.end(), after); + if (pos == stmts_.end()) { + throw malformed_input( + "Inserting after statement that is not in block", s); + } + + ++pos; + + stmts_.insert(pos, s); + set_parent(s, this); + } + + bool replace_stmt(const StmtPtr& old_stmt, const StmtPtr& new_stmt) { + if (new_stmt->get_parent()) { + throw malformed_input( + "Block replace Stmt with existing parent", new_stmt); + } + + auto pos = std::find(stmts_.begin(), stmts_.end(), old_stmt); + if (pos == stmts_.end()) { + return false; + } + stmts_.insert(pos, new_stmt); + stmts_.erase(pos); + set_parent(old_stmt, nullptr); + set_parent(new_stmt, this); + return true; + } + + // Creates a new block by cloning `this` block and replacing the given + // statement with a new statement. Note that `old_stmt` refers to a statement + // in `this` block. If the `old_stmt` is not found, it will return `nullptr`. + BlockPtr clone_and_replace(const StmtPtr& old_stmt, const StmtPtr& new_stmt) { + if (new_stmt->get_parent()) { + throw malformed_input( + "Block replace Stmt with existing parent", new_stmt); + } + + std::vector stmts(stmts_.begin(), stmts_.end()); + std::vector cloned_stmts(stmts.size()); + bool found = false; + for (int i = 0; i < static_cast(stmts.size()); ++i) { + if (stmts[i] == old_stmt) { + found = true; + cloned_stmts[i] = new_stmt; + } else { + cloned_stmts[i] = Stmt::clone(stmts[i]); + } + } + if (!found) { + return nullptr; + } + return alloc(cloned_stmts); + } + + bool remove_stmt(const StmtPtr& stmt) { + auto pos = std::find(stmts_.begin(), stmts_.end(), stmt); + if (pos == stmts_.end()) { + return false; + } + + set_parent(stmt, nullptr); + stmts_.erase(pos); + return true; + } + + std::list stmts() const { + return stmts_; + } + + void clear() { + for (const auto& s : stmts_) { + set_parent(s, nullptr); + } + stmts_.clear(); + } + + void set_stmts(const std::vector& stmts) { + clear(); + init(stmts); + } + + explicit Block(const std::vector& stmts) { + init(stmts); + } + + typedef std::list::iterator iterator; + typedef std::list::const_iterator const_iterator; + + iterator begin() { + return stmts_.begin(); + } + + const_iterator begin() const { + return stmts_.begin(); + } + + iterator end() { + return stmts_.end(); + } + + const_iterator end() const { + return stmts_.end(); + } + + StmtPtr front() { + return stmts_.front(); + } + + StmtPtr front() const { + return stmts_.front(); + } + + StmtPtr back() { + return stmts_.back(); + } + + StmtPtr back() const { + return stmts_.back(); + } + + void splice(Block::iterator it, const BlockPtr& other) { + for (const StmtPtr& s : *other) { + set_parent(s, this); + } + + stmts_.splice(it, other->stmts_); + } + + static BlockPtr getSharedParent(StmtPtr p1, StmtPtr p2) { + std::unordered_set enclosing; + + StmtPtr p1_p = std::move(p1); + while (p1_p) { + if (BlockPtr b = to(p1_p)) { + enclosing.insert(b); + } + p1_p = p1_p->get_parent(); + } + + StmtPtr p2_p = std::move(p2); + while (p2_p) { + if (BlockPtr b = to(p2_p)) { + if (enclosing.count(b) != 0) { + return b; + } + } + p2_p = p2_p->get_parent(); + } + + return nullptr; + } + + // returns the immediate child containing statement s. + StmtPtr getEnclosedRoot(StmtPtr s) const { + while (s && s->get_parent().get() != this) { + s = s->get_parent(); + } + return s; + } + + private: + std::list stmts_; + + void init(const std::vector& stmts) { + for (const StmtPtr& s : stmts) { + if (!s) { + continue; + } + if (!s->get_parent()) { + // If we get here, it's a bug, but we cannot throw an error from a + // constructor. But IR verifier would catch this. + set_parent(s, this); + } + + stmts_.push_back(s); + } + } +}; + +class TORCH_API Store : public StmtNode { + public: + VarPtr base_handle() const { + return buf_->base_handle(); + } + std::vector indices() const { + return indices_; + } + ExprPtr flat_index() const { + TORCH_CHECK(indices_.size() == 1, "Indices haven't been flattened."); + return indices_[0]; + } + ExprPtr value() const { + return value_; + } + BufPtr buf() const { + return buf_; + } + + void set_buf(BufPtr buf) { + buf_ = std::move(buf); + } + + void set_indices(std::vector indices) { + indices_ = std::move(indices); + } + + void set_value(ExprPtr value) { + value_ = std::move(value); + } + + static StorePtr make( + const BufHandle& buf, + const std::vector& indices, + const ExprHandle& value); + + Store(BufPtr buf, std::vector indices, ExprPtr value); + + private: + BufPtr buf_; + std::vector indices_; + ExprPtr value_; +}; + +// Allocate a buffer of given shapes and dtypes and bind it with the given +// buffer var. The life span is at most through the current program, until it is +// explicitly freed. An unfreed memory is likely considered an error. +class TORCH_API Allocate : public StmtNode { + public: + static AllocatePtr make(const BufHandle& buf_handle) { + return alloc(buf_handle.node()); + } + + VarPtr buffer_var() const { + return buf_->base_handle(); + } + + Dtype dtype() const { + return buf_->dtype(); + } + + const std::vector dims() const { + return buf_->dims(); + } + + BufPtr buf() const { + return buf_; + } + + void set_buf(BufPtr buf) { + buf_ = std::move(buf); + } + + explicit Allocate(BufPtr buf) : buf_(std::move(buf)) {} + + private: + BufPtr buf_; + // TODO: add memory types. +}; + +// PlacementAllocate is a variation of the Allocate operator in NNC IR. It does +// not allocate memory but reuse the memory of another buffer for the given +// buffer. +class TORCH_API PlacementAllocate : public StmtNode { + public: + static PlacementAllocatePtr make( + const BufHandle& buf_handle, + const BufHandle& buf_handle_to_reuse) { + return alloc( + buf_handle.node(), buf_handle_to_reuse.node()); + } + + BufPtr buf() const { + return buf_; + } + + BufPtr buf_to_reuse() const { + return buf_to_reuse_; + } + + void set_buf(BufPtr buf) { + buf_ = std::move(buf); + } + + void set_buf_to_reuse(BufPtr buf) { + buf_to_reuse_ = std::move(buf); + } + + explicit PlacementAllocate(BufPtr buf, BufPtr buf_to_reuse) + : buf_(std::move(buf)), buf_to_reuse_(std::move(buf_to_reuse)) {} + + private: + BufPtr buf_; + BufPtr buf_to_reuse_; +}; + +// Free the specific buffer. It is an error. +class TORCH_API Free : public StmtNode { + public: + static FreePtr make(const BufHandle& buf_handle) { + return alloc(buf_handle.node()); + } + + VarPtr buffer_var() const { + return buf_->base_handle(); + } + + BufPtr buf() const { + return buf_; + } + + void set_buf(BufPtr buf) { + buf_ = std::move(buf); + } + + explicit Free(BufPtr buf) : buf_(std::move(buf)) {} + + private: + BufPtr buf_; +}; + +class TORCH_API FreeExt : public StmtNode { + public: + static FreeExtPtr make(const std::vector& bufs); + + std::vector bufs() const { + return bufs_; + } + + void set_bufs(std::vector bufs) { + bufs_ = std::move(bufs); + } + + explicit FreeExt(std::vector bufs) : bufs_(std::move(bufs)) {} + + private: + std::vector bufs_; +}; + +class TORCH_API Let : public StmtNode { + public: + static LetPtr make(const VarHandle& var, const ExprHandle& val) { + return alloc(var.node(), val.node()); + } + + Let(VarPtr var, ExprPtr val) : var_(std::move(var)), val_(std::move(val)) {} + + VarPtr var() const { + return var_; + } + + ExprPtr value() const { + return val_; + } + + void set_var(VarPtr var) { + var_ = std::move(var); + } + + void set_val(ExprPtr val) { + val_ = std::move(val); + } + + private: + VarPtr var_; + ExprPtr val_; +}; + +class TORCH_API Cond : public StmtNode { + public: + static CondPtr make( + const ExprHandle& condition, + const StmtPtr& true_stmt, + const StmtPtr& false_stmt) { + return alloc(condition.node(), true_stmt, false_stmt); + } + + ExprPtr condition() const { + return condition_; + } + + BlockPtr true_stmt() const { + return true_stmt_; + } + + BlockPtr false_stmt() const { + return false_stmt_; + } + + void set_condition(ExprPtr condition) { + condition_ = std::move(condition); + } + + void set_true_stmt(StmtPtr true_stmt) { + if (true_stmt) { + BlockPtr b = to(true_stmt); + if (!b) { + b = alloc(std::vector({std::move(true_stmt)})); + } + true_stmt_ = b; + set_parent(true_stmt_, this); + } + } + + void set_false_stmt(StmtPtr false_stmt) { + if (false_stmt) { + BlockPtr b = to(false_stmt); + if (!b) { + b = alloc(std::vector({std::move(false_stmt)})); + } + false_stmt_ = b; + set_parent(false_stmt_, this); + } + } + + Cond(ExprPtr condition, StmtPtr true_stmt, StmtPtr false_stmt) + : condition_(std::move(condition)) { + set_true_stmt(std::move(true_stmt)); + set_false_stmt(std::move(false_stmt)); + } + + CondPtr cloneWithNewBodies( + const StmtPtr& true_stmt, + const StmtPtr& false_stmt) { + return alloc(condition_, true_stmt, false_stmt); + } + + CondPtr cloneWithNewBody(const StmtPtr& true_stmt) { + return alloc(condition_, true_stmt, nullptr); + } + + private: + ExprPtr condition_; + BlockPtr true_stmt_ = nullptr; + BlockPtr false_stmt_ = nullptr; +}; + +class TORCH_API LoopOptions { + public: + enum { + IDX_UNSET = -1, + IDX_X = 0, + IDX_Y = 1, + IDX_Z = 2, + IDX_W = 3, + IDX_MAX = IDX_W, + }; + // GPU Block Index + bool is_gpu_block_index() const { + return gpu_block_index_ != IDX_UNSET; + } + + int gpu_block_index() const { + return gpu_block_index_; + } + + std::string gpu_block_index_str() const { + if (!is_gpu_block_index()) { + throw malformed_input("Has no GPU block index"); + } + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + static constexpr const char* kBlockIndexNames[] = { + "blockIdx.x", + "blockIdx.y", + "blockIdx.z", + "blockIdx.w", + }; + + if (gpu_block_index_ < IDX_X || gpu_block_index_ > IDX_MAX) { + throw malformed_input("invalid GPU block index"); + } + + return kBlockIndexNames[gpu_block_index_]; + } + + void set_gpu_block_index(int index) { + if (index == IDX_UNSET) { + gpu_block_index_ = IDX_UNSET; + } + + if (is_gpu_thread_index()) { + throw std::runtime_error("Cannot set both gpu block and thread index"); + } + if (is_gpu_block_index() && gpu_block_index() != index) { + throw std::runtime_error("Cannot set a previously set block index"); + } + gpu_block_index_ = index; + } + + // GPU Thread Index + bool is_gpu_thread_index() const { + return gpu_thread_index() != IDX_UNSET; + } + + int gpu_thread_index() const { + return gpu_thread_index_; + } + + std::string gpu_thread_index_str() const { + if (!is_gpu_thread_index()) { + throw malformed_input("has no GPU thread index"); + } + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + static constexpr const char* kThreadIndexNames[] = { + "threadIdx.x", "threadIdx.y", "threadIdx.z", "threadIdx.w"}; + + if (gpu_thread_index_ < IDX_X || gpu_thread_index_ > IDX_MAX) { + throw malformed_input("invalid GPU thread index"); + } + + return kThreadIndexNames[gpu_thread_index_]; + } + + void set_gpu_thread_index(int index) { + if (index == IDX_UNSET) { + gpu_thread_index_ = IDX_UNSET; + } + + if (is_gpu_block_index()) { + throw std::runtime_error("Cannot set both gpu thread and block index"); + } + if (is_gpu_thread_index() && gpu_thread_index() != index) { + throw std::runtime_error("Cannot set a previously set thread index"); + } + gpu_thread_index_ = index; + } + + void set_parallel() { + is_parallel_ = true; + } + + bool is_parallel() const { + return is_parallel_; + } + + std::string ToString() const { + if (is_gpu_block_index()) { + return gpu_block_index_str(); + } else if (is_gpu_thread_index()) { + return gpu_thread_index_str(); + } else if (is_parallel()) { + return "parallel"; + } + return ""; + } + + bool isDefault() const { + return gpu_block_index_ == IDX_UNSET && gpu_thread_index_ == IDX_UNSET && + !is_parallel_; + } + + void set_buffer_mapping(const std::unordered_map& map) { + map_input_to_tensor_bufs_ = map; + } + + std::unordered_map get_buffer_mapping() const { + return map_input_to_tensor_bufs_; + } + + private: + int gpu_block_index_{IDX_UNSET}; + int gpu_thread_index_{IDX_UNSET}; + bool is_parallel_{false}; + std::unordered_map map_input_to_tensor_bufs_; +}; + +class TORCH_API For : public StmtNode { + public: + VarPtr var() const { + return var_; + } + ExprPtr start() const { + return start_; + } + ExprPtr stop() const { + return stop_; + } + BlockPtr body() const { + return body_; + } + static ForPtr make( + const VarHandle& var, + const ExprHandle& start, + const ExprHandle& stop, + const StmtPtr& body) { + if (!body) { + return nullptr; + } + return alloc(var.node(), start.node(), stop.node(), body); + } + static ForPtr make( + const VarHandle& var, + const ExprHandle& start, + const ExprHandle& stop, + const StmtPtr& body, + const LoopOptions& loop_options) { + if (!body) { + return nullptr; + } + return alloc( + var.node(), start.node(), stop.node(), body, loop_options); + } + const LoopOptions loop_options() const { + return loop_options_; + } + + For(VarPtr var, ExprPtr start, ExprPtr stop, StmtPtr body) + : var_(std::move(var)), start_(std::move(start)), stop_(std::move(stop)) { + BlockPtr b = to(body); + if (!b) { + b = alloc(std::vector({std::move(body)})); + } + body_ = b; + set_parent(body_, this); + } + + For(VarPtr var, + ExprPtr start, + ExprPtr stop, + StmtPtr body, + LoopOptions loop_options) + : var_(std::move(var)), + start_(std::move(start)), + stop_(std::move(stop)), + loop_options_(std::move(loop_options)) { + if (!var_) { + throw malformed_input("invalid Var in For loop"); + } else if (!start_) { + throw malformed_input("invalid Start in For loop"); + } else if (!stop_) { + throw malformed_input("invalid Stop in For loop"); + } else if (!body || body->get_parent()) { + throw malformed_input("invalid Body in For loop"); + } + + BlockPtr b = to(body); + if (!b) { + b = alloc(std::vector({std::move(body)})); + } + body_ = b; + set_parent(body_, this); + } + + void set_gpu_block_index(int block_index) { + loop_options_.set_gpu_block_index(block_index); + } + + void set_gpu_thread_index(int thread_index) { + loop_options_.set_gpu_thread_index(thread_index); + } + + void set_parallel() { + loop_options_.set_parallel(); + } + + bool is_parallel() const { + return loop_options_.is_parallel(); + } + + void set_buffer_map(const std::unordered_map& map) { + loop_options_.set_buffer_mapping(map); + } + + ForPtr cloneWithNewBody(const StmtPtr& body) const { + return alloc(var_, start_, stop_, body, loop_options_); + } + + BlockPtr removeBody() { + auto res = body_; + set_parent(res, nullptr); + body_ = nullptr; + return res; + } + + void set_body(StmtPtr body) { + BlockPtr b = to(body); + if (!b) { + b = alloc(std::vector({std::move(body)})); + } + body_ = b; + set_parent(body_, this); + } + + void set_start(ExprPtr start) { + start_ = std::move(start); + } + + void set_stop(ExprPtr stop) { + stop_ = std::move(stop); + } + + void set_var(VarPtr var) { + var_ = std::move(var); + } + + private: + VarPtr var_; + ExprPtr start_; + ExprPtr stop_; + BlockPtr body_; + LoopOptions loop_options_; +}; + +// A backend specific IR Node that implements atomic-add. +// This node could only shows up as an internal with GPU backends. +// TODO: move to this an internal IR. +// TODO: make IR nodes extensible. +class TORCH_API AtomicAdd : public StmtNode { + public: + AtomicAdd(BufPtr buf, std::vector indices, ExprPtr value) + : buf_(std::move(buf)), + indices_(std::move(indices)), + value_(std::move(value)) {} + + VarPtr base_handle() const { + return buf_->base_handle(); + } + + BufPtr buf() const { + return buf_; + } + + ExprPtr flat_index() const { + TORCH_CHECK(indices_.size() == 1, "Indices haven't been flattened."); + return indices_[0]; + } + + ExprPtr value() const { + return value_; + } + + const std::vector& indices() const { + return indices_; + } + + void set_buf(BufPtr buf) { + buf_ = std::move(buf); + } + + void set_indices(std::vector indices) { + indices_ = std::move(indices); + } + + void set_value(ExprPtr value) { + value_ = std::move(value); + } + + private: + BufPtr buf_; + std::vector indices_; + ExprPtr value_; +}; + +class TORCH_API SyncThreads : public StmtNode { + public: + SyncThreads() = default; +}; + +/* + * ExternalCall statement represents a call to an external function that would + * compute the contents of the output buffer. An ExternalCall statement consists + * of: + * 1) output buffer - the buffer that'll be initialized by the call + * 2) external function name - a key from the NNC function registry to lookup + * the actual function to call + * 3) buffer arguments - the input buffers used by the function + * 4) non-buffer arguments - scalar arguments to pass to the function + * + * An example: + * A = nnc_conv2d(buf_args={Input, Weight, Bias}, args={1}) + * Here 'A' is the output buffer, "nnc_conv2d" is the function name, the buffer + * arguments are 'Input', 'Weight', and 'Bias', and there is a single non-buffer + * argument - 1. + * + * The semantics of the scalar arguments is defined solely by the implementation + * of the external function. + */ +class TORCH_API ExternalCall : public StmtNode { + public: + static ExternalCallPtr make( + BufHandle buf, + const std::string& func_name, + const std::vector& buf_args, + const std::vector& args); + + BufPtr buf() const { + return buf_; + } + + std::string func_name() const { + return func_name_; + } + + std::vector buf_args() const { + return buf_args_; + } + + std::vector args() const { + return args_; + } + + void set_buf(BufPtr buf) { + buf_ = std::move(buf); + } + + void set_buf_args(std::vector buf_args) { + buf_args_ = std::move(buf_args); + } + + void set_args(std::vector args) { + args_ = std::move(args); + } + + ExternalCall( + BufPtr buf, + std::string func_name, + std::vector buf_args, + std::vector args) + : buf_(std::move(buf)), + func_name_(std::move(func_name)), + buf_args_(std::move(buf_args)), + args_(std::move(args)) {} + + private: + BufPtr buf_; + std::string func_name_; + std::vector buf_args_; + std::vector args_; +}; + +class TORCH_API ExternalCallWithAlloc : public StmtNode { + public: + static ExternalCallWithAllocPtr make( + const std::string& func_name, + const std::vector& buf_out_args, + const std::vector& buf_args, + const std::vector& args); + + std::vector buf_out_args() const { + return buf_out_args_; + } + + std::string func_name() const { + return func_name_; + } + + std::vector buf_args() const { + return buf_args_; + } + + std::vector args() const { + return args_; + } + + void set_buf_out_args(std::vector buf_out_args) { + buf_out_args_ = std::move(buf_out_args); + } + + void set_buf_args(std::vector buf_args) { + buf_args_ = std::move(buf_args); + } + + void set_args(std::vector args) { + args_ = std::move(args); + } + + ExternalCallWithAlloc( + std::string func_name, + std::vector buf_out_args, + std::vector buf_args, + std::vector args) + : func_name_(std::move(func_name)), + buf_out_args_(std::move(buf_out_args)), + buf_args_(std::move(buf_args)), + args_(std::move(args)) {} + + private: + std::string func_name_; + std::vector buf_out_args_; + std::vector buf_args_; + std::vector args_; +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..54ff410d9de8bad9027a6e8fac7698f50722cc35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h @@ -0,0 +1,326 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { + +class TORCH_API Tensor { + public: + Tensor(BufPtr buf, const std::vector& args, const ExprPtr& body) + : buf_(std::move(buf)) { + stmt_ = constructStmt(args, body, {}, {}); + } + Tensor(BufHandle buf, const std::vector& args, ExprHandle body) + : Tensor(buf.node(), VarHandleVectorToVarVector(args), body.node()) {} + + Tensor( + BufPtr buf, + const std::vector& args, + const std::vector& reduce_dims, + const std::vector& reduce_args, + const ExprPtr& body) + : buf_(std::move(buf)) { + stmt_ = constructStmt(args, body, reduce_dims, reduce_args); + } + Tensor( + BufHandle buf, + const std::vector& args, + const std::vector& reduce_dims, + const std::vector& reduce_args, + ExprHandle body) + : Tensor( + buf.node(), + VarHandleVectorToVarVector(args), + ExprHandleVectorToExprVector(reduce_dims), + VarHandleVectorToVarVector(reduce_args), + body.node()) {} + + Tensor(BufPtr buf, StmtPtr stmt) + : buf_(std::move(buf)), stmt_(std::move(stmt)) {} + + BufPtr buf() const { + return buf_; + } + + StmtPtr stmt() const { + return stmt_; + } + + template + inline ExprHandle load(const std::vector& args) const; + template + inline ExprHandle load(const Ts&... ts) const; + + private: + StmtPtr constructStmt( + const std::vector& args, + const ExprPtr& body, + const std::vector& reduce_dims, + const std::vector& reduce_args) const; + + BufPtr buf_; + StmtPtr stmt_; +}; + +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function& + body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function& + body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function< + ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>& + body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function< + ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>& + body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function&)>& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function&)>& body_func); + +inline std::vector create_index_vars( + const std::vector& dims) { + std::vector vars; + vars.reserve(dims.size()); + for (const ExprHandle& dim : dims) { + vars.emplace_back(alloc( + "i", dim.dtype().scalar_type() == ScalarType::Long ? kLong : kInt)); + } + return vars; +} + +// Handle reductions over a Reducer and a body_func which produces values. +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const InitFunc& init_func, + const BodyFunc& body_func, + const std::vector& reduce_dims) { + std::vector vars = create_index_vars(dims); + std::vector reduce_vars = create_index_vars(reduce_dims); + + // If reduce_vars is empty, then it's not a reduction, but rather a simple + // copy + if (reduce_vars.empty()) { + ExprHandle body = Reducer::getReduceBody(body_func, vars); + BufHandle func_result = + Buf::make(func_name, dims, body.dtype(), std::nullopt, strides); + return Tensor(std::move(func_result), vars, std::move(body)); + } + + std::vector all_vars; + all_vars.insert(all_vars.end(), vars.begin(), vars.end()); + all_vars.insert(all_vars.end(), reduce_vars.begin(), reduce_vars.end()); + + ExprHandle body = Reducer::getReduceBody(body_func, all_vars); + std::vector output_args(vars.begin(), vars.end()); + ExprHandle init_expr = Cast::make(body.dtype(), init_func(vars)); + BufHandle func_result = Buf::make(func_name, dims, body.dtype(), init_expr); + + ExprHandle reduce_op = reducer(func_result, body, output_args, reduce_vars); + if (body.dtype() == kBFloat16) { + ExprHandle init_expr_acc = Cast::make(kFloat, init_func(vars)); + BufHandle func_result_acc = + Buf::make(func_name + "_acc", dims, kFloat, init_expr_acc); + reduce_op = reducer( + func_result, + std::move(func_result_acc), + body, + output_args, + reduce_vars); + } + + Tensor t = Tensor( + std::move(func_result), + vars, + reduce_dims, + reduce_vars, + std::move(reduce_op)); + return t; +} +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const Reducer& reducer, + const InitFunc& init_func, + const BodyFunc& body_func, + const std::vector& reduce_dims) { + return Reduce( + func_name, + dims, + std::nullopt, + reducer, + init_func, + body_func, + reduce_dims); +} + +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const BodyFunc& body_func, + const std::vector& reduce_dims) { + return Reduce( + func_name, + dims, + strides, + reducer, + [&](ParameterList& p [[maybe_unused]]) { + return ExprHandle(reducer.initializer()); + }, + body_func, + reduce_dims); +} +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const Reducer& reducer, + const BodyFunc& body_func, + const std::vector& reduce_dims) { + return Reduce( + func_name, dims, std::nullopt, reducer, body_func, reduce_dims); +} + +// Overload which allows inline lambda functions for the body_func. +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const BodyFunc&& body_func, + const std::vector& reduce_dims) { + return Reduce(func_name, dims, strides, reducer, body_func, reduce_dims); +} +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const Reducer& reducer, + const BodyFunc&& body_func, + const std::vector& reduce_dims) { + return Reduce(func_name, dims, std::nullopt, reducer, body_func, reduce_dims); +} + +TORCH_API Tensor Reduce( + const std::string& name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const BufHandle& buffer, + const std::vector& reduce_dims); +TORCH_API Tensor Reduce( + const std::string& name, + const std::vector& dims, + const Reducer& reducer, + const BufHandle& buffer, + const std::vector& reduce_dims); + +// Overload for the common case of all dimensions of a previously Computed +// Tensor. +TORCH_API Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const Tensor& tensor, + const std::vector& reduce_dims); +TORCH_API Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const Reducer& reducer, + const Tensor& tensor, + const std::vector& reduce_dims); + +template +inline ExprHandle Tensor::load(const Ts&... ts) const { + std::vector params({ExprHandle(ts)...}); + return Load::make(BufHandle(this->buf()), params); +} + +template +inline ExprHandle Tensor::load(const std::vector& args) const { + std::vector params(args.begin(), args.end()); + return Load::make(BufHandle(this->buf()), params); +} + +template +inline ExprHandle BufHandle::load(const Ts&... ts) const { + std::vector params({ExprHandle(ts)...}); + return ExprHandle(alloc(node(), ExprHandleVectorToExprVector(params))); +} + +template +inline ExprHandle BufHandle::load(const std::vector& args) const { + std::vector params(args.begin(), args.end()); + return ExprHandle(alloc(node(), ExprHandleVectorToExprVector(params))); +} + +inline ExprHandle BufHandle::load(const std::vector& args) const { + return this->template load(args); +} + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h new file mode 100644 index 0000000000000000000000000000000000000000..247b679de43aa244ab779527304da5adb74e9e7b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { +// Initialize Python bindings for Tensor Expressions +void initTensorExprBindings(PyObject* module); +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/types.h new file mode 100644 index 0000000000000000000000000000000000000000..5615ba08951841b9e8086df7156d70d565ca155c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/types.h @@ -0,0 +1,163 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +using int32 = std::int32_t; + +class Dtype; +TORCH_API std::ostream& operator<<(std::ostream& stream, const Dtype& dtype); + +using ScalarType = c10::ScalarType; + +enum ElementType { + kAllTypes = 0, + kIntegralTypes = 1 << 0, + kFloatingPointTypes = 1 << 1, + kBoolType = 1 << 2, + kComplexTypes = 1 << 3, + kQintTypes = 1 << 4, + kNonComplexOrQintTypes = kIntegralTypes | kBoolType | kFloatingPointTypes, +}; + +// Data types for scalar and vector elements. +class TORCH_API Dtype { + public: + explicit Dtype(int8_t type) + : scalar_type_(static_cast(type)), lanes_(1) {} + explicit Dtype(ScalarType type) : scalar_type_(type), lanes_(1) {} + Dtype(int8_t type, int64_t lanes) + : scalar_type_(static_cast(type)), lanes_(lanes) {} + Dtype(ScalarType type, int64_t lanes) : scalar_type_(type), lanes_(lanes) {} + Dtype(Dtype type, int64_t lanes) + : scalar_type_(type.scalar_type_), lanes_(lanes) { + if (type.lanes() != 1) { + throw malformed_input("dtype lanes dont match"); + } + } + int64_t lanes() const { + return lanes_; + } + ScalarType scalar_type() const { + return scalar_type_; + } + Dtype scalar_dtype() const; + bool operator==(const Dtype& other) const { + return scalar_type_ == other.scalar_type_ && lanes_ == other.lanes_; + } + bool operator!=(const Dtype& other) const { + return !(*this == other); + } + int byte_size() const; + std::string ToCppString() const; + + bool is_integral() const { + return c10::isIntegralType(scalar_type_, true); + } + bool is_floating_point() const { + return c10::isFloatingType(scalar_type_); + } + bool is_signed() const { + return c10::isSignedType(scalar_type_); + } + + Dtype cloneWithScalarType(ScalarType nt) const { + return Dtype(nt, lanes_); + } + + private: + friend TORCH_API std::ostream& operator<<( + std::ostream& stream, + const Dtype& dtype); + ScalarType scalar_type_; + int64_t lanes_; // the width of the element for a vector time +}; + +extern TORCH_API Dtype kHandle; + +#define NNC_DTYPE_DECLARATION(ctype, name) extern TORCH_API Dtype k##name; + +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, NNC_DTYPE_DECLARATION) +NNC_DTYPE_DECLARATION(c10::quint8, QUInt8) +NNC_DTYPE_DECLARATION(c10::qint8, QInt8) +#undef NNC_DTYPE_DECLARATION + +template +TORCH_API Dtype ToDtype(); + +#define NNC_TODTYPE_DECLARATION(ctype, name) \ + template <> \ + inline Dtype ToDtype() { \ + return k##name; \ + } +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, NNC_TODTYPE_DECLARATION) +NNC_TODTYPE_DECLARATION(c10::quint8, QUInt8) +NNC_TODTYPE_DECLARATION(c10::qint8, QInt8) +#undef NNC_TODTYPE_DECLARATION + +TORCH_API Dtype ToDtype(ScalarType type); + +inline Dtype promoteTypes(Dtype a, Dtype b) { + if (a.lanes() != b.lanes()) { + throw malformed_input("promoting types with different lanes"); + } + return Dtype( + static_cast(c10::promoteTypes( + static_cast(a.scalar_type()), + static_cast(b.scalar_type()))), + a.lanes()); +} + +inline Dtype BinaryOpDtype( + Dtype op1_dtype, + Dtype op2_dtype, + ScalarType ret_type = ScalarType::Undefined) { + if (op1_dtype == op2_dtype) { + if (ret_type == ScalarType::Undefined) { + return op1_dtype; + } + + return ToDtype(ret_type); + } + + if (op1_dtype.lanes() != op2_dtype.lanes()) { + throw malformed_input("lanes dont match"); + } + int64_t lanes = op1_dtype.lanes(); + + Dtype resultType = promoteTypes(op1_dtype, op2_dtype); + if (resultType.scalar_type() == ScalarType::Undefined) { + throw malformed_input("scalar type doesn't match"); + } + + if (lanes == 1) { + // Use the fixed scalar Dtypes. + return ToDtype(resultType.scalar_type()); + } + + return resultType; +} + +} // namespace torch::jit::tensorexpr + +namespace std { + +using torch::jit::tensorexpr::Dtype; +std::string to_string(const Dtype& dtype); +using torch::jit::tensorexpr::ScalarType; +std::string to_string(const ScalarType& dtype); + +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..7ef8ec508cbffcf573d68d34f65636b4f04e11b4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h @@ -0,0 +1,38 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { + +class VarHandle; +class Var; + +using VarNameMap = std::unordered_map; + +// A manager to get unique names from vars. +// It starts with the name hints of the var and append "_" + $counter until it +// hits a unique name. +class TORCH_API UniqueNameManager { + public: + const std::string& get_unique_name(const VarHandle& v); + + const std::string& get_unique_name(const VarPtr& v); + + private: + friend class ScopedVarName; + VarNameMap unique_name_mapping_; + std::unordered_map unique_name_count_; + std::unordered_set all_unique_names_; +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h new file mode 100644 index 0000000000000000000000000000000000000000..b74c53c9c9cb33318ccc10822058a0b0bea1448f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h @@ -0,0 +1,66 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +using VarMapping = std::vector>; + +class VarSubMutator : public IRMutator { + public: + VarSubMutator(const VarMapping& var_mapping) { + for (auto& entry : var_mapping) { + VarPtr key_var = entry.first; + ExprPtr value = entry.second; + if (!key_var) { + throw malformed_input("missing key in VarSubMutator"); + } + var_mapping_[std::move(key_var)] = std::move(value); + } + } + + ExprPtr mutate(const VarPtr& var) override { + auto iter = var_mapping_.find(var); + if (iter == var_mapping_.end()) { + return var; + } + return iter->second; + } + + ExprPtr mutate(const ReduceOpPtr& var) override { + auto body = var->body()->accept_mutator(this); + std::vector new_inner; + + for (const auto& v : var->reduce_args()) { + ExprPtr e = v->accept_mutator(this); + if (VarPtr new_var = to(e)) { + new_inner.push_back(std::move(new_var)); + } else { + VarFinder varFinder; + e->accept(&varFinder); + auto varlist = varFinder.vars(); + new_inner.insert(new_inner.end(), varlist.begin(), varlist.end()); + } + } + + return alloc(body, new_inner, var->reducer()); + } + + private: + std::unordered_map var_mapping_; +}; + +} // namespace torch::jit::tensorexpr + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/catch_utils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/catch_utils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a361da0933df1d61e9f4fea6a50120f8a26daffb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/catch_utils.hpp @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#define CATCH_CONFIG_PREFIX_ALL +#include + +// CATCH_REQUIRE_THROWS is not defined identically to REQUIRE_THROWS and causes +// warning; define our own version that doesn't warn. +#define _CATCH_REQUIRE_THROWS(...) \ + INTERNAL_CATCH_THROWS( \ + "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__) + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h new file mode 100644 index 0000000000000000000000000000000000000000..d21536d075419323681874e9cb02caa1fe713b5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h @@ -0,0 +1,84 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +struct Graph; + +namespace testing { + +struct FileCheckImpl; + +struct FileCheck { + public: + TORCH_API explicit FileCheck(); + TORCH_API ~FileCheck(); + + // Run FileCheck against test string + TORCH_API void run(const std::string& test_string); + + // Run FileCheck against dump of graph IR + TORCH_API void run(const Graph& graph); + + // Parsing input checks string and run against test string / dump of graph IR + TORCH_API void run( + const std::string& input_checks_string, + const std::string& test_string); + TORCH_API void run( + const std::string& input_checks_string, + const Graph& graph); + + // Checks that the string occurs, starting at the end of the most recent match + TORCH_API FileCheck* check(const std::string& str); + + // Checks that the string does not occur between the previous match and next + // match. Consecutive check_nots test against the same previous match and next + // match + TORCH_API FileCheck* check_not(const std::string& str); + + // Checks that the string occurs on the same line as the previous match + TORCH_API FileCheck* check_same(const std::string& str); + + // Checks that the string occurs on the line immediately following the + // previous match + TORCH_API FileCheck* check_next(const std::string& str); + + // Checks that the string occurs count number of times, starting at the end + // of the previous match. If exactly is true, checks that there are exactly + // count many matches + TORCH_API FileCheck* check_count( + const std::string& str, + size_t count, + bool exactly = false); + + // A series of consecutive check_dags get turned into a group of checks + // which can appear in any order relative to each other. The checks begin + // at the end of the previous match, and the match for the check_dag group + // is the minimum match of all individual checks to the maximum match of all + // individual checks. + TORCH_API FileCheck* check_dag(const std::string& str); + + // Checks that source token is highlighted in str (usually an error message). + TORCH_API FileCheck* check_source_highlighted(const std::string& str); + + // Checks that the regex matched string occurs, starting at the end of the + // most recent match + TORCH_API FileCheck* check_regex(const std::string& str); + + // reset checks + TORCH_API void reset(); + + private: + bool has_run = false; + std::unique_ptr fcImpl; +}; +} // namespace testing +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h new file mode 100644 index 0000000000000000000000000000000000000000..5547574692493b6585214a68622523c962308322 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::jit { +struct Module; + +using ModuleHook = std::function; +using FunctionHook = std::function; + +TORCH_API void didFinishEmitModule(Module module); +TORCH_API void didFinishEmitFunction(StrongFunctionPtr defined); +TORCH_API void setEmitHooks(ModuleHook for_module, FunctionHook for_fn); + +TORCH_API std::pair getEmitHooks(); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_data.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_data.h new file mode 100644 index 0000000000000000000000000000000000000000..75f05b99b69aca3439c9b5be53685dd65622ebcc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_data.h @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::lazy { + +class TORCH_API BackendData { + public: + struct Info { + /** + * Used by Lazy Graph Executor to tag info on BackendData objs + * */ + virtual ~Info() = default; + }; + /** + * Represents (Tensor) data stored on a backend device + * in its native format. + * */ + using Handle = int64_t; + + BackendData(BackendDevice device, Shape shape) + : device_(std::move(device)), shape_(std::move(shape)) {} + + virtual ~BackendData() = default; + + const BackendDevice& device() const { + return device_; + } + + const Shape& shape() const { + return shape_; + } + + Info* info() const { + return info_.get(); + } + + std::shared_ptr SetInfo(std::shared_ptr info) { + std::swap(info, info_); + return info; + } + + virtual Handle GetHandle() = 0; + + virtual void Assign(const BackendData& data) = 0; + + virtual bool HasValue() const = 0; + + private: + BackendDevice device_; + Shape shape_; + std::shared_ptr info_; +}; + +using BackendDataPtr = std::shared_ptr; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_device.h new file mode 100644 index 0000000000000000000000000000000000000000..b5e697035bb12196ea0d59b4b5cda3ab1fa9cee3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_device.h @@ -0,0 +1,105 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace c10 { +struct Device; +} + +namespace torch::lazy { + +// Backend should extend it and define their own supported hardware types. +struct TORCH_API BackendDeviceType { + int8_t type{(int8_t)at::kCPU}; + // Note: previous default value was '0', which actually maps to at::kCPU, at + // least now it is explicit, we may want to make default/undefined semantics + // more clear though + BackendDeviceType() : type((int8_t)at::kCPU) {} + BackendDeviceType(int8_t type) : type(type) {} + + virtual ~BackendDeviceType() = default; + virtual std::string toString() const { + return "Unknown"; + } +}; + +class TORCH_API BackendDevice { + public: + // The default constructor will set both the device type and ordinal + // to backend specific defaults. + BackendDevice(); + BackendDevice(std::shared_ptr&& type, int64_t ordinal); + + int8_t type() const; + int64_t ordinal() const { + return ordinal_; + } + + bool operator==(const BackendDevice& other) const { + return compare(other) == 0; + } + bool operator!=(const BackendDevice& other) const { + return compare(other) != 0; + } + bool operator<(const BackendDevice& rhs) const { + return compare(rhs) < 0; + } + + std::string toString() const; + + private: + int compare(const BackendDevice& rhs) const; + + // Use shared_ptr instead of unique_ptr so that BackendDevice can be copied. + std::shared_ptr type_; + int64_t ordinal_; +}; + +TORCH_API std::ostream& operator<<( + std::ostream& os, + const BackendDevice& device); + +// Helpers for converting a c10::Device to BackendDevice and vice versa. +TORCH_API BackendDevice atenDeviceToBackendDevice(const c10::Device& device); +TORCH_API c10::Device backendDeviceToAtenDevice(const BackendDevice& device); + +// Tries to extract the backend device out of the lazy tensor. Returns nullopt +// if the input is not a lazy tensor. +TORCH_API std::optional GetBackendDevice( + const at::ITensorListRef tensors); +TORCH_API std::optional GetBackendDevice( + const at::TensorList tensors); +TORCH_API std::optional GetBackendDevice( + const at::Tensor& tensor); +TORCH_API std::optional GetBackendDevice( + const std::optional& device); + +// For variadic template. +TORCH_API std::optional GetBackendDevice(); + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Winfinite-recursion") +template +std::optional GetBackendDevice( + const T& tensor, + const Args&... forward_tensors) { + auto optional_device = GetBackendDevice(tensor); + if (optional_device) { + return optional_device; + } + return GetBackendDevice(forward_tensors...); +} +C10_DIAGNOSTIC_POP() + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..9f885d4d4c71618d6c824f197ef109b0c0c76dfc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_interface.h @@ -0,0 +1,160 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +struct IrBuilder; + +/** + * Work in progress- don't treat this as a stable interface yet! + */ +class TORCH_API BackendImplInterface { + public: + virtual ~BackendImplInterface() = default; + + /** + * Initialization/Teardown + * */ + // No-op by default. Allows custom functionality to be exposed through + // extension bindings. + virtual void InitializeAtenBindings() const {} + + virtual void PrepareToExit() const = 0; + + /** + * Configuration + * */ + + virtual void SetRngSeed(size_t seed) const = 0; + + /** + * IR Tracing + * */ + + virtual const IrBuilder* GetIrBuilder() const = 0; + + /** + * Data Transfer + * */ + + virtual BackendDataPtr MakeComputationDataFromTensor( + const at::Tensor& tensor, + const Shape& shape, + const BackendDevice& device) const = 0; + virtual BackendDataPtr MakeComputationDataFromScalar( + const at::Scalar& scalar, + const torch::lazy::BackendDevice& device) const = 0; + virtual BackendDataPtr CreateDataPlaceholder( + const BackendDevice& device, + const Shape& shape) const = 0; + + // Gets backend data if the node is a device data node. Otherwise returns + // nullptr + virtual BackendDataPtr GetComputationDataFromNode(const Node*) const = 0; + + virtual at::Tensor MakeTensorFromComputationData( + const BackendDataPtr data, + std::optional logical_scalar_type) const = 0; + + /** + * Lowering, Compilation, Execution + * */ + + virtual std::unique_ptr CreateLoweringContext( + const std::string& name, + BackendDevice device, + c10::ArrayRef post_order, + Util::EmissionMap emit_status) const = 0; + + virtual std::unique_ptr CreateLoweringContext( + const std::string& name, + BackendDevice device) const = 0; + + // TODO(whc) need to keep this? + virtual std::vector GetCompilationDevices( + const std::string& device, + c10::ArrayRef devices) const = 0; + + virtual std::vector Compile( + std::vector instances) const = 0; + + virtual std::vector ExecuteComputation( + torch::lazy::ComputationPtr computation, + c10::ArrayRef arguments, + const BackendDevice& device) const = 0; + + /** + * Device Configuration + * */ + + // Set or get the default device type. + // For backends used with virtual c10::Devices, this configures what real + // device type the backend should use, and matters if the backend supports + // more than one type of real device. + virtual std::shared_ptr GetDefaultDeviceType() const = 0; + virtual void SetDefaultDeviceType(int8_t type) = 0; + + // Set or get the default device ordinal. + // For backends that supports multi-device, this configures what the + // default device the backend should use. + virtual int64_t GetDefaultDeviceOrdinal() const = 0; + virtual void SetDefaultDeviceOrdinal(int64_t) = 0; + + // Specify which aten device should be used for eager fallback + // may change depending on current 'Default' DeviceType + virtual at::DeviceType EagerFallbackDeviceType() const = 0; + + // Query all available backend devices + virtual std::vector GetBackendDevices() const = 0; + + virtual std::string CreateMetricReport() const { + return ""; + } + + // Map a particular c10:: device to a concrete backend device + // Note:: c10:: devices may be virtual or concrete. xla:: and lazy:: are + // virtual devices, meaning they may map to a gpu, tpu, etc. behind the + // scenes. In the future, non-virtual c10:: devices may also use lazy tensors + // through a mode, in which case these APIs should still work, but should be + // identity mappings. + virtual BackendDevice GetBackendDevice(c10::Device device) const = 0; + + // TODO(whc) + // Additional APIs expected for supporting distributed training, to be + // designed + + /** + * Debug/Metrics + * */ + + // virtual std::map GetMetrics() const = 0; + + // virtual MemoryInfo GetMemoryInfo(const std::string& device) = 0; + + virtual std::string GetComputationBackendText( + const ComputationPtr computation) const = 0; +}; + +class TORCH_API BackendRegistrar { + public: + BackendRegistrar(const BackendImplInterface* backend_impl_interface); +}; + +TORCH_API bool hasBackend(); +TORCH_API const BackendImplInterface* getBackend(); + +TORCH_API const IrBuilder* getIrBuilder(); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h new file mode 100644 index 0000000000000000000000000000000000000000..8de72ec167fdd9d27412ba13b8ac143e16d2c0b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h @@ -0,0 +1,115 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace torch::lazy { + +class TORCH_API Computation { + public: + virtual int parameters_size() const = 0; + + virtual const std::vector& parameter_shapes() const = 0; + + virtual const std::vector& parameter_names() const = 0; + + virtual const Shape& result_shape() const = 0; + + virtual const std::string to_string() const = 0; + + virtual ~Computation() = default; + + // Indicates whether this computation is being executed inside a mark step + // Assume false unless set otherwise + bool in_mark_step = false; +}; + +using ComputationPtr = std::shared_ptr; + +// Keeps track of the code generation state. +class TORCH_API LoweringContext { + public: + LoweringContext(const std::string& name, BackendDevice device); + LoweringContext( + const std::string& name, + BackendDevice device, + c10::ArrayRef post_order, + Util::EmissionMap emit_status); + + virtual ~LoweringContext() = default; + + static std::unique_ptr Create( + const std::string& name, + BackendDevice device, + c10::ArrayRef post_order, + Util::EmissionMap emit_status); + + static std::unique_ptr Create( + const std::string& name, + BackendDevice device); + + const BackendDevice& device() const { + return device_; + } + + // Retrieves the vector holding all the tensors associated with the parameter + // instructions which have been created. + const std::vector& GetParametersData() const; + + // Adds a new input/output alias. + virtual void SetUpAlias( + const std::vector& output_index, + int64_t param_number, + const std::vector& param_index, + bool must_alias = false) { + // Dummy default implementation to do nothing. + } + + // Check if parameter shape matches result at index. + virtual bool CheckResultShape( + const BackendDataPtr& parameter_data, + size_t result_idx) { + // Dummy default implementation to do nothing. + return false; + } + + // Adds the given output as a component of the result tuple and returns its + // assigned position within the tuple. + virtual size_t AddResult(const torch::lazy::Output& output) = 0; + + // Associates the given output with the input parameter of the given index and + // shape. Only used for the operator-by-operator execution, mostly for + // debugging purposes. + virtual void AddParameter( + const torch::lazy::Output& output, + size_t index, + const Shape& shape, + const std::string& name) = 0; + + // Build the computation capturing all the operations created with the + // embedded builder (returned by the builder() API). + virtual ComputationPtr Build() = 0; + + size_t GetEmittedNodeCount() const { + return emit_status_.size(); + } + + protected: + BackendDevice device_; + std::vector parameters_; + std::vector parameter_sequence_; + Util::EmissionMap emit_status_; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/cache.h new file mode 100644 index 0000000000000000000000000000000000000000..a34161654e64d8277e0af2508360dcaa9aa782b8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/cache.h @@ -0,0 +1,148 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** + * Cache utils in this file is adapted from PyTorch/XLA + * https://github.com/pytorch/xla/blob/e0e5f937a0ba8d904f9608137dc8c51ba439df2d/third_party/xla_client/cache.h + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +// Generic key and object cache with LRU expiration policy. The objects of type +// T will be stored as std::shared_ptr and taken and returned as such, by the +// cache API. +template < + typename K, + typename T, + typename H = std::hash, + typename E = std::equal_to> +class Cache { + public: + using TypePtr = std::shared_ptr; + using Element = std::pair; + + explicit Cache(size_t max_size) : max_size_(max_size) {} + + // Adds an object to the cache, unless it already exists. If the cache grows + // beyond the limit set during construction, the oldest used object will be + // removed from the cache. + TypePtr Add(K key, TypePtr object) { + if (!max_size_) { + return object; + } + std::lock_guard slock(lock_); + element_list_.emplace_front(Element(std::move(key), std::move(object))); + auto it = element_list_.begin(); + auto emplace_result = element_map_.emplace(&it->first, it); + if (!emplace_result.second) { + element_list_.erase(it); + DoLRU(emplace_result.first->second); + } else if (element_list_.size() > max_size_) { + Element* last = &element_list_.back(); + element_map_.erase(&last->first); + element_list_.pop_back(); + } + return emplace_result.first->second->second; + } + + // Retrieves the existing object if it exists. If it does, its position in + // the LRU list gets moved to the head of the list. + // Returns nullptr if no object with the specified key is found within the + // cache. + TypePtr Get(const K& key) { + if (!max_size_) { + return nullptr; + } + std::lock_guard slock(lock_); + auto it = element_map_.find(&key); + if (it == element_map_.end()) { + return nullptr; + } + DoLRU(it->second); + return it->second->second; + } + + TypePtr GetLatest() { + std::lock_guard g(lock_); + TORCH_CHECK(!element_list_.empty()); + return element_list_.front().second; + } + + bool Erase(const K& key) { + if (!max_size_) { + return false; + } + std::lock_guard slock(lock_); + auto it = element_map_.find(&key); + if (it == element_map_.end()) { + return false; + } + auto lit = it->second; + element_map_.erase(it); + element_list_.erase(lit); + return true; + } + + void Clear() { + if (!max_size_) { + return; + } + std::lock_guard slock(lock_); + element_map_.clear(); + element_list_.clear(); + } + + int Numel() const { + if (!max_size_) { + return 0; + } + std::lock_guard g(lock_); + TORCH_CHECK(element_map_.size() == element_list_.size()); + return element_map_.size(); + } + + private: + using ElementList = std::list; + + struct Hasher { + size_t operator()(const K* key) const { + return hasher(*key); + } + + H hasher; + }; + + struct Equaler { + bool operator()(const K* k1, const K* k2) const { + return equaler(*k1, *k2); + } + + E equaler; + }; + + using ElementMap = std:: + unordered_map; + + void DoLRU(typename ElementList::iterator it) { + element_list_.splice(element_list_.begin(), element_list_, it); + } + + mutable std::mutex lock_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const size_t max_size_ = 0; + ElementList element_list_; + ElementMap element_map_; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/config.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/config.h new file mode 100644 index 0000000000000000000000000000000000000000..83ff42b145fa390c600e4f005c29c1993fdbbff9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/config.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +TORCH_DECLARE_bool(torch_lazy_ir_debug); +TORCH_DECLARE_bool(torch_lazy_handle_special_scalars); +TORCH_DECLARE_bool(torch_lazy_all_numbers_special_scalars); +TORCH_DECLARE_bool(torch_lazy_param_aliasing); +TORCH_DECLARE_bool(torch_lazy_reuse_ir); +TORCH_DECLARE_bool(torch_lazy_use_thread_pool); +TORCH_DECLARE_bool(torch_lazy_enable_device_data_cache); + +TORCH_DECLARE_int(torch_lazy_compilation_cache_size); +TORCH_DECLARE_int(torch_lazy_device_data_cache_size); +TORCH_DECLARE_int(torch_lazy_io_thread_pool_size); +TORCH_DECLARE_int(torch_lazy_metrics_samples); +TORCH_DECLARE_int(torch_lazy_trim_graph_check_frequency); +TORCH_DECLARE_int(torch_lazy_trim_graph_size); + +TORCH_DECLARE_string(torch_lazy_metrics_percentiles); + +TORCH_DECLARE_int(torch_lazy_shape_cache_size); + +namespace torch::lazy { +TORCH_API std::string& getLTCForceFallback(); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/debug_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/debug_util.h new file mode 100644 index 0000000000000000000000000000000000000000..7c3ce3171ce299d10a487dc5f85a9861d7d123c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/debug_util.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::lazy { + +TORCH_API std::function()>& +GetPythonFramesFunction(); + +TORCH_API std::string GetFirstUserFrameInPython(); + +class TORCH_API DebugUtil { + public: + enum GraphFormat { + kText, + kDot, + kBackend, + }; + + static GraphFormat GetDefaultGraphFormat(); + + // Dumps the current Python frame and the IR Graph whose roots are the IR + // values held at the tensors. If indices is not nullptr, it selects the + // indices of the tensors whose graph will be emitted. + static std::string GetTensorsGraphInfo( + c10::ArrayRef tensors, + const std::vector* indices, + GraphFormat format = GetDefaultGraphFormat()); + + // If the environment variable LTC_SAVE_TENSORS_FILE is set to the proper + // output path, an instance of the report returned by GetTensorsGraphInfo() is + // saved. + static void SaveTensorsGraphInfo( + const char* name, + c10::ArrayRef tensors, + const std::vector* indices, + GraphFormat format = GetDefaultGraphFormat()); + + static bool ExperimentEnabled(const std::string& name); +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/dynamic_ir.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/dynamic_ir.h new file mode 100644 index 0000000000000000000000000000000000000000..d21d6feb0ba58ad5e17f7e92b1e14c4334c3475e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/dynamic_ir.h @@ -0,0 +1,53 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +/** + * The goal of "dynamic" Nodes is to patch a hole in our tracing. + * Previously, if a user called `sizes` on a Tensor, it would leak out + * of our tracing system, as `sizes` returns a torch.Size or an int. To + * prevent this from happening, we introduce DimensionNode, a new type + * of Node that abstracts the operation of getting the dimensions of a + * Tensor. + * + * Consider the following example: + * ``` + * numel = x.shape()[0] * x.shape()[1] + * ``` + * + * Here, `x.shape()[i]` will be a SizeNode (subclass of DimensionNode), + * and the multiplication of the two SizeNodes will be represented by + * a SizeMul (also a subclass of DimensionNode). Through this, we can + * prevent `numel` from being represented as a Python int and thus + * burned into the Graph. + */ + +class TORCH_API DimensionNode { + public: + virtual bool isSymbolic() const { + return false; + } + virtual int64_t getDynamicValue() const { + TORCH_CHECK(false, "NYI"); + } + virtual int64_t getStaticValue() const { + TORCH_CHECK(false, "NYI"); + } + virtual ~DimensionNode() = default; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/hash.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/hash.h new file mode 100644 index 0000000000000000000000000000000000000000..f224aae7bf62257f83e4e5db89c843a9323777a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/hash.h @@ -0,0 +1,247 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** + * Hash utils in this file is adapted from PyTorch/XLA + * https://github.com/pytorch/xla/blob/e0e5f937a0ba8d904f9608137dc8c51ba439df2d/third_party/xla_client/util.h + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +using size_t = std::size_t; + +class TORCH_API hash_t : public c10::uint128 { + public: + // Switch from typedef hash_t = uint128 to provide explicit casters + hash_t(int8_t val) : uint128(static_cast(val)) {} + hash_t(int16_t val) : uint128(static_cast(val)) {} + hash_t(int32_t val) : uint128(static_cast(val)) {} + hash_t(int64_t val) : uint128(static_cast(val)) {} + hash_t(uint32_t val) : uint128(val) {} + hash_t(uint64_t val) : uint128(val) {} + hash_t(uint128 val) : uint128(val) {} + hash_t(uint64_t top, uint64_t bottom) : uint128(top, bottom) {} + hash_t() = default; +}; + +// Std* functions use 64-bit hash +size_t TORCH_API StdDataHash(const void* data, size_t size); + +size_t TORCH_API StdHashCombine(uintmax_t a, uintmax_t b); + +// Other functions are all 128-bit +hash_t TORCH_API HashBlock(const void* data, size_t n, const hash_t& seed); + +hash_t TORCH_API DataHash(const void* data, size_t size); + +hash_t TORCH_API HashCombine(const hash_t& a, const hash_t& b); + +size_t TORCH_API HashReduce(const hash_t& a); + +// Returns a string representation of a hash +std::string TORCH_API HashToString(const hash_t& a); + +struct HashReducer { + size_t operator()(const hash_t& value) const { + return HashReduce(value); + } +}; + +static inline hash_t StringHash(const char* data) { + return DataHash(data, std::strlen(data)); +} + +// Automatic templated implementation for 'arithmetic' types +template >* = nullptr> +hash_t Hash(const T& value) { + return DataHash(&value, sizeof(value)); +} + +// added because on macos builds the vector specialization +// breaks falling through to the templated arithmetic types above +hash_t TORCH_API Hash(const std::vector& value); + +// Specialized implementations for proprietary types +static inline hash_t Hash(const c10::ScalarType& value) { + return DataHash(&value, sizeof(value)); +} + +static inline hash_t Hash(const c10::MemoryFormat& value) { + return DataHash(&value, sizeof(value)); +} + +static inline hash_t Hash(const c10::DeviceType& value) { + return DataHash(&value, sizeof(value)); +} + +static inline hash_t Hash(const c10::Device& value) { + return HashCombine(Hash(value.type()), Hash(value.index())); +} + +static inline hash_t Hash(const c10::Layout& value) { + return DataHash(&value, sizeof(value)); +} + +static inline hash_t Hash(const c10::Scalar& value) { + switch (value.type()) { + case c10::ScalarType::ComplexDouble: + return Hash(value.toComplexDouble()); + case c10::ScalarType::Double: + return Hash(value.toDouble()); + case c10::ScalarType::Long: + return Hash(value.toLong()); + case c10::ScalarType::Bool: + return Hash(value.toBool()); + default: + TORCH_INTERNAL_ASSERT(false, "Unknown scalar type.", value.type()); + } +} + +static inline hash_t TensorHash(const at::Tensor& tensor) { + at::Tensor ctensor = tensor.contiguous(); + int64_t size = ctensor.numel() * ctensor.element_size(); + switch (ctensor.scalar_type()) { + case at::ScalarType::Bool: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::Byte: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::Char: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::Short: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::Int: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::Long: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::Float: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::Double: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::BFloat16: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::Half: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::ComplexFloat: + return DataHash(ctensor.const_data_ptr>(), size); + case at::ScalarType::ComplexDouble: + return DataHash(ctensor.const_data_ptr>(), size); + case at::ScalarType::UInt16: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::UInt32: + return DataHash(ctensor.const_data_ptr(), size); + case at::ScalarType::UInt64: + return DataHash(ctensor.const_data_ptr(), size); + default: + TORCH_INTERNAL_ASSERT( + false, "Unsupported scalar type:", ctensor.scalar_type()); + } +} + +static inline hash_t Hash(const std::string& value) { + return DataHash(value.data(), value.size()); +} + +static inline hash_t Hash(const std::string_view& value) { + return DataHash(value.data(), value.size()); +} + +static inline hash_t Hash(const at::Generator& value) { + return TensorHash(value.get_state()); +} + +// Taken from glibc's implementation of hashing optionals, +// we want to include a contribution to the hash to distinguish +// cases where one or another option was null, but we hope it doesn't +// collide with an actually scalar value. +// +// Use an arbitrary randomly-selected 64-bit integer rather than a +// small constant that we then hash at runtime so we don't have to +// repeatedly hash a constant at runtime. +// NOLINTNEXTLINE(*-narrowing-conversions) +static const int64_t kNullOpt = 0x8655d738f3678dda; + +// Hashing for std::optional types contributes to hash +// for optionals with null value, important to distinguish +// between and cases +template +hash_t Hash(const std::optional& value) { + if (value.has_value()) { + return Hash(value.value()); + } else { + return kNullOpt; + } +} + +// Hashing of containers +// Forward declare to allow hashes of vectors of vectors to work. +template +hash_t ContainerHash(const T& values); + +template +hash_t Hash(const std::vector& values) { + return ContainerHash(values); +} + +// Need a special case for std::optional? +template +hash_t Hash(const std::optional>& value) { + if (value.has_value()) { + return ContainerHash(value.value()); + } else { + return kNullOpt; + } +} + +template +hash_t Hash(const std::set& values) { + return ContainerHash(values); +} + +template +hash_t Hash(const std::pair& values) { + return HashCombine(Hash(values.first), Hash(values.second)); +} + +static inline hash_t Hash(const hash_t& value) { + return value; +} + +template +hash_t Hash(c10::ArrayRef values) { + return ContainerHash(values); +} + +template +hash_t ContainerHash(const T& values) { + hash_t h(static_cast(0x85ebca77c2b2ae63)); + for (const auto& value : values) { + h = HashCombine(h, Hash(value)); + } + return h; +} + +// Varargs hashing +template +hash_t MHash() { + return hash_t(static_cast(0x165667b19e3779f9)); +} + +template +hash_t MHash(T value, Targs... Fargs) { + return HashCombine(Hash(value), MHash(Fargs...)); +} + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/helpers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..440e880fcb76b7e60e7a383d6b820ab6a3c7ae34 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/helpers.h @@ -0,0 +1,75 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +// TODO: Consolidate this file with util.h + +namespace torch::lazy { + +// Converts an iterable container to a vector of int64's. +template +static std::vector ToI64Vector(const S& input) { + return ToVector(input); +} + +// Creates a set of dimension by dropping the drop_dims ones. +TORCH_API std::vector DropDimensions( + c10::ArrayRef sizes, + c10::ArrayRef drop_dims); + +// Get the canonical dimension index in the [0, rank) interval. Negative +// indices are interpreted as follows: -1 is rank-1, -2 is rank-2 etc. +TORCH_API int64_t GetCanonicalDimensionIndex(int64_t dim, int64_t rank); + +// Same as above, for multiple dimensions. +TORCH_API std::vector GetCanonicalDimensionIndices( + c10::ArrayRef dimensions, + int64_t rank); + +// Returns the canonical position in the dim dimension, handling negative +// values for the position. +TORCH_API int64_t GetCanonicalPosition( + c10::ArrayRef dimensions, + int64_t dim, + int64_t pos); + +// Creates a transposition from the given input and dimensions. +TORCH_API std::vector MakeTransposePermutation( + int64_t dim0, + int64_t dim1, + int64_t rank); + +// Calculates the protomoted shape to which the input shapes should be +// broadcasted for an elementwise operation. The size of the common dimensions +// (2,3,4 for shape1, and 0,1,2 for shape2) must either match, or either one +// of the two be 1. +// Example: +// shape1 = [9, 7, 6, 1, 2] +// shape2 = [6, 5, 2] +// result_shape = [9, 7, 6, 5, 2] +TORCH_API std::vector GetPromotedShape( + c10::ArrayRef shape1_dims, + c10::ArrayRef shape2_dims); + +TORCH_API Shape +GetPromotedBinaryOpShape(const Shape& shape1, const Shape& shape2); + +TORCH_API std::vector StrSplit(std::string_view text, char delim); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/internal_ops/ltc_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/internal_ops/ltc_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..29c0ebbbe8c4471051f45a7a00e3138c2e54c2f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/internal_ops/ltc_ops.h @@ -0,0 +1,54 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +#include + +namespace torch::lazy { + +class TORCH_API OpKindWrapper { + public: + explicit OpKindWrapper(const char* name) : name_(name) {} + + const OpKind& operator*() const { + return get(); + } + + operator OpKind() const { + return get(); + } + + private: + const OpKind& get() const { + c10::call_once(once_, [this]() { op_kind_ = OpKind::Get(name_); }); + return op_kind_; + } + + const char* name_; + mutable OpKind op_kind_; + mutable c10::once_flag once_; +}; + +const OpKindWrapper ltc_all_to_all("lazy_tensors::all_to_all"); +const OpKindWrapper ltc_cast("lazy_tensors::cast"); +const OpKindWrapper ltc_collective_permute("lazy_tensors::collective_permute"); +const OpKindWrapper ltc_cross_replica_sum("lazy_tensors::cross_replica_sum"); +const OpKindWrapper ltc_device_data("lazy_tensors::device_data"); +const OpKindWrapper ltc_get_dimensions_size( + "lazy_tensors::ltc_get_dimensions_size"); +const OpKindWrapper ltc_moving_average("lazy_tensors::moving_average"); +const OpKindWrapper ltc_nms("lazy_tensors::nms"); +const OpKindWrapper ltc_not_supported("lazy_tensors::not_supported"); +const OpKindWrapper ltc_replication_pad("lazy_tensors::replication_pad"); +const OpKindWrapper ltc_replication_pad_backward( + "lazy_tensors::replication_pad_backward"); +const OpKindWrapper ltc_tensor_data("lazy_tensors::tensor_data"); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir.h new file mode 100644 index 0000000000000000000000000000000000000000..3c096234558d1bfbafe7d4cecf9b2d306480f979 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir.h @@ -0,0 +1,294 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +TORCH_DECLARE_bool(ltc_enable_dynamic_shapes); + +namespace torch::lazy { + +static const hash_t kHashSeed(static_cast(0x5a2d296e9)); + +class Node; +struct Output; +struct Value; + +using NodePtr = std::shared_ptr; + +// The Kind of operation a Node can be associated to. +struct TORCH_API OpKind { + OpKind() = default; + explicit OpKind(c10::Symbol op) : op(op) {} + + bool operator==(const OpKind& rhs) const { + return op == rhs.op; + } + bool operator!=(const OpKind& rhs) const { + return !operator==(rhs); + } + bool operator<(const OpKind& rhs) const { + return c10::unique_t(op) < c10::unique_t(rhs.op); + } + + hash_t hash() const; + + std::string ToString() const { + return op.toQualString(); + } + + // Retrieves an existing operation object, or creates a new one. Operations + // that are specific to lazy tensors, should live within the 'lazy_tensors::' + // namespace. + static OpKind Get(const std::string& name); + + c10::Symbol op; +}; + +inline std::ostream& operator<<(std::ostream& stream, const OpKind& op) { + stream << op.ToString(); + return stream; +} + +using OpList = c10::ArrayRef; + +hash_t OperandHashes( + const OpList& operands, + const hash_t& seed, + bool bakeInSizes); +// A node in the graph. Nodes for operations which require extra data to be +// stored for lowering should inherit from this class and add an operation +// specific member there. For example, a constant might create a new +// NodeConstant class (inheriting from Node) with an extra lazy_tensors::Literal +// field, or a tensor value might create a new NodeTensor with a computation +// client data handle in it. +class TORCH_API Node { + public: + static bool enableDynamicShape(); + + // Creates a new node with the given op name. The op is a unique identifier + // for the operation. The num_outputs tells how many outputs a given operation + // generates. + // + // None leaf node's node_hash does not contains shape information always. + // So we pass in the hash value rather than a function. + Node(OpKind op, size_t num_outputs); + + // Construct node with operands and shapes + Node( + OpKind op, + OpList operands, + std::vector&& shapes, + size_t num_outputs = 1); + + // Construct node with operands and no shape + Node(OpKind op, OpList operands, size_t num_outputs = 1); + + // Construct node with shape and no operands + Node(OpKind op, Shape shape, size_t num_outputs = 1); + + virtual ~Node() = default; + + const OpKind& op() const { + return op_; + } + + size_t num_outputs() const { + return num_outputs_; + } + + // Retrieves the full shape of the IR Node. + virtual c10::ArrayRef shapes() const; + + virtual const Shape& shape(size_t output_index = 0) const; + + // Add the shape computed by the shape_fn + void addComputedShape(const std::function& shape_fn); + + // Compute the shape using the provided shape_fn if not previously cached + Shape computeShape(const std::function& shape_fn); + + virtual const std::vector& operands() const; + + virtual const Output& operand(size_t i) const; + + // Gets operand at index i if index is valid, or kNullOutput otherwise. + virtual const Output& nullable_operand(size_t i) const; + + // Returns the hash of the dag used to look up the compiled graph + virtual hash_t hash() const = 0; + + // Returns the hash of the dag used to for shape caching + virtual hash_t shapeHash() const = 0; + + const MetaData& metadata() const { + return metadata_; + } + + UserMetaData* user_metadata() const { + return user_metadata_.get(); + } + + std::shared_ptr SetUserMetadata( + std::shared_ptr user_meta) { + std::swap(user_metadata_, user_meta); + return user_meta; + } + + virtual std::string ToString() const; + + private: + // The ID of the operation captured by this node. + OpKind op_; + size_t num_outputs_ = 1; + + // The IR specific metadata attached to the IR node. + MetaData metadata_; + // The IR framework user can attach a user defined metadata object deriving + // from UserMetaData. + std::shared_ptr user_metadata_; + + protected: + // Adds node's index output number as operand. + void AddOperand(const NodePtr& node, size_t index = 0); + + std::vector shapes_; + // A node holds a real reference to its operands. + std::vector operands_; + // Outputs do not hold references on the nodes, and neither do the uses, since + // otherwise we get into circular reference counting. + std::vector operands_as_outputs_; +}; + +inline std::ostream& operator<<(std::ostream& stream, const Node& node) { + stream << node.ToString(); + return stream; +} + +// Note: Keep this version of NodeCast for smooth PyTorch/XLA migration, and +// clean up once the migration is done. +template +const T* NodeCast(const Node* node, OpKind op) { + if (op != node->op()) { + return nullptr; + } +#ifdef NDEBUG + return static_cast(node); +#else + return &dynamic_cast(*node); +#endif +} + +template +const T* NodeCast(const Node* node) { + if (T::ClassOpKind() != node->op()) { + return nullptr; + } + // TODO: Some IR classes share the same opkind, such as Mean and MeanDim, so + // static_cast is not safe here. Unless we have opkind unique for each class, + // we have to use dynamic_cast here. + return dynamic_cast(node); +} + +// Represents a specific output produced by a node. Since the output of a node +// can be composed by multiple outputs, the node+index coordinates fully qualify +// each single output. +struct TORCH_API Output { + struct Hasher { + size_t operator()(const Output& output) const; + }; + + Output() = default; + explicit Output(const Node* node, size_t index = 0) + : node(node), index(index) {} + + hash_t hash() const; + hash_t shapeHash() const; + + bool operator==(const Output& rhs) const { + return node == rhs.node && index == rhs.index; + } + + // To compare the operands of to-be-constructed node and to-be-reused node + bool operator==(const Value& rhs) const; + + bool operator!=(const Output& rhs) const { + return !operator==(rhs); + } + + const Shape& shape() const { + return node->shape(index); + } + + std::string ToString() const; + + // The node providing the output. + const Node* node{nullptr}; + // The index in the node's output this output refers to. + size_t index{0}; +}; + +inline std::ostream& operator<<(std::ostream& stream, const Output& output) { + stream << output.ToString(); + return stream; +} + +template +using OutputMap = std::unordered_map; + +// Represents an input/operand for a Node object. +struct TORCH_API Value { + Value() = default; + /* implicit */ Value(NodePtr&& node, size_t index = 0) + : node(std::move(node)), index(index) {} + /* implicit */ Value(const NodePtr& node, size_t index = 0) + : node(node), index(index) {} + + hash_t hash() const; + hash_t shapeHash() const; + + operator bool() const { + return node != nullptr; + } + + operator Output() const { + return Output(node.get(), index); + } + + const Shape& shape() const { + return node->shape(index); + } + + Node* operator->() const { + return node.get(); + } + + NodePtr node; + size_t index = 0; +}; + +} // namespace torch::lazy + +namespace c10 { +// Explicit template instantiation to make ArrayRef work +template class at::ArrayRef; +} // namespace c10 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..c1b1c2abc8f342f42fea0e315b2d6762cace2d33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_builder.h @@ -0,0 +1,153 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +// This file is part of the backend interface. So, ops shouldn't be added or +// removed without due process The exception to this being the view ops which +// will be removed soon pending functionalization + +namespace torch::lazy { + +template +NodePtr ReuseNode(Args&&... args) { + if (FLAGS_torch_lazy_reuse_ir) { + return LookupNodeFromTrieCache(std::forward(args)...); + } + return nullptr; +} + +// Caching an IR node into TrieCache +static inline void CacheNode(NodePtr node) { + if (FLAGS_torch_lazy_reuse_ir) { + TrieCache::Get()->Insert(std::move(node)); + } +} + +template +NodePtr MakeNode(Args&&... args) { + return std::make_shared(std::forward(args)...); +} + +// op is passed in for a more efficient node casting, see the implementation of +// NodeCast +template +NodePtr ReuseOrMakeNode(Args&&... args) { + NodePtr node = ReuseNode(std::forward(args)...); + if (!node) { + node = MakeNode(std::forward(args)...); + CacheNode(node); + } + return node; +} + +struct IrBuilder { + virtual NodePtr MakeDeviceData( + const std::shared_ptr& data) const = 0; + virtual NodePtr MakeScalar( + const at::Scalar& value, + const at::ScalarType& type) const = 0; + virtual NodePtr MakeExpand( + const Value& input0, + const std::vector& size, + const bool& is_scalar_expand) const = 0; + virtual NodePtr MakeCast( + const Value& input0, + const at::ScalarType& dtype, + const std::optional& stype = std::nullopt) const = 0; + virtual NodePtr MakeTensorList(const OpList& inputs) const = 0; + virtual NodePtr MakeGeneric( + const OpKind& op, + const OpList& operands, + const Shape& shape, + const size_t& num_outputs = 1, + const hash_t& hash_seed = static_cast(0x5a2d296e9)) const = 0; + + // dynamic ir nodes + virtual NodePtr MakeSizeNode(const Value& input, size_t dim) const = 0; + virtual NodePtr MakeSizeAdd(const Value& a, const Value& b) const = 0; + virtual NodePtr MakeSizeMul(const Value& a, const Value& b) const = 0; + virtual NodePtr MakeSizeDiv(const Value& a, const Value& b) const = 0; + + virtual ~IrBuilder() = default; +}; + +static inline NodePtr MakeDeviceData(const std::shared_ptr& data) { + return getIrBuilder()->MakeDeviceData(data); +} +static inline NodePtr MakeScalar( + const at::Scalar& value, + const at::ScalarType& type) { + return getIrBuilder()->MakeScalar(value, type); +} +static inline NodePtr MakeExpand( + const Value& input0, + const std::vector& size, + const bool& is_scalar_expand) { + return getIrBuilder()->MakeExpand(input0, size, is_scalar_expand); +} +static inline NodePtr MakeCast( + const Value& input0, + const at::ScalarType& dtype, + const std::optional& stype = std::nullopt) { + return getIrBuilder()->MakeCast(input0, dtype, stype); +} +static inline NodePtr MakeTensorList(const OpList& inputs) { + return getIrBuilder()->MakeTensorList(inputs); +} +static inline NodePtr MakeGeneric( + const OpKind& op, + const OpList& operands, + const Shape& shape, + const size_t& num_outputs = 1, + const hash_t& hash_seed = static_cast(0x5a2d296e9)) { + return getIrBuilder()->MakeGeneric( + op, operands, shape, num_outputs, hash_seed); +} + +// dynamic ir nodes +static inline NodePtr MakeSizeNode(const Value& input, size_t dim) { + return getIrBuilder()->MakeSizeNode(input, dim); +} +static inline NodePtr MakeSizeAdd(const Value& a, const Value& b) { + return getIrBuilder()->MakeSizeAdd(a, b); +} +static inline NodePtr MakeSizeMul(const Value& a, const Value& b) { + return getIrBuilder()->MakeSizeAdd(a, b); +} +static inline NodePtr MakeSizeDiv(const Value& a, const Value& b) { + return getIrBuilder()->MakeSizeDiv(a, b); +} + +inline Value GetSymIntValue(const c10::SymInt& a) { + if (auto ma = a.maybe_as_int()) { + return Value(MakeScalar(*ma, at::kLong), 0); + } else { + return Value( + dynamic_cast(a.toSymNodeImplUnowned()) + ->node_, + 0); + } +} + +// TODO: this should return Value +inline std::vector GetSymIntArrayRefValue(c10::SymIntArrayRef arr) { + std::vector r; + for (const auto& a : arr) { + r.emplace_back(a.guard_int(__FILE__, __LINE__)); + } + return r; +} + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_dump_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_dump_util.h new file mode 100644 index 0000000000000000000000000000000000000000..7a27bd8dbec82daf15acb6ac695a8aba86dac08d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_dump_util.h @@ -0,0 +1,35 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::lazy { + +class BackendDevice; + +class TORCH_API DumpUtil { + public: + static std::string ToDot(c10::ArrayRef nodes); + + static std::string PostOrderToDot( + c10::ArrayRef post_order, + c10::ArrayRef roots); + + static std::string ToText(c10::ArrayRef nodes); + + static std::string PostOrderToText( + c10::ArrayRef post_order, + c10::ArrayRef roots); + + static std::string ToBackend( + c10::ArrayRef values, + const BackendDevice& device); +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_metadata.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..8b913e2342810b322e4470fb01332a98a40d5116 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_metadata.h @@ -0,0 +1,56 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +namespace torch::lazy { +struct SourceLocation { + std::string file; + std::string function; + int line = -1; +}; + +TORCH_API void EmitShortFrameInfo( + std::ostream& stream, + const std::vector& frames); + +TORCH_API std::ostream& operator<<( + std::ostream& stream, + const std::vector& frames); + +// The base class for user defined metadata which is possible to attach to IR +// nodes. +struct TORCH_API UserMetaData { + virtual ~UserMetaData() = default; +}; + +struct TORCH_API MetaData { + std::string scope; + std::vector frame_info; +}; + +// TODO(whc) is this going to be used outside of in IR decompositions? +// RAII data structure to be used a stack variable to enter a new IR scope. IR +// scope names will appear in the IR and will help identifying the source of the +// single IR nodes. +struct TORCH_API ScopePusher { + explicit ScopePusher(const std::string& name); + ~ScopePusher(); + ScopePusher(ScopePusher&& other) = delete; + ScopePusher(const ScopePusher&) = delete; + ScopePusher& operator=(const ScopePusher&) = delete; + ScopePusher& operator=(ScopePusher&&) = delete; + + static void ResetScopes(); +}; + +TORCH_API MetaData GetMetaDataIfDebugging(); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_util.h new file mode 100644 index 0000000000000000000000000000000000000000..bb2f2420a1028cd6aa1d5b58e456dcf767904e5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_util.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::lazy { + +class TORCH_API Util { + public: + // Tracks the emission status of the nodes during the post-order generation. + // It helps tracking loops within the computation graphs. + enum EmitStatus { + kNotEmitted, + kEmitting, + kEmitted, + }; + + using EmissionMap = std::unordered_map; + + // Computes the post order from the given node, without using recursion. The + // emission map can be used as saved state, for multiple separate calls to + // this API. The returned post-order can be empty if the node has already been + // emitted inside the emission map. An error is generated if a loop is + // detected. + static std::vector ComputePostOrder( + const Node* node, + EmissionMap* emap); + + static std::vector ComputePostOrder( + c10::ArrayRef nodes, + EmissionMap* emap); + + // Same as above, but computes the post order on the set of nodes specified as + // argument. + static std::vector ComputePostOrder( + c10::ArrayRef nodes); + + // Retrieves the number of nodes within the graph whose sink are passed in the + // nodes argument. + static size_t GetGraphSize(c10::ArrayRef nodes); +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/lazy_graph_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/lazy_graph_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..f7937602a8f3877b698ec06844bb5445d3e580ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/lazy_graph_executor.h @@ -0,0 +1,434 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +class TORCH_API LazyGraphExecutor { + public: + struct DeviceDataInfo : public BackendData::Info { + DeviceDataInfo(int64_t tensor_id, bool read_only) + : tensor_id(tensor_id), read_only(read_only) {} + + int64_t tensor_id = 0; + bool read_only = false; + }; + + // Register a lazy graph executor instance that can be retrieved using Get() + static void Register(LazyGraphExecutor* /*executor*/); + static LazyGraphExecutor* Get(); + + virtual ~LazyGraphExecutor() = default; + + // Override these methods to perform custom tensor registration and + // unregistration Note: It is vital that the parent implementations are also + // called in order for the tensors to show up in the live tensor list + virtual void RegisterTensor(std::shared_ptr data); + virtual void UnregisterTensor(LazyTensor::Data* data); + + // Seed for random generator. + // Override to supply your own DeviceContextArena. + virtual Value GetRngSeed(const BackendDevice& device); + virtual uint64_t GetRunningSeed(const BackendDevice& device); + virtual void SetRngSeed(const BackendDevice& device, uint64_t seed); + + void DeviceBarrier(const BackendDevice& device); + + BackendDataPtr GetDeviceData( + const at::Tensor& tensor, + const BackendDevice& device); + + BackendDataPtr GetDeviceData( + const at::Scalar& value, + at::ScalarType scalar_type, + const BackendDevice& device); + + // Retrieves the set of lazy tensors which are currently live in the system, + // for the given device. If device is nullptr, the live tensors for all + // devices will be returned. Returned tensors are sorted by device as primary + // key, and by unique ID as secondary key. + std::vector GetLiveTensors(const BackendDevice* device); + + // Makes sure that any outstanding IR operation accumulated over live tensors, + // gets turned into device data. If wait is true, the sync operation will be + // run synchronously. The devices argument, if not empty, tells the devices + // which should be partecipating into the replicated computation. + virtual void SyncLiveTensorsGraph( + const BackendDevice* device, + c10::ArrayRef devices, + bool wait); + + // Applies all the pending IR operations queued over the input tensors. All + // the tensors must be on the same device. If wait is true, the sync operation + // will be run synchronously. The devices argument, if not empty, tells the + // devices which should be partecipating into the replicated computation. + void SyncTensorsGraph( + std::vector* tensors, + c10::ArrayRef devices, + bool wait, + bool sync_ltc_data); + + // Marks an execution step, which allows the tensor framework to understand + // the computation boundaries. + // Override to supply your own DeviceContextArena. + virtual void MarkStep(const BackendDevice& device); + + // Waits for all the outstanding operations on all the supplied devices. + // If devices is empty, the wait will happen for all local devices. + void WaitDeviceOps(c10::ArrayRef devices); + + // Retrieves the PyTorch CPU tensors behind the lazy tensors IR operations. + // All the tensors must be on the same device. + std::vector GetTensors(std::vector* tensors); + + size_t IncTrimCounter() const; + + // Dumps the backend specific text of the computation accumulated in the graph + // which is attached the tensors. + std::string DumpBackendComputation(const std::vector& tensors); + + Value GetDeviceDataIrValue( + const at::Scalar& value, + c10::ScalarType type, + const BackendDevice& device); + Value GetIrValueForScalar( + const at::Scalar& value, + c10::ScalarType type, + const BackendDevice& device); + Value GetIrValueForScalar( + const at::Scalar& value, + const BackendDevice& device); + + // TODO: even though this API is currently used **only** in codegen to + // generate real scalar IR values vs scalar tensors, we would like to + // use it in other cases where `GetIrValueForXXXScalar` is used, as well + // In order to do that, we need to untangle the cases where we don't need + // `expand` and where we don't expect a scalar tensor + Value GetIrValueForScalarFromCodegen( + const at::Scalar& value, + const BackendDevice& device); + Value GetIrValueForExpandedScalar( + const at::Scalar& value, + const Shape& shape, + const BackendDevice& device); + + struct CachedComputation { + explicit CachedComputation(ComputationPtr computation) + : computation(std::move(computation)) {} + + ComputationPtr computation; + }; + + using ComputationCache = Cache; + + ComputationCache* GetComputationCache(); + + hash_t GetGraphHash(const std::vector& tensors); + + // Clear the computation cache. + void ClearComputationCache(); + // Remove a specific computation cache entry from its hash. + void RemoveFromComputationCache(const hash_t& hash); + + protected: + // TODO(alanwaketan): Revisit if all of them need to be accessible to + // derived classes. + + struct SyncTensorsConfig { + // Whether we want to force data on the target tensors (hence trimming + // the IR graph above them). + bool force_ltc_data = true; + // Whether when setting the data, the other properties of the tensor + // state should be reset. + bool sync_ltc_data = true; + }; + + struct SyncTensorCollection { + SyncTensorCollection() : hash(0) {} + + SyncTensorsConfig config; + std::vector indices; + hash_t hash; + std::vector unlocker; + BackendDevice device; + }; + + struct PostOrderData { + std::vector post_order; + Util::EmissionMap emission_map; + std::vector parameters_data; + std::vector parameter_sequence; + }; + + // Locking: + // We perform two kinds of operations of tensors, synchronous and + // asynchronous. The ApplyPendingGraph() are synchronous, as we need the + // device data result immediately. Before the synchronous operations can + // start, they need to wait that the pending asynchronous operations have + // completed. Synchronous operations do not hold device locks, since they are + // strictly sequential, dictated by the PyTorch execution order. The + // SyncTensorsGraph() is asynchronous, and returns immediately after having + // scheduled the asynchronous operation. While executing, the asynchronous + // operations will hold locks on all the participating devices (in most common + // cases there will be only one device). + // Since asynchronous operations capture device locks, only one asynchronous + // operation can execute at the same time, on a given device. Tensor + // operations which send data to device do not need to hold any device locks + // while doing so. Only operations which _use_ device data (computations, and + // transfer from server) need to wait for asynchronous operations to complete + // (barrier). + + class DeviceLocker { + public: + explicit DeviceLocker(BackendDevice device) : device_(std::move(device)) {} + + const BackendDevice& device() const { + return device_; + } + + void Lock(); + void Unlock(std::exception_ptr exptr); + void Barrier(); + + private: + void CheckResetException(); + + BackendDevice device_; + std::mutex mutex_; + std::condition_variable cv_; + bool locked_ = false; + std::exception_ptr exptr_; + }; + + class DeviceLockerArena { + public: + static DeviceLockerArena* Get(); + + std::shared_ptr GetLocker(const BackendDevice& device); + + void DeviceBarrier(const BackendDevice& device); + + // Use a set to impose an order on the device locking sequence (ABBA + // prevention). + std::vector LockDevices( + const std::set& devices); + + private: + ExceptionCleanup LockDevice(const BackendDevice& device); + + std::mutex mutex_; + std::map> lockers_; + }; + + class DataCacheArena { + public: + static DataCacheArena* Get(); + + BackendDataPtr GetDeviceData( + const at::Tensor& tensor, + const BackendDevice& device); + + BackendDataPtr GetDeviceData( + const at::Scalar& value, + at::ScalarType scalar_type, + const BackendDevice& device); + + private: + struct TensorHasher { + size_t operator()(const at::Tensor& tensor) const; + }; + struct TensorComparer { + bool operator()(const at::Tensor& tensor1, const at::Tensor& tensor2) + const; + }; + + explicit DataCacheArena(size_t max_cache_size); + + using DataCache = + Cache; + + DataCache* GetDataCache(const BackendDevice& device); + + size_t max_cache_size_ = 0; + std::mutex mutex_; + std::map> device_caches_; + }; + + // The DeviceContextArena holds per device live information and statistics, + // among which the lazy tensors which are currently alive in the system. This + // is used to create computation "barriers" in order to flush pending + // operations and ensure the same computations are created during the training + // loops. + // TODO(alanwaketan): Add a registry such that we don't need to make all + // related methods virtual. + class DeviceContextArena { + protected: + struct DeviceContext { + std::mutex lock; + std::map> tensors_data; + uint64_t seed = 101; + uint64_t running_seed = 101; + Value seed_ir_value; + }; + + public: + static DeviceContextArena* Get(); + virtual ~DeviceContextArena() = default; + + void RegisterTensor(std::shared_ptr data); + void UnregisterTensor(LazyTensor::Data* data); + + std::vector GetLiveTensors(const BackendDevice* device); + + // Overriding it allow derived class to use their own IRs for Value. + virtual Value GetRngSeed(const BackendDevice& device); + uint64_t GetRunningSeed(const BackendDevice& device); + void SetRngSeed(const BackendDevice& device, uint64_t seed); + + void MarkStep(const BackendDevice& device); + + std::vector GetActiveDevices(); + + protected: + DeviceContext* GetDeviceContext(const BackendDevice& device); + + void ForAllDeviceContexts( + const std::function& fn, + const BackendDevice* device); + + // Overriding it allow derived class to use their own conversions. + virtual Value IrValueFromScalar( + const at::Scalar& value, + at::ScalarType scalar_type, + const BackendDevice& device); + + private: + std::vector GetAllDeviceContexts(); + + std::mutex lock_; + std::map device_contexts_; + }; + + struct Async { + Async( + SyncTensorCollection* coll, + std::vector parameters_data, + std::vector tensors_data, + ComputationCache::TypePtr cached_computation); + virtual ~Async() = default; + + void Wait(); + + MultiWait mwait; + std::vector indices; + std::vector unlocker; + std::vector parameters_data; + BackendDevice device; + ComputationCache::TypePtr cached_computation; + std::vector tensors_data; + }; + + void ResetTrimCounter() const; + + // Waits for this SyncTensorCollection's device barrier and acquire the lock. + virtual void TensorCollectionBarrier(SyncTensorCollection* coll); + + // One can override to insert your own profiler. + virtual PostOrderData RunPostOrder( + const std::vector& ir_values, + SyncTensorCollection* coll); + + private: + struct CompilationResult { + BackendDevice device; + size_t emitted_nodes = 0; + ComputationPtr computation; + std::vector parameters_data; + }; + + virtual bool ShouldSyncTensor(const LazyTensorPtr& tensor) const; + + SyncTensorCollection CollectSyncTensors( + const std::vector& tensors, + const SyncTensorsConfig& config); + + std::vector CollectRoots( + const std::vector& tensors, + c10::ArrayRef indices); + + std::vector SetTensorData( + std::vector* tensors, + const SyncTensorsConfig& config, + c10::ArrayRef indices, + const std::vector& tensor_data_vec); + + void ExtractIRAndPrepareTensorData( + std::vector* tensors, + const SyncTensorsConfig& config, + c10::ArrayRef indices, + std::vector& ir_values, + std::vector& tensor_data_vec); + + std::shared_ptr TryRunCachedSync( + std::vector* tensors, + SyncTensorCollection* coll, + PostOrderData* po_data, + const std::vector& tensor_data_vec); + + CompilationResult Compile( + const std::vector& tensors, + c10::ArrayRef devices, + const SyncTensorCollection& coll, + PostOrderData* po_data, + const std::vector& ir_values); + + ComputationCache::TypePtr LookupCachedCompile(const hash_t& hash); + + std::shared_ptr SyncTensorsGraphInternal( + std::vector* tensors, + c10::ArrayRef devices, + const SyncTensorsConfig& config); + + // Schedules the execution of a sync tensors operation in background. The + // asynchronous operation will hold the device locks by capturing the ones + // present within the coll structure. + std::shared_ptr ScheduleSyncTensorsGraph( + SyncTensorCollection* coll, + std::vector parameters_data, + std::vector tensors_data, + ComputationCache::TypePtr cached_computation); + + std::shared_ptr ScheduleSyncTensorsGraph( + std::vector* tensors, + SyncTensorCollection* coll, + std::vector parameters_data, + ComputationCache::TypePtr cached_computation, + const std::vector& tensor_data_vec); + + std::vector GetTensorsFused(std::vector* tensors); + + std::vector FetchTensors( + std::vector* tensors, + c10::ArrayRef tensors_data, + const std::vector* indices); + + // Gathers the device data for all the input tensors, after an + // asynchronous operation. + std::vector GatherTensorsData( + const std::vector& tensors, + c10::ArrayRef indices, + c10::ArrayRef tensors_data); +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/metrics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/metrics.h new file mode 100644 index 0000000000000000000000000000000000000000..a175d9358ce87beb902226c1700403b5c0f70bc5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/metrics.h @@ -0,0 +1,293 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** + * This file is adapted from PyTorch/XLA + * https://github.com/pytorch/xla/blob/e0e5f937a0ba8d904f9608137dc8c51ba439df2d/third_party/xla_client/metrics.h + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace torch::lazy { + +struct TORCH_API Sample { + Sample() = default; + Sample(int64_t timestamp_ns, double value) + : timestamp_ns(timestamp_ns), value(value) {} + + int64_t timestamp_ns = 0; + double value = 0; +}; + +using MetricReprFn = std::function; + +// Class used to collect time-stamped numeric samples. The samples are stored in +// a circular buffer whose size can be configured at constructor time. +class TORCH_API MetricData { + public: + // Creates a new MetricData object with the internal circular buffer storing + // max_samples samples. The repr_fn argument allow to specify a function which + // pretty-prints a sample value. + MetricData(MetricReprFn repr_fn, size_t max_samples); + + // Returns the total values of all the samples being posted to this metric. + double Accumulator() const; + + size_t TotalSamples() const; + + void AddSample(int64_t timestamp_ns, double value); + + // Returns a vector with all the current samples, from the oldest to the + // newer. If accumulator is not nullptr, it will receive the current value of + // the metrics' accumulator (the sum of all posted values). If total_samples + // is not nullptr, it will receive the count of the posted values. + std::vector Samples(double* accumulator, size_t* total_samples) const; + + std::string Repr(double value) const { + return repr_fn_(value); + } + + void Reset(); + + bool IsValid() const { + return TotalSamples() > 0; + } + + private: + mutable std::mutex lock_; + MetricReprFn repr_fn_; + size_t count_ = 0; + std::vector samples_; + double accumulator_ = 0.0; +}; + +// Counters are a very lightweight form of metrics which do not need to track +// sample time. +class TORCH_API CounterData { + public: + CounterData() : value_(0) {} + + void AddValue(int64_t value) { + value_ += value; + } + + int64_t Value() const { + return value_; + } + + void Reset() { + value_ = 0; + } + + bool IsValid() const { + return value_ > 0; + } + + private: + std::atomic value_; +}; + +class TORCH_API MetricsArena { + public: + static MetricsArena* Get(); + + void ResetCounters(); + void ResetMetrics(); + + // Registers a new metric in the global arena. + void RegisterMetric( + const std::string& name, + MetricReprFn repr_fn, + size_t max_samples, + std::shared_ptr* data); + + void RegisterCounter( + const std::string& name, + std::shared_ptr* data); + + void ForEachMetric( + const std::function& metric_func); + + void ForEachCounter( + const std::function& + counter_func); + + std::vector GetMetricNames(); + + MetricData* GetMetric(const std::string& name); + + std::vector GetCounterNames(); + + CounterData* GetCounter(const std::string& name); + + private: + std::mutex lock_; + std::map> metrics_; + std::map> counters_; +}; + +// Emits the value in a to_string() conversion. +TORCH_API std::string MetricFnValue(double value); +// Emits the value in a humanized bytes representation. +TORCH_API std::string MetricFnBytes(double value); +// Emits the value in a humanized time representation. The value is expressed in +// nanoseconds EPOCH time. +TORCH_API std::string MetricFnTime(double value); + +// The typical use of a Metric is one in which it gets created either in a +// global scope context: +// static Metric* metric = new Metric("RpcCount"); +// Or within a function scope: +// void MyFunction(...) { +// static Metric* metric = new Metric("RpcCount"); +// ... +// metric->AddSample(ts_nanos, some_value); +// } +class TORCH_API Metric { + public: + explicit Metric( + std::string name, + MetricReprFn repr_fn = MetricFnValue, + size_t max_samples = 0); + + const std::string& Name() const { + return name_; + } + + double Accumulator() const; + + void AddSample(int64_t timestamp_ns, double value); + + void AddSample(double value); + + std::vector Samples(double* accumulator, size_t* total_samples) const; + + std::string Repr(double value) const; + + private: + MetricData* GetData() const; + + std::string name_; + MetricReprFn repr_fn_; + size_t max_samples_; + mutable std::shared_ptr data_ptr_; + mutable std::atomic data_; +}; + +// A Counter is a lightweight form of metric which tracks an integer value which +// can increase or decrease. +// A typical use is as: +// static Counter* counter = new Counter("MyCounter"); +// ... +// counter->AddValue(+1); +class TORCH_API Counter { + public: + explicit Counter(std::string name); + + void AddValue(int64_t value) { + GetData()->AddValue(value); + } + + int64_t Value() const { + return GetData()->Value(); + } + + private: + CounterData* GetData() const; + + std::string name_; + mutable std::shared_ptr data_ptr_; + mutable std::atomic data_; +}; + +#define TORCH_LAZY_COUNTER(name, value) \ + do { \ + static ::torch::lazy::Counter* __counter = \ + new ::torch::lazy::Counter(name); \ + __counter->AddValue(value); \ + } while (0) + +#define TORCH_LAZY_FN_COUNTER(ns) TORCH_LAZY_COUNTER(c10::str(ns, __func__), 1) + +#define TORCH_LAZY_VALUE_METRIC(name, value) \ + do { \ + static ::torch::lazy::Metric* __metric = \ + new ::torch::lazy::Metric(name, torch::lazy::MetricFnValue); \ + __metric->AddSample(value); \ + } while (0) + +// Creates a report with the current metrics statistics. +TORCH_API std::string CreateMetricReport(); + +// Creates a report with the selected metrics statistics. +TORCH_API std::string CreateMetricReport( + const std::vector& counter_names, + const std::vector& metric_names); + +// Returns the currently registered metric names. Note that the list can grow +// since metrics are usually function initialized (they are static function +// variables). +TORCH_API std::vector GetMetricNames(); + +// Retrieves the metric data of a given metric, or nullptr if such metric does +// not exist. +TORCH_API MetricData* GetMetric(const std::string& name); + +// Returns the currently registered counter names. Note that the list can grow +// since counters are usually function initialized (they are static function +// variables). +TORCH_API std::vector GetCounterNames(); + +// Retrieves the counter data of a given counter, or nullptr if such counter +// does not exist. +TORCH_API CounterData* GetCounter(const std::string& name); + +// Retrieves the current EPOCH time in nanoseconds. +TORCH_API int64_t NowNs(); + +// Scope based utility class TORCH_API to measure the time the code takes within +// a given C++ scope. +class TORCH_API TimedSection { + public: + explicit TimedSection(Metric* metric) : metric_(metric), start_(NowNs()) {} + + TimedSection(TimedSection&& other) = delete; + TimedSection(const TimedSection&) = delete; + TimedSection& operator=(const TimedSection&) = delete; + TimedSection& operator=(TimedSection&&) = delete; + ~TimedSection() { + int64_t now = NowNs(); + metric_->AddSample(now, static_cast(now - start_)); + } + + double Elapsed() const { + return 1e-9 * static_cast(NowNs() - start_); + } + + private: + Metric* metric_; + int64_t start_; +}; + +#define TORCH_LAZY_TIMED(name) \ + static torch::lazy::Metric* timed_metric = \ + new torch::lazy::Metric(name, torch::lazy::MetricFnTime); \ + torch::lazy::TimedSection timed_section(timed_metric) + +#define TORCH_LAZY_FN_COUNTER_TIMED_TRACING(ns) \ + TORCH_LAZY_FN_COUNTER(ns); \ + TORCH_LAZY_TIMED("LazyTracing") + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/multi_wait.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/multi_wait.h new file mode 100644 index 0000000000000000000000000000000000000000..c808d3cc6dc6221ea61fee86f86e114e5fdee08c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/multi_wait.h @@ -0,0 +1,65 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** + * This file is adapted from PyTorch/XLA + * https://github.com/pytorch/xla/blob/e0e5f937a0ba8d904f9608137dc8c51ba439df2d/third_party/xla_client/multi_wait.h + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include + +namespace torch::lazy { + +// Support waiting for a number of tasks to complete. +class TORCH_API MultiWait { + public: + explicit MultiWait(size_t count) : count_(count) {} + + // Signal the completion of a single task. + void Done(); + + // Waits until at least count (passed as constructor value) completions + // happened. + void Wait(); + + // Same as above, but waits up to wait_seconds. + void Wait(double wait_seconds); + + // Resets the threshold counter for the MultiWait object. The completed count + // is also reset to zero. + void Reset(size_t count); + + // Creates a completer functor which signals the mult wait object once func + // has completed. Handles exceptions by signaling the multi wait with the + // proper status value. This API returns a function which captures a MultiWait + // reference, so care must be taken such that the reference remains valid for + // the whole lifetime of the returned function. + std::function Completer(std::function func); + + // Similar as the above API, but with explicit capture of the MultiWait shared + // pointer. + static std::function Completer( + std::shared_ptr mwait, + std::function func); + + private: + void Complete(const std::function& func); + + std::mutex mutex_; + std::condition_variable cv_; + size_t count_ = 0; + size_t completed_count_ = 0; + std::exception_ptr exptr_; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ops/arithmetic_ir_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ops/arithmetic_ir_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ff4fe2341d2bd27f1e13d716782ddaced8cb2b79 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ops/arithmetic_ir_ops.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::lazy { + +TORCH_API NodePtr operator+(const Value& node1, const Value& node2); +TORCH_API NodePtr operator-(const Value& node1, const Value& node2); +TORCH_API NodePtr operator*(const Value& node1, const Value& node2); +TORCH_API NodePtr operator/(const Value& node1, const Value& node2); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ops/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ops/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f900b65fa2280f3cf08fc43942ba815ee3e6c45f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ops/utils.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +#include +#include + +namespace torch::lazy { + +TORCH_API bool StrideIsSupported(c10::ArrayRef stride); + +TORCH_API std::vector GetArrayStridePermutation( + c10::ArrayRef stride); + +TORCH_API Shape MakeDiagonalShape( + const Shape& shape, + int64_t offset, + int64_t dim1, + int64_t dim2); + +TORCH_API Shape +MakePermuteShape(const Shape& source_shape, c10::ArrayRef permutation); + +TORCH_API Shape MakeSelectShape( + const Shape& shape, + int64_t dim, + int64_t start, + int64_t end, + int64_t stride); + +TORCH_API int64_t GetStride(int64_t start, int64_t end, int64_t stride); + +TORCH_API std::vector BuildSqueezedDimensions( + c10::ArrayRef dimensions, + int64_t squeeze_dim); + +TORCH_API std::vector BuildUnsqueezedDimensions( + c10::ArrayRef dimensions, + int64_t squeeze_dim); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/permutation_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/permutation_util.h new file mode 100644 index 0000000000000000000000000000000000000000..6a3d5aaa7946fb920ac8d63c3b7524925a4b7b3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/permutation_util.h @@ -0,0 +1,46 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace torch::lazy { + +TORCH_API std::vector InversePermutation( + c10::ArrayRef input_permutation); + +TORCH_API bool IsPermutation(c10::ArrayRef permutation); + +// Gathers the input using the order specified by the permutation. For each i, +// output[i] = dimensions[permutation[i]]. The given permutation must be the +// same size as the input. +template +std::vector PermuteDimensions( + c10::ArrayRef permutation, + const Container& dimensions) { + using T = typename Container::value_type; + TORCH_CHECK( + dimensions.size() == permutation.size(), + "Invalid permutation specified. dimensions.size() != permutation.size() (", + dimensions.size(), + " vs. ", + permutation.size(), + ")"); + TORCH_CHECK( + IsPermutation(permutation), + "Invalid permutation specified. Permutation is not permutation"); + std::vector output(dimensions.size()); + for (const auto i : c10::irange(permutation.size())) { + output[i] = dimensions[permutation[i]]; + } + return output; +} + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/shape.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/shape.h new file mode 100644 index 0000000000000000000000000000000000000000..7d4fdb375aa018a79d2df149297705c7cc4bc3f3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/shape.h @@ -0,0 +1,83 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +TORCH_DECLARE_bool(ltc_enable_symbolic_shapes); + +namespace torch::lazy { + +class TORCH_API Shape { + public: + Shape() = default; + + Shape( + at::ScalarType scalar_type, + c10::ArrayRef sizes, + std::optional> is_symbolic = std::nullopt); + + std::string to_string() const; + + c10::ScalarType scalar_type() const { + return scalar_type_; + } + void set_scalar_type(at::ScalarType value) { + scalar_type_ = value; + } + + int64_t dim() const { + return static_cast(sizes_.size()); + } + c10::ArrayRef sizes() const { + return sizes_; + } + int64_t size(int64_t dim) const { + return sizes_.at(dim); + } + void set_size(int64_t dim, int64_t size) { + sizes_.at(dim) = size; + } + + const std::optional>& is_symbolic() const { + return is_symbolic_; + } + + // Makes a copy with symbolic dims applied + Shape with_symbolic_dims( + std::optional> symbolic_dims) const; + + size_t numel() const; + hash_t hash(bool bakeInSizes) const; + + bool operator==(const Shape& other) const; + + private: + c10::ScalarType scalar_type_{c10::ScalarType::Undefined}; + + // Sizes are the upper bound sizes for a tensor, used by XLA. + std::vector sizes_; + // Stores which dimensions are symbolic + // If nullopt, either it hasn't been initialized or the symbolic + // dimensions are not calculable + std::optional> is_symbolic_ = std::nullopt; +}; + +TORCH_API std::ostream& operator<<(std::ostream& out, const Shape& shape); + +TORCH_API bool symbolicShapeEnabled(); +// Calculate and applies symbolic shapes onto the +// Shape objects passed to result_shapes +TORCH_API void applySymbolicShapesOnLT( + const char* schema_str, + std::vector args, + std::vector& result_shapes); +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/shape_inference.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/shape_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..9d1e9a1cd4c0087e9361f29e5c5319586cb05a3f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/shape_inference.h @@ -0,0 +1,127 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { +// Turn clang-format off, as we rely on the whole signature being on one line +// for codegen. +// clang-format off +TORCH_API std::vector compute_shape__adaptive_avg_pool2d(const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API std::vector compute_shape__adaptive_avg_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self); +TORCH_API std::vector compute_shape__adaptive_avg_pool3d(const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API std::vector compute_shape__adaptive_avg_pool3d_backward(const at::Tensor & grad_output, const at::Tensor & self); +TORCH_API std::vector compute_shape_abs(const at::Tensor & self); +TORCH_API std::vector compute_shape_arange_out(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::Tensor & out); +TORCH_API std::vector compute_shape_bernoulli(const at::Tensor & self, ::std::optional generator); +TORCH_API std::vector compute_shape_bernoulli(const at::Tensor & self, double p, ::std::optional generator); +TORCH_API std::vector compute_shape_binary_cross_entropy(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction); +TORCH_API std::vector compute_shape_binary_cross_entropy_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction); +TORCH_API std::vector compute_shape_cat(at::TensorList tensors, int64_t dim); +TORCH_API std::vector compute_shape_cholesky(const at::Tensor & self, bool upper); +TORCH_API std::vector compute_shape_clamp_min(const at::Tensor & self, const at::Scalar & min); +TORCH_API std::vector compute_shape_clone(const at::Tensor & self, ::std::optional memory_format); +TORCH_API std::vector compute_shape_constant_pad_nd(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value); +TORCH_API std::vector compute_shape_convolution(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups); +TORCH_API std::vector compute_shape_convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask); +TORCH_API std::vector compute_shape_embedding(const at::Tensor & weight, const at::Tensor & indices, int64_t padding_idx, bool scale_grad_by_freq, bool sparse); +TORCH_API std::vector compute_shape_embedding_dense_backward(const at::Tensor & grad_output, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +TORCH_API std::vector compute_shape_expand(const at::Tensor & self, at::IntArrayRef size, bool implicit); +TORCH_API std::vector compute_shape_expand(const at::Tensor & self, c10::SymIntArrayRef size, bool implicit); +TORCH_API std::vector compute_shape_flip(const at::Tensor & self, at::IntArrayRef dims); +TORCH_API std::vector compute_shape_glu_backward(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim); +TORCH_API std::vector compute_shape_glu_jvp(const at::Tensor & glu, const at::Tensor & x, const at::Tensor & dx, int64_t dim); +TORCH_API std::vector compute_shape_grid_sampler_2d(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners); +TORCH_API std::vector compute_shape_grid_sampler_2d_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array output_mask); +TORCH_API std::vector compute_shape_index_select(const at::Tensor & self, int64_t dim, const at::Tensor & index); +TORCH_API std::vector compute_shape_inverse(const at::Tensor & self); +TORCH_API std::vector compute_shape_isnan(const at::Tensor & self); +TORCH_API std::vector compute_shape_log_sigmoid_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & buffer); +TORCH_API std::vector compute_shape_log_sigmoid_forward(const at::Tensor & self); +TORCH_API std::vector compute_shape_logdet(const at::Tensor & self); +TORCH_API std::vector compute_shape_logical_and(const at::Tensor & self, const at::Tensor & other); +TORCH_API std::vector compute_shape_logical_not(const at::Tensor & self); +TORCH_API std::vector compute_shape_logical_or(const at::Tensor & self, const at::Tensor & other); +TORCH_API std::vector compute_shape_logical_xor(const at::Tensor & self, const at::Tensor & other); +TORCH_API std::vector compute_shape_masked_fill(const at::Tensor & self, const at::Tensor & mask, const at::Scalar & value); +TORCH_API std::vector compute_shape_masked_fill(const at::Tensor & self, const at::Tensor & mask, const at::Tensor & value); +TORCH_API std::vector compute_shape_max(const at::Tensor & self); +TORCH_API std::vector compute_shape_mean(const at::Tensor & self, ::std::optional dtype); +TORCH_API std::vector compute_shape_min(const at::Tensor & self); +TORCH_API std::vector compute_shape_mv(const at::Tensor & self, const at::Tensor & vec); +TORCH_API std::vector compute_shape_native_batch_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps); +TORCH_API std::vector compute_shape_native_batch_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & running_mean, const ::std::optional & running_var, const ::std::optional & save_mean, const ::std::optional & save_invstd, bool train, double eps, ::std::array output_mask); +TORCH_API std::vector compute_shape_native_dropout(const at::Tensor & input, double p, ::std::optional train); +TORCH_API std::vector compute_shape_native_dropout_backward(const at::Tensor & grad_output, const at::Tensor & mask, double scale); +TORCH_API std::vector compute_shape_native_layer_norm(const at::Tensor & input, at::IntArrayRef normalized_shape, const ::std::optional & weight, const ::std::optional & bias, double eps); +TORCH_API std::vector compute_shape_native_layer_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const ::std::optional & weight, const ::std::optional & bias, ::std::array output_mask); +TORCH_API std::vector compute_shape_new_empty_strided(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +TORCH_API std::vector compute_shape_nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight); +TORCH_API std::vector compute_shape_nll_loss2d_forward(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index); +TORCH_API std::vector compute_shape_nonzero(const at::Tensor & self); +TORCH_API std::vector compute_shape_normal_functional(const at::Tensor & self, double mean, double std, ::std::optional generator); +TORCH_API std::vector compute_shape_random(const at::Tensor & self, ::std::optional generator); +TORCH_API std::vector compute_shape_random(const at::Tensor & self, int64_t to, ::std::optional generator); +TORCH_API std::vector compute_shape_random(const at::Tensor & self, int64_t from, ::std::optional to, ::std::optional generator); +TORCH_API std::vector compute_shape_relu(const at::Tensor & self); +TORCH_API std::vector compute_shape_repeat(const at::Tensor & self, at::IntArrayRef repeats); +TORCH_API std::vector compute_shape_slogdet(const at::Tensor & self); +TORCH_API std::vector compute_shape_smooth_l1_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta); +TORCH_API std::vector compute_shape_sort(const at::Tensor & self, int64_t dim, bool descending); +TORCH_API std::vector compute_shape_stack(at::TensorList tensors, int64_t dim); +TORCH_API std::vector compute_shape_std(const at::Tensor & self, bool unbiased); +TORCH_API std::vector compute_shape_std(const at::Tensor & self, at::OptionalIntArrayRef dim, bool unbiased, bool keepdim); +TORCH_API std::vector compute_shape_std(const at::Tensor & self, at::OptionalIntArrayRef dim, const ::std::optional & correction, bool keepdim); +TORCH_API std::vector compute_shape_sum(const at::Tensor & self, ::std::optional dtype); +TORCH_API std::vector compute_shape__to_copy(const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, bool non_blocking, ::std::optional memory_format); +TORCH_API std::vector compute_shape_take(const at::Tensor & self, const at::Tensor & index); +TORCH_API std::vector compute_shape_trace(const at::Tensor & self); +TORCH_API std::vector compute_shape_zero(const at::Tensor & self); +TORCH_API std::vector compute_shape_narrow_copy_symint(const at::Tensor & self, int64_t dim, int64_t start, c10::SymInt length); +TORCH_API std::vector compute_shape_hardswish(const at::Tensor & self); +TORCH_API std::vector compute_shape_hardswish_backward(const at::Tensor & grad_output, const at::Tensor & self); +TORCH_API std::vector compute_shape_selu(const at::Tensor & self); +TORCH_API std::vector compute_shape_uniform(const at::Tensor & self, double from, double to, ::std::optional generator); + +// Non-Native ops +TORCH_API std::vector compute_shape_scalar(const at::Scalar& value, const at::ScalarType& type); +TORCH_API std::vector compute_shape_expand(const Output& input0, const std::vector& size, const bool& is_scalar_expand); +TORCH_API std::vector compute_shape_view(const Output& input0, const std::vector& output_sizes); +TORCH_API std::vector compute_shape_cast(const Output& input0, const at::ScalarType& dtype, const ::std::optional& stype); + +// View Ops +// (Now that functionalization pass is used, we should kill these in a later PR) +TORCH_API std::vector compute_shape_as_strided_view_update(const Output& target, const Output& input, const std::vector& size, const std::vector& stride, const int64_t& storage_offset); +TORCH_API std::vector compute_shape_as_strided(const Output& input, const std::vector& size, const std::vector& stride, const int64_t& storage_offset); +TORCH_API std::vector compute_shape_diagonal_view_update(const Output& target, const Output& input, const int64_t& offset, const int64_t& dim1, const int64_t& dim2); +TORCH_API std::vector compute_shape_diagonal(const Output& input, const int64_t& offset, const int64_t& dim1, const int64_t& dim2); +TORCH_API std::vector compute_shape_narrow_view_update(const Output& input, const Output& source, const std::vector& base_indices); +TORCH_API std::vector compute_shape_narrow(const Output& input, const std::vector& base_indices, const std::vector& sizes); +TORCH_API std::vector compute_shape_permute(const Output& input, const std::vector& dims); +TORCH_API std::vector compute_shape_resize(const Output& input, const std::vector& size); +TORCH_API std::vector compute_shape_select_view_update(const Output& target, const Output& source, const int64_t& dim, const int64_t& start, const int64_t& end, const int64_t& stride); +TORCH_API std::vector compute_shape_select(const Output& input, const int64_t& dim, const int64_t& start, const int64_t& end, const int64_t& stride); +TORCH_API std::vector compute_shape_squeeze(const Output& input, const int& dim); +TORCH_API std::vector compute_shape_unsqueeze(const Output& input, const int& dim); + +TORCH_API std::vector compute_shape_select_scatter(const at::Tensor & self, const at::Tensor & src, int64_t dim, int64_t index); +TORCH_API std::vector compute_shape_diagonal_scatter(const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2); +TORCH_API std::vector compute_shape_slice_scatter_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step); +TORCH_API std::vector compute_shape_as_strided_scatter_symint(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset); +// clang-format on +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..16a363079fa8fe784f82d8b0dc391264e6edd76f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor.h @@ -0,0 +1,270 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +class TORCH_API SymNodeImpl : public c10::SymNodeImpl { + public: + SymNodeImpl(NodePtr ptr) : node_(std::move(ptr)) {} + NodePtr node_; +}; + +class LazyTensor; +using LazyTensorPtr = c10::intrusive_ptr; + +class TORCH_API LazyTensor : public c10::intrusive_ptr_target { + public: + // This is the core lazy tensor data structure where all the tensor data is + // held. The lazy tensor is nothing more than a shared pointer to a Data + // object. + struct Data { + Data(BackendDataPtr handle, BackendDevice device) + : handle(std::move(handle)), + device(std::move(device)), + unique_id(GetNextTensorId()) {} + Data(Value ir_value, BackendDevice device) + : ir_value(std::move(ir_value)), + device(std::move(device)), + unique_id(GetNextTensorId()) {} + Data(at::Tensor tensor_data, BackendDevice device) + : tensor_data(std::move(tensor_data)), + device(std::move(device)), + unique_id(GetNextTensorId()) {} + // TODO(alanwaketan): Remove this ctor. This is a + // temporary ctor to ease XLA LTC migration. It depends on + // XLA's Functionalization integration. + Data(BackendDevice device) + : device(std::move(device)), unique_id(GetNextTensorId()) {} + + Data(Data&& other) = delete; + Data(const Data&) = delete; + Data& operator=(const Data&) = delete; + Data& operator=(Data&&) = delete; + virtual ~Data(); + + BackendDataPtr handle; + Value ir_value; + std::optional tensor_data; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const BackendDevice device; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const int64_t unique_id = 0; + size_t generation = 1; + }; + + static LazyTensorPtr Create( + const at::Tensor& tensor, + const BackendDevice& device); + static LazyTensorPtr Create(Value ir_value, const BackendDevice& device); + static LazyTensorPtr Create(const BackendDataPtr& handle); + static LazyTensorPtr Create(std::shared_ptr data); + + // The default ctor previously created a null LazyTensor (one with no 'data' + // obj). Creating a null LazyTensor is no longer possible, since the same can + // be achieved by creating a null LazyTensorPtr and it is way too confusing to + // have to check both lazy_tensor_ptr && *lazy_tensor_ptr, so everywhere that + // used to rely on a LazyTensor obj with a null Data can now rely on a null + // LazyTensorPtr instead. + LazyTensor() = delete; + LazyTensor(const LazyTensor&) = default; + LazyTensor(LazyTensor&&) noexcept = default; + LazyTensor& operator=(const LazyTensor&) = default; + LazyTensor& operator=(LazyTensor&&) noexcept = default; + + ~LazyTensor() override = default; + + size_t generation() const { + return data()->generation; + } + + // Override it to use your own Shape. + virtual int64_t size(int64_t dim) const; + + // Override it to use your own graph executor. + virtual at::Tensor ToTensor(bool detached); + + void ShallowCopyTo(const LazyTensorPtr& dest) const; + + // Assigns the tensor value to the lazy tensor. + void SetTensor(at::Tensor tensor); + + void UpdateFromTensor(const at::Tensor& tensor, bool sync); + void UpdateFromTensorOut(const at::Tensor& tensor); + void UpdateFromTensorOut(const LazyTensorPtr& tensor); + + const std::shared_ptr& data() const; + + // Override it to use your own type conversion. + virtual at::ScalarType dtype() const; + + MaybeRef shape() const; + + const BackendDevice& GetDevice() const; + int64_t GetUniqueId() const; + + // Fetches the data behind the tensor. If the tensor has a graph defining + // its current value, executes the graph and fetches the data result. + BackendDataPtr GetDataHandle(); + + // Fetches the current value of the data, which can be missing (nullptr) + // in case the tensor has a graph defining its current value, + BackendDataPtr CurrentDataHandle() const; + + void SetDataHandle(BackendDataPtr handle); + void SetDataHandle(BackendDataPtr handle, bool sync); + + // Retrieves the current IR Node, or nullptr in case no active IR Node is + // available. + Value CurrentIrValue() const; + + // Retrieves the IR Node representing this LazyTensor. One will be created if + // missing. Note that although this is a const API, it actually changes the + // internal state of the object. + Value GetIrValue() const; + + void SetIrValue(Value ir_value); + void SetInPlaceIrValue(Value ir_value); + + std::optional CurrentTensorData() const; + + std::vector MakeOutputTensors(const NodePtr& node) const; + + LazyTensorPtr CopyTensorToDevice(const BackendDevice& device); + + // Applies the queue of operations in preparation for using the data. + // Override it to use your own graph executor. + virtual void ApplyPendingGraph(); + + // Override it to set extra information. + virtual void AssignIrValue(Value ir_value) const; + + protected: + explicit LazyTensor(std::shared_ptr data); + + void SetTensorData(at::Tensor tensor_data); + + // We build a graph accumulating operations, but at a given point we + // need to force a rendering, otherwise the graph can grow without control. + // Think: + // for i in range(0, 100000): + // a = a + b + void TryLimitGraphSize(); + + // Override it to instantiate your own data. + virtual Value GetIrValueForTensor( + const at::Tensor& tensor, + const BackendDevice& device) const; + + Value CreateTensorNode(const BackendDataPtr& data, bool read_only) const; + + private: + LazyTensor(const at::Tensor& tensor, const BackendDevice& device); + LazyTensor(Value ir_value, const BackendDevice& device); + explicit LazyTensor(const BackendDataPtr& handle); + + static int64_t GetNextTensorId(); + + std::shared_ptr data_; +}; + +// Utils to convert at::Tensor to LazyTensor, and vice versa. + +// Section 0: c10::Tensorlist ==> lazy::TensorList +// note: GetTensorList is not totally parallel to GetLtcTensor; A TensorList +// skips +// the LazyTensor wrappers, assuming that the list of underlying IR nodes +// is actually more useful for downstream computations. TBD. +TORCH_API torch::lazy::Value GetTensorList(at::ITensorListRef tensors); + +// Section 1: at::Tensor => LazyTensor. +// Extracts the LazyTensor out of an at::Tensor. Returns a null LazyTensor +// if the tensor is not a lazy tensor. +TORCH_API LazyTensorPtr TryGetLtcTensor(const at::Tensor& tensor); + +// Extracts the LazyTensor out of an at::Tensor. Throws an exception +// if the tensor is not a lazy tensor. +TORCH_API LazyTensorPtr GetLtcTensor(const at::Tensor& tensor); + +// Same as above, applied to a list of tensors. +TORCH_API std::vector GetLtcTensors( + c10::ArrayRef tensors); + +// If tensor is a lazy tensor type, returns the LazyTensor embedded within it, +// otherwise creates a new lazy tensor type with tensor as data. +TORCH_API LazyTensorPtr GetOrCreateLtcTensor( + const std::optional& tensor, + const BackendDevice& device); + +TORCH_API LazyTensorPtr GetLtcTensorOrCreateForWrappedNumber( + const at::Tensor& tensor, + const BackendDevice& device); + +// Section 2: LazyTensor => at::Tensor. +// Creates an ATen tensor from an LazyTensor. +TORCH_API at::Tensor CreateAtenFromLtcTensor(const LazyTensorPtr& ltc_tensor); +TORCH_API at::Tensor CreateAtenFromLtcTensor(LazyTensor&& ltc_tensor); + +// Note [Lazy Tensor Functionalization] +// The functionalization pass is implemented by wrapping all TensorImpl +// objects in C++ with an extra FunctionalTensorWrapper object, +// that knows how to perform functionalization +// +// Certain functions in the aten API serve as entry/exit points for +// functionalization, where we need to perform the wrapping/unwrapping: +// - aten::to.device +// - aten::empty + +// Given a non-lazy tensor, this function creates a lazy tensor on the specified +// (lazy) device. The functionalize_output determines whether or not we should +// wrap the output in a "functional wrapper". +// +// How do you know whether to pass true/false for functionalize_output? +// +// Case 1: nonlazy -> lazy +// If you're implementing a function that takes in nonlazy tensors and returns +// lazy tensors, then you should think of that function as an "entrypoint" to +// functionalization, and use functionalize_output=true Examples include: +// - factory functions (the LTC kernel for at::empty) +// - CPU -> Lazy device conversions (the LTC kernel for at::to_device) +// +// Case 2: lazy -> lazy +// If you're implementing a function that takes in lazy tensors and returns +// lazy tensors, +// **but** requires creating lazy tensors internally, +// then you can assume that the current function is running inside of some +// outer context where functionalization is already running, that will take +// care of doing the wrapping for you, and use functionalize_output=true +// Examples include: +// - CPU fallback (takes in lazy tensors, converts to cpu, calls kernel, +// converts returns back to lazy tensors). +TORCH_API at::Tensor to_lazy_tensor( + const at::Tensor& self, + const c10::TensorOptions& options, + at::Device device, + bool non_blocking, + bool functionalize_output); + +template +auto TupleAtenFromLtcTensorsImpl( + const std::vector& tensors, + std::index_sequence /*unused*/) { + return std::make_tuple(CreateAtenFromLtcTensor(tensors[Indices])...); +} + +template +auto TupleAtenFromLtcTensors(const std::vector& tensors) { + return TupleAtenFromLtcTensorsImpl(tensors, std::make_index_sequence{}); +} + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..161008918c8ccb22011e0f13ef2cae0e16f5b133 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor_impl.h @@ -0,0 +1,66 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace torch::lazy { + +// Tensor implementation class used to be fed to the at::Tensor. +// Its scope is just to handle an LazyTensor. +class TORCH_API LTCTensorImpl final : public c10::TensorImpl { + public: + explicit LTCTensorImpl(const LazyTensorPtr& tensor); + explicit LTCTensorImpl(const LazyTensor& tensor); + explicit LTCTensorImpl(LazyTensor&& tensor); + + LazyTensorPtr tensor() { + return tensor_; + } + + void set_tensor(const LazyTensorPtr& lazy_tensor); + + void force_refresh_sizes() { + generation_ = 0; + } + + c10::intrusive_ptr shallow_copy_and_detach( + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const override; + + c10::intrusive_ptr shallow_copy_and_detach( + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const override; + + void shallow_copy_from(const c10::intrusive_ptr& impl) override; + + at::IntArrayRef sizes_custom() const override; + at::IntArrayRef strides_custom() const override; + int64_t numel_custom() const override; + int64_t storage_offset_custom() const override; + int64_t dim_custom() const override; + bool is_strides_like_custom(at::MemoryFormat memory_format) const override; + c10::SymBool sym_is_non_overlapping_and_dense_custom() const override; + + c10::SymBool sym_is_contiguous_custom( + at::MemoryFormat memory_format) const override; + c10::SymIntArrayRef sym_sizes_custom() const override; + c10::SymIntArrayRef sym_strides_custom() const override; + c10::SymInt sym_numel_custom() const override; + + private: + void setup_size_properties(); + + LazyTensorPtr tensor_; + mutable std::optional> sym_sizes_; + size_t generation_{0}; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor_util.h new file mode 100644 index 0000000000000000000000000000000000000000..e47484f16265b9675645aa947f06d5cdf59d54cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor_util.h @@ -0,0 +1,81 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +#include +#include + +namespace torch::lazy { + +TORCH_API std::vector ComputeArrayStrides( + c10::ArrayRef sizes); + +TORCH_API std::vector DataHandlesToTensors( + c10::ArrayRef data_handles, + at::ScalarType dest_element_type); + +// Uploads an ATEN tensor data to the device and fetches the corresponding +// device data handle. +TORCH_API BackendDataPtr +TensorToDataHandle(const at::Tensor& tensor, const BackendDevice& device); + +// Retrieves the device data handles by parallel uploading data onto the +// corresponding devices. +TORCH_API std::vector CreateTensorsData( + const std::vector& tensors, + const std::vector& devices); + +// Makes a deep copy of an ATEN tensor. +inline at::Tensor CopyTensor(const at::Tensor& ref) { + return ref.to(ref.options(), /*non_blocking=*/false, /*copy=*/true); +} + +// Same as above, with an additional cast. +inline at::Tensor CopyTensor( + const at::Tensor& ref, + at::ScalarType dest_type, + bool copy = true) { + return ref.to(ref.options().dtype(dest_type), /*non_blocking=*/false, copy); +} + +template +T OptionalOr(const std::optional& value, T defval) { + return value ? static_cast(*value) : defval; +} + +// Unwraps tensor to target dtype if it's a wrapped number. +inline at::Tensor UnwrapNumber(const at::Tensor& tensor, at::ScalarType dtype) { + return tensor.unsafeGetTensorImpl()->is_wrapped_number() ? tensor.to(dtype) + : tensor; +} + +template +at::Scalar MakeIntScalar(T value) { + return at::Scalar(static_cast(value)); +} + +// Routing values to device data maximizes the changes for compilation cache +// hits, but it can prevent the compiler to perform optimizations. So tensor +// values which are within a given set, are routed to constant scalars if this +// API returns true. +TORCH_API bool IsSpecialScalar(const at::Scalar& value); + +// Note: returns a reference instead of a fresh tensor to avoid refcount bumps. +inline const at::Tensor& maybe_unwrap_functional(const at::Tensor& tensor) { + if (at::functionalization::impl::isFunctionalTensor(tensor)) { + return at::functionalization::impl::unsafeGetFunctionalWrapper(tensor) + ->value(); + } else { + return tensor; + } +} + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/thread_pool.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/thread_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..ac54c00f81a1bc0b7d47ce5d6402b98f1007f104 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/thread_pool.h @@ -0,0 +1,41 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** + * This file is adapted from PyTorch/XLA + * https://github.com/pytorch/xla/blob/e0e5f937a0ba8d904f9608137dc8c51ba439df2d/third_party/xla_client/metrics.h + */ + +#pragma once + +#include +#include +#include + +#include + +namespace torch::lazy { + +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) +class TORCH_API Completion { + public: + class Data; + + explicit Completion(std::shared_ptr data); + + ~Completion(); + + void Wait(); + + private: + std::shared_ptr data_; +}; + +// Schedules a closure which might wait for IO or other events/conditions. +TORCH_API void ScheduleIoClosure(std::function closure); +TORCH_API Completion +ScheduleIoClosureWithCompletion(std::function closure); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/trie.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/trie.h new file mode 100644 index 0000000000000000000000000000000000000000..ca5fc4645c2e69fd3894c382a7fcf47dc64ff398 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/trie.h @@ -0,0 +1,82 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch::lazy { + +struct TORCH_API TrieNode { + static size_t GetNextUniqueId() { + static thread_local size_t id_generator = 0; + return id_generator++; + } + + size_t unique_id; + size_t hit_counter; + NodePtr ir_node; + std::list> successors; + + TrieNode() : unique_id(GetNextUniqueId()), hit_counter(0), ir_node(nullptr) {} + explicit TrieNode(NodePtr node) + : unique_id(GetNextUniqueId()), + hit_counter(0), + ir_node(std::move(node)) {} +}; + +class TORCH_API TrieCache { + public: + static TrieCache* Get(); + + TrieNode* Current() const; + // Take an iterator as the input because we want to move the corresponding + // node in the successor list to achieve a LRU caching effect + void SetCurrent(std::list>::iterator& iter); + // Used in MarkStep to indicate the end of one tracing + void ResetCurrent(); + + // Create a new TrieNode for ir_node and insert into the TrieCache + void Insert(NodePtr ir_node); + + // Clear all TrieCache nodes + // TODO: Because we don't expect user to explicitly call this function via + // a Python API, we may need to introduce a threshold on the size of the cache + // to avoid holding tensors for too long. + void Clear(); + + void DumpToDotFile(const std::string& file_name); + + private: + TrieCache(); + + std::shared_ptr root_; + TrieNode* current_; +}; + +template +NodePtr LookupNodeFromTrieCache(Args&&... args) { + auto& successors = TrieCache::Get()->Current()->successors; + for (auto it = successors.begin(); it != successors.end(); it++) { + NodePtr ir_node = (*it)->ir_node; + const T* concrete_node = NodeCast(ir_node.get()); + if (concrete_node && + concrete_node->CanBeReused(std::forward(args)...)) { + TORCH_LAZY_COUNTER( + "IrNodeReused_" + c10::demangle((typeid(T).name())), 1); + (*it)->hit_counter++; + TrieCache::Get()->SetCurrent(it); + return ir_node; + } + } + return nullptr; +} + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/unique.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/unique.h new file mode 100644 index 0000000000000000000000000000000000000000..718cac504751dc9b08fc72d69fcf91dbfbe77376 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/unique.h @@ -0,0 +1,59 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** + * Unique in this file is adapted from PyTorch/XLA + * https://github.com/pytorch/xla/blob/e0e5f937a0ba8d904f9608137dc8c51ba439df2d/third_party/xla_client/unique.h + */ + +#pragma once + +#include + +#include +#include + +namespace torch::lazy { + +// Helper class to allow tracking zero or more things, which should be forcibly +// be one only thing. +template > +class Unique { + public: + std::pair set(const T& value) { + if (value_) { + TORCH_CHECK(C()(*value_, value), "'", *value_, "' vs '", value); + return std::pair(false, *value_); + } + value_ = value; + return std::pair(true, *value_); + } + + operator bool() const { + return value_.has_value(); + } + operator const T&() const { + return *value_; + } + const T& operator*() const { + return *value_; + } + const T* operator->() const { + return value_.operator->(); + } + + std::set AsSet() const { + std::set vset; + if (value_.has_value()) { + vset.insert(*value_); + } + return vset; + } + + private: + std::optional value_; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/util.h new file mode 100644 index 0000000000000000000000000000000000000000..4324148de300340fa58151cc73ee6032f1f530ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/util.h @@ -0,0 +1,130 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** + * Most of the utils in this file is adapted from PyTorch/XLA + * https://github.com/pytorch/xla/blob/e0e5f937a0ba8d904f9608137dc8c51ba439df2d/third_party/xla_client/util.h + */ + +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch::lazy { + +// Similar to c10::scope_exit but with a status. +// TODO(alanwaketan): Consolidate it with c10::scope_exit. +template +class Cleanup { + public: + using StatusType = T; + + explicit Cleanup(std::function&& func) + : func_(std::move(func)) {} + Cleanup(Cleanup&& ref) noexcept + : func_(std::move(ref.func_)), status_(std::move(ref.status_)) {} + Cleanup(const Cleanup&) = delete; + + ~Cleanup() { + if (func_ != nullptr) { + func_(std::move(status_)); + } + } + + Cleanup& operator=(const Cleanup&) = delete; + + Cleanup& operator=(Cleanup&& ref) noexcept { + if (this != &ref) { + func_ = std::move(ref.func_); + status_ = std::move(ref.status_); + } + return *this; + } + + void Release() { + func_ = nullptr; + } + + void SetStatus(StatusType&& status) { + status_ = std::move(status); + } + + const StatusType& GetStatus() const { + return status_; + } + + private: + std::function func_; + StatusType status_; +}; + +using ExceptionCleanup = Cleanup; + +// Allows APIs which might return const references and values, to not be forced +// to return values in the signature. +// TODO(alanwaketan): This is clever, but is there really no std or c10 +// supports? Needs more investigations. +template +class MaybeRef { + public: + /* implicit */ MaybeRef(const T& ref) : ref_(ref) {} + /* implicit */ MaybeRef(T&& value) + : storage_(std::move(value)), ref_(*storage_) {} + + const T& Get() const { + return ref_; + } + const T& operator*() const { + return Get(); + } + operator const T&() const { + return Get(); + } + + bool IsStored() const { + return storage_.has_value(); + } + + private: + std::optional storage_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const T& ref_; +}; + +template +std::vector Iota(size_t size, T init = 0, T incr = 1) { + std::vector result(size); + T value = init; + for (size_t i = 0; i < size; ++i, value += incr) { + result[i] = value; + } + return result; +} + +template +std::vector ToVector(const S& input) { + return std::vector(input.begin(), input.end()); +} + +template +std::optional> ToOptionalVector( + c10::OptionalArrayRef arrayRef) { + if (arrayRef) { + return arrayRef->vec(); + } + return std::nullopt; +} + +template +std::underlying_type_t GetEnumValue(T value) { + return static_cast>(value); +} + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyIr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyIr.h new file mode 100644 index 0000000000000000000000000000000000000000..dfd6a881958c2d7eb0cbbe5006d4302669450d4d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyIr.h @@ -0,0 +1,10312 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// This file contains autogenerated LazyTensor IR nodes +#include +#include +#include +#include +#include +#include +#include +#include "torch/csrc/lazy/ts_backend/ts_node.h" + +namespace torch { +namespace lazy { +using at::operator<<; + +// kNullValue is used to contribute a static hash value any time +// a node has an Optional input that is nullopt. It is important +// to differentiate between HASH(std::nullopt, something) and HASH(something, std::nullopt), +// and using kNullValue in the hash function in the order of arguments +// serves this purpose. +static const torch::lazy::Value kNullValue = torch::lazy::Value(); + +class AdaptiveAvgPool2d : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::_adaptive_avg_pool2d); + } + + AdaptiveAvgPool2d(const torch::lazy::Value& self, const ::std::vector& output_size, std::vector&& shapes) + : TsNode( + AdaptiveAvgPool2d::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(output_size)), + output_size(output_size) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", output_size=" << output_size; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& output_size) const { + size_t i = 0; + return (operand(i++) == self && + this->output_size == output_size); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("output_size", output_size); + + torch::lazy::TSOpVector _adaptive_avg_pool2d_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(_adaptive_avg_pool2d_out.size(), 1); + + return _adaptive_avg_pool2d_out; + + } + + + ::std::vector output_size; + + +}; + +class AdaptiveAvgPool2dBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::_adaptive_avg_pool2d_backward); + } + + AdaptiveAvgPool2dBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + AdaptiveAvgPool2dBackward::ClassOpKind(), + OpList{grad_output, self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector _adaptive_avg_pool2d_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(_adaptive_avg_pool2d_backward_out.size(), 1); + + return _adaptive_avg_pool2d_backward_out; + + } + + + + + +}; + +class LogSoftmax : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::_log_softmax); + } + + LogSoftmax(const torch::lazy::Value& self, const int64_t& dim, const bool& half_to_float, std::vector&& shapes) + : TsNode( + LogSoftmax::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, half_to_float)), + dim(dim), + half_to_float(half_to_float) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", half_to_float=" << half_to_float; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const bool& half_to_float) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim && + this->half_to_float == half_to_float); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("half_to_float", half_to_float); + + torch::lazy::TSOpVector _log_softmax_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(_log_softmax_out.size(), 1); + + return _log_softmax_out; + + } + + + int64_t dim; + bool half_to_float; + + +}; + +class LogSoftmaxBackwardData : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::_log_softmax_backward_data); + } + + LogSoftmaxBackwardData(const torch::lazy::Value& grad_output, const torch::lazy::Value& output, const int64_t& dim, const at::ScalarType& input_dtype, std::vector&& shapes) + : TsNode( + LogSoftmaxBackwardData::ClassOpKind(), + OpList{grad_output, output}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, input_dtype)), + dim(dim), + input_dtype(input_dtype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", input_dtype=" << input_dtype; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& output, const int64_t& dim, const at::ScalarType& input_dtype) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == output && + this->dim == dim && + this->input_dtype == input_dtype); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("input_dtype", input_dtype); + + torch::lazy::TSOpVector _log_softmax_backward_data_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(_log_softmax_backward_data_out.size(), 1); + + return _log_softmax_backward_data_out; + + } + + + int64_t dim; + at::ScalarType input_dtype; + + +}; + +class ReshapeAliasCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::_reshape_alias_copy); + } + + ReshapeAliasCopy(const torch::lazy::Value& self, const ::std::vector& size, const ::std::vector& stride, std::vector&& shapes) + : TsNode( + ReshapeAliasCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(size, stride)), + size(size), + stride(stride) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", size=" << size; + ss << ", stride=" << stride; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& size, const ::std::vector& stride) const { + size_t i = 0; + return (operand(i++) == self && + this->size == size && + this->stride == stride); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("size", size); + arguments.emplace_back("stride", stride); + + torch::lazy::TSOpVector _reshape_alias_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(_reshape_alias_copy_out.size(), 1); + + return _reshape_alias_copy_out; + + } + + + ::std::vector size; + ::std::vector stride; + + +}; + +class Softmax : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::_softmax); + } + + Softmax(const torch::lazy::Value& self, const int64_t& dim, const bool& half_to_float, std::vector&& shapes) + : TsNode( + Softmax::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, half_to_float)), + dim(dim), + half_to_float(half_to_float) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", half_to_float=" << half_to_float; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const bool& half_to_float) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim && + this->half_to_float == half_to_float); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("half_to_float", half_to_float); + + torch::lazy::TSOpVector _softmax_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(_softmax_out.size(), 1); + + return _softmax_out; + + } + + + int64_t dim; + bool half_to_float; + + +}; + +class SoftmaxBackwardData : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::_softmax_backward_data); + } + + SoftmaxBackwardData(const torch::lazy::Value& grad_output, const torch::lazy::Value& output, const int64_t& dim, const at::ScalarType& input_dtype, std::vector&& shapes) + : TsNode( + SoftmaxBackwardData::ClassOpKind(), + OpList{grad_output, output}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, input_dtype)), + dim(dim), + input_dtype(input_dtype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", input_dtype=" << input_dtype; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& output, const int64_t& dim, const at::ScalarType& input_dtype) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == output && + this->dim == dim && + this->input_dtype == input_dtype); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("input_dtype", input_dtype); + + torch::lazy::TSOpVector _softmax_backward_data_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(_softmax_backward_data_out.size(), 1); + + return _softmax_backward_data_out; + + } + + + int64_t dim; + at::ScalarType input_dtype; + + +}; + +class Abs : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::abs); + } + + Abs(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Abs::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector abs_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(abs_out.size(), 1); + + return abs_out; + + } + + + + + +}; + +class AddTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::add); + } + + AddTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, const torch::lazy::Value& alpha, std::vector&& shapes) + : TsNode( + AddTensor::ClassOpKind(), + OpList{self, other, alpha}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other, const torch::lazy::Value& alpha) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other && + operand(i++) == alpha); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("alpha", loctx->GetOutputOp(operand(i++))); + torch::lazy::TSOpVector add_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(add_out.size(), 1); + + return add_out; + + } + + + + + +}; + +class Addcdiv : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::addcdiv); + } + + Addcdiv(const torch::lazy::Value& self, const torch::lazy::Value& tensor1, const torch::lazy::Value& tensor2, const torch::lazy::Value& value, std::vector&& shapes) + : TsNode( + Addcdiv::ClassOpKind(), + OpList{self, tensor1, tensor2, value}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& tensor1, const torch::lazy::Value& tensor2, const torch::lazy::Value& value) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == tensor1 && + operand(i++) == tensor2 && + operand(i++) == value); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("value", loctx->GetOutputOp(operand(i++))); + torch::lazy::TSOpVector addcdiv_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(addcdiv_out.size(), 1); + + return addcdiv_out; + + } + + + + + +}; + +class Addcmul : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::addcmul); + } + + Addcmul(const torch::lazy::Value& self, const torch::lazy::Value& tensor1, const torch::lazy::Value& tensor2, const torch::lazy::Value& value, std::vector&& shapes) + : TsNode( + Addcmul::ClassOpKind(), + OpList{self, tensor1, tensor2, value}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& tensor1, const torch::lazy::Value& tensor2, const torch::lazy::Value& value) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == tensor1 && + operand(i++) == tensor2 && + operand(i++) == value); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("value", loctx->GetOutputOp(operand(i++))); + torch::lazy::TSOpVector addcmul_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(addcmul_out.size(), 1); + + return addcmul_out; + + } + + + + + +}; + +class Addmm : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::addmm); + } + + Addmm(const torch::lazy::Value& self, const torch::lazy::Value& mat1, const torch::lazy::Value& mat2, const torch::lazy::Value& beta, const torch::lazy::Value& alpha, std::vector&& shapes) + : TsNode( + Addmm::ClassOpKind(), + OpList{self, mat1, mat2, beta, alpha}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& mat1, const torch::lazy::Value& mat2, const torch::lazy::Value& beta, const torch::lazy::Value& alpha) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == mat1 && + operand(i++) == mat2 && + operand(i++) == beta && + operand(i++) == alpha); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(2); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("beta", loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("alpha", loctx->GetOutputOp(operand(i++))); + torch::lazy::TSOpVector addmm_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(addmm_out.size(), 1); + + return addmm_out; + + } + + + + + +}; + +class AliasCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::alias_copy); + } + + AliasCopy(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + AliasCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector alias_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(alias_copy_out.size(), 1); + + return alias_copy_out; + + } + + + + + +}; + +class All : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::all); + } + + All(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + All::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector all_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(all_out.size(), 1); + + return all_out; + + } + + + + + +}; + +class Any : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::any); + } + + Any(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Any::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector any_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(any_out.size(), 1); + + return any_out; + + } + + + + + +}; + +class ArangeStartOut : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::arange); + } + + ArangeStartOut(const torch::lazy::Value& start, const torch::lazy::Value& end, const torch::lazy::Value& step, const torch::lazy::Value& out, std::vector&& shapes) + : TsNode( + ArangeStartOut::ClassOpKind(), + OpList{start, end, step, out}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& start, const torch::lazy::Value& end, const torch::lazy::Value& step, const torch::lazy::Value& out) const { + size_t i = 0; + return (operand(i++) == start && + operand(i++) == end && + operand(i++) == step && + operand(i++) == out); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("out", loctx->GetOutputOp(operand(i++))); + torch::lazy::TSOpVector arange_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(arange_out.size(), 1); + + return arange_out; + + } + + + + + +}; + +class AsStridedCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::as_strided_copy); + } + + AsStridedCopy(const torch::lazy::Value& self, const ::std::vector& size, const ::std::vector& stride, const ::std::optional& storage_offset, std::vector&& shapes) + : TsNode( + AsStridedCopy::ClassOpKind(), + OpList{self, storage_offset.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(size, stride)), + size(size), + stride(stride) + { + has_storage_offset = !!storage_offset; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", size=" << size; + ss << ", stride=" << stride; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& size, const ::std::vector& stride, const ::std::optional& storage_offset) const { + size_t i = 0; + return (operand(i++) == self && + nullable_operand(i++) == storage_offset.value_or(kNullValue) && + this->size == size && + this->stride == stride); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("size", size); + arguments.emplace_back("stride", stride); + arguments.emplace_back(has_storage_offset ? loctx->GetOutputOp(operand(i++)) : nullptr); + + torch::lazy::TSOpVector as_strided_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(as_strided_copy_out.size(), 1); + + return as_strided_copy_out; + + } + + + ::std::vector size; + ::std::vector stride; + bool has_storage_offset: 1; + +}; + +class AsStridedScatter : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::as_strided_scatter); + } + + AsStridedScatter(const torch::lazy::Value& self, const torch::lazy::Value& src, const ::std::vector& size, const ::std::vector& stride, const ::std::optional& storage_offset, std::vector&& shapes) + : TsNode( + AsStridedScatter::ClassOpKind(), + OpList{self, src, storage_offset.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(size, stride)), + size(size), + stride(stride) + { + has_storage_offset = !!storage_offset; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", size=" << size; + ss << ", stride=" << stride; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& src, const ::std::vector& size, const ::std::vector& stride, const ::std::optional& storage_offset) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == src && + nullable_operand(i++) == storage_offset.value_or(kNullValue) && + this->size == size && + this->stride == stride); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("size", size); + arguments.emplace_back("stride", stride); + arguments.emplace_back(has_storage_offset ? loctx->GetOutputOp(operand(i++)) : nullptr); + + torch::lazy::TSOpVector as_strided_scatter_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(as_strided_scatter_out.size(), 1); + + return as_strided_scatter_out; + + } + + + ::std::vector size; + ::std::vector stride; + bool has_storage_offset: 1; + +}; + +class AvgPool2d : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::avg_pool2d); + } + + AvgPool2d(const torch::lazy::Value& self, const ::std::vector& kernel_size, const ::std::vector& stride, const ::std::vector& padding, const bool& ceil_mode, const bool& count_include_pad, const ::std::optional& divisor_override, std::vector&& shapes) + : TsNode( + AvgPool2d::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override)), + kernel_size(kernel_size), + stride(stride), + padding(padding), + ceil_mode(ceil_mode), + count_include_pad(count_include_pad), + divisor_override(divisor_override) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", kernel_size=" << kernel_size; + ss << ", stride=" << stride; + ss << ", padding=" << padding; + ss << ", ceil_mode=" << ceil_mode; + ss << ", count_include_pad=" << count_include_pad; + if (divisor_override.has_value()) { + ss << ", divisor_override=" << divisor_override.value(); + } else { + ss << ", divisor_override=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& kernel_size, const ::std::vector& stride, const ::std::vector& padding, const bool& ceil_mode, const bool& count_include_pad, const ::std::optional& divisor_override) const { + size_t i = 0; + return (operand(i++) == self && + this->kernel_size == kernel_size && + this->stride == stride && + this->padding == padding && + this->ceil_mode == ceil_mode && + this->count_include_pad == count_include_pad && + ((!this->divisor_override&&!divisor_override) || (this->divisor_override&&divisor_override && *(this->divisor_override) == *divisor_override))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(7); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("kernel_size", kernel_size); + arguments.emplace_back("stride", stride); + arguments.emplace_back("padding", padding); + arguments.emplace_back("ceil_mode", ceil_mode); + arguments.emplace_back("count_include_pad", count_include_pad); + arguments.emplace_back("divisor_override", divisor_override); + + torch::lazy::TSOpVector avg_pool2d_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(avg_pool2d_out.size(), 1); + + return avg_pool2d_out; + + } + + + ::std::vector kernel_size; + ::std::vector stride; + ::std::vector padding; + bool ceil_mode; + bool count_include_pad; + ::std::optional divisor_override; + + +}; + +class AvgPool2dBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::avg_pool2d_backward); + } + + AvgPool2dBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const ::std::vector& kernel_size, const ::std::vector& stride, const ::std::vector& padding, const bool& ceil_mode, const bool& count_include_pad, const ::std::optional& divisor_override, std::vector&& shapes) + : TsNode( + AvgPool2dBackward::ClassOpKind(), + OpList{grad_output, self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override)), + kernel_size(kernel_size), + stride(stride), + padding(padding), + ceil_mode(ceil_mode), + count_include_pad(count_include_pad), + divisor_override(divisor_override) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", kernel_size=" << kernel_size; + ss << ", stride=" << stride; + ss << ", padding=" << padding; + ss << ", ceil_mode=" << ceil_mode; + ss << ", count_include_pad=" << count_include_pad; + if (divisor_override.has_value()) { + ss << ", divisor_override=" << divisor_override.value(); + } else { + ss << ", divisor_override=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const ::std::vector& kernel_size, const ::std::vector& stride, const ::std::vector& padding, const bool& ceil_mode, const bool& count_include_pad, const ::std::optional& divisor_override) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + this->kernel_size == kernel_size && + this->stride == stride && + this->padding == padding && + this->ceil_mode == ceil_mode && + this->count_include_pad == count_include_pad && + ((!this->divisor_override&&!divisor_override) || (this->divisor_override&&divisor_override && *(this->divisor_override) == *divisor_override))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(8); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("kernel_size", kernel_size); + arguments.emplace_back("stride", stride); + arguments.emplace_back("padding", padding); + arguments.emplace_back("ceil_mode", ceil_mode); + arguments.emplace_back("count_include_pad", count_include_pad); + arguments.emplace_back("divisor_override", divisor_override); + + torch::lazy::TSOpVector avg_pool2d_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(avg_pool2d_backward_out.size(), 1); + + return avg_pool2d_backward_out; + + } + + + ::std::vector kernel_size; + ::std::vector stride; + ::std::vector padding; + bool ceil_mode; + bool count_include_pad; + ::std::optional divisor_override; + + +}; + +class Baddbmm : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::baddbmm); + } + + Baddbmm(const torch::lazy::Value& self, const torch::lazy::Value& batch1, const torch::lazy::Value& batch2, const torch::lazy::Value& beta, const torch::lazy::Value& alpha, std::vector&& shapes) + : TsNode( + Baddbmm::ClassOpKind(), + OpList{self, batch1, batch2, beta, alpha}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& batch1, const torch::lazy::Value& batch2, const torch::lazy::Value& beta, const torch::lazy::Value& alpha) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == batch1 && + operand(i++) == batch2 && + operand(i++) == beta && + operand(i++) == alpha); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(2); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("beta", loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("alpha", loctx->GetOutputOp(operand(i++))); + torch::lazy::TSOpVector baddbmm_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(baddbmm_out.size(), 1); + + return baddbmm_out; + + } + + + + + +}; + +class Bernoulli : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::bernoulli); + } + + Bernoulli(const torch::lazy::Value& self, const ::std::optional& generator, std::vector&& shapes) + : TsNode( + Bernoulli::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(generator)), + generator(generator) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (generator.has_value()) { + ss << ", generator=" << "torch.Generator()"; + } else { + ss << ", generator=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional& generator) const { + size_t i = 0; + return (operand(i++) == self && + ((!this->generator&&!generator) || (this->generator&&generator && *(this->generator) == *generator))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("generator", generator); + torch::lazy::TSOpVector bernoulli_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(bernoulli_out.size(), 1); + + return bernoulli_out; + + } + + + ::std::optional generator; + + +}; + +class BernoulliP : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::bernoulli); + } + + BernoulliP(const torch::lazy::Value& self, const double& p, const ::std::optional& generator, std::vector&& shapes) + : TsNode( + BernoulliP::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(p, generator)), + p(p), + generator(generator) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", p=" << p; + if (generator.has_value()) { + ss << ", generator=" << "torch.Generator()"; + } else { + ss << ", generator=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const double& p, const ::std::optional& generator) const { + size_t i = 0; + return (operand(i++) == self && + this->p == p && + ((!this->generator&&!generator) || (this->generator&&generator && *(this->generator) == *generator))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("p", p); + kwarguments.emplace_back("generator", generator); + torch::lazy::TSOpVector bernoulli_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(bernoulli_out.size(), 1); + + return bernoulli_out; + + } + + + double p; + ::std::optional generator; + + +}; + +class BinaryCrossEntropy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::binary_cross_entropy); + } + + BinaryCrossEntropy(const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, std::vector&& shapes) + : TsNode( + BinaryCrossEntropy::ClassOpKind(), + OpList{self, target, weight.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(reduction)), + reduction(reduction) + { + has_weight = !!weight; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", reduction=" << reduction; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == target && + nullable_operand(i++) == weight.value_or(kNullValue) && + this->reduction == reduction); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("reduction", reduction); + + torch::lazy::TSOpVector binary_cross_entropy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(binary_cross_entropy_out.size(), 1); + + return binary_cross_entropy_out; + + } + + + int64_t reduction; + bool has_weight: 1; + +}; + +class BinaryCrossEntropyBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::binary_cross_entropy_backward); + } + + BinaryCrossEntropyBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, std::vector&& shapes) + : TsNode( + BinaryCrossEntropyBackward::ClassOpKind(), + OpList{grad_output, self, target, weight.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(reduction)), + reduction(reduction) + { + has_weight = !!weight; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", reduction=" << reduction; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == target && + nullable_operand(i++) == weight.value_or(kNullValue) && + this->reduction == reduction); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("reduction", reduction); + + torch::lazy::TSOpVector binary_cross_entropy_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(binary_cross_entropy_backward_out.size(), 1); + + return binary_cross_entropy_backward_out; + + } + + + int64_t reduction; + bool has_weight: 1; + +}; + +class BitwiseAndTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::bitwise_and); + } + + BitwiseAndTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + BitwiseAndTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector bitwise_and_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(bitwise_and_out.size(), 1); + + return bitwise_and_out; + + } + + + + + +}; + +class BitwiseOrTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::bitwise_or); + } + + BitwiseOrTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + BitwiseOrTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector bitwise_or_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(bitwise_or_out.size(), 1); + + return bitwise_or_out; + + } + + + + + +}; + +class Bmm : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::bmm); + } + + Bmm(const torch::lazy::Value& self, const torch::lazy::Value& mat2, std::vector&& shapes) + : TsNode( + Bmm::ClassOpKind(), + OpList{self, mat2}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& mat2) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == mat2); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector bmm_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(bmm_out.size(), 1); + + return bmm_out; + + } + + + + + +}; + +class Cat : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::cat); + } + + Cat(const torch::lazy::Value& tensors, const int64_t& dim, std::vector&& shapes) + : TsNode( + Cat::ClassOpKind(), + OpList{tensors}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& tensors, const int64_t& dim) const { + size_t i = 0; + return (operand(i++) == tensors && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + + torch::lazy::TSOpVector cat_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(cat_out.size(), 1); + + return cat_out; + + } + + + int64_t dim; + + +}; + +class Clamp : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::clamp); + } + + Clamp(const torch::lazy::Value& self, const ::std::optional& min, const ::std::optional& max, std::vector&& shapes) + : TsNode( + Clamp::ClassOpKind(), + OpList{self, min.value_or(kNullValue), max.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + has_min = !!min; + has_max = !!max; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional& min, const ::std::optional& max) const { + size_t i = 0; + return (operand(i++) == self && + nullable_operand(i++) == min.value_or(kNullValue) && + nullable_operand(i++) == max.value_or(kNullValue)); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_min ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_max ? loctx->GetOutputOp(operand(i++)) : nullptr); + + torch::lazy::TSOpVector clamp_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(clamp_out.size(), 1); + + return clamp_out; + + } + + + + bool has_min: 1; + bool has_max: 1; + +}; + +class ClampMin : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::clamp_min); + } + + ClampMin(const torch::lazy::Value& self, const torch::lazy::Value& min, std::vector&& shapes) + : TsNode( + ClampMin::ClassOpKind(), + OpList{self, min}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& min) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == min); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector clamp_min_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(clamp_min_out.size(), 1); + + return clamp_min_out; + + } + + + + + +}; + +class ConstantPadNd : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::constant_pad_nd); + } + + ConstantPadNd(const torch::lazy::Value& self, const ::std::vector& pad, const torch::lazy::Value& value, std::vector&& shapes) + : TsNode( + ConstantPadNd::ClassOpKind(), + OpList{self, value}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(pad)), + pad(pad) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", pad=" << pad; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& pad, const torch::lazy::Value& value) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == value && + this->pad == pad); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("pad", pad); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector constant_pad_nd_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(constant_pad_nd_out.size(), 1); + + return constant_pad_nd_out; + + } + + + ::std::vector pad; + + +}; + +class Convolution : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::convolution); + } + + Convolution(const torch::lazy::Value& input, const torch::lazy::Value& weight, const ::std::optional& bias, const ::std::vector& stride, const ::std::vector& padding, const ::std::vector& dilation, const bool& transposed, const ::std::vector& output_padding, const int64_t& groups, std::vector&& shapes) + : TsNode( + Convolution::ClassOpKind(), + OpList{input, weight, bias.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(stride, padding, dilation, transposed, output_padding, groups)), + stride(stride), + padding(padding), + dilation(dilation), + transposed(transposed), + output_padding(output_padding), + groups(groups) + { + has_bias = !!bias; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", stride=" << stride; + ss << ", padding=" << padding; + ss << ", dilation=" << dilation; + ss << ", transposed=" << transposed; + ss << ", output_padding=" << output_padding; + ss << ", groups=" << groups; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& input, const torch::lazy::Value& weight, const ::std::optional& bias, const ::std::vector& stride, const ::std::vector& padding, const ::std::vector& dilation, const bool& transposed, const ::std::vector& output_padding, const int64_t& groups) const { + size_t i = 0; + return (operand(i++) == input && + operand(i++) == weight && + nullable_operand(i++) == bias.value_or(kNullValue) && + this->stride == stride && + this->padding == padding && + this->dilation == dilation && + this->transposed == transposed && + this->output_padding == output_padding && + this->groups == groups); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(9); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_bias ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("stride", stride); + arguments.emplace_back("padding", padding); + arguments.emplace_back("dilation", dilation); + arguments.emplace_back("transposed", transposed); + arguments.emplace_back("output_padding", output_padding); + arguments.emplace_back("groups", groups); + + torch::lazy::TSOpVector convolution_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(convolution_out.size(), 1); + + return convolution_out; + + } + + + ::std::vector stride; + ::std::vector padding; + ::std::vector dilation; + bool transposed; + ::std::vector output_padding; + int64_t groups; + bool has_bias: 1; + +}; + +class ConvolutionBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::convolution_backward); + } + + ConvolutionBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& input, const torch::lazy::Value& weight, const ::std::optional<::std::vector>& bias_sizes, const ::std::vector& stride, const ::std::vector& padding, const ::std::vector& dilation, const bool& transposed, const ::std::vector& output_padding, const int64_t& groups, const ::std::vector& output_mask, std::vector&& shapes) + : TsNode( + ConvolutionBackward::ClassOpKind(), + OpList{grad_output, input, weight}, + std::move(shapes), + /* num_outputs */ 3, + torch::lazy::MHash(bias_sizes, stride, padding, dilation, transposed, output_padding, groups, output_mask)), + bias_sizes(bias_sizes), + stride(stride), + padding(padding), + dilation(dilation), + transposed(transposed), + output_padding(output_padding), + groups(groups), + output_mask(output_mask) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (bias_sizes.has_value()) { + ss << ", bias_sizes=" << bias_sizes.value(); + } else { + ss << ", bias_sizes=null"; + } + ss << ", stride=" << stride; + ss << ", padding=" << padding; + ss << ", dilation=" << dilation; + ss << ", transposed=" << transposed; + ss << ", output_padding=" << output_padding; + ss << ", groups=" << groups; + ss << ", output_mask=" << output_mask; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& input, const torch::lazy::Value& weight, const ::std::optional<::std::vector>& bias_sizes, const ::std::vector& stride, const ::std::vector& padding, const ::std::vector& dilation, const bool& transposed, const ::std::vector& output_padding, const int64_t& groups, const ::std::vector& output_mask) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == input && + operand(i++) == weight && + ((!this->bias_sizes&&!bias_sizes) || (this->bias_sizes&&bias_sizes && *(this->bias_sizes) == *bias_sizes)) && + this->stride == stride && + this->padding == padding && + this->dilation == dilation && + this->transposed == transposed && + this->output_padding == output_padding && + this->groups == groups && + this->output_mask == output_mask); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(11); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("bias_sizes", bias_sizes); + arguments.emplace_back("stride", stride); + arguments.emplace_back("padding", padding); + arguments.emplace_back("dilation", dilation); + arguments.emplace_back("transposed", transposed); + arguments.emplace_back("output_padding", output_padding); + arguments.emplace_back("groups", groups); + arguments.emplace_back("output_mask", output_mask); + + torch::lazy::TSOpVector convolution_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(convolution_backward_out.size(), 3); + + return convolution_backward_out; + + } + + + ::std::optional<::std::vector> bias_sizes; + ::std::vector stride; + ::std::vector padding; + ::std::vector dilation; + bool transposed; + ::std::vector output_padding; + int64_t groups; + ::std::vector output_mask; + + +}; + +class Cos : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::cos); + } + + Cos(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Cos::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector cos_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(cos_out.size(), 1); + + return cos_out; + + } + + + + + +}; + +class Cumsum : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::cumsum); + } + + Cumsum(const torch::lazy::Value& self, const int64_t& dim, const ::std::optional& dtype, std::vector&& shapes) + : TsNode( + Cumsum::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, dtype)), + dim(dim), + dtype(dtype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + if (dtype.has_value()) { + ss << ", dtype=" << dtype.value(); + } else { + ss << ", dtype=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const ::std::optional& dtype) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim && + ((!this->dtype&&!dtype) || (this->dtype&&dtype && *(this->dtype) == *dtype))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + kwarguments.emplace_back("dtype", dtype); + torch::lazy::TSOpVector cumsum_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(cumsum_out.size(), 1); + + return cumsum_out; + + } + + + int64_t dim; + ::std::optional dtype; + + +}; + +class DetachCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::detach_copy); + } + + DetachCopy(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + DetachCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector detach_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(detach_copy_out.size(), 1); + + return detach_copy_out; + + } + + + + + +}; + +class DiagonalCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::diagonal_copy); + } + + DiagonalCopy(const torch::lazy::Value& self, const int64_t& offset, const int64_t& dim1, const int64_t& dim2, std::vector&& shapes) + : TsNode( + DiagonalCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(offset, dim1, dim2)), + offset(offset), + dim1(dim1), + dim2(dim2) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", offset=" << offset; + ss << ", dim1=" << dim1; + ss << ", dim2=" << dim2; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& offset, const int64_t& dim1, const int64_t& dim2) const { + size_t i = 0; + return (operand(i++) == self && + this->offset == offset && + this->dim1 == dim1 && + this->dim2 == dim2); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("offset", offset); + arguments.emplace_back("dim1", dim1); + arguments.emplace_back("dim2", dim2); + + torch::lazy::TSOpVector diagonal_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(diagonal_copy_out.size(), 1); + + return diagonal_copy_out; + + } + + + int64_t offset; + int64_t dim1; + int64_t dim2; + + +}; + +class DiagonalScatter : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::diagonal_scatter); + } + + DiagonalScatter(const torch::lazy::Value& self, const torch::lazy::Value& src, const int64_t& offset, const int64_t& dim1, const int64_t& dim2, std::vector&& shapes) + : TsNode( + DiagonalScatter::ClassOpKind(), + OpList{self, src}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(offset, dim1, dim2)), + offset(offset), + dim1(dim1), + dim2(dim2) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", offset=" << offset; + ss << ", dim1=" << dim1; + ss << ", dim2=" << dim2; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& src, const int64_t& offset, const int64_t& dim1, const int64_t& dim2) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == src && + this->offset == offset && + this->dim1 == dim1 && + this->dim2 == dim2); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("offset", offset); + arguments.emplace_back("dim1", dim1); + arguments.emplace_back("dim2", dim2); + + torch::lazy::TSOpVector diagonal_scatter_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(diagonal_scatter_out.size(), 1); + + return diagonal_scatter_out; + + } + + + int64_t offset; + int64_t dim1; + int64_t dim2; + + +}; + +class DivTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::div); + } + + DivTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + DivTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector div_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(div_out.size(), 1); + + return div_out; + + } + + + + + +}; + +class DivTensorMode : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::div); + } + + DivTensorMode(const torch::lazy::Value& self, const torch::lazy::Value& other, const ::std::optional& rounding_mode, std::vector&& shapes) + : TsNode( + DivTensorMode::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(rounding_mode)), + rounding_mode(rounding_mode.has_value() ? ::std::make_optional(std::string(*rounding_mode)) : ::std::nullopt) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (rounding_mode.has_value()) { + ss << ", rounding_mode=" << rounding_mode.value(); + } else { + ss << ", rounding_mode=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other, const ::std::optional& rounding_mode) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other && + ((!this->rounding_mode&&!rounding_mode) || (this->rounding_mode&&rounding_mode && *(this->rounding_mode) == *rounding_mode))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("rounding_mode", rounding_mode); + torch::lazy::TSOpVector div_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(div_out.size(), 1); + + return div_out; + + } + + + ::std::optional rounding_mode; + + +}; + +class Elu : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::elu); + } + + Elu(const torch::lazy::Value& self, const torch::lazy::Value& alpha, const torch::lazy::Value& scale, const torch::lazy::Value& input_scale, std::vector&& shapes) + : TsNode( + Elu::ClassOpKind(), + OpList{self, alpha, scale, input_scale}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& alpha, const torch::lazy::Value& scale, const torch::lazy::Value& input_scale) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == alpha && + operand(i++) == scale && + operand(i++) == input_scale); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector elu_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(elu_out.size(), 1); + + return elu_out; + + } + + + + + +}; + +class EluBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::elu_backward); + } + + EluBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& alpha, const torch::lazy::Value& scale, const torch::lazy::Value& input_scale, const bool& is_result, const torch::lazy::Value& self_or_result, std::vector&& shapes) + : TsNode( + EluBackward::ClassOpKind(), + OpList{grad_output, alpha, scale, input_scale, self_or_result}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(is_result)), + is_result(is_result) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", is_result=" << is_result; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& alpha, const torch::lazy::Value& scale, const torch::lazy::Value& input_scale, const bool& is_result, const torch::lazy::Value& self_or_result) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == alpha && + operand(i++) == scale && + operand(i++) == input_scale && + operand(i++) == self_or_result && + this->is_result == is_result); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(6); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("is_result", is_result); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector elu_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(elu_backward_out.size(), 1); + + return elu_backward_out; + + } + + + bool is_result; + + +}; + +class Embedding : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::embedding); + } + + Embedding(const torch::lazy::Value& weight, const torch::lazy::Value& indices, const int64_t& padding_idx, const bool& scale_grad_by_freq, const bool& sparse, std::vector&& shapes) + : TsNode( + Embedding::ClassOpKind(), + OpList{weight, indices}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(padding_idx, scale_grad_by_freq, sparse)), + padding_idx(padding_idx), + scale_grad_by_freq(scale_grad_by_freq), + sparse(sparse) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", padding_idx=" << padding_idx; + ss << ", scale_grad_by_freq=" << scale_grad_by_freq; + ss << ", sparse=" << sparse; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& weight, const torch::lazy::Value& indices, const int64_t& padding_idx, const bool& scale_grad_by_freq, const bool& sparse) const { + size_t i = 0; + return (operand(i++) == weight && + operand(i++) == indices && + this->padding_idx == padding_idx && + this->scale_grad_by_freq == scale_grad_by_freq && + this->sparse == sparse); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("padding_idx", padding_idx); + arguments.emplace_back("scale_grad_by_freq", scale_grad_by_freq); + arguments.emplace_back("sparse", sparse); + + torch::lazy::TSOpVector embedding_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(embedding_out.size(), 1); + + return embedding_out; + + } + + + int64_t padding_idx; + bool scale_grad_by_freq; + bool sparse; + + +}; + +class EmbeddingDenseBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::embedding_dense_backward); + } + + EmbeddingDenseBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& indices, const int64_t& num_weights, const int64_t& padding_idx, const bool& scale_grad_by_freq, std::vector&& shapes) + : TsNode( + EmbeddingDenseBackward::ClassOpKind(), + OpList{grad_output, indices}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(num_weights, padding_idx, scale_grad_by_freq)), + num_weights(num_weights), + padding_idx(padding_idx), + scale_grad_by_freq(scale_grad_by_freq) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", num_weights=" << num_weights; + ss << ", padding_idx=" << padding_idx; + ss << ", scale_grad_by_freq=" << scale_grad_by_freq; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& indices, const int64_t& num_weights, const int64_t& padding_idx, const bool& scale_grad_by_freq) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == indices && + this->num_weights == num_weights && + this->padding_idx == padding_idx && + this->scale_grad_by_freq == scale_grad_by_freq); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("num_weights", num_weights); + arguments.emplace_back("padding_idx", padding_idx); + arguments.emplace_back("scale_grad_by_freq", scale_grad_by_freq); + + torch::lazy::TSOpVector embedding_dense_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(embedding_dense_backward_out.size(), 1); + + return embedding_dense_backward_out; + + } + + + int64_t num_weights; + int64_t padding_idx; + bool scale_grad_by_freq; + + +}; + +class EqScalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::eq); + } + + EqScalar(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + EqScalar::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector eq_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(eq_out.size(), 1); + + return eq_out; + + } + + + + + +}; + +class EqTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::eq); + } + + EqTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + EqTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector eq_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(eq_out.size(), 1); + + return eq_out; + + } + + + + + +}; + +class Exp : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::exp); + } + + Exp(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Exp::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector exp_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(exp_out.size(), 1); + + return exp_out; + + } + + + + + +}; + +class ExpandCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::expand_copy); + } + + ExpandCopy(const torch::lazy::Value& self, const ::std::vector& size, const bool& implicit, std::vector&& shapes) + : TsNode( + ExpandCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(size, implicit)), + size(size), + implicit(implicit) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", size=" << size; + ss << ", implicit=" << implicit; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& size, const bool& implicit) const { + size_t i = 0; + return (operand(i++) == self && + this->size == size && + this->implicit == implicit); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("size", size); + kwarguments.emplace_back("implicit", implicit); + torch::lazy::TSOpVector expand_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(expand_copy_out.size(), 1); + + return expand_copy_out; + + } + + + ::std::vector size; + bool implicit; + + +}; + +class Flip : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::flip); + } + + Flip(const torch::lazy::Value& self, const ::std::vector& dims, std::vector&& shapes) + : TsNode( + Flip::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dims)), + dims(dims) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dims=" << dims; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& dims) const { + size_t i = 0; + return (operand(i++) == self && + this->dims == dims); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dims", dims); + + torch::lazy::TSOpVector flip_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(flip_out.size(), 1); + + return flip_out; + + } + + + ::std::vector dims; + + +}; + +class Floor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::floor); + } + + Floor(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Floor::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector floor_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(floor_out.size(), 1); + + return floor_out; + + } + + + + + +}; + +class Frac : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::frac); + } + + Frac(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Frac::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector frac_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(frac_out.size(), 1); + + return frac_out; + + } + + + + + +}; + +class Gather : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::gather); + } + + Gather(const torch::lazy::Value& self, const int64_t& dim, const torch::lazy::Value& index, const bool& sparse_grad, std::vector&& shapes) + : TsNode( + Gather::ClassOpKind(), + OpList{self, index}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, sparse_grad)), + dim(dim), + sparse_grad(sparse_grad) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", sparse_grad=" << sparse_grad; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const torch::lazy::Value& index, const bool& sparse_grad) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == index && + this->dim == dim && + this->sparse_grad == sparse_grad); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("sparse_grad", sparse_grad); + torch::lazy::TSOpVector gather_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(gather_out.size(), 1); + + return gather_out; + + } + + + int64_t dim; + bool sparse_grad; + + +}; + +class GeScalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::ge); + } + + GeScalar(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + GeScalar::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector ge_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(ge_out.size(), 1); + + return ge_out; + + } + + + + + +}; + +class GeTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::ge); + } + + GeTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + GeTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector ge_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(ge_out.size(), 1); + + return ge_out; + + } + + + + + +}; + +class Gelu : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::gelu); + } + + Gelu(const torch::lazy::Value& self, const c10::string_view& approximate, std::vector&& shapes) + : TsNode( + Gelu::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(approximate)), + approximate(approximate) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", approximate=" << approximate; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const c10::string_view& approximate) const { + size_t i = 0; + return (operand(i++) == self && + this->approximate == approximate); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("approximate", approximate); + torch::lazy::TSOpVector gelu_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(gelu_out.size(), 1); + + return gelu_out; + + } + + + std::string approximate; + + +}; + +class GeluBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::gelu_backward); + } + + GeluBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const c10::string_view& approximate, std::vector&& shapes) + : TsNode( + GeluBackward::ClassOpKind(), + OpList{grad_output, self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(approximate)), + approximate(approximate) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", approximate=" << approximate; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const c10::string_view& approximate) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + this->approximate == approximate); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("approximate", approximate); + torch::lazy::TSOpVector gelu_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(gelu_backward_out.size(), 1); + + return gelu_backward_out; + + } + + + std::string approximate; + + +}; + +class Glu : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::glu); + } + + Glu(const torch::lazy::Value& self, const int64_t& dim, std::vector&& shapes) + : TsNode( + Glu::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + + torch::lazy::TSOpVector glu_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(glu_out.size(), 1); + + return glu_out; + + } + + + int64_t dim; + + +}; + +class GluBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::glu_backward); + } + + GluBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const int64_t& dim, std::vector&& shapes) + : TsNode( + GluBackward::ClassOpKind(), + OpList{grad_output, self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const int64_t& dim) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + + torch::lazy::TSOpVector glu_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(glu_backward_out.size(), 1); + + return glu_backward_out; + + } + + + int64_t dim; + + +}; + +class GluJvp : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::glu_jvp); + } + + GluJvp(const torch::lazy::Value& glu, const torch::lazy::Value& x, const torch::lazy::Value& dx, const int64_t& dim, std::vector&& shapes) + : TsNode( + GluJvp::ClassOpKind(), + OpList{glu, x, dx}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& glu, const torch::lazy::Value& x, const torch::lazy::Value& dx, const int64_t& dim) const { + size_t i = 0; + return (operand(i++) == glu && + operand(i++) == x && + operand(i++) == dx && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + + torch::lazy::TSOpVector glu_jvp_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(glu_jvp_out.size(), 1); + + return glu_jvp_out; + + } + + + int64_t dim; + + +}; + +class GridSampler2d : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::grid_sampler_2d); + } + + GridSampler2d(const torch::lazy::Value& input, const torch::lazy::Value& grid, const int64_t& interpolation_mode, const int64_t& padding_mode, const bool& align_corners, std::vector&& shapes) + : TsNode( + GridSampler2d::ClassOpKind(), + OpList{input, grid}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(interpolation_mode, padding_mode, align_corners)), + interpolation_mode(interpolation_mode), + padding_mode(padding_mode), + align_corners(align_corners) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", interpolation_mode=" << interpolation_mode; + ss << ", padding_mode=" << padding_mode; + ss << ", align_corners=" << align_corners; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& input, const torch::lazy::Value& grid, const int64_t& interpolation_mode, const int64_t& padding_mode, const bool& align_corners) const { + size_t i = 0; + return (operand(i++) == input && + operand(i++) == grid && + this->interpolation_mode == interpolation_mode && + this->padding_mode == padding_mode && + this->align_corners == align_corners); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("interpolation_mode", interpolation_mode); + arguments.emplace_back("padding_mode", padding_mode); + arguments.emplace_back("align_corners", align_corners); + + torch::lazy::TSOpVector grid_sampler_2d_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(grid_sampler_2d_out.size(), 1); + + return grid_sampler_2d_out; + + } + + + int64_t interpolation_mode; + int64_t padding_mode; + bool align_corners; + + +}; + +class GridSampler2dBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::grid_sampler_2d_backward); + } + + GridSampler2dBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& input, const torch::lazy::Value& grid, const int64_t& interpolation_mode, const int64_t& padding_mode, const bool& align_corners, const ::std::vector& output_mask, std::vector&& shapes) + : TsNode( + GridSampler2dBackward::ClassOpKind(), + OpList{grad_output, input, grid}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash(interpolation_mode, padding_mode, align_corners, output_mask)), + interpolation_mode(interpolation_mode), + padding_mode(padding_mode), + align_corners(align_corners), + output_mask(output_mask) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", interpolation_mode=" << interpolation_mode; + ss << ", padding_mode=" << padding_mode; + ss << ", align_corners=" << align_corners; + ss << ", output_mask=" << output_mask; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& input, const torch::lazy::Value& grid, const int64_t& interpolation_mode, const int64_t& padding_mode, const bool& align_corners, const ::std::vector& output_mask) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == input && + operand(i++) == grid && + this->interpolation_mode == interpolation_mode && + this->padding_mode == padding_mode && + this->align_corners == align_corners && + this->output_mask == output_mask); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(7); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("interpolation_mode", interpolation_mode); + arguments.emplace_back("padding_mode", padding_mode); + arguments.emplace_back("align_corners", align_corners); + arguments.emplace_back("output_mask", output_mask); + + torch::lazy::TSOpVector grid_sampler_2d_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(grid_sampler_2d_backward_out.size(), 2); + + return grid_sampler_2d_backward_out; + + } + + + int64_t interpolation_mode; + int64_t padding_mode; + bool align_corners; + ::std::vector output_mask; + + +}; + +class GtScalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::gt); + } + + GtScalar(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + GtScalar::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector gt_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(gt_out.size(), 1); + + return gt_out; + + } + + + + + +}; + +class GtTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::gt); + } + + GtTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + GtTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector gt_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(gt_out.size(), 1); + + return gt_out; + + } + + + + + +}; + +class Hardsigmoid : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::hardsigmoid); + } + + Hardsigmoid(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Hardsigmoid::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector hardsigmoid_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(hardsigmoid_out.size(), 1); + + return hardsigmoid_out; + + } + + + + + +}; + +class IndexSelect : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::index_select); + } + + IndexSelect(const torch::lazy::Value& self, const int64_t& dim, const torch::lazy::Value& index, std::vector&& shapes) + : TsNode( + IndexSelect::ClassOpKind(), + OpList{self, index}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const torch::lazy::Value& index) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == index && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector index_select_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(index_select_out.size(), 1); + + return index_select_out; + + } + + + int64_t dim; + + +}; + +class LeScalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::le); + } + + LeScalar(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + LeScalar::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector le_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(le_out.size(), 1); + + return le_out; + + } + + + + + +}; + +class LeTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::le); + } + + LeTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + LeTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector le_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(le_out.size(), 1); + + return le_out; + + } + + + + + +}; + +class LeakyRelu : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::leaky_relu); + } + + LeakyRelu(const torch::lazy::Value& self, const torch::lazy::Value& negative_slope, std::vector&& shapes) + : TsNode( + LeakyRelu::ClassOpKind(), + OpList{self, negative_slope}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& negative_slope) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == negative_slope); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector leaky_relu_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(leaky_relu_out.size(), 1); + + return leaky_relu_out; + + } + + + + + +}; + +class LeakyReluBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::leaky_relu_backward); + } + + LeakyReluBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& negative_slope, const bool& self_is_result, std::vector&& shapes) + : TsNode( + LeakyReluBackward::ClassOpKind(), + OpList{grad_output, self, negative_slope}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(self_is_result)), + self_is_result(self_is_result) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", self_is_result=" << self_is_result; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& negative_slope, const bool& self_is_result) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == negative_slope && + this->self_is_result == self_is_result); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("self_is_result", self_is_result); + + torch::lazy::TSOpVector leaky_relu_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(leaky_relu_backward_out.size(), 1); + + return leaky_relu_backward_out; + + } + + + bool self_is_result; + + +}; + +class Log : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::log); + } + + Log(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Log::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector log_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(log_out.size(), 1); + + return log_out; + + } + + + + + +}; + +class Log2 : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::log2); + } + + Log2(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Log2::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector log2_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(log2_out.size(), 1); + + return log2_out; + + } + + + + + +}; + +class LogSigmoidBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::log_sigmoid_backward); + } + + LogSigmoidBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& buffer, std::vector&& shapes) + : TsNode( + LogSigmoidBackward::ClassOpKind(), + OpList{grad_output, self, buffer}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& buffer) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == buffer); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector log_sigmoid_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(log_sigmoid_backward_out.size(), 1); + + return log_sigmoid_backward_out; + + } + + + + + +}; + +class LogSigmoidForward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::log_sigmoid_forward); + } + + LogSigmoidForward(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + LogSigmoidForward::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector log_sigmoid_forward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(log_sigmoid_forward_out.size(), 2); + + return log_sigmoid_forward_out; + + } + + + + + +}; + +class Logdet : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::logdet); + } + + Logdet(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Logdet::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector logdet_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(logdet_out.size(), 1); + + return logdet_out; + + } + + + + + +}; + +class LtScalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::lt); + } + + LtScalar(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + LtScalar::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector lt_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(lt_out.size(), 1); + + return lt_out; + + } + + + + + +}; + +class LtTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::lt); + } + + LtTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + LtTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector lt_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(lt_out.size(), 1); + + return lt_out; + + } + + + + + +}; + +class MaskedFillScalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::masked_fill); + } + + MaskedFillScalar(const torch::lazy::Value& self, const torch::lazy::Value& mask, const torch::lazy::Value& value, std::vector&& shapes) + : TsNode( + MaskedFillScalar::ClassOpKind(), + OpList{self, mask, value}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& mask, const torch::lazy::Value& value) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == mask && + operand(i++) == value); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector masked_fill_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(masked_fill_out.size(), 1); + + return masked_fill_out; + + } + + + + + +}; + +class MaskedFillTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::masked_fill); + } + + MaskedFillTensor(const torch::lazy::Value& self, const torch::lazy::Value& mask, const torch::lazy::Value& value, std::vector&& shapes) + : TsNode( + MaskedFillTensor::ClassOpKind(), + OpList{self, mask, value}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& mask, const torch::lazy::Value& value) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == mask && + operand(i++) == value); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector masked_fill_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(masked_fill_out.size(), 1); + + return masked_fill_out; + + } + + + + + +}; + +class MaxDim : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::max); + } + + MaxDim(const torch::lazy::Value& self, const int64_t& dim, const bool& keepdim, std::vector&& shapes) + : TsNode( + MaxDim::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash(dim, keepdim)), + dim(dim), + keepdim(keepdim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", keepdim=" << keepdim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const bool& keepdim) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim && + this->keepdim == keepdim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("keepdim", keepdim); + + torch::lazy::TSOpVector max_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(max_out.size(), 2); + + return max_out; + + } + + + int64_t dim; + bool keepdim; + + +}; + +class Max : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::max); + } + + Max(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Max::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector max_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(max_out.size(), 1); + + return max_out; + + } + + + + + +}; + +class MaxPool2dWithIndices : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::max_pool2d_with_indices); + } + + MaxPool2dWithIndices(const torch::lazy::Value& self, const ::std::vector& kernel_size, const ::std::vector& stride, const ::std::vector& padding, const ::std::vector& dilation, const bool& ceil_mode, std::vector&& shapes) + : TsNode( + MaxPool2dWithIndices::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash(kernel_size, stride, padding, dilation, ceil_mode)), + kernel_size(kernel_size), + stride(stride), + padding(padding), + dilation(dilation), + ceil_mode(ceil_mode) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", kernel_size=" << kernel_size; + ss << ", stride=" << stride; + ss << ", padding=" << padding; + ss << ", dilation=" << dilation; + ss << ", ceil_mode=" << ceil_mode; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& kernel_size, const ::std::vector& stride, const ::std::vector& padding, const ::std::vector& dilation, const bool& ceil_mode) const { + size_t i = 0; + return (operand(i++) == self && + this->kernel_size == kernel_size && + this->stride == stride && + this->padding == padding && + this->dilation == dilation && + this->ceil_mode == ceil_mode); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(6); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("kernel_size", kernel_size); + arguments.emplace_back("stride", stride); + arguments.emplace_back("padding", padding); + arguments.emplace_back("dilation", dilation); + arguments.emplace_back("ceil_mode", ceil_mode); + + torch::lazy::TSOpVector max_pool2d_with_indices_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(max_pool2d_with_indices_out.size(), 2); + + return max_pool2d_with_indices_out; + + } + + + ::std::vector kernel_size; + ::std::vector stride; + ::std::vector padding; + ::std::vector dilation; + bool ceil_mode; + + +}; + +class MaxPool2dWithIndicesBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::max_pool2d_with_indices_backward); + } + + MaxPool2dWithIndicesBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const ::std::vector& kernel_size, const ::std::vector& stride, const ::std::vector& padding, const ::std::vector& dilation, const bool& ceil_mode, const torch::lazy::Value& indices, std::vector&& shapes) + : TsNode( + MaxPool2dWithIndicesBackward::ClassOpKind(), + OpList{grad_output, self, indices}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(kernel_size, stride, padding, dilation, ceil_mode)), + kernel_size(kernel_size), + stride(stride), + padding(padding), + dilation(dilation), + ceil_mode(ceil_mode) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", kernel_size=" << kernel_size; + ss << ", stride=" << stride; + ss << ", padding=" << padding; + ss << ", dilation=" << dilation; + ss << ", ceil_mode=" << ceil_mode; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const ::std::vector& kernel_size, const ::std::vector& stride, const ::std::vector& padding, const ::std::vector& dilation, const bool& ceil_mode, const torch::lazy::Value& indices) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == indices && + this->kernel_size == kernel_size && + this->stride == stride && + this->padding == padding && + this->dilation == dilation && + this->ceil_mode == ceil_mode); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(8); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("kernel_size", kernel_size); + arguments.emplace_back("stride", stride); + arguments.emplace_back("padding", padding); + arguments.emplace_back("dilation", dilation); + arguments.emplace_back("ceil_mode", ceil_mode); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector max_pool2d_with_indices_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(max_pool2d_with_indices_backward_out.size(), 1); + + return max_pool2d_with_indices_backward_out; + + } + + + ::std::vector kernel_size; + ::std::vector stride; + ::std::vector padding; + ::std::vector dilation; + bool ceil_mode; + + +}; + +class Maximum : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::maximum); + } + + Maximum(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + Maximum::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector maximum_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(maximum_out.size(), 1); + + return maximum_out; + + } + + + + + +}; + +class Mean : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::mean); + } + + Mean(const torch::lazy::Value& self, const ::std::optional& dtype, std::vector&& shapes) + : TsNode( + Mean::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dtype)), + dtype(dtype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (dtype.has_value()) { + ss << ", dtype=" << dtype.value(); + } else { + ss << ", dtype=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional& dtype) const { + size_t i = 0; + return (operand(i++) == self && + ((!this->dtype&&!dtype) || (this->dtype&&dtype && *(this->dtype) == *dtype))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("dtype", dtype); + torch::lazy::TSOpVector mean_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(mean_out.size(), 1); + + return mean_out; + + } + + + ::std::optional dtype; + + +}; + +class MeanDim : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::mean); + } + + MeanDim(const torch::lazy::Value& self, const ::std::optional<::std::vector>& dim, const bool& keepdim, const ::std::optional& dtype, std::vector&& shapes) + : TsNode( + MeanDim::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, keepdim, dtype)), + dim(dim), + keepdim(keepdim), + dtype(dtype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (dim.has_value()) { + ss << ", dim=" << dim.value(); + } else { + ss << ", dim=null"; + } + ss << ", keepdim=" << keepdim; + if (dtype.has_value()) { + ss << ", dtype=" << dtype.value(); + } else { + ss << ", dtype=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional<::std::vector>& dim, const bool& keepdim, const ::std::optional& dtype) const { + size_t i = 0; + return (operand(i++) == self && + ((!this->dim&&!dim) || (this->dim&&dim && *(this->dim) == *dim)) && + this->keepdim == keepdim && + ((!this->dtype&&!dtype) || (this->dtype&&dtype && *(this->dtype) == *dtype))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("keepdim", keepdim); + kwarguments.emplace_back("dtype", dtype); + torch::lazy::TSOpVector mean_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(mean_out.size(), 1); + + return mean_out; + + } + + + ::std::optional<::std::vector> dim; + bool keepdim; + ::std::optional dtype; + + +}; + +class Min : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::min); + } + + Min(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Min::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector min_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(min_out.size(), 1); + + return min_out; + + } + + + + + +}; + +class Minimum : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::minimum); + } + + Minimum(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + Minimum::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector minimum_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(minimum_out.size(), 1); + + return minimum_out; + + } + + + + + +}; + +class Mm : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::mm); + } + + Mm(const torch::lazy::Value& self, const torch::lazy::Value& mat2, std::vector&& shapes) + : TsNode( + Mm::ClassOpKind(), + OpList{self, mat2}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& mat2) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == mat2); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector mm_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(mm_out.size(), 1); + + return mm_out; + + } + + + + + +}; + +class MulTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::mul); + } + + MulTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + MulTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector mul_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(mul_out.size(), 1); + + return mul_out; + + } + + + + + +}; + +class Mv : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::mv); + } + + Mv(const torch::lazy::Value& self, const torch::lazy::Value& vec, std::vector&& shapes) + : TsNode( + Mv::ClassOpKind(), + OpList{self, vec}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& vec) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == vec); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector mv_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(mv_out.size(), 1); + + return mv_out; + + } + + + + + +}; + +class NativeBatchNorm : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::native_batch_norm); + } + + NativeBatchNorm(const torch::lazy::Value& input, const ::std::optional& weight, const ::std::optional& bias, const ::std::optional& running_mean, const ::std::optional& running_var, const bool& training, const double& momentum, const double& eps, std::vector&& shapes) + : TsNode( + NativeBatchNorm::ClassOpKind(), + OpList{input, weight.value_or(kNullValue), bias.value_or(kNullValue), running_mean.value_or(kNullValue), running_var.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 3, + torch::lazy::MHash(training, momentum, eps)), + training(training), + momentum(momentum), + eps(eps) + { + has_weight = !!weight; + has_bias = !!bias; + has_running_mean = !!running_mean; + has_running_var = !!running_var; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", training=" << training; + ss << ", momentum=" << momentum; + ss << ", eps=" << eps; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& input, const ::std::optional& weight, const ::std::optional& bias, const ::std::optional& running_mean, const ::std::optional& running_var, const bool& training, const double& momentum, const double& eps) const { + size_t i = 0; + return (operand(i++) == input && + nullable_operand(i++) == weight.value_or(kNullValue) && + nullable_operand(i++) == bias.value_or(kNullValue) && + nullable_operand(i++) == running_mean.value_or(kNullValue) && + nullable_operand(i++) == running_var.value_or(kNullValue) && + this->training == training && + this->momentum == momentum && + this->eps == eps); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(8); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_bias ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_running_mean ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_running_var ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("training", training); + arguments.emplace_back("momentum", momentum); + arguments.emplace_back("eps", eps); + + torch::lazy::TSOpVector native_batch_norm_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(native_batch_norm_out.size(), 3); + + return native_batch_norm_out; + + } + + + bool training; + double momentum; + double eps; + bool has_weight: 1; + bool has_bias: 1; + bool has_running_mean: 1; + bool has_running_var: 1; + +}; + +class NativeBatchNormBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::native_batch_norm_backward); + } + + NativeBatchNormBackward(const torch::lazy::Value& grad_out, const torch::lazy::Value& input, const ::std::optional& weight, const ::std::optional& running_mean, const ::std::optional& running_var, const ::std::optional& save_mean, const ::std::optional& save_invstd, const bool& train, const double& eps, const ::std::vector& output_mask, std::vector&& shapes) + : TsNode( + NativeBatchNormBackward::ClassOpKind(), + OpList{grad_out, input, weight.value_or(kNullValue), running_mean.value_or(kNullValue), running_var.value_or(kNullValue), save_mean.value_or(kNullValue), save_invstd.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 3, + torch::lazy::MHash(train, eps, output_mask)), + train(train), + eps(eps), + output_mask(output_mask) + { + has_weight = !!weight; + has_running_mean = !!running_mean; + has_running_var = !!running_var; + has_save_mean = !!save_mean; + has_save_invstd = !!save_invstd; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", train=" << train; + ss << ", eps=" << eps; + ss << ", output_mask=" << output_mask; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_out, const torch::lazy::Value& input, const ::std::optional& weight, const ::std::optional& running_mean, const ::std::optional& running_var, const ::std::optional& save_mean, const ::std::optional& save_invstd, const bool& train, const double& eps, const ::std::vector& output_mask) const { + size_t i = 0; + return (operand(i++) == grad_out && + operand(i++) == input && + nullable_operand(i++) == weight.value_or(kNullValue) && + nullable_operand(i++) == running_mean.value_or(kNullValue) && + nullable_operand(i++) == running_var.value_or(kNullValue) && + nullable_operand(i++) == save_mean.value_or(kNullValue) && + nullable_operand(i++) == save_invstd.value_or(kNullValue) && + this->train == train && + this->eps == eps && + this->output_mask == output_mask); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(10); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_running_mean ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_running_var ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_save_mean ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_save_invstd ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("train", train); + arguments.emplace_back("eps", eps); + arguments.emplace_back("output_mask", output_mask); + + torch::lazy::TSOpVector native_batch_norm_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(native_batch_norm_backward_out.size(), 3); + + return native_batch_norm_backward_out; + + } + + + bool train; + double eps; + ::std::vector output_mask; + bool has_weight: 1; + bool has_running_mean: 1; + bool has_running_var: 1; + bool has_save_mean: 1; + bool has_save_invstd: 1; + +}; + +class NativeDropout : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::native_dropout); + } + + NativeDropout(const torch::lazy::Value& input, const double& p, const ::std::optional& train, std::vector&& shapes) + : TsNode( + NativeDropout::ClassOpKind(), + OpList{input}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash(p, train)), + p(p), + train(train) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", p=" << p; + if (train.has_value()) { + ss << ", train=" << train.value(); + } else { + ss << ", train=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& input, const double& p, const ::std::optional& train) const { + size_t i = 0; + return (operand(i++) == input && + this->p == p && + ((!this->train&&!train) || (this->train&&train && *(this->train) == *train))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("p", p); + arguments.emplace_back("train", train); + + torch::lazy::TSOpVector native_dropout_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(native_dropout_out.size(), 2); + + return native_dropout_out; + + } + + + double p; + ::std::optional train; + + +}; + +class NativeDropoutBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::native_dropout_backward); + } + + NativeDropoutBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& mask, const double& scale, std::vector&& shapes) + : TsNode( + NativeDropoutBackward::ClassOpKind(), + OpList{grad_output, mask}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(scale)), + scale(scale) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", scale=" << scale; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& mask, const double& scale) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == mask && + this->scale == scale); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("scale", scale); + + torch::lazy::TSOpVector native_dropout_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(native_dropout_backward_out.size(), 1); + + return native_dropout_backward_out; + + } + + + double scale; + + +}; + +class NativeLayerNorm : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::native_layer_norm); + } + + NativeLayerNorm(const torch::lazy::Value& input, const ::std::vector& normalized_shape, const ::std::optional& weight, const ::std::optional& bias, const double& eps, std::vector&& shapes) + : TsNode( + NativeLayerNorm::ClassOpKind(), + OpList{input, weight.value_or(kNullValue), bias.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 3, + torch::lazy::MHash(normalized_shape, eps)), + normalized_shape(normalized_shape), + eps(eps) + { + has_weight = !!weight; + has_bias = !!bias; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", normalized_shape=" << normalized_shape; + ss << ", eps=" << eps; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& input, const ::std::vector& normalized_shape, const ::std::optional& weight, const ::std::optional& bias, const double& eps) const { + size_t i = 0; + return (operand(i++) == input && + nullable_operand(i++) == weight.value_or(kNullValue) && + nullable_operand(i++) == bias.value_or(kNullValue) && + this->normalized_shape == normalized_shape && + this->eps == eps); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("normalized_shape", normalized_shape); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_bias ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("eps", eps); + + torch::lazy::TSOpVector native_layer_norm_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(native_layer_norm_out.size(), 3); + + return native_layer_norm_out; + + } + + + ::std::vector normalized_shape; + double eps; + bool has_weight: 1; + bool has_bias: 1; + +}; + +class NativeLayerNormBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::native_layer_norm_backward); + } + + NativeLayerNormBackward(const torch::lazy::Value& grad_out, const torch::lazy::Value& input, const ::std::vector& normalized_shape, const torch::lazy::Value& mean, const torch::lazy::Value& rstd, const ::std::optional& weight, const ::std::optional& bias, const ::std::vector& output_mask, std::vector&& shapes) + : TsNode( + NativeLayerNormBackward::ClassOpKind(), + OpList{grad_out, input, mean, rstd, weight.value_or(kNullValue), bias.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 3, + torch::lazy::MHash(normalized_shape, output_mask)), + normalized_shape(normalized_shape), + output_mask(output_mask) + { + has_weight = !!weight; + has_bias = !!bias; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", normalized_shape=" << normalized_shape; + ss << ", output_mask=" << output_mask; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_out, const torch::lazy::Value& input, const ::std::vector& normalized_shape, const torch::lazy::Value& mean, const torch::lazy::Value& rstd, const ::std::optional& weight, const ::std::optional& bias, const ::std::vector& output_mask) const { + size_t i = 0; + return (operand(i++) == grad_out && + operand(i++) == input && + operand(i++) == mean && + operand(i++) == rstd && + nullable_operand(i++) == weight.value_or(kNullValue) && + nullable_operand(i++) == bias.value_or(kNullValue) && + this->normalized_shape == normalized_shape && + this->output_mask == output_mask); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(8); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("normalized_shape", normalized_shape); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_bias ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("output_mask", output_mask); + + torch::lazy::TSOpVector native_layer_norm_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(native_layer_norm_backward_out.size(), 3); + + return native_layer_norm_backward_out; + + } + + + ::std::vector normalized_shape; + ::std::vector output_mask; + bool has_weight: 1; + bool has_bias: 1; + +}; + +class NeScalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::ne); + } + + NeScalar(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + NeScalar::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector ne_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(ne_out.size(), 1); + + return ne_out; + + } + + + + + +}; + +class NeTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::ne); + } + + NeTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + NeTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector ne_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(ne_out.size(), 1); + + return ne_out; + + } + + + + + +}; + +class Neg : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::neg); + } + + Neg(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Neg::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector neg_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(neg_out.size(), 1); + + return neg_out; + + } + + + + + +}; + +class NllLoss2dBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::nll_loss2d_backward); + } + + NllLoss2dBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, const int64_t& ignore_index, const torch::lazy::Value& total_weight, std::vector&& shapes) + : TsNode( + NllLoss2dBackward::ClassOpKind(), + OpList{grad_output, self, target, weight.value_or(kNullValue), total_weight}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(reduction, ignore_index)), + reduction(reduction), + ignore_index(ignore_index) + { + has_weight = !!weight; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", reduction=" << reduction; + ss << ", ignore_index=" << ignore_index; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, const int64_t& ignore_index, const torch::lazy::Value& total_weight) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == target && + nullable_operand(i++) == weight.value_or(kNullValue) && + operand(i++) == total_weight && + this->reduction == reduction && + this->ignore_index == ignore_index); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(7); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("reduction", reduction); + arguments.emplace_back("ignore_index", ignore_index); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector nll_loss2d_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(nll_loss2d_backward_out.size(), 1); + + return nll_loss2d_backward_out; + + } + + + int64_t reduction; + int64_t ignore_index; + bool has_weight: 1; + +}; + +class NllLoss2dForward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::nll_loss2d_forward); + } + + NllLoss2dForward(const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, const int64_t& ignore_index, std::vector&& shapes) + : TsNode( + NllLoss2dForward::ClassOpKind(), + OpList{self, target, weight.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash(reduction, ignore_index)), + reduction(reduction), + ignore_index(ignore_index) + { + has_weight = !!weight; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", reduction=" << reduction; + ss << ", ignore_index=" << ignore_index; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, const int64_t& ignore_index) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == target && + nullable_operand(i++) == weight.value_or(kNullValue) && + this->reduction == reduction && + this->ignore_index == ignore_index); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("reduction", reduction); + arguments.emplace_back("ignore_index", ignore_index); + + torch::lazy::TSOpVector nll_loss2d_forward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(nll_loss2d_forward_out.size(), 2); + + return nll_loss2d_forward_out; + + } + + + int64_t reduction; + int64_t ignore_index; + bool has_weight: 1; + +}; + +class NllLossBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::nll_loss_backward); + } + + NllLossBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, const int64_t& ignore_index, const torch::lazy::Value& total_weight, std::vector&& shapes) + : TsNode( + NllLossBackward::ClassOpKind(), + OpList{grad_output, self, target, weight.value_or(kNullValue), total_weight}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(reduction, ignore_index)), + reduction(reduction), + ignore_index(ignore_index) + { + has_weight = !!weight; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", reduction=" << reduction; + ss << ", ignore_index=" << ignore_index; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, const int64_t& ignore_index, const torch::lazy::Value& total_weight) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == target && + nullable_operand(i++) == weight.value_or(kNullValue) && + operand(i++) == total_weight && + this->reduction == reduction && + this->ignore_index == ignore_index); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(7); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("reduction", reduction); + arguments.emplace_back("ignore_index", ignore_index); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector nll_loss_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(nll_loss_backward_out.size(), 1); + + return nll_loss_backward_out; + + } + + + int64_t reduction; + int64_t ignore_index; + bool has_weight: 1; + +}; + +class NllLossForward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::nll_loss_forward); + } + + NllLossForward(const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, const int64_t& ignore_index, std::vector&& shapes) + : TsNode( + NllLossForward::ClassOpKind(), + OpList{self, target, weight.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash(reduction, ignore_index)), + reduction(reduction), + ignore_index(ignore_index) + { + has_weight = !!weight; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", reduction=" << reduction; + ss << ", ignore_index=" << ignore_index; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& target, const ::std::optional& weight, const int64_t& reduction, const int64_t& ignore_index) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == target && + nullable_operand(i++) == weight.value_or(kNullValue) && + this->reduction == reduction && + this->ignore_index == ignore_index); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_weight ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("reduction", reduction); + arguments.emplace_back("ignore_index", ignore_index); + + torch::lazy::TSOpVector nll_loss_forward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(nll_loss_forward_out.size(), 2); + + return nll_loss_forward_out; + + } + + + int64_t reduction; + int64_t ignore_index; + bool has_weight: 1; + +}; + +class Nonzero : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::nonzero); + } + + Nonzero(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Nonzero::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector nonzero_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(nonzero_out.size(), 1); + + return nonzero_out; + + } + + + + + +}; + +class NormScalaroptDim : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::norm); + } + + NormScalaroptDim(const torch::lazy::Value& self, const ::std::optional& p, const ::std::vector& dim, const bool& keepdim, std::vector&& shapes) + : TsNode( + NormScalaroptDim::ClassOpKind(), + OpList{self, p.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, keepdim)), + dim(dim), + keepdim(keepdim) + { + has_p = !!p; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", keepdim=" << keepdim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional& p, const ::std::vector& dim, const bool& keepdim) const { + size_t i = 0; + return (operand(i++) == self && + nullable_operand(i++) == p.value_or(kNullValue) && + this->dim == dim && + this->keepdim == keepdim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(has_p ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back("dim", dim); + arguments.emplace_back("keepdim", keepdim); + + torch::lazy::TSOpVector norm_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(norm_out.size(), 1); + + return norm_out; + + } + + + ::std::vector dim; + bool keepdim; + bool has_p: 1; + +}; + +class NormalFunctional : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::normal_functional); + } + + NormalFunctional(const torch::lazy::Value& self, const double& mean, const double& std, const ::std::optional& generator, std::vector&& shapes) + : TsNode( + NormalFunctional::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(mean, std, generator)), + mean(mean), + std(std), + generator(generator) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", mean=" << mean; + ss << ", std=" << std; + if (generator.has_value()) { + ss << ", generator=" << "torch.Generator()"; + } else { + ss << ", generator=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const double& mean, const double& std, const ::std::optional& generator) const { + size_t i = 0; + return (operand(i++) == self && + this->mean == mean && + this->std == std && + ((!this->generator&&!generator) || (this->generator&&generator && *(this->generator) == *generator))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("mean", mean); + arguments.emplace_back("std", std); + kwarguments.emplace_back("generator", generator); + torch::lazy::TSOpVector normal_functional_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(normal_functional_out.size(), 1); + + return normal_functional_out; + + } + + + double mean; + double std; + ::std::optional generator; + + +}; + +class PermuteCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::permute_copy); + } + + PermuteCopy(const torch::lazy::Value& self, const ::std::vector& dims, std::vector&& shapes) + : TsNode( + PermuteCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dims)), + dims(dims) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dims=" << dims; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& dims) const { + size_t i = 0; + return (operand(i++) == self && + this->dims == dims); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dims", dims); + + torch::lazy::TSOpVector permute_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(permute_copy_out.size(), 1); + + return permute_copy_out; + + } + + + ::std::vector dims; + + +}; + +class PowTensorTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::pow); + } + + PowTensorTensor(const torch::lazy::Value& self, const torch::lazy::Value& exponent, std::vector&& shapes) + : TsNode( + PowTensorTensor::ClassOpKind(), + OpList{self, exponent}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& exponent) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == exponent); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector pow_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(pow_out.size(), 1); + + return pow_out; + + } + + + + + +}; + +class PowTensorScalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::pow); + } + + PowTensorScalar(const torch::lazy::Value& self, const torch::lazy::Value& exponent, std::vector&& shapes) + : TsNode( + PowTensorScalar::ClassOpKind(), + OpList{self, exponent}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& exponent) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == exponent); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector pow_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(pow_out.size(), 1); + + return pow_out; + + } + + + + + +}; + +class RandomFrom : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::random); + } + + RandomFrom(const torch::lazy::Value& self, const int64_t& from, const ::std::optional& to, const ::std::optional& generator, std::vector&& shapes) + : TsNode( + RandomFrom::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(from, to, generator)), + from(from), + to(to), + generator(generator) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", from=" << from; + if (to.has_value()) { + ss << ", to=" << to.value(); + } else { + ss << ", to=null"; + } + if (generator.has_value()) { + ss << ", generator=" << "torch.Generator()"; + } else { + ss << ", generator=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& from, const ::std::optional& to, const ::std::optional& generator) const { + size_t i = 0; + return (operand(i++) == self && + this->from == from && + ((!this->to&&!to) || (this->to&&to && *(this->to) == *to)) && + ((!this->generator&&!generator) || (this->generator&&generator && *(this->generator) == *generator))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("from", from); + arguments.emplace_back("to", to); + kwarguments.emplace_back("generator", generator); + torch::lazy::TSOpVector random_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(random_out.size(), 1); + + return random_out; + + } + + + int64_t from; + ::std::optional to; + ::std::optional generator; + + +}; + +class RandomTo : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::random); + } + + RandomTo(const torch::lazy::Value& self, const int64_t& to, const ::std::optional& generator, std::vector&& shapes) + : TsNode( + RandomTo::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(to, generator)), + to(to), + generator(generator) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", to=" << to; + if (generator.has_value()) { + ss << ", generator=" << "torch.Generator()"; + } else { + ss << ", generator=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& to, const ::std::optional& generator) const { + size_t i = 0; + return (operand(i++) == self && + this->to == to && + ((!this->generator&&!generator) || (this->generator&&generator && *(this->generator) == *generator))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("to", to); + kwarguments.emplace_back("generator", generator); + torch::lazy::TSOpVector random_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(random_out.size(), 1); + + return random_out; + + } + + + int64_t to; + ::std::optional generator; + + +}; + +class Random : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::random); + } + + Random(const torch::lazy::Value& self, const ::std::optional& generator, std::vector&& shapes) + : TsNode( + Random::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(generator)), + generator(generator) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (generator.has_value()) { + ss << ", generator=" << "torch.Generator()"; + } else { + ss << ", generator=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional& generator) const { + size_t i = 0; + return (operand(i++) == self && + ((!this->generator&&!generator) || (this->generator&&generator && *(this->generator) == *generator))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("generator", generator); + torch::lazy::TSOpVector random_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(random_out.size(), 1); + + return random_out; + + } + + + ::std::optional generator; + + +}; + +class Reciprocal : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::reciprocal); + } + + Reciprocal(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Reciprocal::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector reciprocal_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(reciprocal_out.size(), 1); + + return reciprocal_out; + + } + + + + + +}; + +class Relu : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::relu); + } + + Relu(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Relu::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector relu_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(relu_out.size(), 1); + + return relu_out; + + } + + + + + +}; + +class RemainderTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::remainder); + } + + RemainderTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, std::vector&& shapes) + : TsNode( + RemainderTensor::ClassOpKind(), + OpList{self, other}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector remainder_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(remainder_out.size(), 1); + + return remainder_out; + + } + + + + + +}; + +class Repeat : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::repeat); + } + + Repeat(const torch::lazy::Value& self, const ::std::vector& repeats, std::vector&& shapes) + : TsNode( + Repeat::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(repeats)), + repeats(repeats) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", repeats=" << repeats; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& repeats) const { + size_t i = 0; + return (operand(i++) == self && + this->repeats == repeats); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("repeats", repeats); + + torch::lazy::TSOpVector repeat_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(repeat_out.size(), 1); + + return repeat_out; + + } + + + ::std::vector repeats; + + +}; + +class Rsqrt : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::rsqrt); + } + + Rsqrt(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Rsqrt::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector rsqrt_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(rsqrt_out.size(), 1); + + return rsqrt_out; + + } + + + + + +}; + +class ScatterAdd : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::scatter_add); + } + + ScatterAdd(const torch::lazy::Value& self, const int64_t& dim, const torch::lazy::Value& index, const torch::lazy::Value& src, std::vector&& shapes) + : TsNode( + ScatterAdd::ClassOpKind(), + OpList{self, index, src}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const torch::lazy::Value& index, const torch::lazy::Value& src) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == index && + operand(i++) == src && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector scatter_add_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(scatter_add_out.size(), 1); + + return scatter_add_out; + + } + + + int64_t dim; + + +}; + +class SelectCopyInt : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::select_copy); + } + + SelectCopyInt(const torch::lazy::Value& self, const int64_t& dim, const int64_t& index, std::vector&& shapes) + : TsNode( + SelectCopyInt::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, index)), + dim(dim), + index(index) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", index=" << index; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const int64_t& index) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim && + this->index == index); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("index", index); + + torch::lazy::TSOpVector select_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(select_copy_out.size(), 1); + + return select_copy_out; + + } + + + int64_t dim; + int64_t index; + + +}; + +class SelectScatter : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::select_scatter); + } + + SelectScatter(const torch::lazy::Value& self, const torch::lazy::Value& src, const int64_t& dim, const int64_t& index, std::vector&& shapes) + : TsNode( + SelectScatter::ClassOpKind(), + OpList{self, src}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, index)), + dim(dim), + index(index) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", index=" << index; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& src, const int64_t& dim, const int64_t& index) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == src && + this->dim == dim && + this->index == index); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("index", index); + + torch::lazy::TSOpVector select_scatter_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(select_scatter_out.size(), 1); + + return select_scatter_out; + + } + + + int64_t dim; + int64_t index; + + +}; + +class Selu : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::selu); + } + + Selu(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Selu::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector selu_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(selu_out.size(), 1); + + return selu_out; + + } + + + + + +}; + +class Sgn : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::sgn); + } + + Sgn(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Sgn::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector sgn_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(sgn_out.size(), 1); + + return sgn_out; + + } + + + + + +}; + +class Sigmoid : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::sigmoid); + } + + Sigmoid(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Sigmoid::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector sigmoid_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(sigmoid_out.size(), 1); + + return sigmoid_out; + + } + + + + + +}; + +class SigmoidBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(c10::Symbol::fromQualString("aten::sigmoid_backward")); + } + + SigmoidBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& output, std::vector&& shapes) + : TsNode( + SigmoidBackward::ClassOpKind(), + OpList{grad_output, output}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& output) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == output); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector sigmoid_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(sigmoid_backward_out.size(), 1); + + return sigmoid_backward_out; + + } + + + + + +}; + +class Silu : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::silu); + } + + Silu(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Silu::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector silu_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(silu_out.size(), 1); + + return silu_out; + + } + + + + + +}; + +class SliceCopyTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::slice_copy); + } + + SliceCopyTensor(const torch::lazy::Value& self, const int64_t& dim, const ::std::optional& start, const ::std::optional& end, const torch::lazy::Value& step, std::vector&& shapes) + : TsNode( + SliceCopyTensor::ClassOpKind(), + OpList{self, start.value_or(kNullValue), end.value_or(kNullValue), step}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + has_start = !!start; + has_end = !!end; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const ::std::optional& start, const ::std::optional& end, const torch::lazy::Value& step) const { + size_t i = 0; + return (operand(i++) == self && + nullable_operand(i++) == start.value_or(kNullValue) && + nullable_operand(i++) == end.value_or(kNullValue) && + operand(i++) == step && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back(has_start ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_end ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector slice_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(slice_copy_out.size(), 1); + + return slice_copy_out; + + } + + + int64_t dim; + bool has_start: 1; + bool has_end: 1; + +}; + +class SliceScatter : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::slice_scatter); + } + + SliceScatter(const torch::lazy::Value& self, const torch::lazy::Value& src, const int64_t& dim, const ::std::optional& start, const ::std::optional& end, const torch::lazy::Value& step, std::vector&& shapes) + : TsNode( + SliceScatter::ClassOpKind(), + OpList{self, src, start.value_or(kNullValue), end.value_or(kNullValue), step}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + has_start = !!start; + has_end = !!end; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& src, const int64_t& dim, const ::std::optional& start, const ::std::optional& end, const torch::lazy::Value& step) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == src && + nullable_operand(i++) == start.value_or(kNullValue) && + nullable_operand(i++) == end.value_or(kNullValue) && + operand(i++) == step && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(6); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back(has_start ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(has_end ? loctx->GetOutputOp(operand(i++)) : nullptr); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector slice_scatter_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(slice_scatter_out.size(), 1); + + return slice_scatter_out; + + } + + + int64_t dim; + bool has_start: 1; + bool has_end: 1; + +}; + +class SmoothL1Loss : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::smooth_l1_loss); + } + + SmoothL1Loss(const torch::lazy::Value& self, const torch::lazy::Value& target, const int64_t& reduction, const double& beta, std::vector&& shapes) + : TsNode( + SmoothL1Loss::ClassOpKind(), + OpList{self, target}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(reduction, beta)), + reduction(reduction), + beta(beta) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", reduction=" << reduction; + ss << ", beta=" << beta; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& target, const int64_t& reduction, const double& beta) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == target && + this->reduction == reduction && + this->beta == beta); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("reduction", reduction); + arguments.emplace_back("beta", beta); + + torch::lazy::TSOpVector smooth_l1_loss_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(smooth_l1_loss_out.size(), 1); + + return smooth_l1_loss_out; + + } + + + int64_t reduction; + double beta; + + +}; + +class SmoothL1LossBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::smooth_l1_loss_backward); + } + + SmoothL1LossBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& target, const int64_t& reduction, const double& beta, std::vector&& shapes) + : TsNode( + SmoothL1LossBackward::ClassOpKind(), + OpList{grad_output, self, target}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(reduction, beta)), + reduction(reduction), + beta(beta) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", reduction=" << reduction; + ss << ", beta=" << beta; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& target, const int64_t& reduction, const double& beta) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == target && + this->reduction == reduction && + this->beta == beta); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("reduction", reduction); + arguments.emplace_back("beta", beta); + + torch::lazy::TSOpVector smooth_l1_loss_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(smooth_l1_loss_backward_out.size(), 1); + + return smooth_l1_loss_backward_out; + + } + + + int64_t reduction; + double beta; + + +}; + +class Softplus : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::softplus); + } + + Softplus(const torch::lazy::Value& self, const torch::lazy::Value& beta, const torch::lazy::Value& threshold, std::vector&& shapes) + : TsNode( + Softplus::ClassOpKind(), + OpList{self, beta, threshold}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& beta, const torch::lazy::Value& threshold) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == beta && + operand(i++) == threshold); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector softplus_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(softplus_out.size(), 1); + + return softplus_out; + + } + + + + + +}; + +class SoftplusBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::softplus_backward); + } + + SoftplusBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& beta, const torch::lazy::Value& threshold, std::vector&& shapes) + : TsNode( + SoftplusBackward::ClassOpKind(), + OpList{grad_output, self, beta, threshold}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& beta, const torch::lazy::Value& threshold) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == beta && + operand(i++) == threshold); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector softplus_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(softplus_backward_out.size(), 1); + + return softplus_backward_out; + + } + + + + + +}; + +class Sort : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::sort); + } + + Sort(const torch::lazy::Value& self, const int64_t& dim, const bool& descending, std::vector&& shapes) + : TsNode( + Sort::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash(dim, descending)), + dim(dim), + descending(descending) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + ss << ", descending=" << descending; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim, const bool& descending) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim && + this->descending == descending); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("descending", descending); + + torch::lazy::TSOpVector sort_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(sort_out.size(), 2); + + return sort_out; + + } + + + int64_t dim; + bool descending; + + +}; + +class Sqrt : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::sqrt); + } + + Sqrt(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Sqrt::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector sqrt_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(sqrt_out.size(), 1); + + return sqrt_out; + + } + + + + + +}; + +class SqueezeCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::squeeze_copy); + } + + SqueezeCopy(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + SqueezeCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector squeeze_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(squeeze_copy_out.size(), 1); + + return squeeze_copy_out; + + } + + + + + +}; + +class SqueezeCopyDim : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::squeeze_copy); + } + + SqueezeCopyDim(const torch::lazy::Value& self, const int64_t& dim, std::vector&& shapes) + : TsNode( + SqueezeCopyDim::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + + torch::lazy::TSOpVector squeeze_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(squeeze_copy_out.size(), 1); + + return squeeze_copy_out; + + } + + + int64_t dim; + + +}; + +class SqueezeCopyDims : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::squeeze_copy); + } + + SqueezeCopyDims(const torch::lazy::Value& self, const ::std::vector& dim, std::vector&& shapes) + : TsNode( + SqueezeCopyDims::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& dim) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + + torch::lazy::TSOpVector squeeze_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(squeeze_copy_out.size(), 1); + + return squeeze_copy_out; + + } + + + ::std::vector dim; + + +}; + +class Stack : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::stack); + } + + Stack(const torch::lazy::Value& tensors, const int64_t& dim, std::vector&& shapes) + : TsNode( + Stack::ClassOpKind(), + OpList{tensors}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& tensors, const int64_t& dim) const { + size_t i = 0; + return (operand(i++) == tensors && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + + torch::lazy::TSOpVector stack_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(stack_out.size(), 1); + + return stack_out; + + } + + + int64_t dim; + + +}; + +class Std : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::std); + } + + Std(const torch::lazy::Value& self, const bool& unbiased, std::vector&& shapes) + : TsNode( + Std::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(unbiased)), + unbiased(unbiased) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", unbiased=" << unbiased; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const bool& unbiased) const { + size_t i = 0; + return (operand(i++) == self && + this->unbiased == unbiased); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("unbiased", unbiased); + + torch::lazy::TSOpVector std_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(std_out.size(), 1); + + return std_out; + + } + + + bool unbiased; + + +}; + +class StdDim : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::std); + } + + StdDim(const torch::lazy::Value& self, const ::std::optional<::std::vector>& dim, const bool& unbiased, const bool& keepdim, std::vector&& shapes) + : TsNode( + StdDim::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, unbiased, keepdim)), + dim(dim), + unbiased(unbiased), + keepdim(keepdim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (dim.has_value()) { + ss << ", dim=" << dim.value(); + } else { + ss << ", dim=null"; + } + ss << ", unbiased=" << unbiased; + ss << ", keepdim=" << keepdim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional<::std::vector>& dim, const bool& unbiased, const bool& keepdim) const { + size_t i = 0; + return (operand(i++) == self && + ((!this->dim&&!dim) || (this->dim&&dim && *(this->dim) == *dim)) && + this->unbiased == unbiased && + this->keepdim == keepdim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("unbiased", unbiased); + arguments.emplace_back("keepdim", keepdim); + + torch::lazy::TSOpVector std_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(std_out.size(), 1); + + return std_out; + + } + + + ::std::optional<::std::vector> dim; + bool unbiased; + bool keepdim; + + +}; + +class StdCorrection : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::std); + } + + StdCorrection(const torch::lazy::Value& self, const ::std::optional<::std::vector>& dim, const ::std::optional& correction, const bool& keepdim, std::vector&& shapes) + : TsNode( + StdCorrection::ClassOpKind(), + OpList{self, correction.value_or(kNullValue)}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, keepdim)), + dim(dim), + keepdim(keepdim) + { + has_correction = !!correction; + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (dim.has_value()) { + ss << ", dim=" << dim.value(); + } else { + ss << ", dim=null"; + } + ss << ", keepdim=" << keepdim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional<::std::vector>& dim, const ::std::optional& correction, const bool& keepdim) const { + size_t i = 0; + return (operand(i++) == self && + nullable_operand(i++) == correction.value_or(kNullValue) && + ((!this->dim&&!dim) || (this->dim&&dim && *(this->dim) == *dim)) && + this->keepdim == keepdim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(2); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + kwarguments.emplace_back("correction", has_correction ? loctx->GetOutputOp(operand(i++)) : nullptr); + kwarguments.emplace_back("keepdim", keepdim); + torch::lazy::TSOpVector std_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(std_out.size(), 1); + + return std_out; + + } + + + ::std::optional<::std::vector> dim; + bool keepdim; + bool has_correction: 1; + +}; + +class SubTensor : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::sub); + } + + SubTensor(const torch::lazy::Value& self, const torch::lazy::Value& other, const torch::lazy::Value& alpha, std::vector&& shapes) + : TsNode( + SubTensor::ClassOpKind(), + OpList{self, other, alpha}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& other, const torch::lazy::Value& alpha) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == other && + operand(i++) == alpha); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("alpha", loctx->GetOutputOp(operand(i++))); + torch::lazy::TSOpVector sub_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(sub_out.size(), 1); + + return sub_out; + + } + + + + + +}; + +class Sum : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::sum); + } + + Sum(const torch::lazy::Value& self, const ::std::optional& dtype, std::vector&& shapes) + : TsNode( + Sum::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dtype)), + dtype(dtype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (dtype.has_value()) { + ss << ", dtype=" << dtype.value(); + } else { + ss << ", dtype=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional& dtype) const { + size_t i = 0; + return (operand(i++) == self && + ((!this->dtype&&!dtype) || (this->dtype&&dtype && *(this->dtype) == *dtype))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("dtype", dtype); + torch::lazy::TSOpVector sum_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(sum_out.size(), 1); + + return sum_out; + + } + + + ::std::optional dtype; + + +}; + +class SumDimIntlist : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::sum); + } + + SumDimIntlist(const torch::lazy::Value& self, const ::std::optional<::std::vector>& dim, const bool& keepdim, const ::std::optional& dtype, std::vector&& shapes) + : TsNode( + SumDimIntlist::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim, keepdim, dtype)), + dim(dim), + keepdim(keepdim), + dtype(dtype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + if (dim.has_value()) { + ss << ", dim=" << dim.value(); + } else { + ss << ", dim=null"; + } + ss << ", keepdim=" << keepdim; + if (dtype.has_value()) { + ss << ", dtype=" << dtype.value(); + } else { + ss << ", dtype=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::optional<::std::vector>& dim, const bool& keepdim, const ::std::optional& dtype) const { + size_t i = 0; + return (operand(i++) == self && + ((!this->dim&&!dim) || (this->dim&&dim && *(this->dim) == *dim)) && + this->keepdim == keepdim && + ((!this->dtype&&!dtype) || (this->dtype&&dtype && *(this->dtype) == *dtype))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + arguments.emplace_back("keepdim", keepdim); + kwarguments.emplace_back("dtype", dtype); + torch::lazy::TSOpVector sum_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(sum_out.size(), 1); + + return sum_out; + + } + + + ::std::optional<::std::vector> dim; + bool keepdim; + ::std::optional dtype; + + +}; + +class TCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::t_copy); + } + + TCopy(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + TCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector t_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(t_copy_out.size(), 1); + + return t_copy_out; + + } + + + + + +}; + +class Tanh : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::tanh); + } + + Tanh(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Tanh::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector tanh_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(tanh_out.size(), 1); + + return tanh_out; + + } + + + + + +}; + +class TanhBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::tanh_backward); + } + + TanhBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& output, std::vector&& shapes) + : TsNode( + TanhBackward::ClassOpKind(), + OpList{grad_output, output}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& output) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == output); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector tanh_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(tanh_backward_out.size(), 1); + + return tanh_backward_out; + + } + + + + + +}; + +class Threshold : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::threshold); + } + + Threshold(const torch::lazy::Value& self, const torch::lazy::Value& threshold, const torch::lazy::Value& value, std::vector&& shapes) + : TsNode( + Threshold::ClassOpKind(), + OpList{self, threshold, value}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const torch::lazy::Value& threshold, const torch::lazy::Value& value) const { + size_t i = 0; + return (operand(i++) == self && + operand(i++) == threshold && + operand(i++) == value); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector threshold_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(threshold_out.size(), 1); + + return threshold_out; + + } + + + + + +}; + +class ThresholdBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::threshold_backward); + } + + ThresholdBackward(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& threshold, std::vector&& shapes) + : TsNode( + ThresholdBackward::ClassOpKind(), + OpList{grad_output, self, threshold}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const torch::lazy::Value& self, const torch::lazy::Value& threshold) const { + size_t i = 0; + return (operand(i++) == grad_output && + operand(i++) == self && + operand(i++) == threshold); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector threshold_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(threshold_backward_out.size(), 1); + + return threshold_backward_out; + + } + + + + + +}; + +class Topk : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::topk); + } + + Topk(const torch::lazy::Value& self, const int64_t& k, const int64_t& dim, const bool& largest, const bool& sorted, std::vector&& shapes) + : TsNode( + Topk::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 2, + torch::lazy::MHash(k, dim, largest, sorted)), + k(k), + dim(dim), + largest(largest), + sorted(sorted) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", k=" << k; + ss << ", dim=" << dim; + ss << ", largest=" << largest; + ss << ", sorted=" << sorted; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& k, const int64_t& dim, const bool& largest, const bool& sorted) const { + size_t i = 0; + return (operand(i++) == self && + this->k == k && + this->dim == dim && + this->largest == largest && + this->sorted == sorted); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("k", k); + arguments.emplace_back("dim", dim); + arguments.emplace_back("largest", largest); + arguments.emplace_back("sorted", sorted); + + torch::lazy::TSOpVector topk_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(topk_out.size(), 2); + + return topk_out; + + } + + + int64_t k; + int64_t dim; + bool largest; + bool sorted; + + +}; + +class Trace : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::trace); + } + + Trace(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Trace::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector trace_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(trace_out.size(), 1); + + return trace_out; + + } + + + + + +}; + +class TransposeCopyInt : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::transpose_copy); + } + + TransposeCopyInt(const torch::lazy::Value& self, const int64_t& dim0, const int64_t& dim1, std::vector&& shapes) + : TsNode( + TransposeCopyInt::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim0, dim1)), + dim0(dim0), + dim1(dim1) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim0=" << dim0; + ss << ", dim1=" << dim1; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim0, const int64_t& dim1) const { + size_t i = 0; + return (operand(i++) == self && + this->dim0 == dim0 && + this->dim1 == dim1); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim0", dim0); + arguments.emplace_back("dim1", dim1); + + torch::lazy::TSOpVector transpose_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(transpose_copy_out.size(), 1); + + return transpose_copy_out; + + } + + + int64_t dim0; + int64_t dim1; + + +}; + +class Tril : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::tril); + } + + Tril(const torch::lazy::Value& self, const int64_t& diagonal, std::vector&& shapes) + : TsNode( + Tril::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(diagonal)), + diagonal(diagonal) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", diagonal=" << diagonal; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& diagonal) const { + size_t i = 0; + return (operand(i++) == self && + this->diagonal == diagonal); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("diagonal", diagonal); + + torch::lazy::TSOpVector tril_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(tril_out.size(), 1); + + return tril_out; + + } + + + int64_t diagonal; + + +}; + +class Triu : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::triu); + } + + Triu(const torch::lazy::Value& self, const int64_t& diagonal, std::vector&& shapes) + : TsNode( + Triu::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(diagonal)), + diagonal(diagonal) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", diagonal=" << diagonal; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& diagonal) const { + size_t i = 0; + return (operand(i++) == self && + this->diagonal == diagonal); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("diagonal", diagonal); + + torch::lazy::TSOpVector triu_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(triu_out.size(), 1); + + return triu_out; + + } + + + int64_t diagonal; + + +}; + +class Trunc : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::trunc); + } + + Trunc(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Trunc::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector trunc_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(trunc_out.size(), 1); + + return trunc_out; + + } + + + + + +}; + +class UnfoldCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::unfold_copy); + } + + UnfoldCopy(const torch::lazy::Value& self, const int64_t& dimension, const int64_t& size, const int64_t& step, std::vector&& shapes) + : TsNode( + UnfoldCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dimension, size, step)), + dimension(dimension), + size(size), + step(step) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dimension=" << dimension; + ss << ", size=" << size; + ss << ", step=" << step; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dimension, const int64_t& size, const int64_t& step) const { + size_t i = 0; + return (operand(i++) == self && + this->dimension == dimension && + this->size == size && + this->step == step); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dimension", dimension); + arguments.emplace_back("size", size); + arguments.emplace_back("step", step); + + torch::lazy::TSOpVector unfold_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(unfold_copy_out.size(), 1); + + return unfold_copy_out; + + } + + + int64_t dimension; + int64_t size; + int64_t step; + + +}; + +class Uniform : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::uniform); + } + + Uniform(const torch::lazy::Value& self, const double& from, const double& to, const ::std::optional& generator, std::vector&& shapes) + : TsNode( + Uniform::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(from, to, generator)), + from(from), + to(to), + generator(generator) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", from=" << from; + ss << ", to=" << to; + if (generator.has_value()) { + ss << ", generator=" << "torch.Generator()"; + } else { + ss << ", generator=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const double& from, const double& to, const ::std::optional& generator) const { + size_t i = 0; + return (operand(i++) == self && + this->from == from && + this->to == to && + ((!this->generator&&!generator) || (this->generator&&generator && *(this->generator) == *generator))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(3); + kwarguments.reserve(1); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("from", from); + arguments.emplace_back("to", to); + kwarguments.emplace_back("generator", generator); + torch::lazy::TSOpVector uniform_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(uniform_out.size(), 1); + + return uniform_out; + + } + + + double from; + double to; + ::std::optional generator; + + +}; + +class UnsqueezeCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::unsqueeze_copy); + } + + UnsqueezeCopy(const torch::lazy::Value& self, const int64_t& dim, std::vector&& shapes) + : TsNode( + UnsqueezeCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dim)), + dim(dim) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dim=" << dim; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const int64_t& dim) const { + size_t i = 0; + return (operand(i++) == self && + this->dim == dim); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dim", dim); + + torch::lazy::TSOpVector unsqueeze_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(unsqueeze_copy_out.size(), 1); + + return unsqueeze_copy_out; + + } + + + int64_t dim; + + +}; + +class UpsampleBilinear2d : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::upsample_bilinear2d); + } + + UpsampleBilinear2d(const torch::lazy::Value& self, const ::std::vector& output_size, const bool& align_corners, const ::std::optional& scales_h, const ::std::optional& scales_w, std::vector&& shapes) + : TsNode( + UpsampleBilinear2d::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(output_size, align_corners, scales_h, scales_w)), + output_size(output_size), + align_corners(align_corners), + scales_h(scales_h), + scales_w(scales_w) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", output_size=" << output_size; + ss << ", align_corners=" << align_corners; + if (scales_h.has_value()) { + ss << ", scales_h=" << scales_h.value(); + } else { + ss << ", scales_h=null"; + } + if (scales_w.has_value()) { + ss << ", scales_w=" << scales_w.value(); + } else { + ss << ", scales_w=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& output_size, const bool& align_corners, const ::std::optional& scales_h, const ::std::optional& scales_w) const { + size_t i = 0; + return (operand(i++) == self && + this->output_size == output_size && + this->align_corners == align_corners && + ((!this->scales_h&&!scales_h) || (this->scales_h&&scales_h && *(this->scales_h) == *scales_h)) && + ((!this->scales_w&&!scales_w) || (this->scales_w&&scales_w && *(this->scales_w) == *scales_w))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("output_size", output_size); + arguments.emplace_back("align_corners", align_corners); + arguments.emplace_back("scales_h", scales_h); + arguments.emplace_back("scales_w", scales_w); + + torch::lazy::TSOpVector upsample_bilinear2d_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(upsample_bilinear2d_out.size(), 1); + + return upsample_bilinear2d_out; + + } + + + ::std::vector output_size; + bool align_corners; + ::std::optional scales_h; + ::std::optional scales_w; + + +}; + +class UpsampleBilinear2dBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::upsample_bilinear2d_backward); + } + + UpsampleBilinear2dBackward(const torch::lazy::Value& grad_output, const ::std::vector& output_size, const ::std::vector& input_size, const bool& align_corners, const ::std::optional& scales_h, const ::std::optional& scales_w, std::vector&& shapes) + : TsNode( + UpsampleBilinear2dBackward::ClassOpKind(), + OpList{grad_output}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(output_size, input_size, align_corners, scales_h, scales_w)), + output_size(output_size), + input_size(input_size), + align_corners(align_corners), + scales_h(scales_h), + scales_w(scales_w) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", output_size=" << output_size; + ss << ", input_size=" << input_size; + ss << ", align_corners=" << align_corners; + if (scales_h.has_value()) { + ss << ", scales_h=" << scales_h.value(); + } else { + ss << ", scales_h=null"; + } + if (scales_w.has_value()) { + ss << ", scales_w=" << scales_w.value(); + } else { + ss << ", scales_w=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const ::std::vector& output_size, const ::std::vector& input_size, const bool& align_corners, const ::std::optional& scales_h, const ::std::optional& scales_w) const { + size_t i = 0; + return (operand(i++) == grad_output && + this->output_size == output_size && + this->input_size == input_size && + this->align_corners == align_corners && + ((!this->scales_h&&!scales_h) || (this->scales_h&&scales_h && *(this->scales_h) == *scales_h)) && + ((!this->scales_w&&!scales_w) || (this->scales_w&&scales_w && *(this->scales_w) == *scales_w))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(6); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("output_size", output_size); + arguments.emplace_back("input_size", input_size); + arguments.emplace_back("align_corners", align_corners); + arguments.emplace_back("scales_h", scales_h); + arguments.emplace_back("scales_w", scales_w); + + torch::lazy::TSOpVector upsample_bilinear2d_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(upsample_bilinear2d_backward_out.size(), 1); + + return upsample_bilinear2d_backward_out; + + } + + + ::std::vector output_size; + ::std::vector input_size; + bool align_corners; + ::std::optional scales_h; + ::std::optional scales_w; + + +}; + +class UpsampleNearest2d : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::upsample_nearest2d); + } + + UpsampleNearest2d(const torch::lazy::Value& self, const ::std::vector& output_size, const ::std::optional& scales_h, const ::std::optional& scales_w, std::vector&& shapes) + : TsNode( + UpsampleNearest2d::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(output_size, scales_h, scales_w)), + output_size(output_size), + scales_h(scales_h), + scales_w(scales_w) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", output_size=" << output_size; + if (scales_h.has_value()) { + ss << ", scales_h=" << scales_h.value(); + } else { + ss << ", scales_h=null"; + } + if (scales_w.has_value()) { + ss << ", scales_w=" << scales_w.value(); + } else { + ss << ", scales_w=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& output_size, const ::std::optional& scales_h, const ::std::optional& scales_w) const { + size_t i = 0; + return (operand(i++) == self && + this->output_size == output_size && + ((!this->scales_h&&!scales_h) || (this->scales_h&&scales_h && *(this->scales_h) == *scales_h)) && + ((!this->scales_w&&!scales_w) || (this->scales_w&&scales_w && *(this->scales_w) == *scales_w))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(4); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("output_size", output_size); + arguments.emplace_back("scales_h", scales_h); + arguments.emplace_back("scales_w", scales_w); + + torch::lazy::TSOpVector upsample_nearest2d_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(upsample_nearest2d_out.size(), 1); + + return upsample_nearest2d_out; + + } + + + ::std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + + +}; + +class UpsampleNearest2dBackward : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::upsample_nearest2d_backward); + } + + UpsampleNearest2dBackward(const torch::lazy::Value& grad_output, const ::std::vector& output_size, const ::std::vector& input_size, const ::std::optional& scales_h, const ::std::optional& scales_w, std::vector&& shapes) + : TsNode( + UpsampleNearest2dBackward::ClassOpKind(), + OpList{grad_output}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(output_size, input_size, scales_h, scales_w)), + output_size(output_size), + input_size(input_size), + scales_h(scales_h), + scales_w(scales_w) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", output_size=" << output_size; + ss << ", input_size=" << input_size; + if (scales_h.has_value()) { + ss << ", scales_h=" << scales_h.value(); + } else { + ss << ", scales_h=null"; + } + if (scales_w.has_value()) { + ss << ", scales_w=" << scales_w.value(); + } else { + ss << ", scales_w=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& grad_output, const ::std::vector& output_size, const ::std::vector& input_size, const ::std::optional& scales_h, const ::std::optional& scales_w) const { + size_t i = 0; + return (operand(i++) == grad_output && + this->output_size == output_size && + this->input_size == input_size && + ((!this->scales_h&&!scales_h) || (this->scales_h&&scales_h && *(this->scales_h) == *scales_h)) && + ((!this->scales_w&&!scales_w) || (this->scales_w&&scales_w && *(this->scales_w) == *scales_w))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(5); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("output_size", output_size); + arguments.emplace_back("input_size", input_size); + arguments.emplace_back("scales_h", scales_h); + arguments.emplace_back("scales_w", scales_w); + + torch::lazy::TSOpVector upsample_nearest2d_backward_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(upsample_nearest2d_backward_out.size(), 1); + + return upsample_nearest2d_backward_out; + + } + + + ::std::vector output_size; + ::std::vector input_size; + ::std::optional scales_h; + ::std::optional scales_w; + + +}; + +class ViewCopy : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::view_copy); + } + + ViewCopy(const torch::lazy::Value& self, const ::std::vector& size, std::vector&& shapes) + : TsNode( + ViewCopy::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(size)), + size(size) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", size=" << size; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const ::std::vector& size) const { + size_t i = 0; + return (operand(i++) == self && + this->size == size); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("size", size); + + torch::lazy::TSOpVector view_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(view_copy_out.size(), 1); + + return view_copy_out; + + } + + + ::std::vector size; + + +}; + +class ViewCopyDtype : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::view_copy); + } + + ViewCopyDtype(const torch::lazy::Value& self, const at::ScalarType& dtype, std::vector&& shapes) + : TsNode( + ViewCopyDtype::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash(dtype)), + dtype(dtype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dtype=" << dtype; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self, const at::ScalarType& dtype) const { + size_t i = 0; + return (operand(i++) == self && + this->dtype == dtype); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(2); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + arguments.emplace_back("dtype", dtype); + + torch::lazy::TSOpVector view_copy_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(view_copy_out.size(), 1); + + return view_copy_out; + + } + + + at::ScalarType dtype; + + +}; + +class Zero : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::zero); + } + + Zero(const torch::lazy::Value& self, std::vector&& shapes) + : TsNode( + Zero::ClassOpKind(), + OpList{self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash()) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& self) const { + size_t i = 0; + return (operand(i++) == self); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(0); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + + torch::lazy::TSOpVector zero_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(zero_out.size(), 1); + + return zero_out; + + } + + + + + +}; + +} // namespace lazy +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyNativeFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyNativeFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..82f63eb0acc9037329361360459e52f8eda6d55c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyNativeFunctions.h @@ -0,0 +1,216 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// an external backend might generate file within its code tree +// and check all the source files within the tree with clang-format. +// so, disable it since the backend might have a different config. +// clang-format off + +// Autogenerated file by gen_backend_stubs.py. Do not edit directly! + +#include + +namespace torch { +namespace lazy { + +struct LazyNativeFunctions { + +static ::std::tuple convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask); +static ::std::tuple native_batch_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps); +static ::std::tuple native_batch_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & running_mean, const ::std::optional & running_var, const ::std::optional & save_mean, const ::std::optional & save_invstd, bool train, double eps, ::std::array output_mask); +static ::std::tuple native_layer_norm(const at::Tensor & input, at::IntArrayRef normalized_shape, const ::std::optional & weight, const ::std::optional & bias, double eps); +static ::std::tuple native_layer_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const ::std::optional & weight, const ::std::optional & bias, ::std::array output_mask); +static ::std::tuple svd(const at::Tensor & self, bool some, bool compute_uv); +static ::std::tuple grid_sampler_2d_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array output_mask); +static ::std::tuple log_sigmoid_forward(const at::Tensor & self); +static ::std::tuple max(const at::Tensor & self, int64_t dim, bool keepdim); +static ::std::tuple max_pool2d_with_indices(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); +static ::std::tuple max_pool3d_with_indices(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); +static ::std::tuple native_dropout(const at::Tensor & input, double p, ::std::optional train); +static ::std::tuple nll_loss2d_forward(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index); +static ::std::tuple nll_loss_forward(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index); +static ::std::tuple sort(const at::Tensor & self, int64_t dim, bool descending); +static ::std::tuple topk(const at::Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted); +static at::Tensor & arange_out(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::Tensor & out); +static at::Tensor & fill_(at::Tensor & self, const at::Scalar & value); +static at::Tensor & logsumexp_out(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, at::Tensor & out); +static at::Tensor _adaptive_avg_pool2d(const at::Tensor & self, at::IntArrayRef output_size); +static at::Tensor _adaptive_avg_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self); +static at::Tensor _copy_from(const at::Tensor & self, const at::Tensor & dst, bool non_blocking); +static at::Tensor _copy_from_and_resize(const at::Tensor & self, const at::Tensor & dst); +static at::Tensor _log_softmax(const at::Tensor & self, int64_t dim, bool half_to_float); +static at::Tensor _log_softmax_backward_data(const at::Tensor & grad_output, const at::Tensor & output, int64_t dim, at::ScalarType input_dtype); +static at::Tensor _reshape_alias_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); +static at::Tensor _softmax(const at::Tensor & self, int64_t dim, bool half_to_float); +static at::Tensor _softmax_backward_data(const at::Tensor & grad_output, const at::Tensor & output, int64_t dim, at::ScalarType input_dtype); +static at::Tensor _to_copy(const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, bool non_blocking, ::std::optional memory_format); +static at::Tensor _trilinear(const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim); +static at::Tensor _unsafe_view(const at::Tensor & self, at::IntArrayRef size); +static at::Tensor abs(const at::Tensor & self); +static at::Tensor add(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha); +static at::Tensor addcdiv(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value); +static at::Tensor addcmul(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value); +static at::Tensor addmm(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha); +static at::Tensor alias_copy(const at::Tensor & self); +static at::Tensor all(const at::Tensor & self); +static at::Tensor any(const at::Tensor & self); +static at::Tensor as_strided_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset); +static at::Tensor as_strided_scatter_symint(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset); +static at::Tensor avg_pool2d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad, ::std::optional divisor_override); +static at::Tensor avg_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad, ::std::optional divisor_override); +static at::Tensor baddbmm(const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); +static at::Tensor bernoulli(const at::Tensor & self, ::std::optional generator); +static at::Tensor bernoulli(const at::Tensor & self, double p, ::std::optional generator); +static at::Tensor binary_cross_entropy(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction); +static at::Tensor binary_cross_entropy_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction); +static at::Tensor bitwise_and(const at::Tensor & self, const at::Tensor & other); +static at::Tensor bitwise_or(const at::Tensor & self, const at::Tensor & other); +static at::Tensor block_diag(at::TensorList tensors); +static at::Tensor bmm(const at::Tensor & self, const at::Tensor & mat2); +static at::Tensor cat(const at::ITensorListRef & tensors, int64_t dim); +static at::Tensor clamp(const at::Tensor & self, const ::std::optional & min, const ::std::optional & max); +static at::Tensor clamp_min(const at::Tensor & self, const at::Scalar & min); +static at::Tensor clone(const at::Tensor & self, ::std::optional memory_format); +static at::Tensor constant_pad_nd(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value); +static at::Tensor convolution(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups); +static at::Tensor cos(const at::Tensor & self); +static at::Tensor cumsum(const at::Tensor & self, int64_t dim, ::std::optional dtype); +static at::Tensor detach_copy(const at::Tensor & self); +static at::Tensor diag_embed(const at::Tensor & self, int64_t offset, int64_t dim1, int64_t dim2); +static at::Tensor diagonal_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2); +static at::Tensor diagonal_copy(const at::Tensor & self, int64_t offset, int64_t dim1, int64_t dim2); +static at::Tensor diagonal_scatter(const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2); +static at::Tensor div(const at::Tensor & self, const at::Tensor & other); +static at::Tensor div(const at::Tensor & self, const at::Tensor & other, ::std::optional rounding_mode); +static at::Tensor elu(const at::Tensor & self, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale); +static at::Tensor elu_backward(const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result); +static at::Tensor embedding(const at::Tensor & weight, const at::Tensor & indices, int64_t padding_idx, bool scale_grad_by_freq, bool sparse); +static at::Tensor embedding_dense_backward(const at::Tensor & grad_output, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +static at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +static at::Tensor empty_symint(c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); +static at::Tensor eq(const at::Tensor & self, const at::Scalar & other); +static at::Tensor eq(const at::Tensor & self, const at::Tensor & other); +static at::Tensor exp(const at::Tensor & self); +static at::Tensor expand_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size, bool implicit); +static at::Tensor flip(const at::Tensor & self, at::IntArrayRef dims); +static at::Tensor floor(const at::Tensor & self); +static at::Tensor frac(const at::Tensor & self); +static at::Tensor gather(const at::Tensor & self, int64_t dim, const at::Tensor & index, bool sparse_grad); +static at::Tensor ge(const at::Tensor & self, const at::Scalar & other); +static at::Tensor ge(const at::Tensor & self, const at::Tensor & other); +static at::Tensor gelu(const at::Tensor & self, c10::string_view approximate); +static at::Tensor gelu_backward(const at::Tensor & grad_output, const at::Tensor & self, c10::string_view approximate); +static at::Tensor glu(const at::Tensor & self, int64_t dim); +static at::Tensor glu_backward(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim); +static at::Tensor glu_jvp(const at::Tensor & glu, const at::Tensor & x, const at::Tensor & dx, int64_t dim); +static at::Tensor grid_sampler_2d(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners); +static at::Tensor gt(const at::Tensor & self, const at::Scalar & other); +static at::Tensor gt(const at::Tensor & self, const at::Tensor & other); +static at::Tensor hardsigmoid(const at::Tensor & self); +static at::Tensor index_select(const at::Tensor & self, int64_t dim, const at::Tensor & index); +static at::Tensor le(const at::Tensor & self, const at::Scalar & other); +static at::Tensor le(const at::Tensor & self, const at::Tensor & other); +static at::Tensor leaky_relu(const at::Tensor & self, const at::Scalar & negative_slope); +static at::Tensor leaky_relu_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result); +static at::Tensor lift(const at::Tensor & self); +static at::Tensor lift_fresh(const at::Tensor & self); +static at::Tensor linalg_pinv(const at::Tensor & self, const ::std::optional & atol, const ::std::optional & rtol, bool hermitian); +static at::Tensor log(const at::Tensor & self); +static at::Tensor log2(const at::Tensor & self); +static at::Tensor log_sigmoid_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & buffer); +static at::Tensor logdet(const at::Tensor & self); +static at::Tensor lt(const at::Tensor & self, const at::Scalar & other); +static at::Tensor lt(const at::Tensor & self, const at::Tensor & other); +static at::Tensor masked_fill(const at::Tensor & self, const at::Tensor & mask, const at::Scalar & value); +static at::Tensor masked_fill(const at::Tensor & self, const at::Tensor & mask, const at::Tensor & value); +static at::Tensor max(const at::Tensor & self); +static at::Tensor max_pool2d_with_indices_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, const at::Tensor & indices); +static at::Tensor max_pool3d_with_indices_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, const at::Tensor & indices); +static at::Tensor maximum(const at::Tensor & self, const at::Tensor & other); +static at::Tensor mean(const at::Tensor & self, ::std::optional dtype); +static at::Tensor mean(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, ::std::optional dtype); +static at::Tensor min(const at::Tensor & self); +static at::Tensor minimum(const at::Tensor & self, const at::Tensor & other); +static at::Tensor mm(const at::Tensor & self, const at::Tensor & mat2); +static at::Tensor mul(const at::Tensor & self, const at::Tensor & other); +static at::Tensor mv(const at::Tensor & self, const at::Tensor & vec); +static at::Tensor narrow_copy_symint(const at::Tensor & self, int64_t dim, c10::SymInt start, c10::SymInt length); +static at::Tensor native_dropout_backward(const at::Tensor & grad_output, const at::Tensor & mask, double scale); +static at::Tensor ne(const at::Tensor & self, const at::Scalar & other); +static at::Tensor ne(const at::Tensor & self, const at::Tensor & other); +static at::Tensor neg(const at::Tensor & self); +static at::Tensor new_empty_strided_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +static at::Tensor nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight); +static at::Tensor nll_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight); +static at::Tensor nonzero(const at::Tensor & self); +static at::Tensor norm(const at::Tensor & self, const ::std::optional & p, at::IntArrayRef dim, bool keepdim); +static at::Tensor normal_functional(const at::Tensor & self, double mean, double std, ::std::optional generator); +static at::Tensor permute_copy(const at::Tensor & self, at::IntArrayRef dims); +static at::Tensor pixel_shuffle(const at::Tensor & self, int64_t upscale_factor); +static at::Tensor pixel_unshuffle(const at::Tensor & self, int64_t downscale_factor); +static at::Tensor pow(const at::Tensor & self, const at::Scalar & exponent); +static at::Tensor pow(const at::Tensor & self, const at::Tensor & exponent); +static at::Tensor random(const at::Tensor & self, ::std::optional generator); +static at::Tensor random(const at::Tensor & self, int64_t from, ::std::optional to, ::std::optional generator); +static at::Tensor random(const at::Tensor & self, int64_t to, ::std::optional generator); +static at::Tensor reciprocal(const at::Tensor & self); +static at::Tensor relu(const at::Tensor & self); +static at::Tensor remainder(const at::Tensor & self, const at::Tensor & other); +static at::Tensor repeat(const at::Tensor & self, at::IntArrayRef repeats); +static at::Tensor rsqrt(const at::Tensor & self); +static at::Tensor scatter_add(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src); +static at::Tensor select_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt index); +static at::Tensor select_copy(const at::Tensor & self, int64_t dim, int64_t index); +static at::Tensor select_scatter(const at::Tensor & self, const at::Tensor & src, int64_t dim, int64_t index); +static at::Tensor sgn(const at::Tensor & self); +static at::Tensor sigmoid(const at::Tensor & self); +static at::Tensor sigmoid_backward(const at::Tensor & grad_output, const at::Tensor & output); +static at::Tensor silu(const at::Tensor & self); +static at::Tensor slice_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt start, c10::SymInt end, c10::SymInt step); +static at::Tensor slice_copy_symint(const at::Tensor & self, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step); +static at::Tensor slice_scatter_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step); +static at::Tensor smooth_l1_loss(const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta); +static at::Tensor smooth_l1_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta); +static at::Tensor softplus(const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold); +static at::Tensor softplus_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold); +static at::Tensor sqrt(const at::Tensor & self); +static at::Tensor squeeze_copy(const at::Tensor & self); +static at::Tensor squeeze_copy(const at::Tensor & self, at::IntArrayRef dim); +static at::Tensor squeeze_copy(const at::Tensor & self, int64_t dim); +static at::Tensor stack(at::TensorList tensors, int64_t dim); +static at::Tensor std(const at::Tensor & self, at::OptionalIntArrayRef dim, bool unbiased, bool keepdim); +static at::Tensor std(const at::Tensor & self, at::OptionalIntArrayRef dim, const ::std::optional & correction, bool keepdim); +static at::Tensor std(const at::Tensor & self, bool unbiased); +static at::Tensor sub(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha); +static at::Tensor sum(const at::Tensor & self, ::std::optional dtype); +static at::Tensor sum(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, ::std::optional dtype); +static at::Tensor t_copy(const at::Tensor & self); +static at::Tensor tanh(const at::Tensor & self); +static at::Tensor tanh_backward(const at::Tensor & grad_output, const at::Tensor & output); +static at::Tensor threshold(const at::Tensor & self, const at::Scalar & threshold, const at::Scalar & value); +static at::Tensor threshold_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & threshold); +static at::Tensor trace(const at::Tensor & self); +static at::Tensor transpose_copy(const at::Tensor & self, int64_t dim0, int64_t dim1); +static at::Tensor tril(const at::Tensor & self, int64_t diagonal); +static at::Tensor triu(const at::Tensor & self, int64_t diagonal); +static at::Tensor trunc(const at::Tensor & self); +static at::Tensor unfold_copy(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step); +static at::Tensor uniform(const at::Tensor & self, double from, double to, ::std::optional generator); +static at::Tensor unsqueeze_copy(const at::Tensor & self, int64_t dim); +static at::Tensor upsample_bilinear2d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w); +static at::Tensor upsample_bilinear2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w); +static at::Tensor upsample_nearest2d(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales_h, ::std::optional scales_w); +static at::Tensor upsample_nearest2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales_h, ::std::optional scales_w); +static at::Tensor view_copy(const at::Tensor & self, at::ScalarType dtype); +static at::Tensor view_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size); +static at::Tensor zero(const at::Tensor & self); +static ::std::tuple native_group_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, int64_t N, int64_t C, int64_t HxW, int64_t group, double eps); +static at::Tensor max_pool3d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); + +}; +} // namespace lazy +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyNonNativeIr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyNonNativeIr.h new file mode 100644 index 0000000000000000000000000000000000000000..4cea78933ef5fb0fe8fb8dea61f56825200d92bc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyNonNativeIr.h @@ -0,0 +1,160 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +// This file contains autogenerated LazyTensor Non Native IR nodes + +namespace torch { +namespace lazy { + +class Scalar : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::prim::Constant); + } + + Scalar(const at::Scalar& value, const at::ScalarType& type) + : TsNode( + Scalar::ClassOpKind(), + OpList{}, + compute_shape_scalar(value, type), + /* num_outputs */ 1, + torch::lazy::MHash(value, type)), + value(value), + type(type) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", value=" << value; + ss << ", type=" << type; + return ss.str(); + } + + + + bool CanBeReused(const at::Scalar& value, const at::ScalarType& type) const; + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override; + + at::Scalar value; + at::ScalarType type; + + +}; + +class Expand : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(at::aten::expand); + } + + Expand(const torch::lazy::Value& input, const ::std::vector& size, const bool& is_scalar_expand) + : TsNode( + Expand::ClassOpKind(), + OpList{input}, + [&](){ return compute_shape_expand(operand(0), size, is_scalar_expand)[0]; }, + /* num_outputs */ 1, + torch::lazy::MHash(size, is_scalar_expand)), + size(size), + is_scalar_expand(is_scalar_expand) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", size=" << size; + ss << ", is_scalar_expand=" << is_scalar_expand; + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& input, const ::std::vector& size, const bool& is_scalar_expand) const { + size_t i = 0; + return (operand(i++) == input && + this->size == size && + this->is_scalar_expand == is_scalar_expand); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override; + + ::std::vector size; + bool is_scalar_expand; + + +}; + +class Cast : public TsNode { + public: + static torch::lazy::OpKind ClassOpKind() { + return torch::lazy::OpKind(ltc_cast); + } + + Cast(const torch::lazy::Value& input, const at::ScalarType& dtype, const ::std::optional& stype) + : TsNode( + Cast::ClassOpKind(), + OpList{input}, + compute_shape_cast(input, dtype, stype), + /* num_outputs */ 1, + torch::lazy::MHash(dtype, stype)), + dtype(dtype), + stype(stype) + { + + } + + std::string ToString() const override { + std::stringstream ss; + ss << TsNode::ToString(); + ss << ", dtype=" << dtype; + if (stype.has_value()) { + ss << ", stype=" << stype.value(); + } else { + ss << ", stype=null"; + } + return ss.str(); + } + + + + bool CanBeReused(const torch::lazy::Value& input, const at::ScalarType& dtype, const ::std::optional& stype) const { + size_t i = 0; + return (operand(i++) == input && + this->dtype == dtype && + ((!this->stype&&!stype) || (this->stype&&stype && *(this->stype) == *stype))); + } + + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override; + + at::ScalarType dtype; + ::std::optional stype; + + +}; + +} // namespace lazy +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/python/init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/python/init.h new file mode 100644 index 0000000000000000000000000000000000000000..56e5f624fcff53187e799126003008a0d2874429 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/python/init.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::lazy { + +TORCH_PYTHON_API void initLazyBindings(PyObject* module); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/python/python_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/python/python_util.h new file mode 100644 index 0000000000000000000000000000000000000000..dc5777bb0f45af1f31d11fc08adb7f873f7bfe46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/python/python_util.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::lazy { + +std::optional TORCH_PYTHON_API GetPythonFrameTop(); + +std::vector TORCH_PYTHON_API GetPythonFrames(); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/config.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/config.h new file mode 100644 index 0000000000000000000000000000000000000000..0157b30fc7817ed9a74cca3ceb769db3a31b320b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/config.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +// TODO(whc) unclear if this is useful, has only been tested as true +TORCH_DECLARE_bool(torch_lazy_ts_tensor_update_sync); + +TORCH_DECLARE_bool(torch_lazy_ts_cuda); + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/dynamic_ir.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/dynamic_ir.h new file mode 100644 index 0000000000000000000000000000000000000000..4c42b0831100df2c145d7d5ddc0933f7c2085460 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/dynamic_ir.h @@ -0,0 +1,82 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +TORCH_DECLARE_bool(ltc_enable_dynamic_shapes); + +namespace torch::lazy { + +/** + * The goal of "dynamic" Nodes is to patch a hole in our tracing. + * Previously, if a user called `sizes` on a Tensor, it would leak out + * of our tracing system, as `sizes` returns a torch.Size or an int. To + * prevent this from happening, we introduce DimensionNode, a new type + * of Node that abstracts the operation of getting the dimensions of a + * Tensor. + * + * Consider the following example: + * ``` + * numel = x.shape()[0] * x.shape()[1] + * ``` + * + * Here, `x.shape()[i]` will be a SizeNode (subclass of DimensionNode), + * and the multiplication of the two SizeNodes will be represented by + * a SizeMul (also a subclass of DimensionNode). Through this, we can + * prevent `numel` from being represented as a Python int and thus + * burned into the Graph. + */ + +// Represents the result of calling `size` on a Tensor +class TORCH_API SizeNode : public TsNode, public DimensionNode { + public: + SizeNode(Value input, size_t dim); + int64_t getStaticValue() const override; + bool isSymbolic() const override; + std::string ToString() const override; + size_t dim_ = 0; + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + TSLoweringContext* loctx) const override; +}; + +class TORCH_API SizeAdd : public TsNode, public DimensionNode { + public: + SizeAdd(Value a, Value b); + int64_t getStaticValue() const override; + bool isSymbolic() const override; + std::string ToString() const override; +}; + +class TORCH_API SizeMul : public TsNode, public DimensionNode { + public: + SizeMul(Value a, Value b); + int64_t getStaticValue() const override; + bool isSymbolic() const override; + std::string ToString() const override; +}; + +class TORCH_API SizeDiv : public TsNode, public DimensionNode { + public: + SizeDiv(Value a, Value b); + int64_t getStaticValue() const override; + bool isSymbolic() const override; + std::string ToString() const override; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..7d8dd8c804cc68910334fc737043c58e90cc4ea0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h @@ -0,0 +1,74 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +struct TorchScriptIrBuilder : IrBuilder { + NodePtr MakeDeviceData( + const std::shared_ptr& data) const override { + return DeviceData::Create(data); + } + // TODO: Scalar node is not currently used by ts_backend. Enable reusing + // Scalar node later if needed. + NodePtr MakeScalar(const at::Scalar& value, const at::ScalarType& type) + const override { + return MakeNode(value, type); + } + NodePtr MakeExpand( + const Value& input0, + const std::vector& size, + const bool& is_scalar_expand) const override { + return ReuseOrMakeNode(input0, size, is_scalar_expand); + } + NodePtr MakeCast( + const Value& input0, + const at::ScalarType& dtype, + const std::optional& stype = + std::nullopt) const override { + return ReuseOrMakeNode(input0, dtype, stype); + } + NodePtr MakeTensorList(const OpList& inputs) const override { + return ReuseOrMakeNode(inputs); + } + // Generic needs cleanup + NodePtr MakeGeneric( + const OpKind& op, + const OpList& operands, + const Shape& shape, + const size_t& num_outputs = 1, + const hash_t& hash_seed = + static_cast(0x5a2d296e9)) const override { + return MakeNode(op, operands, shape, num_outputs, hash_seed); + } + + // dynamic ir nodes + // TODO: verify if IR node reusing works for Dynamic shape ops + NodePtr MakeSizeNode(const Value& input, size_t dim) const override { + return MakeNode(input, dim); + } + NodePtr MakeSizeAdd(const Value& a, const Value& b) const override { + return MakeNode(a, b); + } + NodePtr MakeSizeMul(const Value& a, const Value& b) const override { + return MakeNode(a, b); + } + NodePtr MakeSizeDiv(const Value& a, const Value& b) const override { + return MakeNode(a, b); + } +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/device_data.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/device_data.h new file mode 100644 index 0000000000000000000000000000000000000000..f258cf99c580b129f640070fd14839230a6f881f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/device_data.h @@ -0,0 +1,55 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace torch::lazy { + +class TORCH_API DeviceData : public TsNode { + public: + static OpKind ClassOpKind() { + return ltc_device_data; + } + + explicit DeviceData(std::shared_ptr data); + + // A DeviceData node can be reused if the shape matches, + // but we will substitute the actual data_ pointer under + // the hood. + bool CanBeReused(const std::shared_ptr& data) const { + return data_->shape() == data->shape(); + } + + std::string ToString() const override; + + const std::shared_ptr& data() const { + return data_; + } + + void SetData(std::shared_ptr data) { + data_ = std::move(data); + } + + static const DeviceData* Cast(const Node* node); + + // To reuse IR nodes, use this method to create DeviceData nodes + // instead of calling the constructor directconst ly. + static NodePtr Create(const std::shared_ptr& data); + + TSOpVector Lower( + std::shared_ptr function, + TSLoweringContext* loctx) const override; + + private: + std::shared_ptr data_; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/generic.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/generic.h new file mode 100644 index 0000000000000000000000000000000000000000..8334391a593aa80e966f057b94eb47b43834c03e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/generic.h @@ -0,0 +1,57 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::lazy { + +// Generic IR Node implementation for nodes which can simply be described by a +// specific OpKind and a lowering function. IR nodes carrying +// metadata should not be using this class TORCH_API (and have the metadata +// captured by the LowerFn), but they should instead create a dedicated IR node. +// Doing the former would limit IR introspection. +class TORCH_API Generic : public TsNode { + public: + Generic( + OpKind op, + OpList operands, + Shape shape, + size_t num_outputs = 1, + hash_t hash_seed = static_cast(0x5a2d296e9)); + + Generic( + OpKind op, + OpList operands, + const std::function& shape_fn, + size_t num_outputs = 1, + hash_t hash_seed = static_cast(0x5a2d296e9)); + + Generic( + OpKind op, + OpList operands, + size_t num_outputs = 1, + hash_t hash_seed = static_cast(0x5a2d296e9)); + + Generic(OpKind op, Shape shape, size_t num_outputs, hash_t hash_seed); + + private: + hash_t hash_seed_; +}; + +inline NodePtr GenericOp( + OpKind op, + OpList operands, + Shape shape, + size_t num_outputs = 1, + hash_t hash_seed = static_cast(0x5a2d296e9)) { + return MakeNode( + op, operands, std::move(shape), num_outputs, hash_seed); +} + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/to_copy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/to_copy.h new file mode 100644 index 0000000000000000000000000000000000000000..121cd0ffcbc99e5680c16e312013059d6dd5e74c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/to_copy.h @@ -0,0 +1,130 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::lazy { + +// This IR was copied from code-generated output, but the entire _to_copy +// operator cannot be trivially code generated since it is only desirable to +// capture IR for certain permutations of _to_copy (e.g. dtype), and for the +// others it is difficult to even invoke the aten/eager fallback necessitating +// directly implementing the right to(device) behavior +class ToCopy : public torch::lazy::TsNode { + public: + static OpKind ClassOpKind() { + return OpKind(at::aten::_to_copy); + } + + ToCopy( + const torch::lazy::Value& self, + const std::optional& dtype, + const std::optional& layout, + const std::optional& device, + const std::optional& pin_memory, + const bool& non_blocking, + const std::optional& memory_format, + std::vector&& shapes) + : torch::lazy::TsNode( + ClassOpKind(), + {self}, + std::move(shapes), + /* num_outputs */ 1, + torch::lazy::MHash( + dtype, + layout, + device, + pin_memory, + non_blocking, + memory_format)), + + dtype(dtype), + layout(layout), + device(device), + pin_memory(pin_memory), + non_blocking(non_blocking), + memory_format(memory_format) {} + + bool CanBeReused( + const torch::lazy::Value& self, + const std::optional& dtype, + const std::optional& layout, + const std::optional& device, + const std::optional& pin_memory, + const bool& non_blocking, + const std::optional& memory_format) const { + size_t i = 0; + return ( + operand(i++) == self && this->dtype == dtype && + this->layout == layout && this->device == device && + this->pin_memory == pin_memory && this->non_blocking == non_blocking && + this->memory_format == memory_format); + } + + std::string ToString() const override { + std::stringstream ss; + ss << torch::lazy::TsNode::ToString(); + if (dtype.has_value()) { + ss << ", dtype=" << dtype.value(); + } else { + ss << ", dtype=null"; + } + if (layout.has_value()) { + ss << ", layout=" << layout.value(); + } else { + ss << ", layout=null"; + } + if (device.has_value()) { + ss << ", device=" << device.value(); + } else { + ss << ", device=null"; + } + if (pin_memory.has_value()) { + ss << ", pin_memory=" << pin_memory.value(); + } else { + ss << ", pin_memory=null"; + } + ss << ", non_blocking=" << non_blocking; + if (memory_format.has_value()) { + ss << ", memory_format=" << memory_format.value(); + } else { + ss << ", memory_format=null"; + } + return ss.str(); + } + + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override { + std::vector arguments; + std::vector kwarguments; + arguments.reserve(1); + kwarguments.reserve(6); + size_t i = 0; + arguments.emplace_back(loctx->GetOutputOp(operand(i++))); + kwarguments.emplace_back("dtype", dtype); + kwarguments.emplace_back("layout", layout); + kwarguments.emplace_back("device", device); + kwarguments.emplace_back("pin_memory", pin_memory); + kwarguments.emplace_back("non_blocking", non_blocking); + kwarguments.emplace_back("memory_format", memory_format); + torch::lazy::TSOpVector _to_copy_out = + torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ(_to_copy_out.size(), 1); + + return _to_copy_out; + } + + std::optional dtype; + std::optional layout; + std::optional device; + std::optional pin_memory; + bool non_blocking; + std::optional memory_format; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/tensor_aten_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/tensor_aten_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b6d42fb70a08f6942e1a9c89ea387b0221878cb2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/tensor_aten_ops.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::lazy { + +////////////////////////////////////////////////////////////////////////////// +// ATEN operators follows here, listed in alphabetical order. +////////////////////////////////////////////////////////////////////////////// + +void copy_(torch::lazy::LazyTensorPtr& input, torch::lazy::LazyTensorPtr& src); +// Fills the input with the given value. +void fill_(torch::lazy::LazyTensorPtr& input, const at::Scalar& value); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_autograd_functions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_autograd_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..3d7ba8436e4923dac4fe138a1a90cb62b084b546 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_autograd_functions.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::lazy { + +struct MaxPool3dAutogradFunctionTS + : public torch::autograd::Function { + static at::Tensor forward( + torch::autograd::AutogradContext* ctx, + const at::Tensor& self, + at::IntArrayRef kernel_size, + at::IntArrayRef stride, + at::IntArrayRef padding, + at::IntArrayRef dilation, + bool ceil_mode); + static torch::autograd::variable_list backward( + torch::autograd::AutogradContext* ctx, + torch::autograd::variable_list grad_output); +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_backend_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_backend_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..d00d8f1812545994e00b2137df9cdc11c1cf20e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_backend_impl.h @@ -0,0 +1,57 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::lazy { + +class TORCH_API TSData : public torch::lazy::BackendData { + public: + TSData(const at::Scalar& scalar, const torch::lazy::BackendDevice& device) + : torch::lazy::BackendData(device, torch::lazy::Shape(scalar.type(), {})), + scalar(scalar) {} + + TSData( + at::Tensor data, + const torch::lazy::Shape& shape, + const torch::lazy::BackendDevice& device) + : torch::lazy::BackendData(device, shape), data_(std::move(data)) {} + + TSData( + const torch::lazy::Shape& shape, + const torch::lazy::BackendDevice& device) + : torch::lazy::BackendData(device, shape) {} + + Handle GetHandle() override { + return reinterpret_cast(this); + } + + void Assign(const torch::lazy::BackendData& data) override { + data_ = static_cast(data).data_; + } + + bool HasValue() const override { + return data_.defined(); + } + + at::Tensor data() { + return data_; + } + + std::optional scalar; + + private: + at::Tensor data_; +}; + +TORCH_API torch::lazy::BackendImplInterface* GetTSBackendImpl(); + +TORCH_PYTHON_API void InitTorchScriptBackend(); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_eager_fallback.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_eager_fallback.h new file mode 100644 index 0000000000000000000000000000000000000000..3cbf6f8a37d864acfe1f2be569a1b7cc436801fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_eager_fallback.h @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::lazy { + +bool force_eager_fallback(c10::Symbol op); +void ltc_eager_fallback( + const c10::OperatorHandle& op, + torch::jit::Stack* stack); + +void ts_eager_fallback( + const c10::OperatorHandle& op, + torch::jit::Stack* stack, + c10::DeviceType device_type); + +// The TorchScript backend does not register itself with pytorch dispatcher +// until it is explicitly initialized. This function should only be called +// by the main Torchscript backend init function. +void register_ts_ltc_eager_fallback(); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_lowering_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_lowering_context.h new file mode 100644 index 0000000000000000000000000000000000000000..3ab1b3191135cd0ef213962515cc264459f9f28b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_lowering_context.h @@ -0,0 +1,156 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +using TSOpVector = std::vector; + +class TORCH_API TSComputation : public Computation { + public: + TSComputation(const std::shared_ptr& graph) + : graph_(graph), graph_executor_(graph, "") { + for (torch::jit::Value* input : graph_->inputs()) { + parameter_names_.push_back(input->debugName()); + } + } + + int parameters_size() const override { + return static_cast(parameter_names_.size()); + } + + const std::vector& parameter_shapes() const override { + TORCH_CHECK( + false, "TODO(whc) implement TS computation shapes or change interface"); + return parameter_shapes_; + } + + const std::vector& parameter_names() const override { + return parameter_names_; + } + + const Shape& result_shape() const override { + TORCH_CHECK( + false, "TODO(whc) implement TS computation shapes or change interface"); + return result_shape_; + } + + const std::string to_string() const override { + std::ostringstream oss; + oss << *graph_; + return oss.str(); + } + + std::shared_ptr graph() const { + return graph_; + } + + torch::jit::GraphExecutor& graph_executor() { + return graph_executor_; + } + + private: + std::shared_ptr graph_; + torch::jit::GraphExecutor graph_executor_; + std::vector parameter_names_; + std::vector parameter_shapes_; + Shape result_shape_; +}; + +class TORCH_API TSLoweringContext : public LoweringContext { + public: + TSLoweringContext(const std::string& name, const BackendDevice device); + + TSLoweringContext( + const std::string& name, + BackendDevice device, + c10::ArrayRef post_order, + Util::EmissionMap emit_status); + + size_t AddResult(const Output& output) override { + return AddResult(GetOutputOp(output)); + } + + void AddParameter( + const torch::lazy::Output& output, + size_t index, + const Shape& shape, + const std::string& name) override { + TORCH_INTERNAL_ASSERT(false, "not implemented"); + } + + void Lower(const Node* node); + + ComputationPtr Build() override { + for (torch::jit::Value* output : root_tuple_) { + graph_->block()->registerOutput(output); + } + return std::make_shared(graph_); + } + + // Retrieves the lowered operation for an output. If the requested output is + // not available yet, the graph behind the output's Node is lowered, and the + // corresponding TS operation returned. + torch::jit::Value* GetOutputOp(const Output& output) { + auto it = emitted_outputs_.find(output); + if (it == emitted_outputs_.end()) { + auto post_order = Util::ComputePostOrder(output.node, &emit_status_); + for (auto node : post_order) { + Lower(node); + } + // At this point the output better be present, otherwise there is an issue + // with the lowering code. + it = emitted_outputs_.find(output); + TORCH_CHECK( + it != emitted_outputs_.end(), + "No TS operation emitted for output: ", + output.ToString()); + } + return it->second; + } + + // Assigns the given TS operation to the specified output. As outputs are + // lowered in a post-order fashion, later nodes should always find their + // operands among the emitted outputs. + void AssignOutputOp(const Output& output, torch::jit::Value* op); + + // If a parameter associated with data has already been declared, it will be + // returned. Otherwise a new one will be created, associated with the tensor + // held in data. + torch::jit::Value* GetParameter(const BackendDataPtr& data); + + std::shared_ptr graph() const { + return graph_; + } + + private: + struct Parameter { + torch::jit::Value* param{nullptr}; + size_t index = 0; + }; + + size_t AddResult(torch::jit::Value* op) { + root_tuple_.push_back(op); + return root_tuple_.size() - 1; + } + + std::shared_ptr graph_; + std::shared_ptr function_; + std::unordered_map parameters_map_; + std::vector root_tuple_; + OutputMap emitted_outputs_; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node.h new file mode 100644 index 0000000000000000000000000000000000000000..5efd7eed90acd7f260b9f9a64fd86819cc9fb6c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node.h @@ -0,0 +1,109 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { + +using TSOpVector = std::vector; + +class TORCH_API TsNode : public lazy::Node { + public: + TsNode( + OpKind op, + OpList operands, + std::vector&& shapes, + size_t num_outputs, + hash_t hash_seed = kHashSeed); + + TsNode( + OpKind op, + OpList operands, + const std::function& shape_fn, + size_t num_outputs, + hash_t hash_seed = kHashSeed); + + TsNode( + OpKind op, + OpList operands, + size_t num_outputs, + hash_t hash_seed = kHashSeed); + + TsNode( + OpKind op, + Shape shape, + size_t num_outputs, + hash_t hash_seed = kHashSeed); + + ~TsNode() override = default; + + hash_t hash() const override; + + hash_t shapeHash() const override; + + const std::string getPythonStacktrace() const; + + // Lower is a backend-specific method since it returns a backend specific + // type. hence, it is convenient to define it differently per-backend rather + // than at Node API + virtual TSOpVector Lower( + std::shared_ptr function, + TSLoweringContext* loctx) const; + + private: + // The hash of the dag WITH size info. Used for shape caching + hash_t shape_hash_; + // The hash of the dag used to look up the compiled graph by a hash + // in this case, we will use the dag hash WITHOUT size info if dynamic shape + // is enabled and use the dag hash WITH size info otherwise. + hash_t dag_hash_; +}; + +// Note: this OpKind is separate from ltc_ops.h since it would be a circular +// import otherwise, I like leaving TensorList in this file, and I think most of +// ltc_ops special cases will be deleted anyway +const OpKind tensor_list_opkind = OpKind::Get("lazy_tensors::tensor_list"); + +// TensorList represents an at::TensorList which is a vector[Tensor] but is also +// a first-class IValue and can be fed as a single input to a TS program. It is +// much easier to handle TensorLists in Lazy Tensor code if they are represented +// as a single Node so there can be more than one TensorList and more than one +// Tensor side-by-side as operands to an op. +// +// Note: shape is undefined for TensorList. We assert in some places that +// #shapes matches #outputs and this stems from +// the fact that currently all IR nodes represent tensors (there is no +// type system for this IR). Because of this, TensorList is a bit of a +// hack. +// +// TODO(whc) once Shape() API is moved to Node base, also make it virtual, and +// then implement it as NotImplemented for TensorList, also fixing the assertion +// that would fail. +struct TORCH_API TensorList : public TsNode { + static OpKind ClassOpKind() { + return tensor_list_opkind; + } + + TensorList() = delete; + TensorList(OpList values); + + bool CanBeReused(OpList values) const { + return operands() == std::vector(values.begin(), values.end()); + } + + TSOpVector Lower( + std::shared_ptr function, + TSLoweringContext* loctx) const override; +}; + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node_lowering.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node_lowering.h new file mode 100644 index 0000000000000000000000000000000000000000..37a11e964bb5e8e4eeaff374b8a5b7792c3502b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node_lowering.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::lazy { +using TSOpVector = std::vector; + +TORCH_API TSOpVector LowerTSBuiltin( + const std::shared_ptr& function, + c10::Symbol sym, + const std::vector& arguments, + const std::vector& kwarguments = {}); + +} // namespace torch::lazy + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/counters.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/counters.h new file mode 100644 index 0000000000000000000000000000000000000000..137c149ed6737e3484f6536a6dba0462c47f33ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/counters.h @@ -0,0 +1,285 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include + +#include + +namespace torch::monitor { + +constexpr int NUM_AGGREGATIONS = 7; + +// Aggregation is the list of possible aggregations for Stats. +// These use bitwise flags so they can be efficiently stored. +enum class C10_API_ENUM Aggregation { + // NONE means no aggregations are set. + NONE = 0, + // VALUE exports the most recently set value. + VALUE = 1, + // MEAN computes the mean of the set values within the window. Zero if no + // values. + MEAN = 2, + // COUNT tracks the number of times a value is set within the window. + COUNT = 3, + // SUM computes the sum of the values set within the window. + SUM = 4, + // MIN computes the minimum of the values set within the window. Zero if no + // values. + MAX = 5, + // MAX computes the maximum of the values set within the window. Zero if no + // values. + MIN = 6, +}; + +struct TORCH_API AggregationHash{template std::size_t operator()( + T t) const {return static_cast(t); +} // namespace torch::monitor +} +; + +// aggregationName returns the human readable name corresponding to the +// aggregation. +TORCH_API const char* aggregationName(Aggregation agg); + +template +class Stat; + +namespace { +template +inline std::bitset merge(T& list) { + std::bitset a; + for (Aggregation b : list) { + a.set(static_cast(b)); + } + return a; +} +} // namespace + +namespace detail { +void TORCH_API registerStat(Stat* stat); +void TORCH_API registerStat(Stat* stat); +void TORCH_API unregisterStat(Stat* stat); +void TORCH_API unregisterStat(Stat* stat); +} // namespace detail + +// Stat is used to compute summary statistics in a performant way over fixed +// intervals. Stat logs the statistics as an Event once every `windowSize` +// duration. When the window closes the stats are logged via the event handlers +// as a `torch.monitor.Stat` event. +// +// `windowSize` should be set to something relatively high to avoid a huge +// number of events being logged. Ex: 60s. Stat uses millisecond precision. +// +// If maxSamples is set, the stat will cap the number of samples per window by +// discarding `add` calls once `maxSamples` adds have occurred. If it's not set, +// all `add` calls during the window will be included. +// This is an optional field to make aggregations more directly comparable +// across windows when the number of samples might vary. +// +// Stats support double and int64_t data types depending on what needs to be +// logged and needs to be templatized with one of them. +// +// When the Stat is destructed it will log any remaining data even if the window +// hasn't elapsed. +template +class Stat { + private: + struct Values { + T value{0}; + T sum{0}; + T min{0}; + T max{0}; + int64_t count{0}; + }; + + public: + Stat( + std::string name, + std::initializer_list aggregations, + std::chrono::milliseconds windowSize, + int64_t maxSamples = std::numeric_limits::max()) + : name_(std::move(name)), + aggregations_(merge(aggregations)), + windowSize_(windowSize), + maxSamples_(maxSamples) { + detail::registerStat(this); + } + + Stat( + std::string name, + std::vector aggregations, + std::chrono::milliseconds windowSize, + int64_t maxSamples = std::numeric_limits::max()) + : name_(std::move(name)), + aggregations_(merge(aggregations)), + windowSize_(windowSize), + maxSamples_(maxSamples) { + detail::registerStat(this); + } + Stat(const Stat&) = delete; + Stat(Stat&&) = delete; + Stat& operator=(const Stat&) = delete; + Stat& operator=(Stat&&) = delete; + + virtual ~Stat() { + { + // on destruction log if there's unlogged data + std::lock_guard guard(mu_); + logLocked(); + } + detail::unregisterStat(this); + } + + // add adds the value v to the current window. + void add(T v) { + std::lock_guard guard(mu_); + maybeLogLocked(); + + if (alreadyLogged()) { + return; + } + + if (aggregations_.test(static_cast(Aggregation::VALUE))) { + current_.value = v; + } + if (aggregations_.test(static_cast(Aggregation::MEAN)) || + aggregations_.test(static_cast(Aggregation::SUM))) { + current_.sum += v; + } + + if (aggregations_.test(static_cast(Aggregation::MAX))) { + if (current_.max < v || current_.count == 0) { + current_.max = v; + } + } + if (aggregations_.test(static_cast(Aggregation::MIN))) { + if (current_.min > v || current_.count == 0) { + current_.min = v; + } + } + + current_.count += 1; + maybeLogLocked(); + } + + const std::string& name() const noexcept { + return name_; + } + + // count returns the number of items in the current open window. + int64_t count() noexcept { + std::lock_guard guard(mu_); + + return current_.count; + } + + std::unordered_map get() noexcept { + std::lock_guard guard(mu_); + return getLocked(); + } + + protected: + virtual uint64_t currentWindowId() const { + std::chrono::milliseconds now = + std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()); + + // always returns a currentWindowId of at least 1 to avoid 0 window issues + return (now / windowSize_) + 1; + } + + private: + bool alreadyLogged() { + return lastLoggedWindowId_ == currentWindowId(); + } + + void maybeLogLocked() { + auto windowId = currentWindowId(); + bool shouldLog = windowId_ != windowId || current_.count >= maxSamples_; + if (shouldLog && !alreadyLogged()) { + logLocked(); + lastLoggedWindowId_ = windowId_; + windowId_ = windowId; + } + } + + void logLocked() { + prev_ = current_; + current_ = Values(); + + // don't log event if there's no data + if (prev_.count == 0) { + return; + } + + Event e; + e.name = "torch.monitor.Stat"; + e.timestamp = std::chrono::system_clock::now(); + + auto stats = getLocked(); + e.data.reserve(stats.size()); + for (auto& kv : stats) { + std::stringstream key; + key << name_; + key << '.'; + key << aggregationName(kv.first); + e.data[key.str()] = kv.second; + } + + logEvent(e); + } + + std::unordered_map getLocked() + const noexcept { + std::unordered_map out; + out.reserve(aggregations_.count()); + + if (aggregations_.test(static_cast(Aggregation::VALUE))) { + out.emplace(Aggregation::VALUE, prev_.value); + } + if (aggregations_.test(static_cast(Aggregation::MEAN))) { + if (prev_.count == 0) { + out.emplace(Aggregation::MEAN, 0); + } else { + out.emplace(Aggregation::MEAN, prev_.sum / prev_.count); + } + } + if (aggregations_.test(static_cast(Aggregation::COUNT))) { + out.emplace(Aggregation::COUNT, prev_.count); + } + if (aggregations_.test(static_cast(Aggregation::SUM))) { + out.emplace(Aggregation::SUM, prev_.sum); + } + if (aggregations_.test(static_cast(Aggregation::MAX))) { + out.emplace(Aggregation::MAX, prev_.max); + } + if (aggregations_.test(static_cast(Aggregation::MIN))) { + out.emplace(Aggregation::MIN, prev_.min); + } + + return out; + } + + const std::string name_; + const std::bitset aggregations_; + + std::mutex mu_; + Values current_; + Values prev_; + + uint64_t windowId_{0}; + uint64_t lastLoggedWindowId_{0}; + const std::chrono::milliseconds windowSize_; + const int64_t maxSamples_; +}; +} // namespace torch::monitor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/events.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/events.h new file mode 100644 index 0000000000000000000000000000000000000000..320d63457f91c46c501bfc9c62d1e3aeb8624676 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/events.h @@ -0,0 +1,76 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::monitor { + +// data_value_t is the type for Event data values. +using data_value_t = std::variant; + +// Event represents a single event that can be logged out to an external +// tracker. This does acquire a lock on logging so should be used relatively +// infrequently to avoid performance issues. +struct TORCH_API Event { + // name is the name of the event. This is a static string that's used to + // differentiate between event types for programmatic access. The type should + // be in the format of a fully qualified Python-style class name. + // Ex: torch.monitor.MonitorEvent + std::string name; + + // timestamp is a timestamp relative to the Unix epoch time. + std::chrono::system_clock::time_point timestamp; + + // data contains rich information about the event. The contents are event + // specific so you should check the type to ensure it's what you expect before + // accessing the data. + // + // NOTE: these events are not versioned and it's up to the consumer of the + // events to check the fields to ensure backwards compatibility. + std::unordered_map data; +}; + +inline bool operator==(const Event& lhs, const Event& rhs) { + return lhs.name == rhs.name && lhs.timestamp == rhs.timestamp && + lhs.data == rhs.data; +} + +// EventHandler represents an abstract event handler that can be registered to +// capture events. Every time an event is logged every handler will be called +// with the events contents. +// +// NOTE: The handlers should avoid any IO, blocking calls or heavy computation +// as this may block the main thread and cause performance issues. +class TORCH_API EventHandler { + public: + virtual ~EventHandler() = default; + + // handle needs to be implemented to handle the events. This may be called + // from multiple threads so needs to be thread safe. + virtual void handle(const Event& e) = 0; +}; + +// logEvent calls each registered event handler with the event. This method can +// be called from concurrently from multiple threads. +TORCH_API void logEvent(const Event& e); + +// registerEventHandler registers an EventHandler so it receives any logged +// events. Typically an EventHandler will be registered during program +// setup and unregistered at the end. +TORCH_API void registerEventHandler(std::shared_ptr p); + +// unregisterEventHandler unregisters the event handler pointed to by the +// shared_ptr. +TORCH_API void unregisterEventHandler(const std::shared_ptr& p); + +} // namespace torch::monitor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/python_init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/python_init.h new file mode 100644 index 0000000000000000000000000000000000000000..bfe66eacb1ec44f7734a1ac71bfba64614e1d6a8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/python_init.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::monitor { + +void initMonitorBindings(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mps/Module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mps/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..f636e580b673f35d4e0fbbc7308c79f020d72bc5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mps/Module.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::mps { + +PyMethodDef* python_functions(); +void initModule(PyObject* module); + +} // namespace torch::mps + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/Module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..84259c7651ebceace7f29d7429e5e3217eba57a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/Module.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::mtia { + +// PyMethodDef* python_functions(); +void initModule(PyObject* module); + +} // namespace torch::mtia + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/profiler/MTIAMemoryProfiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/profiler/MTIAMemoryProfiler.h new file mode 100644 index 0000000000000000000000000000000000000000..b50d495618218335dd644f3da308eb59f28a9eac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/profiler/MTIAMemoryProfiler.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::mtia { +using namespace torch::profiler::impl::python_tracer; + +void initMemoryProfiler(); + +std::unique_ptr getMemoryTracer(); + +class MTIAMemoryProfiler final : public PythonMemoryTracerBase { + public: + explicit MTIAMemoryProfiler() = default; + ~MTIAMemoryProfiler() override = default; + void start() override; + void stop() override; + void export_memory_history(const std::string& path) override; +}; + +} // namespace torch::mtia + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/multiprocessing/init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/multiprocessing/init.h new file mode 100644 index 0000000000000000000000000000000000000000..1800ffa2ce1dd605a0daae7e707516920537060f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/multiprocessing/init.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::multiprocessing { + +const PyMethodDef* python_functions(); + +} // namespace torch::multiprocessing + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/back_compat.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/back_compat.h new file mode 100644 index 0000000000000000000000000000000000000000..5132fe262ac095863a64efb85bf0358dbde14e35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/back_compat.h @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::onnx { + +// The following constants are defined here to avoid breaking Meta's internal +// usage of ONNX which pre-dates ONNX 1.14 and thus does not support FLOAT8: +// cf. https://github.com/pytorch/pytorch/pull/106379#issuecomment-1675189340 +// -abock, 2023-08-25 +// +// ::ONNX_NAMESPACE::TensorProto_DataType_FLOAT8E4M3FN +constexpr auto TensorProto_DataType_FLOAT8E4M3FN = + static_cast<::ONNX_NAMESPACE::TensorProto_DataType>(17); +// ::ONNX_NAMESPACE::TensorProto_DataType_FLOAT8E4M3FNUZ +constexpr auto TensorProto_DataType_FLOAT8E4M3FNUZ = + static_cast<::ONNX_NAMESPACE::TensorProto_DataType>(18); +// ::ONNX_NAMESPACE::TensorProto_DataType_FLOAT8E5M2 +constexpr auto TensorProto_DataType_FLOAT8E5M2 = + static_cast<::ONNX_NAMESPACE::TensorProto_DataType>(19); +// ::ONNX_NAMESPACE::TensorProto_DataType_FLOAT8E5M2FNUZ +constexpr auto TensorProto_DataType_FLOAT8E5M2FNUZ = + static_cast<::ONNX_NAMESPACE::TensorProto_DataType>(20); + +} // namespace torch::onnx + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/init.h new file mode 100644 index 0000000000000000000000000000000000000000..4c451df8c9e5f9af3b5ece63f82e9c93cdd785ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/init.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::onnx { + +void initONNXBindings(PyObject* module); + +} // namespace torch::onnx + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/onnx.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..6a5eb189134d0eaac3e056b939ef8cf539edb8d9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/onnx.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::onnx { + +enum class OperatorExportTypes { + ONNX, // Strict ONNX export + ONNX_ATEN, // ONNX With ATen op everywhere + ONNX_ATEN_FALLBACK, // ONNX export with ATen fallback + ONNX_FALLTHROUGH, // Export supported ONNX ops. Pass through unsupported ops. +}; + +enum class TrainingMode { + EVAL, // Inference mode + PRESERVE, // Preserve model state (eval/training) + TRAINING, // Training mode +}; + +constexpr auto kOnnxNodeNameAttribute = "onnx_name"; + +} // namespace torch::onnx + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/api.h new file mode 100644 index 0000000000000000000000000000000000000000..02514ee197c4cacafa6b324da402be8ed4504787 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/api.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// There are some components which use these symbols. Until we migrate them +// we have to mirror them in the old autograd namespace. + +namespace torch::autograd::profiler { +using torch::profiler::impl::ActivityType; +using torch::profiler::impl::getProfilerConfig; +using torch::profiler::impl::ProfilerConfig; +using torch::profiler::impl::profilerEnabled; +using torch::profiler::impl::ProfilerState; +} // namespace torch::autograd::profiler + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/collection.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/collection.h new file mode 100644 index 0000000000000000000000000000000000000000..9156463cd066b05c998e5f9261aa889d85a0244f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/collection.h @@ -0,0 +1,715 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::profiler::impl { + +enum class EventType : uint8_t { + TorchOp = 0, + Backend, + Vulkan, + Allocation, + OutOfMemory, + PyCall, + PyCCall, + Kineto, + PythonGC +}; + +// ============================================================================ +// == Value (Tensor, Scalar) summary ========================================== +// ============================================================================ +struct TORCH_API RawTensorMetadataBase { + RawTensorMetadataBase() = default; + explicit RawTensorMetadataBase(const at::Tensor& t); + + StorageImplData data_; + c10::ScalarType dtype_{c10::ScalarType::Undefined}; + c10::Layout layout_{c10::Layout::Strided}; + uint32_t size_dim_{0}; +}; + +// Collected during profiling. +struct TORCH_API RawTensorMetadata : RawTensorMetadataBase { + RawTensorMetadata() = default; + RawTensorMetadata(const RawTensorMetadata&) = default; + RawTensorMetadata(RawTensorMetadata&&) noexcept = default; + RawTensorMetadata& operator=(const RawTensorMetadata&) = default; + RawTensorMetadata& operator=(RawTensorMetadata&&) noexcept = default; + ~RawTensorMetadata() = default; + explicit RawTensorMetadata(const at::Tensor& t); + + // Wrap `weak_self_` in `std::optional` and split device into components to + // keep struct default constructable. (which the std::array initializer needs) + std::optional weak_self_; + c10::DeviceType device_type_{c10::DeviceType::CPU}; + c10::DeviceIndex device_index_{-1}; +}; + +// Used during post processing. +struct TORCH_API TensorMetadata : public RawTensorMetadataBase { + TensorMetadata( + const RawTensorMetadata& r, + std::vector sizes, + std::vector strides); + + TensorImplAddress impl() const { + return weak_self_.get(); + } + + WeakTensor weak_self_; + c10::Device device_; + std::vector sizes_; + std::vector strides_; + + // Set during `calculateUniqueTensorIDs`. + std::optional id_; + std::optional allocation_id_; +}; + +// Used during post processing. +struct TORCH_API ProfilerStepInfo { + int64_t start_time_ns; // start time of the profiler step + int64_t end_time_ns; // end time of the profiler step + uint64_t out_idx; // index of the profiler step in the profiler "out" var in + // getRecords + + ProfilerStepInfo(int64_t start, int64_t end, uint64_t out_idx) + : start_time_ns(start), end_time_ns(end), out_idx(out_idx) {} +}; + +using op_input_t = std::variant< + TensorMetadata, + std::vector, + c10::IValue, + std::nullopt_t>; + +// ============================================================================ +// == ExtraFields ============================================================= +// ============================================================================ +template +struct ExtraFields; + +struct TorchOpBasicFields { + int64_t sequence_number_{0}; + uint64_t forward_tid_{0}; + at::RecordScope scope_{}; + bool is_async_{false}; + uint64_t record_function_id_{0}; + int64_t debug_handle_{0}; + std::string name_; + std::string overload_name_; + + // Set in the exit callback. + uint64_t end_tid_{0}; +}; + +using jit_stack_t = std::vector; +using jit_modules_t = std::vector; +using extra_args_t = std::unordered_map; +using extra_meta_t = std::unordered_map; +using kwinputs_t = std::unordered_map; + +struct FallbackPair { + ProfilerVoidEventStub device_event_start_ = nullptr; + ProfilerVoidEventStub device_event_end_ = nullptr; +}; + +template <> +struct ExtraFields : TorchOpBasicFields { + ExtraFields( + TorchOpBasicFields&& f, + uint64_t correlation_id, + c10::time_t end_time_ns, + std::vector&& inputs, + std::vector&& concrete_inputs, + jit_stack_t&& jit_stack, + jit_modules_t&& jit_modules, + extra_args_t&& extra_args, + extra_meta_t&& extra_meta, + kwinputs_t&& kwinputs, + FallbackPair&& device_fallback, + bool allow_tf32_cublas, + std::unique_ptr&& perf_event_counters) + : TorchOpBasicFields(std::move(f)), + correlation_id_{correlation_id}, + end_time_ns_{end_time_ns}, + inputs_{std::move(inputs)}, + concrete_inputs_{std::move(concrete_inputs)}, + jit_stack_{std::move(jit_stack)}, + jit_modules_{std::move(jit_modules)}, + extra_args_{std::move(extra_args)}, + extra_meta_{std::move(extra_meta)}, + kwinputs_{std::move(kwinputs)}, + device_fallback_{std::move(device_fallback)}, + allow_tf32_cublas_{allow_tf32_cublas}, + perf_event_counters_{std::move(perf_event_counters)} {} + uint64_t correlation_id_; + c10::time_t end_time_ns_; + std::vector inputs_; + std::vector concrete_inputs_; + jit_stack_t jit_stack_; + jit_modules_t jit_modules_; + extra_args_t extra_args_; + extra_meta_t extra_meta_; + kwinputs_t kwinputs_; + FallbackPair device_fallback_; + bool allow_tf32_cublas_; + std::unique_ptr perf_event_counters_; + std::string metadata_json_; +}; + +template <> +struct ExtraFields { + int64_t start_time_us_; + int64_t end_time_us_; + int64_t debug_handle_; + at::RecordScope scope_; + std::string name_; + std::string backend_; + jit_stack_t jit_stack_; + jit_modules_t jit_modules_; +}; + +template <> +struct ExtraFields { + std::string phase; + int64_t duration_ns_; +}; + +template <> +struct ExtraFields { + using raw_event_t = std::pair; + std::string name_; + int64_t duration_ns_{0}; + // While building the event tree, we want to report a vulkan event's duration + // as 0 so that its end time doesn't exceed that of its parent cpu op + bool in_tree_building_{false}; +}; + +struct RawAllocation { + c10::approx_time_t start_time_; + void* ptr_; + int64_t alloc_size_; + size_t total_allocated_; + size_t total_reserved_; + c10::DeviceType device_type_; + c10::DeviceIndex device_index_; +}; + +// For performance. +static_assert( + std::is_trivial_v, + "Non-Trivial member of RawAllocation."); + +template <> +struct ExtraFields : RawAllocation { + ExtraFields(const RawAllocation& allocation) : RawAllocation(allocation) {} + + c10::Device device() const { + return {device_type_, device_index_}; + } + + std::optional id_; + std::optional allocation_id_; +}; + +template <> +struct ExtraFields { + c10::approx_time_t start_time_; + int64_t alloc_size_; + size_t total_allocated_; + size_t total_reserved_; + c10::DeviceType device_type_; + c10::DeviceIndex device_index_; +}; + +// For performance. +static_assert( + std::is_trivial_v>, + "Non-Trivial member of ExtraFields."); + +struct PyFrameState { + int line_no_; + at::StringView filename_; + at::StringView funcname_; +}; + +template +using strong_t = strong:: + type, strong::hashable>; + +using PyModuleSelf = strong_t; +using PyModuleCls = strong_t; +using PyMethod = strong_t; +using PyOptimizerSelf = strong_t; +using PyOptimizerCls = strong_t; + +struct NNModuleInfo { + struct ParameterInfo { + std::string name_; + TensorMetadata metadata_; + std::optional grad_metadata_; + }; + + PyModuleSelf self_; + PyModuleCls cls_; + at::StringView cls_name_; + + std::vector parameters_; + // Indicates that `self_` is the kth instance of `cls_` observed. + size_t id_{std::numeric_limits::max()}; +}; + +struct OptimizerInfo { + struct ParameterInfo { + TensorMetadata metadata_; + std::optional grad_metadata_; + std::vector> state_; + }; + + PyOptimizerSelf self_; + PyOptimizerCls cls_; + at::StringView cls_name_; + + std::vector parameters_; +}; + +struct PyExtraFieldsBase { + PyExtraFieldsBase( + c10::time_t end_time_ns, + size_t python_tid, + PyFrameState caller) + : end_time_ns_{end_time_ns}, + python_tid_{python_tid}, + caller_{std::move(caller)} {} + + c10::time_t end_time_ns_; + size_t python_tid_; + PyFrameState caller_; + + // kth python event observed. (Used by TensorBoard) + size_t id_{std::numeric_limits::max()}; +}; + +template <> +struct ExtraFields : public PyExtraFieldsBase { + struct args_t { + PyFrameState frame_state_; + std::optional module_info_; + std::optional optimizer_info_; + }; + + ExtraFields( + c10::time_t end_time_ns, + size_t python_tid, + PyFrameState caller, + args_t args) + : PyExtraFieldsBase(end_time_ns, python_tid, std::move(caller)), + callsite_{std::move(args.frame_state_)}, + module_{std::move(args.module_info_)}, + optimizer_{std::move(args.optimizer_info_)} {} + + PyFrameState callsite_; + std::optional module_; + std::optional optimizer_; +}; + +template <> +struct ExtraFields : public PyExtraFieldsBase { + using args_t = at::StringView; + + ExtraFields( + c10::time_t end_time_ns, + size_t python_tid, + PyFrameState caller, + args_t args) + : PyExtraFieldsBase(end_time_ns, python_tid, std::move(caller)), + function_name_{std::move(args)} {} + + at::StringView function_name_; +}; + +template <> +struct ExtraFields { + // Mirrors `libkineto::GenericTraceActivity::Flow`. This information is used + // during post processing to properly embed Kineto events into the broader + // profiler tree structure. End users are not generally expected to use these + // fields directly, but they are available for debugging. + struct Flow { + uint32_t id{0}; + uint32_t type{0}; + uint32_t start{0}; + }; + + std::string name_; + int64_t duration_ns_{0}; + uint64_t correlation_id_{0}; + libkineto::ActivityType activity_type_; + Flow flow; + std::weak_ptr linked_activity_; + std::string metadata_json_; +}; + +struct TORCH_API Result : public std::enable_shared_from_this { + template + [[nodiscard]] static std::shared_ptr create(Args... args) { + return std::shared_ptr(new Result(std::forward(args)...)); + } + + template + auto visit(T&& visitor) { + return std::visit(std::forward(visitor), extra_fields_); + } + + template + auto visit(T&& visitor) const { + return std::visit(std::forward(visitor), extra_fields_); + } + + template + void visit_if_base(const Fn& fn) const { + visit([&](const auto& extra_fields) { + using extra_fields_t = typename std::remove_cv_t< + typename std::remove_reference_t>; + + if constexpr (std::is_base_of_v) { + fn(extra_fields); + } + }); + } + + EventType tag() const { + return visit([](const auto& i) { return deduceTag(i); }); + } + + std::string name() const; + std::string overload_name() const; + libkineto::ActivityType kinetoType() const; + uint64_t correlationID() const; + int64_t endTimeNS() const; + uint64_t endTID() const; + c10::DeviceType deviceType() const; + + int64_t start_time_ns_; + uint64_t start_tid_; + kineto::DeviceAndResource kineto_info_; + std::variant< + ExtraFields, + ExtraFields, + ExtraFields, + ExtraFields, + ExtraFields, + ExtraFields, + ExtraFields, + ExtraFields, + ExtraFields> + extra_fields_; + + std::weak_ptr parent_; + std::vector> children_; + bool finished_{false}; + bool hidden_{false}; + const torch::profiler::impl::kineto::activity_t* kineto_activity_{nullptr}; + + private: + template + Result( + int64_t start_time_ns, + uint64_t start_tid, + kineto::DeviceAndResource kineto_info, + ExtraFields&& extra_fields) + : start_time_ns_{start_time_ns}, + start_tid_{start_tid}, + kineto_info_{kineto_info}, + extra_fields_{std::move(extra_fields)} {} + + template + static EventType deduceTag(const ExtraFields& /*unused*/) { + return E; + } +}; + +struct KinetoObserverContext : public at::ObserverContext { + struct Event { + TorchOpBasicFields basic_fields_; + c10::approx_time_t start_time_; + + // Set in the exit callback. + c10::approx_time_t end_time_{ + std::numeric_limits::min()}; + + bool allow_tf32_cublas_; + std::unique_ptr counters_; + extra_meta_t* extra_nccl_meta_{}; + }; + + explicit KinetoObserverContext(Event* event) : event_{event} {} + + Event* event_; + FallbackPair* fallback_{nullptr}; +}; + +constexpr int IO_ENCODER_DEFAULT_BLOCK_SIZE = 1024; + +constexpr int SCALAR_LIST_LENGTH_LIMIT = 30; + +// InputOutputEncoder +// Stores each op_events' shapes and dtypes, and concrete values into a +// contiguous AppendOnlyList so that we no longer create vectors for shapes +// and dtypes on every op. Those vectors can be created during +// post-processing. +// It splits the data into two categories: input shapes and concrete inputs. +class InputOutputEncoder final { + public: + void push(c10::ArrayRef values); + + // Used during post-processing to unpack the encoded data. + // Each method returns a "supplier" lambda which takes no arguments; + // invoking the lambda once will return a list of args that represent + // the inputs for one op. + // The data is split into two streams: "input shapes" and "concrete inputs". + // Note: "auto" only works because these are only used in collection.cpp, + // where they are implemented. + auto getInputShapeGenerator(); + auto getConcreteInputGenerator(); + + bool isSupportedScalarList(const c10::IValue& list_candidate); + + void clear(); + + enum class Tag { + Tensor = 0, + UndefinedTensor, + TensorListBegin, // TODO: generalize to other lists. + ScalarList, + Scalar, + Other, + TERMINATOR + }; + + enum class IOType { Shapes, ConcreteInputs, None }; + + private: + void push(const at::Tensor& t); + + // Implementation detail for getInputShapeGenerator and + // getConcreteInputGenerator + auto getIValueGenerator(const IOType& io_type); + + AppendOnlyList tags_; + AppendOnlyList + tensor_metadata_; + AppendOnlyList tensor_sizes_strides_; + AppendOnlyList ivalues_; +}; + +using perf_profiler_t = torch::profiler::impl::linux_perf::PerfProfiler; + +class TORCH_API ThreadLocalSubqueue { + public: + ThreadLocalSubqueue(const uint64_t tid, ProfilerConfig config); + + std::unique_ptr begin_op(const at::RecordFunction& fn); + + template + void emplace_backend_event(Args&&... args) { + backend_events_.emplace_back(std::forward(args)...); + } + + template + void emplace_vulkan_event(Args&&... args) { + vulkan_events_.emplace_back(std::forward(args)...); + } + + template + void emplace_allocation_event(Args&&... args) { + allocations_.emplace_back(std::forward(args)...); + } + + template + void emplace_ooms_event(Args&&... args) { + ooms_.emplace_back(std::forward(args)...); + } + + template + void emplace_py_call(Args&&... args) { + py_calls_.emplace_back(std::forward(args)...); + } + + template + void emplace_gc_call(Args&&... args) { + pythongc_.emplace_back(std::forward(args)...); + } + + uint64_t tid() const { + return tid_; + } + + const kineto::DeviceAndResource& kineto_info() const { + return kineto_info_; + } + + inline void disable_perf_profiler(perf_counters_t& counters) const { + perf_profiler_->Disable(counters); + } + + private: + uint64_t tid_; + ProfilerConfig config_; + kineto::DeviceAndResource kineto_info_; + std::unique_ptr perf_profiler_; + + friend class RecordQueue; + // See `containers.h` for block size benchmarks. + static constexpr size_t BlockSize = 512; + + struct TorchOpStorage { + // NB: This is a destructive operation. + void materialize( + std::vector>& out, + std::vector& step_info, + const std::function& time_converter, + const uint64_t tid, + const kineto::DeviceAndResource& kineto_info); + + template + class EventBlock : public std::array { + public: + EventBlock(); + uint64_t correlation_id(const T* ptr) const; + + private: + uint64_t id_start_; + }; + + using event_t = KinetoObserverContext::Event; + class OpList : public AppendOnlyList { + public: + template + std::pair emplace_back(Args&&... args); + static uint64_t correlationID(const OpList::Iterator& e); + } op_events_; + + // report_input_shapes + InputOutputEncoder inputs_outputs_; + + // with_stack (JIT) + AppendOnlyList jit_stack_; + + // with_modules + AppendOnlyList jit_modules_; + + // with_flops + AppendOnlyList extra_args_; + + // report extra metadata, i.e. collective communication meta + AppendOnlyList extra_meta_; + + // report kwinputs + AppendOnlyList kwinputs_; + + // ProfilerState::KINETO_GPU_FALLBACK or + // ProfilerState::KINETO_PRIVATEUSE1_FALLBACK + AppendOnlyList device_fallback_; + } torch_ops_; + + // reportBackendEventToActiveKinetoProfiler + AppendOnlyList, BlockSize> backend_events_; + + // _reportVulkanEventToProfiler + AppendOnlyList::raw_event_t, BlockSize> + vulkan_events_; + + // reportMemoryUsage + AppendOnlyList allocations_; + + // reportOOMs + AppendOnlyList, BlockSize> ooms_; + + // with_stack (Python) + AppendOnlyList< + std::pair, + BlockSize> + py_calls_; + // gc with_stack (Python) + AppendOnlyList, BlockSize> + pythongc_; +}; + +class TORCH_API RecordQueue { + public: + RecordQueue(ProfilerConfig config, std::set activities); + + bool tracePython() const; + bool getPythonGcEvents() const; + ThreadLocalSubqueue* getSubqueue(); + void stop(); + void restart(); + + // NB: This is a destructive operation. + std::pair< + std::vector>, + std::unique_ptr> + getRecords( + std::function time_converter, + uint64_t start_time_ns, + uint64_t end_time_ns); + + private: + uint32_t id_; + ProfilerConfig config_; + std::set activities_; + ska::flat_hash_map> + sub_queues_; + std::mutex sub_queue_mutex_; + std::unique_ptr python_tracer_; +}; + +TORCH_API bool get_record_concrete_inputs_enabled(); +TORCH_API void set_record_concrete_inputs_enabled_fn( + std::function /*fn*/); +TORCH_API void set_record_concrete_inputs_enabled_val(bool /*val*/); + +TORCH_API bool get_fwd_bwd_enabled(); +TORCH_API void set_fwd_bwd_enabled_fn(std::function /*fn*/); +TORCH_API void set_fwd_bwd_enabled_val(bool /*val*/); + +TORCH_API bool get_cuda_sync_enabled(); +TORCH_API void set_cuda_sync_enabled_fn(std::function /*fn*/); +TORCH_API void set_cuda_sync_enabled_val(bool /*val*/); + +// Comms related RecordFunctions will record information about tensor storage +// locations. +TORCH_API bool get_record_tensor_addrs_enabled(); +TORCH_API void set_record_tensor_addrs_enabled_fn(std::function /*fn*/); +TORCH_API void set_record_tensor_addrs_enabled_val(bool /*val*/); + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/combined_traceback.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/combined_traceback.h new file mode 100644 index 0000000000000000000000000000000000000000..a9d80eddc31f7a142ef93c3b15c65d2cf79a4d26 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/combined_traceback.h @@ -0,0 +1,81 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch { + +// struct that holds the result of symbolizing multiple tracebacks +// each traceback is a list of indices into all_frames +// (lots of Frames get duplicated across traces) +struct TORCH_API SymbolizedTracebacks { + std::vector all_frames; + // index into all_frames, so that + // it is possible to dedupe frame objects in + // construction of python objects + std::vector> tracebacks; +}; + +struct TORCH_API CapturedTraceback : public c10::GatheredContext { + struct PyFrame { + void* code; // PyCodeObject*, but python headers not present + int lasti; + }; + + static std::shared_ptr gather( + bool python, + bool script, + bool cpp); + CapturedTraceback() = default; + CapturedTraceback(const CapturedTraceback&) = delete; + CapturedTraceback& operator=(const CapturedTraceback&) = delete; + CapturedTraceback(CapturedTraceback&&) noexcept = default; + CapturedTraceback& operator=(CapturedTraceback&&) noexcept = delete; + ~CapturedTraceback() override; + + using visitproc = int (*)(void* self, void* arg); + + struct Python { + virtual std::vector gather() = 0; + virtual void release(std::vector& frames) = 0; + virtual void appendSymbolized( + const std::vector& to_symbolize, + SymbolizedTracebacks& st) = 0; + // tp_traverse/tp_clear implementations + virtual int traverse( + std::vector& frames, + visitproc visit, + void* arg) = 0; + virtual int clear(std::vector& frames) = 0; + virtual ~Python() = default; + Python* next_ = nullptr; + }; + // called once by each python interpreter to + // register python stack recording functionality + // p cannot be deleted once added. + static void addPythonUnwinder(Python* p); + + int traversePython(visitproc visit, void* arg); + int clearPython(); + + private: + std::vector frames_; + std::vector cpp_frames_; + std::vector script_frames_; + friend TORCH_API SymbolizedTracebacks + symbolize(const std::vector& to_symbolize); + + // non-owning reference to one of the immortal Python* objects + // registered above. + Python* python_ = nullptr; +}; + +TORCH_API SymbolizedTracebacks +symbolize(const std::vector& to_symbolize); + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/containers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/containers.h new file mode 100644 index 0000000000000000000000000000000000000000..49c872babfc71e7edd119d15c359877962304717 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/containers.h @@ -0,0 +1,208 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::profiler::impl { + +// ============================================================================ +// == AppendOnlyList ========================================================== +// ============================================================================ +// During profiling, we have a very predictable access pattern: we only +// append to the end of the container. We can specialize and outperform both +// std::vector (which must realloc) and std::deque (which performs a double +// indirection), and this class of operation is sufficiently important to the +// profiling hot path to warrant specializing: +// https://godbolt.org/z/rTjozf1c4 +// https://quick-bench.com/q/mmfuu71ogwaiULDCJyHdKnHZms4 (Prototype #1, +// int) https://quick-bench.com/q/5vWDW6jjdXVdoffev2zst8D09no (Prototype +// #1, int pair) https://quick-bench.com/q/IfEkfAQMeJSNBA52xtMP6Agcl-Q +// (Prototype #2, int pair) +// https://quick-bench.com/q/wJV2lKmuXL4XyGJzcI5hs4gEHFg (Prototype #3, int +// pair) https://quick-bench.com/q/xiO8ZaBEkYRYUA9dFrMuPLlW9fo (Full impl, +// int pair) +// AppendOnlyList has 2x lower emplace overhead compared to more generic STL +// containers. +// +// The optimal value of `ChunkSize` will vary by use case, but testing shows +// that a value of 1024 does a good job amortizing the `malloc` cost of growth. +// Performance drops off for larger values, so testing on a case-by-case basis +// is recommended if performance is absolutely critical. + +template < + typename T, + size_t ChunkSize, + template class block_t = std::array> +class AppendOnlyList { + public: + using array_t = block_t; + static_assert( + std::is_base_of_v, array_t>, + "AppendOnlyList expects raw low level pointer storage."); + static_assert(ChunkSize > 0, "Block cannot be empty."); + + AppendOnlyList() : buffer_last_{buffer_.before_begin()} {} + AppendOnlyList(const AppendOnlyList&) = delete; + AppendOnlyList(AppendOnlyList&&) = delete; + AppendOnlyList& operator=(const AppendOnlyList&) = delete; + AppendOnlyList& operator=(AppendOnlyList&&) = delete; + ~AppendOnlyList() = default; + + size_t size() const { + return n_blocks_ * ChunkSize - (size_t)(end_ - next_); + } + + template + T* emplace_back(Args&&... args) { + maybe_grow(); + if constexpr ( + std::is_trivially_destructible_v && + std::is_trivially_destructible_v) { + ::new ((void*)next_) T{std::forward(args)...}; + } else { + *next_ = T{std::forward(args)...}; + } + return next_++; + } + + template + std::enable_if_t && std::is_trivially_copyable_v> + copy(c10::ArrayRef src) { + size_t n = src.size(); + if (C10_UNLIKELY(n == 0)) { + return; + } + maybe_grow(); + if (C10_LIKELY(next_ && (next_ + n <= end_))) { + std::memcpy((void*)next_, (void*)src.begin(), n * sizeof(T0)); + next_ += n; + } else { + // We could chunk this into several `memcpy`s, but because we expect this + // fallback to be infrequent (n << ChunkSize) the performance impact is + // negligible. + for (auto i : src) { + emplace_back(i); + } + } + } + + void clear() { + buffer_.clear(); + buffer_last_ = buffer_.before_begin(); + n_blocks_ = 0; + next_ = nullptr; + end_ = nullptr; + } + + struct Iterator { + using iterator_category = std::forward_iterator_tag; + using difference_type = std::ptrdiff_t; + using value_type = T; + using pointer = T*; + using reference = T&; + + Iterator(std::forward_list& buffer, const size_t size) + : block_{buffer.begin()}, size_{size} {} + + // End iterator. + Iterator() = default; + + bool exhausted() const { + return current_ >= size_; + } + + reference operator*() const { + return *current_ptr(/*checked=*/true); + } + pointer operator->() { + return current_ptr(/*checked=*/true); + } + + // Prefix increment + Iterator& operator++() { + if (!(++current_ % ChunkSize)) { + block_++; + } + return *this; + } + + // Postfix increment + Iterator operator++(int) { + Iterator tmp = *this; + ++(*this); + return tmp; + } + + friend bool operator==(const Iterator& a, const Iterator& b) { + return a.current_ptr() == b.current_ptr(); + } + friend bool operator!=(const Iterator& a, const Iterator& b) { + return a.current_ptr() != b.current_ptr(); + } + + std::pair address() const { + if (current_ >= size_) { + return {nullptr, 0}; + } + return {&(*block_), current_ % ChunkSize}; + } + + private: + T* current_ptr(bool checked = false) const { + auto a = address(); + if (a.first == nullptr) { + TORCH_INTERNAL_ASSERT(!checked, "Invalid access on AppendOnlyList."); + return nullptr; + } + return a.first->data() + a.second; + } + + typename std::forward_list::iterator block_; + size_t current_{0}; + size_t size_{0}; + }; + + Iterator begin() { + return Iterator(buffer_, size()); + } + Iterator end() { + return Iterator(); + } + // TODO: cbegin and cend() + + private: + void maybe_grow() { + if (C10_UNLIKELY(next_ == end_)) { + buffer_last_ = buffer_.emplace_after(buffer_last_); + n_blocks_++; + next_ = buffer_last_->data(); + end_ = next_ + ChunkSize; + } + } + + std::forward_list buffer_; + + // We maintain a pointer to the last element of `buffer_` so that we can + // insert at the end in O(1) time. + size_t n_blocks_{0}; + T* next_{nullptr}; + T* end_{nullptr}; + + protected: + typename std::forward_list::iterator buffer_last_; +}; + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/data_flow.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/data_flow.h new file mode 100644 index 0000000000000000000000000000000000000000..115bd72209f71641b412d124643e5a9242b1b6ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/data_flow.h @@ -0,0 +1,95 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include + +namespace torch::profiler::impl { + +// Identity is a complex concept in PyTorch. A Tensor might not have a +// an associated storage, multiple Tensors might share the same underlying +// storage, the storage of a Tensor might change over time, etc. +// +// For the purpose of profiling we're mostly interested in data flow +// analysis. As a result, we can take an expansive view of identity: +// Tensors share an ID if they share a TensorImpl or storage data. +// +// This identity equality is transitive; If Tensors T0 and T1 share a storage +// S0 and T1 later points to a different storage S1 then all Tensors which +// point to either S0 or S1 are considered to have the same identity. (Since +// profiler cannot reason beyond that.) +// +// The profiler will handle lifetime analysis to ensure that identities do +// not run afoul of the ABA problem. This does, however, mean that identities +// can only be assigned when memory profiling is enabled. +using TensorID = strong::type; + +// Uniquely identifies an allocation. (Generally a StorageImpl's data ptr.) +using AllocationID = strong::type< + size_t, + struct StorageID_, + strong::ordered, + strong::regular, + strong::hashable>; + +// We use a Tensor's TensorImpl address and StorageImpl data start to build the +// data flow graph. We do not hold an owning reference so we wrap them in strong +// types to prevent direct access. +using TensorImplAddress = strong::type< + const c10::TensorImpl*, + struct TensorImplAddress_, + strong::regular, + strong::hashable, + strong::boolean>; + +using StorageImplData = strong::type< + const void*, + struct StorageImplData_, + strong::regular, + strong::hashable, + strong::boolean>; + +// ============================================================================ +// == weak_intrusive_ptr and the ABA problem for TensorImpl* ================== +// ============================================================================ +// Tracking `TensorImpl`s is an important part of identity tracking, because +// a Tensor might change storage; however when it does we want to retain the +// fact that the old and new storage belong to the same logical Tensor. We +// cannot take an owning reference to the Tensor because that would change +// program semantics by extending the lifetime of the Tensor. However if we +// store a raw TensorImpl* pointer the TensorImpl might be deleted and a new +// TensorImpl might be created that reuses the address. (ABA problem) +// +// Fortunately, there is a feature of `c10::intrusive_ptr` that we can use to +// prevent address reuse for the duration of profiling: the weak intrusive ptr. +// When a Tensor's refcount reaches zero but there are outstanding weak +// references (`weakcount_ > 0`) it will free the underlying managed resources +// by calling `target_->release_resources()`, but it will not call `delete`. +// (Instead, `delete` is called when the last weak reference is destroyed.) +// This means that we can safely use address identity to track `TensorImpls`. +class WeakTensor { + public: + explicit WeakTensor(const at::Tensor& t) : weak_self_(t.getIntrusivePtr()) {} + + auto get() const { + return TensorImplAddress{weak_self_._unsafe_get_target()}; + } + + private: + c10::weak_intrusive_ptr weak_self_; +}; + +struct Result; + +void calculateUniqueTensorIDs( + std::vector>& sorted_results); + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/events.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/events.h new file mode 100644 index 0000000000000000000000000000000000000000..83cc186e15f19dc61fb6d0123593631c5d5961d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/events.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::profiler { + +/* A vector type to hold a list of performance counters */ +using perf_counters_t = std::vector; + +/* Standard list of performance events independent of hardware or backend */ +constexpr std::array ProfilerPerfEvents = { + /* + * Number of Processing Element (PE) cycles between two points of interest + * in time. This should correlate positively with wall-time. Measured in + * uint64_t. PE can be non cpu. TBD reporting behavior for multiple PEs + * participating (i.e. threadpool). + */ + "cycles", + + /* Number of PE instructions between two points of interest in time. This + * should correlate positively with wall time and the amount of computation + * (i.e. work). Across repeat executions, the number of instructions should + * be more or less invariant. Measured in uint64_t. PE can be non cpu. + */ + "instructions"}; +} // namespace torch::profiler + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/kineto_client_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/kineto_client_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..12b936c44d1fd363c8c53942f3d2e99a7bbb8f04 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/kineto_client_interface.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch { + +// declare global_kineto_init for libtorch_cpu.so to call +TORCH_API void global_kineto_init(); + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/kineto_shim.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/kineto_shim.h new file mode 100644 index 0000000000000000000000000000000000000000..5dc4fec96d93e180a533a4187783bf12d092cb7b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/kineto_shim.h @@ -0,0 +1,153 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +// Skip Kineto dependency on mobile unless explicitly asked for. +// When is it explicitly asked for? +// KinetoEdgeCPUProfiler uses KinetoProfiler for cpu +// event profiling. This has a dependency on cpu only libkineto +#if defined(USE_KINETO) && defined(C10_MOBILE) && \ + !defined(EDGE_PROFILER_USE_KINETO) +#undef USE_KINETO +#endif + +#include + +#include +#include + +#ifdef USE_KINETO +// Forward declarations so we don't have to include `libkineto.h` in a header. +namespace libkineto { +class GenericTraceActivity; +struct CpuTraceBuffer; +class ActivityTraceInterface; +} // namespace libkineto +#endif + +namespace torch { +namespace profiler { + +#ifdef USE_KINETO +constexpr bool kKinetoAvailable{true}; +#else +constexpr bool kKinetoAvailable{false}; +#endif + +namespace impl::kineto { + +// ---------------------------------------------------------------------------- +// -- Interface (Does not require Kineto) ------------------------------------- +// ---------------------------------------------------------------------------- +struct DeviceAndResource { + int32_t device; + int32_t resource; +}; +const DeviceAndResource kineto_ids(); + +#ifdef USE_KINETO +using trace_t = libkineto::CpuTraceBuffer; +using interface_trace_t = libkineto::ActivityTraceInterface; +using activity_t = libkineto::GenericTraceActivity; +#else +struct DummyTraceBuffer {}; +struct DummyTraceInterface {}; + +using trace_t = DummyTraceBuffer; +using interface_trace_t = DummyTraceBuffer; +struct activity_t; +#endif // USE_KINETO + +void addMetadata( + activity_t* activity, + const std::string& key, + const std::string& value); + +// Wraps: libkineto::CpuTraceBuffer +struct TraceWrapper { + TraceWrapper(const int64_t start_time, const std::string& name); + + // The caller is expected to hold a mutex when calling `addCPUActivity`. + activity_t* addCPUActivity( + const std::string& name, + const libkineto::ActivityType type, + const DeviceAndResource device_and_resource, + const uint64_t correlation_id, + const int64_t start_time, + const int64_t end_time); + + void transferCpuTrace(int64_t end_time); + + explicit operator bool() const; + + std::unique_ptr& get() { + return cpu_trace_; + } + + private: + std::unique_ptr cpu_trace_; +}; + +// Wraps libkineto::ActivityTraceInterface +struct ActivityTraceWrapper { + explicit ActivityTraceWrapper(std::unique_ptr&& trace); + ActivityTraceWrapper() = default; + explicit operator bool() const; + void save(const std::string& path); + + const std::unique_ptr& get() { + return trace_; + } + + private: + std::unique_ptr trace_; +#ifdef USE_KINETO + bool saved_ = false; // Kineto's save is destructive +#endif +}; + +using ActivitySet = std::set; +void prepareTrace( + const bool cpuOnly, + const ActivitySet& activities, + const torch::profiler::impl::ExperimentalConfig& config, + const std::string& trace_id = ""); + +void toggleCollectionDynamic(const bool enable); +void startTrace(); +ActivityTraceWrapper stopTrace(); +void pushCorrelationId(uint64_t correlation_id); +void pushUserCorrelationId(uint64_t correlation_id); +void popCorrelationId(); +void popUserCorrelationId(); +void recordThreadInfo(); +bool collectivesProfilerExists(); + +void logInvariantViolation( + const std::string& assertion, + const std::string& error, + const std::string& profile_id, + const std::string& group_profile_id); + +} // namespace impl::kineto + +} // namespace profiler + +namespace autograd::profiler { +c10::DeviceType deviceTypeFromActivity(libkineto::ActivityType activity_type); + +TORCH_API void addMetadataJson( + const std::string& key, + const std::string& value); + +TORCH_API void profilerStep(); + +} // namespace autograd::profiler + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/observer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/observer.h new file mode 100644 index 0000000000000000000000000000000000000000..b4f14053793a8d67bcdf59630f644091b191d33e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/observer.h @@ -0,0 +1,222 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::profiler::impl { + +// ---------------------------------------------------------------------------- +// -- Profiler Config --------------------------------------------------------- +// ---------------------------------------------------------------------------- +enum class C10_API_ENUM ActivityType { + CPU = 0, + XPU, // XPU kernels, runtime + CUDA, // CUDA kernels, runtime + HPU, // HPU kernels, runtime + MTIA, // MTIA kernels, runtime + PrivateUse1, // PrivateUse1 kernels, runtime + NUM_KINETO_ACTIVITIES, // must be the last one +}; + +inline std::string actToString(ActivityType t) { + const std::array< + std::string, + static_cast(ActivityType::NUM_KINETO_ACTIVITIES)> + ActivityTypeNames = {"CPU", "XPU", "CUDA", "MTIA", "PrivateUse1"}; + return ActivityTypeNames[static_cast(t)]; +} + +enum class C10_API_ENUM ProfilerState { + Disabled = 0, + CPU, // CPU-only profiling + CUDA, // CPU + CUDA events + NVTX, // only emit NVTX markers + ITT, // only emit ITT markers + PRIVATEUSE1, // only emit PRIVATEUSE1 markers + KINETO, // use libkineto + KINETO_GPU_FALLBACK, // use CUDA events when CUPTI is not available + KINETO_PRIVATEUSE1_FALLBACK, // use PrivateUse1 events + KINETO_ONDEMAND, // run the profiler in on-demand mode + NUM_PROFILER_STATES, // must be the last one +}; + +enum class C10_API_ENUM ActiveProfilerType { + NONE = 0, + LEGACY, + KINETO, + NVTX, + ITT, + PRIVATEUSE1 +}; + +struct TORCH_API ExperimentalConfig { + ExperimentalConfig( + std::vector profiler_metrics = {}, + bool profiler_measure_per_kernel = false, + bool verbose = false, + std::vector performance_events = {}, + bool enable_cuda_sync_events = false, + bool adjust_profiler_step = false, + bool disable_external_correlation = false, + bool profile_all_threads = false, + bool capture_overload_names = false, + bool record_python_gc_info = false, + bool expose_kineto_event_metadata = false, + std::string custom_profiler_config = "", + bool adjust_timestamps = false); + explicit operator bool() const; + + std::vector profiler_metrics; + bool profiler_measure_per_kernel; + bool verbose; + /* + * List of performance events to be profiled. + * An empty list will disable performance event based profiling altogether. + */ + std::vector performance_events; + /* + * For CUDA profiling mode, enable adding CUDA synchronization events + * that expose CUDA device, stream and event synchronization activities. + * This feature is new and currently disabled by default. + */ + bool enable_cuda_sync_events; + /* + * Controls whether or not timestamp adjustment for ProfilerStep and parent + * Python events occurs after profiling. This occurs at an O(n) cost and + * affects only the start of profiler step events. + */ + bool adjust_profiler_step; + /* + * Controls whether or not external correlation is disabled. This is used to + * lower the amount of events received by CUPTI as correlation events are + * paired with runtime/gpu events for each kind of correlation + */ + bool disable_external_correlation; + + /* controls whether profiler records cpu events on threads + * that are not spawned from the main thread on which the + * profiler was enabled, similar to on_demand mode */ + bool profile_all_threads; + + /* controls whether overload names are queried from an ATen + * function schema and stored in the profile */ + bool capture_overload_names; + + /* + * Controls whether or not python gc info is recorded. This is used to + * determine if gc collect is slowing down your profile. + */ + bool record_python_gc_info; + + /* controls whether KinetoEvent metadata is exposed to FunctionEvent + * in the PyTorch Profiler as a JSON string */ + bool expose_kineto_event_metadata; + + /* + * A custom_profiler_config option is introduced to allow custom backends + * to apply custom configurations as needed. + */ + std::string custom_profiler_config; + + /* + * Controls whether or not timestamp adjustment occurs after profiling. + * The purpose of this is to adjust Vulkan event timelines to align with those + * of their parent CPU events. + * This sometimes requires increasing CPU event durations (to fully contain + * their child events) and delaying CPU event start times (to + * prevent overlaps), so this should not be used unless Vulkan events are + * being profiled and it is ok to use this modified timestamp/duration + * information instead of the original information. + */ + bool adjust_timestamps; +}; + +struct TORCH_API ProfilerConfig { + explicit ProfilerConfig( + ProfilerState state, + bool report_input_shapes = false, + bool profile_memory = false, + bool with_stack = false, + bool with_flops = false, + bool with_modules = false, + ExperimentalConfig experimental_config = ExperimentalConfig(), + std::string trace_id = ""); + + bool disabled() const; + bool global() const; + bool pushGlobalCallbacks() const; + + ProfilerState state; + ExperimentalConfig experimental_config; + bool report_input_shapes; + bool profile_memory; + bool with_stack; + bool with_flops; + bool with_modules; + std::string trace_id; + + // For serialization + at::IValue toIValue() const; + static ProfilerConfig fromIValue(const at::IValue& profilerConfigIValue); +}; + +// ---------------------------------------------------------------------------- +// -- Profiler base class ----------------------------------------------------- +// ---------------------------------------------------------------------------- +struct TORCH_API ProfilerStateBase : public c10::MemoryReportingInfoBase { + explicit ProfilerStateBase(ProfilerConfig config); + ProfilerStateBase(const ProfilerStateBase&) = delete; + ProfilerStateBase(ProfilerStateBase&&) = delete; + ProfilerStateBase& operator=(const ProfilerStateBase&) = delete; + ProfilerStateBase& operator=(ProfilerStateBase&&) = delete; + ~ProfilerStateBase() override; + + static ProfilerStateBase* get(bool global); + static ProfilerStateBase* get() { + auto* out = get(/*global=*/true); + return out ? out : get(/*global=*/false); + } + + static void push(std::shared_ptr&& state); + + static std::shared_ptr pop(bool global); + static std::shared_ptr pop() { + auto out = pop(/*global=*/true); + return out ? std::move(out) : pop(/*global=*/false); + } + + const ProfilerConfig& config() const { + return config_; + } + + void setCallbackHandle(at::CallbackHandle handle); + void removeCallback(); + + bool memoryProfilingEnabled() const override { + return config_.profile_memory; + } + + virtual ActiveProfilerType profilerType() = 0; + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::mutex state_mutex_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + ProfilerConfig config_ = ProfilerConfig(ProfilerState::Disabled); + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + at::CallbackHandle handle_ = 0; +}; + +// Note: The following are only for the active *thread local* profiler. +TORCH_API bool profilerEnabled(); +TORCH_API ActiveProfilerType profilerType(); +TORCH_API ProfilerConfig getProfilerConfig(); + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/python_tracer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/python_tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..3cfd6d54b173ddb17adf295d33aab4636c3638a2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/python_tracer.h @@ -0,0 +1,82 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace torch::profiler::impl { + +class RecordQueue; +struct Result; +namespace python_tracer { + +using TraceKey = strong::type< + uint64_t, + struct TraceKey_, + strong::regular, + strong::hashable, + strong::ostreamable>; + +struct CompressedEvent { + TraceKey key_; + uint64_t system_tid_{}; + kineto::DeviceAndResource kineto_info_{}; + c10::time_t enter_t_{}; +}; + +/* +Libtorch does not depend on Python (e.g. cannot #include ); however +when we call the profiler from libtorch_python we need the profiler to be able +to ingest the data that we collect from the Python tracer. (`PyEval_SetProfile`) + +In order to solve this dependency issue we define a virtual base and a function +to register a getter. The python tracer then implements these functions and +exposes itself by calling `registerTracer` from `torch/csrc/autograd/init.cpp`. +This pattern of registration for faux python dependencies in libtorch is common +in the PyTorch codebase. +*/ +struct TORCH_API PythonTracerBase { + static std::unique_ptr make(RecordQueue* queue); + virtual ~PythonTracerBase() = default; + + virtual void stop() = 0; + virtual void restart() = 0; + virtual void register_gc_callback() = 0; + virtual std::vector> getEvents( + std::function time_converter, + std::vector& enters, + c10::time_t end_time_ns) = 0; +}; + +using MakeFn = std::unique_ptr (*)(RecordQueue*); +TORCH_API void registerTracer(MakeFn make_tracer); + +/** + * Memory Tracer Implementation + */ +struct TORCH_API PythonMemoryTracerBase { + static std::unique_ptr make(); + virtual ~PythonMemoryTracerBase() = default; + + virtual void start() = 0; + virtual void stop() = 0; + virtual void export_memory_history(const std::string& path) = 0; +}; + +using MakeMemoryFn = std::unique_ptr (*)(); +TORCH_API void registerMemoryTracer(MakeMemoryFn make_memory_tracer); + +} // namespace python_tracer +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/vulkan.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/vulkan.h new file mode 100644 index 0000000000000000000000000000000000000000..577d1299b83600fecfca5ecf03a399c526ed2fd1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/vulkan.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::profiler::impl::vulkan { + +// Using function pointer i.e. [std::tuple (*)(int64_t)] +// doesn't work because we need to capture the QueryPool in the lambda context +// https://stackoverflow.com/a/28746827 +using GetShaderNameAndDurationNsFn = + std::function(int64_t)>; +TORCH_API void registerGetShaderNameAndDurationNs( + GetShaderNameAndDurationNsFn get_shader_name_and_duration_ns); + +TORCH_API void deregisterGetShaderNameAndDurationNs(); + +std::tuple getShaderNameAndDurationNs( + const vulkan_id_t& vulkan_id); + +} // namespace torch::profiler::impl::vulkan + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf-inl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..448e4747807ee871734722b351a58215ad2a4f60 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf-inl.h @@ -0,0 +1,73 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#if defined(__ANDROID__) || defined(__linux__) + +#include + +#include +#include + +#include + +#endif /* __ANDROID__ || __linux__ */ + +#include + +#include + +namespace torch::profiler::impl::linux_perf { + +/* + * PerfEvent + * --------- + */ + +inline void PerfEvent::Disable() const { +#if defined(__ANDROID__) || defined(__linux__) + ioctl(fd_, PERF_EVENT_IOC_DISABLE, 0); +#endif /* __ANDROID__ || __linux__ */ +} + +inline void PerfEvent::Enable() const { +#if defined(__ANDROID__) || defined(__linux__) + ioctl(fd_, PERF_EVENT_IOC_ENABLE, 0); +#endif /* __ANDROID__ || __linux__ */ +} + +inline void PerfEvent::Reset() const { +#if defined(__ANDROID__) || defined(__linux__) + ioctl(fd_, PERF_EVENT_IOC_RESET, 0); +#endif /* __ANDROID__ || __linux__ */ +} + +/* + * PerfProfiler + * ------------ + */ + +inline uint64_t PerfProfiler::CalcDelta(uint64_t start, uint64_t end) const { + if (end < start) { // overflow + return end + (std::numeric_limits::max() - start); + } + // not possible to wrap around start for a 64b cycle counter + return end - start; +} + +inline void PerfProfiler::StartCounting() const { + for (auto& e : events_) { + e.Enable(); + } +} + +inline void PerfProfiler::StopCounting() const { + for (auto& e : events_) { + e.Disable(); + } +} + +} // namespace torch::profiler::impl::linux_perf + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf.h new file mode 100644 index 0000000000000000000000000000000000000000..70ea26a46330fdeb556b76a511add5253b0b2314 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf.h @@ -0,0 +1,106 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace torch::profiler::impl::linux_perf { + +/* + * Maximum number of events supported + * This stems from the hardware limitation on CPU performance counters, and the + * fact that we don't support time multiplexing just yet. + * Time multiplexing involves scaling the counter values proportional to + * the enabled and running time or running the workload multiple times. + */ +constexpr uint8_t MAX_EVENTS = 4; + +struct PerfCounter { + uint64_t value; /* The value of the event */ + uint64_t time_enabled; /* for TIME_ENABLED */ + uint64_t time_running; /* for TIME_RUNNING */ +}; + +/* + * Basic perf event handler for Android and Linux + */ +class PerfEvent { + public: + explicit PerfEvent(std::string& name) : name_(name) {} + + PerfEvent(const PerfEvent& other) = delete; + PerfEvent& operator=(const PerfEvent&) = delete; + PerfEvent& operator=(PerfEvent&& other) noexcept { + if (this != &other) { + fd_ = other.fd_; + other.fd_ = -1; + name_ = std::move(other.name_); + } + return *this; + } + + PerfEvent(PerfEvent&& other) noexcept { + *this = std::move(other); + } + + ~PerfEvent(); + + /* Setup perf events with the Linux Kernel, attaches perf to this process + * using perf_event_open(2) */ + void Init(); + + /* Stop incrementing hardware counters for this event */ + void Disable() const; + + /* Start counting hardware event from this point on */ + void Enable() const; + + /* Zero out the counts for this event */ + void Reset() const; + + /* Returns PerfCounter values for this event from kernel, on non supported + * platforms this always returns zero */ + uint64_t ReadCounter() const; + + private: + /* Name of the event */ + std::string name_; + + int fd_ = -1; +}; + +class PerfProfiler { + public: + /* Configure all the events and track them as individual PerfEvent */ + void Configure(std::vector& event_names); + + /* Enable events counting from here */ + void Enable(); + + /* Disable counting and fill in the caller supplied container with delta + * calculated from the start count values since last Enable() */ + void Disable(perf_counters_t& /*vals*/); + + private: + uint64_t CalcDelta(uint64_t start, uint64_t end) const; + void StartCounting() const; + void StopCounting() const; + + std::vector events_; + std::stack start_values_; +}; +} // namespace torch::profiler::impl::linux_perf + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/combined_traceback.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/combined_traceback.h new file mode 100644 index 0000000000000000000000000000000000000000..0cdb2e1737d860f40c91814405a39ef310cee5b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/combined_traceback.h @@ -0,0 +1,32 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +#include +#include +#include + +namespace torch { + +// symbolize combined traceback objects, converting them into lists of +// dictionaries that are easily consumed in python. + +// returns std::vector because one use is to call it with a batch of +// tracebacks that come from a larger datastructure (e.g. a memory snapshot) +// and then have more c++ code to put those objects in the right place. +TORCH_API std::vector py_symbolize( + std::vector& to_symbolize); + +// Return the callback in json format so that it can be used within cpp +TORCH_API std::vector json_symbolize( + std::vector& to_symbolize); + +// requires GIL to be held, frees any pending free frames +TORCH_PYTHON_API void freeDeadCapturedTracebackFrames(); + +TORCH_PYTHON_API void installCapturedTracebackPython(); + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/init.h new file mode 100644 index 0000000000000000000000000000000000000000..8f5f25ddaf5cb6b647d99e53c45ed81630ce3213 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/init.h @@ -0,0 +1,36 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +namespace pybind11::detail { +using torch::profiler::impl::TensorID; + +#define STRONG_POINTER_TYPE_CASTER(T) \ + template <> \ + struct type_caster : public strong_pointer_type_caster {}; + +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::StorageImplData) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::AllocationID) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::TensorImplAddress) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyModuleSelf) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyModuleCls) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyOptimizerSelf) +#undef STRONG_POINTER_TYPE_CASTER + +template <> +struct type_caster : public strong_uint_type_caster {}; +} // namespace pybind11::detail + +namespace torch::profiler { + +void initPythonBindings(PyObject* module); + +} // namespace torch::profiler + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/pybind.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..39c63a85349c7493d1d06e922941ff6205cb1770 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/pybind.h @@ -0,0 +1,53 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include + +namespace pybind11::detail { +// Strong typedefs don't make much sense in Python since everything is duck +// typed. So instead we simply extract the underlying value and let the caller +// handle correctness. +template +struct strong_pointer_type_caster { + template + static handle cast( + const T_& src, + return_value_policy /*policy*/, + handle /*parent*/) { + const auto* ptr = reinterpret_cast(src.value_of()); + return ptr ? handle(THPUtils_packUInt64(reinterpret_cast(ptr))) + : none(); + } + + bool load(handle /*src*/, bool /*convert*/) { + return false; + } + + PYBIND11_TYPE_CASTER(T, _("strong_pointer")); +}; + +template +struct strong_uint_type_caster { + template + static handle cast( + const T_& src, + return_value_policy /*policy*/, + handle /*parent*/) { + return handle(THPUtils_packUInt64(src.value_of())); + } + + bool load(handle /*src*/, bool /*convert*/) { + return false; + } + + PYBIND11_TYPE_CASTER(T, _("strong_uint")); +}; +} // namespace pybind11::detail + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/execution_trace_observer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/execution_trace_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..cd5a3addd9cc27717340a29fa268b7f96ae561ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/execution_trace_observer.h @@ -0,0 +1,26 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::profiler::impl { + +// Adds the execution trace observer as a global callback function, the data +// will be written to output file path. +TORCH_API bool addExecutionTraceObserver(const std::string& output_file_path); + +// Remove the execution trace observer from the global callback functions. +TORCH_API void removeExecutionTraceObserver(); + +// Enables execution trace observer. +TORCH_API void enableExecutionTraceObserver(); + +// Disables execution trace observer. +TORCH_API void disableExecutionTraceObserver(); + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/itt_observer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/itt_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..e1d340daf8b2917d3b3a4de59f254deb68aefeea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/itt_observer.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::profiler::impl { + +void pushITTCallbacks( + const ProfilerConfig& config, + const std::unordered_set& scopes); + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/nvtx_observer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/nvtx_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..75214a0fbd6b9b776bc8788061461057a9843c2a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/nvtx_observer.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::profiler::impl { + +void pushNVTXCallbacks( + const ProfilerConfig& config, + const std::unordered_set& scopes); + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/privateuse1_observer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/privateuse1_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..e8f393da8ba37ce428a051b3ba4275abb72ffa2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/privateuse1_observer.h @@ -0,0 +1,51 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::profiler::impl { + +using CallBackFnPtr = void (*)( + const ProfilerConfig& config, + const std::unordered_set& scopes); + +struct PushPRIVATEUSE1CallbacksStub { + PushPRIVATEUSE1CallbacksStub() = default; + PushPRIVATEUSE1CallbacksStub(const PushPRIVATEUSE1CallbacksStub&) = delete; + PushPRIVATEUSE1CallbacksStub& operator=(const PushPRIVATEUSE1CallbacksStub&) = + delete; + PushPRIVATEUSE1CallbacksStub(PushPRIVATEUSE1CallbacksStub&&) = default; + PushPRIVATEUSE1CallbacksStub& operator=(PushPRIVATEUSE1CallbacksStub&&) = + default; + ~PushPRIVATEUSE1CallbacksStub() = default; + + template + void operator()(ArgTypes&&... args) { + return (*push_privateuse1_callbacks_fn)(std::forward(args)...); + } + + void set_privateuse1_dispatch_ptr(CallBackFnPtr fn_ptr) { + push_privateuse1_callbacks_fn = fn_ptr; + } + + private: + CallBackFnPtr push_privateuse1_callbacks_fn = nullptr; +}; + +extern TORCH_API struct PushPRIVATEUSE1CallbacksStub + pushPRIVATEUSE1CallbacksStub; + +struct RegisterPRIVATEUSE1Observer { + RegisterPRIVATEUSE1Observer( + PushPRIVATEUSE1CallbacksStub& stub, + CallBackFnPtr value) { + stub.set_privateuse1_dispatch_ptr(value); + } +}; + +#define REGISTER_PRIVATEUSE1_OBSERVER(name, fn) \ + static RegisterPRIVATEUSE1Observer name##__register(name, fn); +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/stubs/base.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/stubs/base.h new file mode 100644 index 0000000000000000000000000000000000000000..fad34ad6b9daae1c143e9b365ae59a85156a832e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/stubs/base.h @@ -0,0 +1,58 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +struct CUevent_st; + +namespace torch::profiler::impl { + +// ---------------------------------------------------------------------------- +// -- Annotation -------------------------------------------------------------- +// ---------------------------------------------------------------------------- +using ProfilerEventStub = std::shared_ptr; +using ProfilerVoidEventStub = std::shared_ptr; + +struct TORCH_API ProfilerStubs { + virtual void record( + c10::DeviceIndex* device, + ProfilerVoidEventStub* event, + int64_t* cpu_ns) const = 0; + virtual float elapsed( + const ProfilerVoidEventStub* event, + const ProfilerVoidEventStub* event2) const = 0; + virtual void mark(const char* name) const = 0; + virtual void rangePush(const char* name) const = 0; + virtual void rangePop() const = 0; + virtual bool enabled() const { + return false; + } + virtual void onEachDevice(std::function op) const = 0; + virtual void synchronize() const = 0; + virtual ~ProfilerStubs() = default; +}; + +TORCH_API void registerCUDAMethods(ProfilerStubs* stubs); +TORCH_API const ProfilerStubs* cudaStubs(); +TORCH_API void registerITTMethods(ProfilerStubs* stubs); +TORCH_API const ProfilerStubs* ittStubs(); +TORCH_API void registerPrivateUse1Methods(ProfilerStubs* stubs); +TORCH_API const ProfilerStubs* privateuse1Stubs(); + +using vulkan_id_t = strong::type< + int64_t, + struct _VulkanID, + strong::regular, + strong::convertible_to, + strong::hashable>; + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/action.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/action.h new file mode 100644 index 0000000000000000000000000000000000000000..c736c45b25a0e92ae94a9f01274216411a87f159 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/action.h @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +namespace torch::unwind { + +enum { + A_UNDEFINED = 0x0, + A_REG_PLUS_DATA = 0x1, // exp = REG[reg] + data0 + A_LOAD_CFA_OFFSET = 0x2, // exp = *(cfa + data0) + A_REG_PLUS_DATA_DEREF = 0x3 // exp = *(REG[reg] + data0) +}; + +// register numbers in dwarf info +enum { + D_UNDEFINED = -1, + D_RBP = 6, + D_RSP = 7, + D_RIP = 16, + D_REG_SIZE = 17, +}; + +struct Action { + uint8_t kind = A_UNDEFINED; + int32_t reg = -1; + int64_t data = 0; + static Action undefined() { + return Action{A_UNDEFINED}; + } + static Action regPlusData(int32_t reg, int64_t offset) { + return Action{A_REG_PLUS_DATA, reg, offset}; + } + static Action regPlusDataDeref(int32_t reg, int64_t offset) { + return Action{A_REG_PLUS_DATA_DEREF, reg, offset}; + } + static Action loadCfaOffset(int64_t offset) { + return Action{A_LOAD_CFA_OFFSET, D_UNDEFINED, offset}; + } + + friend std::ostream& operator<<(std::ostream& out, const Action& self) { + switch (self.kind) { + case A_UNDEFINED: + out << 'u'; + break; + case A_REG_PLUS_DATA: + out << 'r' << (int)self.reg << " + " << self.data; + break; + case A_REG_PLUS_DATA_DEREF: + out << "*(r" << (int)self.reg << " + " << self.data << ')'; + break; + case A_LOAD_CFA_OFFSET: + out << "*(cfa + " << self.data << ')'; + break; + } + return out; + } +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/communicate.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/communicate.h new file mode 100644 index 0000000000000000000000000000000000000000..a5b2281067ca256e2db7c687c313f29525d556ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/communicate.h @@ -0,0 +1,78 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +namespace torch::unwind { +// helper to open a process with stdin/stdout/stderr streams. +struct Communicate { + Communicate(const char* command, const char** args) { + if (pipe(inpipe_.data()) < 0 || pipe(outpipe_.data()) < 0 || + pipe(errpipe_.data()) < 0) { + throw UnwindError("pipe() failed"); + } + pid_t pid = fork(); + if (pid < 0) { + throw UnwindError("fork() failed"); + } else if (pid == 0) { // child process + close(inpipe_[1]); + close(outpipe_[0]); + close(errpipe_[0]); + + dup2(inpipe_[0], STDIN_FILENO); + dup2(outpipe_[1], STDOUT_FILENO); + dup2(errpipe_[1], STDERR_FILENO); + execvp(command, (char* const*)args); + throw UnwindError("failed execvp"); + } else { // parent process + close(inpipe_[0]); + close(outpipe_[1]); + close(errpipe_[1]); + outbuf_ = std::make_unique<__gnu_cxx::stdio_filebuf>( + inpipe_[1], std::ios::out); + inbuf_ = std::make_unique<__gnu_cxx::stdio_filebuf>( + outpipe_[0], std::ios::in); + errbuf_ = std::make_unique<__gnu_cxx::stdio_filebuf>( + errpipe_[0], std::ios::in); + in_ = std::make_unique(inbuf_.get()); + out_ = std::make_unique(outbuf_.get()); + err_ = std::make_unique(errbuf_.get()); + } + } + Communicate(const Communicate&) = delete; + Communicate(Communicate&&) = delete; + Communicate& operator=(const Communicate&) = delete; + Communicate& operator=(Communicate&&) = delete; + ~Communicate() { + close(inpipe_[1]); + close(outpipe_[0]); + close(errpipe_[0]); + } + std::ostream& out() { + return *out_; + } + std::ostream& err() { + return *err_; + } + std::istream& in() { + return *in_; + } + + private: + std::array inpipe_{-1, -1}; + std::array outpipe_{-1, -1}; + std::array errpipe_{-1, -1}; + std::unique_ptr<__gnu_cxx::stdio_filebuf> outbuf_, inbuf_, errbuf_; + std::unique_ptr in_; + std::unique_ptr out_; + std::unique_ptr err_; +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/debug_info.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/debug_info.h new file mode 100644 index 0000000000000000000000000000000000000000..9f4d0fe227613489847733783a13872df1015b1f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/debug_info.h @@ -0,0 +1,285 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace torch::unwind { + +struct DebugInfo { + DebugInfo(Sections& s) : s_(s) {} + + void parse(uint64_t offset) { + auto L = parseHeader(offset); + parseCompileUnit(L); + } + std::optional lineNumberProgramOffset() { + return line_number_program_offset_; + } + uint64_t nextOffset() { + return end_ - s_.debug_info.data; + } + std::vector> ranges() { + if (range_ptr_) { + auto offset = range_ptr_->first; + if (range_ptr_->second == DW_FORM_rnglistx) { + UNWIND_CHECK(rnglists_base_, "rnglistx but not rnglists_base_ set"); + LOG_INFO("index for rnglistx {:x} + {:x}\n", *rnglists_base_, offset); + CheckedLexer L = s_.debug_rnglists.lexer( + *rnglists_base_ + offset * sec_offset_size_); + auto read = readSegmentOffset(L); + offset = *rnglists_base_ + read; + } + return version_ == 4 ? readRanges4(offset) : readRanges5(offset); + } + if (!highpc_) { + return {}; + } + return {{lowpc_, lowpc_ + *highpc_}}; + } + + bool is64bit() { + return is_64bit_; + } + + private: + CheckedLexer parseHeader(uint64_t offset) { + offset_ = offset; + CheckedLexer L = s_.debug_info.lexer(offset_); + std::tie(length_, is_64bit_) = L.readSectionLength(); + sec_offset_size_ = is_64bit_ ? 8 : 4; + end_ = (const char*)L.loc() + length_; + version_ = L.read(); + UNWIND_CHECK( + version_ == 5 || version_ == 4, + "unexpected dwarf version {}", + version_); + uint8_t address_size = 0; + if (version_ == 5) { + auto unit_type = L.read(); + UNWIND_CHECK(unit_type == 0x1, "unexpected unit type {}", unit_type); + address_size = L.read(); + debug_abbrev_offset_ = + is_64bit_ ? L.read() : L.read(); + } else { + debug_abbrev_offset_ = + is_64bit_ ? L.read() : L.read(); + address_size = L.read(); + } + LOG_INFO( + "compilation unit at offset {:x} with length {:x} and debug_abbrev_offset {:x}\n", + offset, + length_, + debug_abbrev_offset_); + UNWIND_CHECK( + address_size == 8, + "expected 64-bit dwarf but found address size {}", + address_size); + return L; + } + + uint64_t readSegmentOffset(CheckedLexer& L) { + return s_.readSegmentOffset(L, is_64bit_); + } + + uint64_t readEncoded(CheckedLexer& L, uint64_t encoding) { + switch (encoding) { + case DW_FORM_data8: + case DW_FORM_addr: + return L.read(); + case DW_FORM_data4: + return L.read(); + case DW_FORM_addrx: { + auto idx = L.readULEB128(); + return s_.debug_addr.lexer(address_base_ + sizeof(uint64_t) * idx) + .read(); + } + case DW_FORM_sec_offset: + return readSegmentOffset(L); + case DW_FORM_rnglistx: { + return L.readULEB128(); + } + default: + UNWIND_CHECK(false, "unexpected encoding"); + } + } + + void parseCompileUnit(CheckedLexer& L) { + auto entry = L.readULEB128(); + auto A = findAbbrev(debug_abbrev_offset_, entry); + while (true) { + auto attr = A.readULEB128(); + auto form = A.readULEB128(); + if (attr == 0 && form == 0) { + break; + } + if (form == DW_FORM_implicit_const) { + A.readSLEB128(); + } + if (attr == DW_AT_low_pc) { + lowpc_ = readEncoded(L, form); + LOG_INFO(" lowpc {:x}\n", lowpc_); + } else if (attr == DW_AT_high_pc) { + highpc_ = readEncoded(L, form); + range_ptr_ = std::nullopt; + LOG_INFO(" highpc {:x}\n", *highpc_); + } else if (attr == DW_AT_addr_base) { + UNWIND_CHECK(form == DW_FORM_sec_offset, "unexpected addr_base form"); + address_base_ = readSegmentOffset(L); + LOG_INFO(" address base {:x}\n", address_base_); + } else if (attr == DW_AT_rnglists_base) { + UNWIND_CHECK( + form == DW_FORM_sec_offset, "unexpected rnglists_base form"); + rnglists_base_ = readSegmentOffset(L); + LOG_INFO(" range base {:x}\n", *rnglists_base_); + } else if (form == DW_FORM_string) { + L.readCString(); + } else if (attr == DW_AT_stmt_list) { + UNWIND_CHECK(form == DW_FORM_sec_offset, "unexpected stmt_list form"); + LOG_INFO(" program table offset {:x}\n", *line_number_program_offset_); + line_number_program_offset_ = readSegmentOffset(L); + } else if (form == DW_FORM_exprloc) { + auto sz = L.readULEB128(); + L.skip(int64_t(sz)); + } else if (form == DW_FORM_block1) { + auto sz = L.read(); + L.skip(int64_t(sz)); + } else if (attr == DW_AT_ranges) { + auto range_offset = readEncoded(L, form); + LOG_INFO("setting range_ptr to {:x} {:x}\n", range_offset, form); + range_ptr_.emplace(range_offset, form); + } else if ( + form == DW_FORM_udata || form == DW_FORM_rnglistx || + form == DW_FORM_strx || form == DW_FORM_loclistx || + form == DW_FORM_addrx) { + L.readULEB128(); + } else if (form == DW_FORM_sdata) { + L.readSLEB128(); + } else { + auto sz = formSize(form, sec_offset_size_); + UNWIND_CHECK(sz, "unsupported form in compilation unit {:x}", form); + L.skip(int64_t(*sz)); + } + } + } + + std::vector> readRanges4(uint64_t offset) { + CheckedLexer L = s_.debug_ranges.lexer(offset); + std::vector> ranges; + uint64_t base = lowpc_; + while (true) { + auto start = L.read(); + auto end = L.read(); + if (start == 0 && end == 0) { + break; + } + if (start == std::numeric_limits::max()) { + base = end; + } else { + ranges.emplace_back(base + start, base + end); + } + } + return ranges; + } + + std::vector> readRanges5(uint64_t offset) { + CheckedLexer L = s_.debug_rnglists.lexer(offset); + uint64_t base = 0; + LOG_INFO("BEGIN RANGES {:x}\n", offset); + std::vector> ranges; + while (true) { + auto op = L.read(); + switch (op) { + case DW_RLE_end_of_list: + LOG_INFO("END RANGES\n"); + return ranges; + case DW_RLE_base_addressx: { + base = readEncoded(L, DW_FORM_addrx); + LOG_INFO("BASE ADDRX {:x}\n", base); + } break; + case DW_RLE_startx_length: { + auto s = readEncoded(L, DW_FORM_addrx); + auto e = L.readULEB128(); + LOG_INFO("startx_length {:x} {:x}\n", s, e); + ranges.emplace_back(s, s + e); + } break; + case DW_RLE_base_address: + base = L.read(); + LOG_INFO("BASE ADDR {:x}\n", base); + break; + case DW_RLE_offset_pair: { + auto s = L.readULEB128(); + auto e = L.readULEB128(); + LOG_INFO("offset_pair {:x} {:x}\n", s, e); + ranges.emplace_back(base + s, base + e); + } break; + case DW_RLE_start_length: { + auto s = L.read(); + auto e = L.readULEB128(); + LOG_INFO("start_length {:x} {:x}\n", s, e); + ranges.emplace_back(s, s + e); + } break; + default: + UNWIND_CHECK(false, "unknown range op: {}", op); + } + } + } + + CheckedLexer findAbbrev(uint64_t offset, uint64_t entry) { + CheckedLexer L = s_.debug_abbrev.lexer(offset); + while (true) { + auto abbrev_code = L.readULEB128(); + UNWIND_CHECK( + abbrev_code != 0, + "could not find entry {} at offset {:x}", + entry, + offset); + auto tag = L.readULEB128(); + L.read(); // has children + if (abbrev_code == entry) { + UNWIND_CHECK( + tag == DW_TAG_compile_unit, + "first entry was not a compile unit but {}", + tag); + return L; + } + while (true) { + auto attr = L.readULEB128(); + auto form = L.readULEB128(); + if (attr == 0 && form == 0) { + break; + } + if (form == DW_FORM_implicit_const) { + L.readSLEB128(); + } + } + } + } + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + Sections& s_; + std::optional line_number_program_offset_; + uint64_t offset_ = 0; + uint8_t sec_offset_size_ = 0; + uint64_t length_ = 0; + const char* end_ = nullptr; + uint64_t debug_abbrev_offset_ = 0; + bool is_64bit_ = false; + + std::optional> range_ptr_; + uint64_t lowpc_ = 0; + std::optional highpc_; + uint16_t version_ = 0; + uint64_t address_base_ = 0; + std::optional rnglists_base_; +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_enums.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_enums.h new file mode 100644 index 0000000000000000000000000000000000000000..2b5c6de344a2e583c1bee8467d4e9f29dfb443bd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_enums.h @@ -0,0 +1,51 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +enum { + DW_EH_PE_absptr = 0x00, + DW_EH_PE_omit = 0xff, + /* FDE data encoding. */ + DW_EH_PE_uleb128 = 0x01, + DW_EH_PE_udata2 = 0x02, + DW_EH_PE_udata4 = 0x03, + DW_EH_PE_udata8 = 0x04, + DW_EH_PE_sleb128 = 0x09, + DW_EH_PE_sdata2 = 0x0a, + DW_EH_PE_sdata4 = 0x0b, + DW_EH_PE_sdata8 = 0x0c, + DW_EH_PE_signed = 0x08, + /* FDE flags. */ + DW_EH_PE_pcrel = 0x10, + DW_EH_PE_textrel = 0x20, + DW_EH_PE_datarel = 0x30, + DW_EH_PE_funcrel = 0x40, + DW_EH_PE_aligned = 0x50, + DW_EH_PE_indirect = 0x80, +}; + +enum { + DW_CFA_nop = 0x0, + DW_CFA_advance_loc = 0x01, + DW_CFA_offset = 0x02, + DW_CFA_restore = 0x03, + DW_CFA_advance_loc1 = 0x02, + DW_CFA_advance_loc2 = 0x03, + DW_CFA_advance_loc4 = 0x04, + DW_CFA_restore_extended = 0x06, + DW_CFA_undefined = 0x07, + DW_CFA_register = 0x09, + DW_CFA_remember_state = 0x0a, + DW_CFA_restore_state = 0x0b, + DW_CFA_def_cfa = 0x0c, + DW_CFA_def_cfa_register = 0x0d, + DW_CFA_def_cfa_offset = 0x0e, + DW_CFA_def_cfa_expression = 0xf, + DW_CFA_expression = 0x10, + DW_CFA_offset_extended_sf = 0x11, + DW_CFA_GNU_args_size = 0x2e, + DW_OP_deref = 0x6, +}; + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_symbolize_enums.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_symbolize_enums.h new file mode 100644 index 0000000000000000000000000000000000000000..d14a1dfd1d01bcd9ef6e06d63605bb91a8a83ba1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_symbolize_enums.h @@ -0,0 +1,184 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +enum { + DW_TAG_subprogram = 0x2e, + DW_TAG_inlined_subroutine = 0x1d, + DW_TAG_compile_unit = 0x11, + DW_AT_sibling = 0x1, // reference + DW_AT_name = 0x3, // string + DW_AT_stmt_list = 0x10, // lineptr + DW_AT_addr_base = 0x73, // sec_offset + DW_AT_rnglists_base = 0x74, // sec_offset + DW_AT_low_pc = 0x11, // address + DW_AT_high_pc = 0x12, // address + DW_AT_specification = 0x47, // reference + DW_AT_abstract_origin = 0x31, // reference + DW_AT_linkage_name = 0x6e, // string + DW_AT_ranges = 0x55, // rnglist + DW_AT_str_offsets_base = 0x72, // sec_offset + DW_FORM_addr = 0x01, + DW_FORM_block2 = 0x03, + DW_FORM_block4 = 0x04, + DW_FORM_data2 = 0x05, + DW_FORM_data4 = 0x06, + DW_FORM_data8 = 0x07, + DW_FORM_string = 0x08, + DW_FORM_block = 0x09, + DW_FORM_block1 = 0x0a, + DW_FORM_data1 = 0x0b, + DW_FORM_flag = 0x0c, + DW_FORM_sdata = 0x0d, + DW_FORM_strp = 0x0e, + DW_FORM_udata = 0x0f, + DW_FORM_ref_addr = 0x10, + DW_FORM_ref1 = 0x11, + DW_FORM_ref2 = 0x12, + DW_FORM_ref4 = 0x13, + DW_FORM_ref8 = 0x14, + DW_FORM_ref_udata = 0x15, + DW_FORM_indirect = 0x16, + DW_FORM_sec_offset = 0x17, + DW_FORM_exprloc = 0x18, + DW_FORM_flag_present = 0x19, + DW_FORM_strx = 0x1a, + DW_FORM_addrx = 0x1b, + DW_FORM_ref_sup4 = 0x1c, + DW_FORM_strp_sup = 0x1d, + DW_FORM_data16 = 0x1e, + DW_FORM_line_strp = 0x1f, + DW_FORM_ref_sig8 = 0x20, + DW_FORM_implicit_const = 0x21, + DW_FORM_loclistx = 0x22, + DW_FORM_rnglistx = 0x23, + DW_FORM_ref_sup8 = 0x24, + DW_FORM_strx1 = 0x25, + DW_FORM_strx2 = 0x26, + DW_FORM_strx3 = 0x27, + DW_FORM_strx4 = 0x28, + DW_FORM_addrx1 = 0x29, + DW_FORM_addrx2 = 0x2a, + DW_FORM_addrx3 = 0x2b, + DW_FORM_addrx4 = 0x2c, + /* GNU Debug Fission extensions. */ + DW_FORM_GNU_addr_index = 0x1f01, + DW_FORM_GNU_str_index = 0x1f02, + DW_FORM_GNU_ref_alt = 0x1f20, /* offset in alternate .debuginfo. */ + DW_FORM_GNU_strp_alt = 0x1f21, /* offset in alternate .debug_str. */ + DW_LNCT_path = 0x1, + DW_LNCT_directory_index = 0x2, + DW_LNS_extended_op = 0x00, + DW_LNE_end_sequence = 0x01, + DW_LNE_set_address = 0x02, + DW_LNS_copy = 0x01, + DW_LNS_advance_pc = 0x02, + DW_LNS_advance_line = 0x03, + DW_LNS_set_file = 0x04, + DW_LNS_const_add_pc = 0x08, + DW_LNS_fixed_advance_pc = 0x09, + DW_RLE_end_of_list = 0x0, + DW_RLE_base_addressx = 0x1, + DW_RLE_startx_endx = 0x2, + DW_RLE_startx_length = 0x3, + DW_RLE_offset_pair = 0x4, + DW_RLE_base_address = 0x5, + DW_RLE_start_end = 0x6, + DW_RLE_start_length = 0x7 +}; + +static std::optional formSize(uint64_t form, uint8_t sec_offset_size) { + switch (form) { + case DW_FORM_addr: + return sizeof(void*); + case DW_FORM_block2: + case DW_FORM_block4: + return std::nullopt; + case DW_FORM_data2: + return 2; + case DW_FORM_data4: + return 4; + case DW_FORM_data8: + return 8; + case DW_FORM_string: + case DW_FORM_block: + case DW_FORM_block1: + return std::nullopt; + case DW_FORM_data1: + case DW_FORM_flag: + return 1; + case DW_FORM_sdata: + return std::nullopt; + case DW_FORM_strp: + return sec_offset_size; + case DW_FORM_udata: + return std::nullopt; + case DW_FORM_ref_addr: + return sec_offset_size; + case DW_FORM_ref1: + return 1; + case DW_FORM_ref2: + return 2; + case DW_FORM_ref4: + return 4; + case DW_FORM_ref8: + return 8; + case DW_FORM_ref_udata: + case DW_FORM_indirect: + return std::nullopt; + case DW_FORM_sec_offset: + return sec_offset_size; + case DW_FORM_exprloc: + return std::nullopt; + case DW_FORM_flag_present: + return 0; + case DW_FORM_strx: + case DW_FORM_addrx: + return std::nullopt; + case DW_FORM_ref_sup4: + return 4; + case DW_FORM_strp_sup: + return sec_offset_size; + case DW_FORM_data16: + return 16; + case DW_FORM_line_strp: + return sec_offset_size; + case DW_FORM_ref_sig8: + return 8; + case DW_FORM_implicit_const: + return 0; + case DW_FORM_loclistx: + case DW_FORM_rnglistx: + return std::nullopt; + case DW_FORM_ref_sup8: + return 8; + case DW_FORM_strx1: + return 1; + case DW_FORM_strx2: + return 2; + case DW_FORM_strx3: + return 3; + case DW_FORM_strx4: + return 4; + case DW_FORM_addrx1: + return 1; + case DW_FORM_addrx2: + return 2; + case DW_FORM_addrx3: + return 3; + case DW_FORM_addrx4: + return 4; + case DW_FORM_GNU_addr_index: + case DW_FORM_GNU_str_index: + case DW_FORM_GNU_ref_alt: + case DW_FORM_GNU_strp_alt: + default: + return std::nullopt; + } +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/eh_frame_hdr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/eh_frame_hdr.h new file mode 100644 index 0000000000000000000000000000000000000000..865ddaecbacc94de1b0995effefbe628f3aefaa8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/eh_frame_hdr.h @@ -0,0 +1,105 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +#include +#include + +// Overview of the format described in +// https://refspecs.linuxfoundation.org/LSB_1.3.0/gLSB/gLSB/ehframehdr.html +namespace torch::unwind { + +struct EHFrameHdr { + EHFrameHdr(void* base) : base_(base) { + Lexer L(base, base); + version_ = L.read(); + eh_frame_ptr_enc_ = L.read(); + fde_count_enc_ = L.read(); + table_enc_ = L.read(); + if (table_enc_ == DW_EH_PE_omit) { + table_size_ = 0; + } else { + switch (table_enc_ & 0xF) { + case DW_EH_PE_udata2: + case DW_EH_PE_sdata2: + table_size_ = 2; + break; + case DW_EH_PE_udata4: + case DW_EH_PE_sdata4: + table_size_ = 4; + break; + case DW_EH_PE_udata8: + case DW_EH_PE_sdata8: + table_size_ = 8; + break; + case DW_EH_PE_uleb128: + case DW_EH_PE_sleb128: + throw UnwindError("uleb/sleb table encoding not supported"); + break; + default: + throw UnwindError("unknown table encoding"); + } + } + // NOLINTNEXTLINE(performance-no-int-to-ptr) + eh_frame_ = (void*)L.readEncodedOr(eh_frame_ptr_enc_, 0); + fde_count_ = L.readEncodedOr(fde_count_enc_, 0); + table_start_ = L.loc(); + } + size_t nentries() const { + return fde_count_; + } + + uint64_t lowpc(size_t i) const { + return Lexer(table_start_, base_) + .skip(2 * i * table_size_) + .readEncoded(table_enc_); + } + void* fde(size_t i) const { + // NOLINTNEXTLINE(performance-no-int-to-ptr) + return (void*)Lexer(table_start_, base_) + .skip((2 * i + 1) * table_size_) + .readEncoded(table_enc_); + } + + void* entryForAddr(uint64_t addr) const { + if (!table_size_ || !nentries()) { + throw UnwindError("search table not present"); + } + uint64_t low = 0; + uint64_t high = nentries(); + while (low + 1 < high) { + auto mid = (low + high) / 2; + if (addr < lowpc(mid)) { + high = mid; + } else { + low = mid; + } + } + return fde(low); + } + + friend std::ostream& operator<<(std::ostream& out, const EHFrameHdr& self) { + out << "EHFrameHeader(version=" << self.version_ + << ",table_size=" << self.table_size_ + << ",fde_count=" << self.fde_count_ << ')'; + return out; + } + + private: + void* base_; + void* table_start_; + uint8_t version_; + uint8_t eh_frame_ptr_enc_; + uint8_t fde_count_enc_; + uint8_t table_enc_; + void* eh_frame_ = nullptr; + int64_t fde_count_; + uint32_t table_size_; +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/fast_symbolizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/fast_symbolizer.h new file mode 100644 index 0000000000000000000000000000000000000000..2740c50054b41a55ff7190aacc9e7258464f5fa7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/fast_symbolizer.h @@ -0,0 +1,113 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::unwind { + +#define UNWIND_WARN(w, ...) \ + do { \ + w.emplace_back(fmt::format(__VA_ARGS__)); \ + LOG_INFO("WARNING: {}\n", w.back()); \ + } while (0); + +struct FastSymbolizer { + FastSymbolizer() = default; + Frame symbolize(const std::string& library, uint64_t offset) { + LOG_INFO("symbolizing {} + 0x{:x}\n", library, offset); + Frame frame; + frame.funcname = "??"; + frame.filename = library; + frame.lineno = offset; + auto s = getOrCreateSections(library); + if (auto e = s->findSubprogramName(offset)) { + frame.funcname = *e; + } else { + UNWIND_WARN( + warnings_, + "failed to find subprogram name for {} 0x{:x}", + library, + offset); + } + if (auto e = findLine(s, offset)) { + frame.filename = e->first; + frame.lineno = e->second; + } else { + UNWIND_WARN( + warnings_, "failed to find file/line for {} 0x{:x}", library, offset); + } + return frame; + } + const std::vector& warnings() { + return warnings_; + } + + private: + void parseDebugInfo(Sections* s) { + uint64_t offset = 0; + while (offset < s->debug_info.size) { + DebugInfo info(*s); + info.parse(offset); + if (auto lnp_offset = info.lineNumberProgramOffset()) { + for (auto r : info.ranges()) { + s->addDebugInfoRange(r.first, r.second, line_number_programs_.size()); + } + line_number_programs_.emplace_back( + std::make_unique(*s, *lnp_offset)); + } + offset = info.nextOffset(); + } + } + Sections* getOrCreateSections(const std::string& library) { + auto it = libraries_.find(library); + if (it == libraries_.end()) { + it = libraries_.insert({library, std::make_unique()}).first; + try { + Sections* s = it->second.get(); + s->parse(library.c_str()); + parseDebugInfo(s); + } catch (UnwindError& err) { + UNWIND_WARN( + warnings_, "failed to parse library {}: {}", library, err.what()); + } + } + return it->second.get(); + } + std::optional> findLine( + Sections* s, + uint64_t offset) { + if (auto idx = s->findDebugInfoOffset(offset)) { + auto r = line_number_programs_.at(*idx).get(); + try { + r->parse(); + } catch (UnwindError& err) { + UNWIND_WARN( + warnings_, + "failed to read line number program [{:x}] {}", + r->offset(), + err.what()); + } + if (auto e = r->find(offset)) { + return std::make_pair(r->filename(e->file), e->line); + } + } + return std::nullopt; + } + std::unordered_map> libraries_; + std::vector> line_number_programs_; + std::vector warnings_; +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/fde.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/fde.h new file mode 100644 index 0000000000000000000000000000000000000000..d9b3aef3dd6337a5fa48a3904c1886d5ca617ff8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/fde.h @@ -0,0 +1,416 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::unwind { + +struct TableState { + Action cfa; + std::array registers; + friend std::ostream& operator<<(std::ostream& out, const TableState& self) { + out << "cfa = " << self.cfa << "; "; + for (auto r : c10::irange(self.registers.size())) { + if (self.registers.at(r).kind != A_UNDEFINED) { + out << 'r' << r << " = " << self.registers.at(r) << "; "; + } + } + return out; + } +}; + +// FDE - Frame Description Entry (Concept in ELF spec) +// This format is explained well by +// https://www.airs.com/blog/archives/460 +// Details of different dwarf actions are explained +// in the spec document: +// https://web.archive.org/web/20221129184704/https://dwarfstd.org/doc/DWARF4.doc +// An overview of how DWARF unwinding works is given in +// https://dl.acm.org/doi/pdf/10.1145/3360572 +// A similar implementation written in rust is: +// https://github.com/mstange/framehop/ + +template +struct FDE { + FDE(void* data, const char* library_name, uint64_t load_bias) + : library_name_(library_name), load_bias_(load_bias) { + Lexer L(data); + auto length = L.read4or8Length(); + void* fde_start = L.loc(); + // NOLINTNEXTLINE(performance-no-int-to-ptr) + void* cie_data = (void*)((int64_t)fde_start - L.read()); + Lexer LC(cie_data); + auto cie_length = LC.read4or8Length(); + void* cie_start = LC.loc(); + auto zero = LC.read(); + TORCH_INTERNAL_ASSERT(zero == 0, "expected 0 for CIE"); + auto version = LC.read(); + TORCH_INTERNAL_ASSERT( + version == 1 || version == 3, "non-1 version for CIE"); + augmentation_string_ = LC.readCString(); + if (hasAugmentation("eh")) { + throw UnwindError("unsupported 'eh' augmentation string"); + } + code_alignment_factor_ = static_cast(LC.readULEB128()); + data_alignment_factor_ = LC.readSLEB128(); + if (version == 1) { + ra_register_ = LC.read(); + } else { + ra_register_ = static_cast(LC.readULEB128()); + } + // we assume this in the state + TORCH_INTERNAL_ASSERT(ra_register_ == 16, "unexpected number of registers"); + if (augmentation_string_ && *augmentation_string_ == 'z') { + augmentation_length_ = static_cast(LC.readULEB128()); + Lexer A(LC.loc()); + for (auto ap = augmentation_string_ + 1; *ap; ap++) { + switch (*ap) { + case 'L': + lsda_enc = A.read(); + break; + case 'R': + fde_enc = A.read(); + break; + case 'P': { + uint8_t personality_enc = A.read(); + A.readEncoded(personality_enc); + } break; + case 'S': { + // signal handler + } break; + default: { + throw UnwindError("unknown augmentation string"); + } break; + } + } + } + LC.skip(augmentation_length_); + low_pc_ = L.readEncoded(fde_enc); + high_pc_ = low_pc_ + L.readEncodedValue(fde_enc); + + if (hasAugmentation("z")) { + augmentation_length_fde_ = static_cast(L.readULEB128()); + } + L.readEncodedOr(lsda_enc, 0); + + cie_begin_ = LC.loc(); + fde_begin_ = L.loc(); + cie_end_ = (void*)((const char*)cie_start + cie_length); + fde_end_ = (void*)((const char*)fde_start + length); + } + + // OP Code implementations + + void advance_raw(int64_t amount) { + auto previous_pc = current_pc_; + current_pc_ += amount; + if (LOG) { + (*out_) << (void*)(previous_pc - load_bias_) << '-' + << (void*)(current_pc_ - load_bias_) << ": " << state() << '\n'; + } + } + + void advance_loc(int64_t amount) { + if (LOG) { + (*out_) << "advance_loc " << amount << '\n'; + } + advance_raw(amount * code_alignment_factor_); + } + + void offset(int64_t reg, int64_t offset) { + if (LOG) { + (*out_) << "offset " << reg << ' ' << offset << '\n'; + } + if (reg > (int64_t)state().registers.size()) { + if (LOG) { + (*out_) << "OFFSET OF BIG REGISTER " << reg << "ignored...\n"; + } + return; + } + state().registers.at(reg) = + Action{A_LOAD_CFA_OFFSET, -1, offset * data_alignment_factor_}; + } + + void restore(int64_t reg) { + if (LOG) { + (*out_) << "restore " << reg << '\n'; + } + if (reg > (int64_t)state().registers.size()) { + if (LOG) { + (*out_) << "RESTORE OF BIG REGISTER " << reg << "ignored...\n"; + } + return; + } + state().registers.at(reg) = initial_state_.registers.at(reg); + } + + void def_cfa(int64_t reg, int64_t off) { + if (LOG) { + (*out_) << "def_cfa " << reg << ' ' << off << '\n'; + } + last_reg_ = reg; + last_offset_ = off; + state().cfa = Action::regPlusData(static_cast(reg), off); + } + void def_cfa_register(int64_t reg) { + def_cfa(reg, last_offset_); + } + void def_cfa_offset(int64_t off) { + def_cfa(last_reg_, off); + } + + void remember_state() { + if (LOG) { + (*out_) << "remember_state\n"; + } + state_stack_.push_back(state()); + } + void restore_state() { + if (LOG) { + (*out_) << "restore_state\n"; + } + state_stack_.pop_back(); + } + + void undefined(int64_t reg) { + if (LOG) { + (*out_) << "undefined " << reg << '\n'; + } + state().registers.at(reg) = Action::undefined(); + } + void register_(int64_t reg, int64_t rhs_reg) { + if (LOG) { + (*out_) << "register " << reg << ' ' << rhs_reg << '\n'; + } + state().registers.at(reg) = + Action::regPlusData(static_cast(reg), 0); + } + + TableState& state() { + return state_stack_.back(); + } + + void dump(std::ostream& out) { + out_ = &out; + out << "FDE(augmentation_string=" << augmentation_string_ + << ", low_pc=" << (void*)(low_pc_ - load_bias_) + << ",high_pc=" << (void*)(high_pc_ - load_bias_) + << ",code_alignment_factor=" << code_alignment_factor_ + << ", data_alignment_factor=" << data_alignment_factor_ + << ", ra_register_=" << ra_register_ << ")\n"; + readUpTo(high_pc_); + out_ = &std::cout; + } + + TableState readUpTo(uint64_t addr) { + if (addr < low_pc_ || addr > high_pc_) { + throw UnwindError("Address not in range"); + } + if (LOG) { + // NOLINTNEXTLINE(performance-no-int-to-ptr) + (*out_) << "readUpTo " << (void*)addr << " for " << library_name_ + << " at " << (void*)load_bias_ << '\n'; + } + state_stack_.emplace_back(); + current_pc_ = low_pc_; + // parse instructions... + Lexer LC(cie_begin_); + while (LC.loc() < cie_end_ && current_pc_ <= addr) { + readInstruction(LC); + } + if (current_pc_ > addr) { + return state(); + } + + initial_state_ = state_stack_.back(); + + if (LOG) { + (*out_) << "--\n"; + } + + Lexer L(fde_begin_); + while (L.loc() < fde_end_ && current_pc_ <= addr) { + readInstruction(L); + } + // so that we print the full range in debugging + if (current_pc_ <= addr) { + advance_raw(addr - current_pc_); + } + return state(); + } + + void dumpAddr2Line() { + std::cout << "addr2line -f -e " << library_name_ << ' ' + << (void*)(low_pc_ - load_bias_) << '\n'; + } + + void readInstruction(Lexer& L) { + uint8_t bc = L.read(); + auto op = bc >> 6; + auto lowbits = bc & 0x3F; + switch (op) { + case 0x0: { + switch (lowbits) { + case DW_CFA_nop: { + return; // nop + } + case DW_CFA_advance_loc1: { + auto delta = L.read(); + return advance_loc(delta); + } + case DW_CFA_advance_loc2: { + auto delta = L.read(); + return advance_loc(delta); + } + case DW_CFA_advance_loc4: { + auto delta = L.read(); + return advance_loc(delta); + } + case DW_CFA_restore_extended: { + auto reg = L.readULEB128(); + return restore(reg); + } + case DW_CFA_undefined: { + auto reg = L.readULEB128(); + return undefined(reg); + } + case DW_CFA_register: { + auto reg = L.readULEB128(); + auto rhs_reg = L.readULEB128(); + return register_(reg, rhs_reg); + } + case DW_CFA_def_cfa: { + auto reg = L.readULEB128(); + auto off = L.readULEB128(); + return def_cfa(reg, off); + } + case DW_CFA_def_cfa_register: { + auto reg = L.readULEB128(); + return def_cfa_register(reg); + } + case DW_CFA_def_cfa_offset: { + auto off = L.readULEB128(); + return def_cfa_offset(off); + } + case DW_CFA_offset_extended_sf: { + auto reg = L.readULEB128(); + auto off = L.readSLEB128(); + return offset(reg, off); + } + case DW_CFA_remember_state: { + return remember_state(); + } + case DW_CFA_restore_state: { + return restore_state(); + } + case DW_CFA_GNU_args_size: { + // GNU_args_size, we do not need to know it.. + L.readULEB128(); + return; + } + case DW_CFA_expression: { + auto reg = L.readULEB128(); + auto len = L.readULEB128(); + // NOLINTNEXTLINE(performance-no-int-to-ptr) + auto end = (void*)((uint64_t)L.loc() + len); + auto op = L.read(); + if ((op & 0xF0) == 0x70) { // DW_bregX + auto rhs_reg = (op & 0xF); + auto addend = L.readSLEB128(); + if (L.loc() == end) { + state().registers.at(reg) = + Action::regPlusDataDeref(rhs_reg, addend); + return; + } + } + throw UnwindError("Unsupported dwarf expression"); + } + case DW_CFA_def_cfa_expression: { + auto len = L.readULEB128(); + // NOLINTNEXTLINE(performance-no-int-to-ptr) + auto end = (void*)((uint64_t)L.loc() + len); + auto op = L.read(); + if ((op & 0xF0) == 0x70) { // DW_bregX + auto rhs_reg = (op & 0xF); + auto addend = L.readSLEB128(); + if (L.loc() != end) { + auto op2 = L.read(); + if (op2 == DW_OP_deref && L.loc() == end) { // deref + state().cfa = Action::regPlusDataDeref(rhs_reg, addend); + return; + } + } + } + throw UnwindError("Unsupported def_cfa dwarf expression"); + } + default: { + std::stringstream ss; + // NOLINTNEXTLINE(performance-no-int-to-ptr) + ss << "unknown op code " << (void*)(uint64_t)lowbits; + throw UnwindError(ss.str()); + } + } + } + case DW_CFA_advance_loc: { + return advance_loc(lowbits); + } + case DW_CFA_offset: { + auto off = L.readULEB128(); + return offset(lowbits, off); + } + case DW_CFA_restore: { + return restore(lowbits); + } + } + } + // used for debug printing + const char* library_name_; + uint64_t load_bias_; + + // parsed from the eh_string data structures: + const char* augmentation_string_ = nullptr; + int64_t augmentation_length_ = 0; + int64_t augmentation_length_fde_ = 0; + + int64_t code_alignment_factor_; + int64_t data_alignment_factor_; + void* cie_data_{nullptr}; + + int64_t ra_register_; + uint8_t lsda_enc = DW_EH_PE_omit; + uint8_t fde_enc = DW_EH_PE_absptr; + uint64_t low_pc_ = UINT64_MAX; + uint64_t high_pc_ = UINT64_MAX; + + void* cie_begin_; + void* fde_begin_; + void* cie_end_; + void* fde_end_; + + // state accumulated while parsing instructions + int64_t last_reg_ = 0; + int64_t last_offset_ = 0; + uint64_t current_pc_ = 0; + + TableState + initial_state_; // state after the initial instructions, used by restore + std::vector state_stack_; + + std::ostream* out_ = &std::cout; // for debug dumping + private: + bool hasAugmentation(const char* s) { + return strstr(augmentation_string_, s) != nullptr; + } +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/lexer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/lexer.h new file mode 100644 index 0000000000000000000000000000000000000000..f9580a88c4574ba9d74464bd61b7d4e0ec527730 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/lexer.h @@ -0,0 +1,164 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include + +namespace torch::unwind { + +template +struct LexerImpl { + LexerImpl(void* data, void* base = nullptr, void* end = nullptr) + : next_((const char*)data), + base_((int64_t)base), + end_((const char*)end) {} + + template + T read() { + T result; + auto end = next_ + sizeof(T); + UNWIND_CHECK( + !checked || end <= end_, + "read out of bounds {} >= {}", + (void*)end, + (void*)end_); + memcpy(&result, next_, sizeof(T)); + next_ = end; + return result; + } + + // SLEB/ULEB code adapted from LLVM equivalents + int64_t readSLEB128() { + int64_t Value = 0; + unsigned Shift = 0; + uint8_t Byte = 0; + do { + Byte = read(); + uint64_t Slice = Byte & 0x7f; + if ((Shift >= 64 && Slice != (Value < 0 ? 0x7f : 0x00)) || + (Shift == 63 && Slice != 0 && Slice != 0x7f)) { + throw UnwindError("sleb128 too big for int64"); + } + Value |= int64_t(Slice << Shift); + Shift += 7; + } while (Byte >= 128); + // Sign extend negative numbers if needed. + if (Shift < 64 && (Byte & 0x40)) { + Value |= int64_t((-1ULL) << Shift); + } + return Value; + } + + uint64_t readULEB128() { + uint64_t Value = 0; + unsigned Shift = 0; + uint8_t p = 0; + do { + p = read(); + uint64_t Slice = p & 0x7f; + if ((Shift >= 64 && Slice != 0) || Slice << Shift >> Shift != Slice) { + throw UnwindError("uleb128 too big for uint64"); + } + Value += Slice << Shift; + Shift += 7; + } while (p >= 128); + return Value; + } + const char* readCString() { + auto result = next_; + if (!checked) { + next_ += strlen(next_) + 1; + return result; + } + while (next_ < end_) { + if (*next_++ == '\0') { + return result; + } + } + UNWIND_CHECK( + false, "string is out of bounds {} >= {}", (void*)next_, (void*)end_); + } + int64_t readEncoded(uint8_t enc) { + int64_t r = 0; + switch (enc & (~DW_EH_PE_indirect & 0xF0)) { + case DW_EH_PE_absptr: + break; + case DW_EH_PE_pcrel: + r = (int64_t)next_; + break; + case DW_EH_PE_datarel: + r = base_; + break; + default: + throw UnwindError("unknown encoding"); + } + return r + readEncodedValue(enc); + } + int64_t readEncodedOr(uint8_t enc, int64_t orelse) { + if (enc == DW_EH_PE_omit) { + return orelse; + } + return readEncoded(enc); + } + + int64_t read4or8Length() { + return readSectionLength().first; + } + + std::pair readSectionLength() { + int64_t length = read(); + if (length == 0xFFFFFFFF) { + return std::make_pair(read(), true); + } + return std::make_pair(length, false); + } + + void* loc() const { + return (void*)next_; + } + LexerImpl& skip(size_t bytes) { + next_ += bytes; + return *this; + } + + int64_t readEncodedValue(uint8_t enc) { + switch (enc & 0xF) { + case DW_EH_PE_udata2: + return read(); + case DW_EH_PE_sdata2: + return read(); + case DW_EH_PE_udata4: + return read(); + case DW_EH_PE_sdata4: + return read(); + case DW_EH_PE_udata8: + return read(); + case DW_EH_PE_sdata8: + return read(); + case DW_EH_PE_uleb128: + return readULEB128(); + case DW_EH_PE_sleb128: + return readSLEB128(); + default: + throw UnwindError("not implemented"); + } + } + + private: + const char* next_; + int64_t base_; + const char* end_; +}; + +// using Lexer = LexerImpl; +using CheckedLexer = LexerImpl; +using Lexer = LexerImpl; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/line_number_program.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/line_number_program.h new file mode 100644 index 0000000000000000000000000000000000000000..32fbc59c4655a7d99c2c795c04c88b125b12193c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/line_number_program.h @@ -0,0 +1,333 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::unwind { + +struct LineNumberProgram { + LineNumberProgram(Sections& s, uint64_t offset) : s_(s), offset_(offset) {} + + uint64_t offset() { + return offset_; + } + void parse() { + if (parsed_) { + return; + } + parsed_ = true; + CheckedLexer L = s_.debug_line.lexer(offset_); + std::tie(length_, is_64bit_) = L.readSectionLength(); + program_end_ = (char*)L.loc() + length_; + auto version = L.read(); + UNWIND_CHECK( + version == 5 || version == 4, + "expected version 4 or 5 but found {}", + version); + if (version == 5) { + auto address_size = L.read(); + UNWIND_CHECK( + address_size == 8, + "expected 64-bit dwarf but found address size {}", + address_size); + segment_selector_size_ = L.read(); + } + header_length_ = is_64bit_ ? L.read() : L.read(); + program_ = L; + program_.skip(int64_t(header_length_)); + minimum_instruction_length_ = L.read(); + maximum_operations_per_instruction_ = L.read(); + default_is_stmt_ = L.read(); + line_base_ = L.read(); + line_range_ = L.read(); + opcode_base_ = L.read(); + UNWIND_CHECK(line_range_ != 0, "line_range_ must be non-zero"); + standard_opcode_lengths_.resize(opcode_base_); + for (size_t i = 1; i < opcode_base_; i++) { + standard_opcode_lengths_[i] = L.read(); + } + // fmt::print("{:x} {:x} {} {} {} {} {}\n", offset_, header_length_, + // minimum_instruction_length_, maximum_operations_per_instruction_, + // line_base_, line_range_, opcode_base_); + uint8_t directory_entry_format_count = L.read(); + + if (version == 5) { + struct Member { + uint64_t content_type; + uint64_t form; + }; + std::vector directory_members; + directory_members.reserve(directory_entry_format_count); + for (size_t i = 0; i < directory_entry_format_count; i++) { + directory_members.push_back({L.readULEB128(), L.readULEB128()}); + } + uint64_t directories_count = L.readULEB128(); + for (size_t i = 0; i < directories_count; i++) { + for (auto& member : directory_members) { + switch (member.content_type) { + case DW_LNCT_path: { + include_directories_.emplace_back( + s_.readString(L, member.form, is_64bit_)); + } break; + default: { + skipForm(L, member.form); + } break; + } + } + } + + for (auto i : c10::irange(directories_count)) { + (void)i; + LOG_INFO("{} {}\n", i, include_directories_[i]); + } + auto file_name_entry_format_count = L.read(); + std::vector file_members; + file_members.reserve(file_name_entry_format_count); + for (size_t i = 0; i < file_name_entry_format_count; i++) { + file_members.push_back({L.readULEB128(), L.readULEB128()}); + } + auto files_count = L.readULEB128(); + for (size_t i = 0; i < files_count; i++) { + for (auto& member : file_members) { + switch (member.content_type) { + case DW_LNCT_path: { + file_names_.emplace_back( + s_.readString(L, member.form, is_64bit_)); + } break; + case DW_LNCT_directory_index: { + file_directory_index_.emplace_back(readData(L, member.form)); + UNWIND_CHECK( + file_directory_index_.back() < include_directories_.size(), + "directory index out of range"); + } break; + default: { + skipForm(L, member.form); + } break; + } + } + } + for (auto i : c10::irange(files_count)) { + (void)i; + LOG_INFO("{} {} {}\n", i, file_names_[i], file_directory_index_[i]); + } + } else { + include_directories_.emplace_back(""); // implicit cwd + while (true) { + auto str = L.readCString(); + if (*str == '\0') { + break; + } + include_directories_.emplace_back(str); + } + file_names_.emplace_back(""); + file_directory_index_.emplace_back(0); + while (true) { + auto str = L.readCString(); + if (*str == '\0') { + break; + } + auto directory_index = L.readULEB128(); + L.readULEB128(); // mod_time + L.readULEB128(); // file_length + file_names_.emplace_back(str); + file_directory_index_.push_back(directory_index); + } + } + UNWIND_CHECK( + maximum_operations_per_instruction_ == 1, + "maximum_operations_per_instruction_ must be 1"); + UNWIND_CHECK( + minimum_instruction_length_ == 1, + "minimum_instruction_length_ must be 1"); + readProgram(); + } + struct Entry { + uint32_t file = 1; + int64_t line = 1; + }; + std::optional find(uint64_t address) { + auto e = program_index_.find(address); + if (!e) { + return std::nullopt; + } + return all_programs_.at(*e).find(address); + } + std::string filename(uint64_t index) { + return fmt::format( + "{}/{}", + include_directories_.at(file_directory_index_.at(index)), + file_names_.at(index)); + } + + private: + void skipForm(CheckedLexer& L, uint64_t form) { + auto sz = formSize(form, is_64bit_ ? 8 : 4); + UNWIND_CHECK(sz, "unsupported form {}", form); + L.skip(int64_t(*sz)); + } + + uint64_t readData(CheckedLexer& L, uint64_t encoding) { + switch (encoding) { + case DW_FORM_data1: + return L.read(); + case DW_FORM_data2: + return L.read(); + case DW_FORM_data4: + return L.read(); + case DW_FORM_data8: + return L.read(); + case DW_FORM_udata: + return L.readULEB128(); + default: + UNWIND_CHECK(false, "unsupported data encoding {}", encoding); + } + } + + void produceEntry() { + if (shadow_) { + return; + } + if (ranges_.size() == 1) { + start_address_ = address_; + } + PRINT_LINE_TABLE( + "{:x}\t{}\t{}\n", address_, filename(entry_.file), entry_.line); + UNWIND_CHECK( + entry_.file < file_names_.size(), + "file index {} > {} entries", + entry_.file, + file_names_.size()); + ranges_.add(address_, entry_, true); + } + void endSequence() { + if (shadow_) { + return; + } + PRINT_LINE_TABLE( + "{:x}\tEND\n", address_, filename(entry_.file), entry_.line); + program_index_.add(start_address_, all_programs_.size(), false); + program_index_.add(address_, std::nullopt, false); + all_programs_.emplace_back(std::move(ranges_)); + ranges_ = RangeTable(); + } + void readProgram() { + while (program_.loc() < program_end_) { + PRINT_INST("{:x}: ", (char*)program_.loc() - (s_.debug_line.data)); + uint8_t op = program_.read(); + if (op >= opcode_base_) { + auto op2 = int64_t(op - opcode_base_); + address_ += op2 / line_range_; + entry_.line += line_base_ + (op2 % line_range_); + PRINT_INST( + "address += {}, line += {}\n", + op2 / line_range_, + line_base_ + (op2 % line_range_)); + produceEntry(); + } else { + switch (op) { + case DW_LNS_extended_op: { + auto len = program_.readULEB128(); + auto extended_op = program_.read(); + switch (extended_op) { + case DW_LNE_end_sequence: { + PRINT_INST("end_sequence\n"); + endSequence(); + entry_ = Entry{}; + } break; + case DW_LNE_set_address: { + address_ = program_.read(); + if (!shadow_) { + PRINT_INST( + "set address {:x} {:x} {:x}\n", + address_, + min_address_, + max_address_); + } + shadow_ = address_ == 0; + } break; + default: { + PRINT_INST("skip extended op {}\n", extended_op); + program_.skip(int64_t(len - 1)); + } break; + } + } break; + case DW_LNS_copy: { + PRINT_INST("copy\n"); + produceEntry(); + } break; + case DW_LNS_advance_pc: { + PRINT_INST("advance pc\n"); + address_ += program_.readULEB128(); + } break; + case DW_LNS_advance_line: { + entry_.line += program_.readSLEB128(); + PRINT_INST("advance line {}\n", entry_.line); + + } break; + case DW_LNS_set_file: { + PRINT_INST("set file\n"); + entry_.file = program_.readULEB128(); + } break; + case DW_LNS_const_add_pc: { + PRINT_INST("const add pc\n"); + address_ += (255 - opcode_base_) / line_range_; + } break; + case DW_LNS_fixed_advance_pc: { + PRINT_INST("fixed advance pc\n"); + address_ += program_.read(); + } break; + default: { + PRINT_INST("other {}\n", op); + auto n = standard_opcode_lengths_[op]; + for (int i = 0; i < n; ++i) { + program_.readULEB128(); + } + } break; + } + } + } + PRINT_INST( + "{:x}: end {:x}\n", + ((char*)program_.loc() - s_.debug_line.data), + program_end_ - s_.debug_line.data); + } + + uint64_t address_ = 0; + bool shadow_ = false; + bool parsed_ = false; + Entry entry_ = {}; + std::vector include_directories_; + std::vector file_names_; + std::vector file_directory_index_; + uint8_t segment_selector_size_ = 0; + uint8_t minimum_instruction_length_ = 0; + uint8_t maximum_operations_per_instruction_ = 0; + int8_t line_base_ = 0; + uint8_t line_range_ = 0; + uint8_t opcode_base_ = 0; + bool default_is_stmt_ = false; + CheckedLexer program_ = {nullptr}; + char* program_end_ = nullptr; + uint64_t header_length_ = 0; + uint64_t length_ = 0; + bool is_64bit_ = false; + std::vector standard_opcode_lengths_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + Sections& s_; + uint64_t offset_; + uint64_t start_address_ = 0; + RangeTable program_index_; + std::vector> all_programs_; + RangeTable ranges_; +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/mem_file.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/mem_file.h new file mode 100644 index 0000000000000000000000000000000000000000..15f6821012f0306007a061499867a8d1d97b7ec2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/mem_file.h @@ -0,0 +1,164 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::unwind { + +struct Section { + char* data = nullptr; + size_t size = 0; + const char* string(size_t offset) { + return lexer(offset).readCString(); + } + CheckedLexer lexer(size_t offset) { + return CheckedLexer(data + offset, data, data + size); + } +}; + +/// Memory maps a file into the address space read-only, and manages the +/// lifetime of the mapping. Here are a few use cases: +/// 1. Used in the loader to read in initial image, and to inspect +// ELF files for dependencies before calling dlopen. +/// +/// 2. Used in unity to load the elf file. +struct MemFile { + explicit MemFile(const char* filename_) + : fd_(open(filename_, O_RDONLY)), name_(filename_) { + UNWIND_CHECK( + fd_ != -1, + "failed to open {}: {}", + filename_, + c10::utils::str_error(errno)); + struct stat s{}; + if (-1 == fstat(fd_, &s)) { + close(fd_); // destructors don't run during exceptions + UNWIND_CHECK( + false, + "failed to stat {}: {}", + filename_, + c10::utils::str_error(errno)); + } + n_bytes_ = s.st_size; + UNWIND_CHECK( + n_bytes_ > sizeof(Elf64_Ehdr), "empty shared library: {}", filename_); + mem_ = (char*)mmap(nullptr, n_bytes_, PROT_READ, MAP_SHARED, fd_, 0); + if (MAP_FAILED == mem_) { + close(fd_); + UNWIND_CHECK( + false, + "failed to mmap {}: {}", + filename_, + c10::utils::str_error(errno)); + } + ehdr_ = (Elf64_Ehdr*)mem_; +#define ELF_CHECK(cond) UNWIND_CHECK(cond, "not an ELF file: {}", filename_) + ELF_CHECK(ehdr_->e_ident[EI_MAG0] == ELFMAG0); + ELF_CHECK(ehdr_->e_ident[EI_MAG1] == ELFMAG1); + ELF_CHECK(ehdr_->e_ident[EI_MAG2] == ELFMAG2); + ELF_CHECK(ehdr_->e_ident[EI_MAG3] == ELFMAG3); + ELF_CHECK(ehdr_->e_ident[EI_CLASS] == ELFCLASS64); + ELF_CHECK(ehdr_->e_ident[EI_VERSION] == EV_CURRENT); + ELF_CHECK(ehdr_->e_version == EV_CURRENT); + ELF_CHECK(ehdr_->e_machine == EM_X86_64); +#undef ELF_CHECK + UNWIND_CHECK( + ehdr_->e_shoff + sizeof(Elf64_Shdr) * ehdr_->e_shnum <= n_bytes_, + "invalid section header table {} {} {}", + ehdr_->e_shoff + sizeof(Elf64_Shdr) * ehdr_->e_shnum, + n_bytes_, + ehdr_->e_shnum); + shdr_ = (Elf64_Shdr*)(mem_ + ehdr_->e_shoff); + UNWIND_CHECK( + ehdr_->e_shstrndx < ehdr_->e_shnum, "invalid strtab section offset"); + auto& strtab_hdr = shdr_[ehdr_->e_shstrndx]; + strtab_ = getSection(strtab_hdr); + } + + MemFile(const MemFile&) = delete; + MemFile(MemFile&&) = delete; + MemFile& operator=(const MemFile&) = delete; + MemFile& operator=(MemFile&&) = delete; + [[nodiscard]] const char* data() const { + return (const char*)mem_; + } + + /// Returns whether or not the file descriptor + /// of the underlying file is valid. + int valid() { + return fcntl(fd_, F_GETFD) != -1 || errno != EBADF; + } + + ~MemFile() { + if (mem_) { + munmap((void*)mem_, n_bytes_); + } + if (fd_ >= 0) { + close(fd_); + } + } + + /// Returns the size of the underlying file defined by the `MemFile` + size_t size() { + return n_bytes_; + } + [[nodiscard]] int fd() const { + return fd_; + } + + Section getSection(const Elf64_Shdr& shdr) { + UNWIND_CHECK(shdr.sh_offset + shdr.sh_size <= n_bytes_, "invalid section"); + return Section{mem_ + shdr.sh_offset, shdr.sh_size}; + } + + Section getSection(const char* name, bool optional) { + for (int i = 0; i < ehdr_->e_shnum; i++) { + if (strcmp(strtab_.string(shdr_[i].sh_name), name) == 0) { + return getSection(shdr_[i]); + } + } + UNWIND_CHECK(optional, "{} has no section {}", name_, name); + return Section{nullptr, 0}; + } + + Section strtab() { + return strtab_; + } + + private: + template + T* load(size_t offset) { + UNWIND_CHECK(offset < n_bytes_, "out of range"); + return (T*)(mem_ + offset); + } + int fd_; + char* mem_{nullptr}; + size_t n_bytes_{0}; + std::string name_; + Elf64_Ehdr* ehdr_; + Elf64_Shdr* shdr_; + Section strtab_ = {nullptr, 0}; +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/range_table.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/range_table.h new file mode 100644 index 0000000000000000000000000000000000000000..a08bf00133fe6c4aa5f9fa7ef528b99d1c6b547b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/range_table.h @@ -0,0 +1,78 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +namespace torch::unwind { +template +struct RangeTable { + RangeTable() { + // guarantee that lower_bound[-1] is always valid + addresses_.push_back(0); + payloads_.emplace_back(std::nullopt); + } + void add(uint64_t address, std::optional payload, bool sorted) { + if (addresses_.back() > address) { + UNWIND_CHECK(!sorted, "expected addresses to be sorted"); + sorted_ = false; + } + addresses_.push_back(address); + payloads_.emplace_back(std::move(payload)); + } + std::optional find(uint64_t address) { + maybeSort(); + auto it = std::upper_bound(addresses_.begin(), addresses_.end(), address); + return payloads_.at(it - addresses_.begin() - 1); + } + void dump() { + for (size_t i = 0; i < addresses_.size(); i++) { + fmt::print("{} {:x}: {}\n", i, addresses_[i], payloads_[i] ? "" : "END"); + } + } + size_t size() const { + return addresses_.size(); + } + uint64_t back() { + maybeSort(); + return addresses_.back(); + } + + private: + void maybeSort() { + if (sorted_) { + return; + } + std::vector indices; + indices.reserve(addresses_.size()); + for (size_t i = 0; i < addresses_.size(); i++) { + indices.push_back(i); + } + std::sort(indices.begin(), indices.end(), [&](uint64_t a, uint64_t b) { + return addresses_[a] < addresses_[b] || + (addresses_[a] == addresses_[b] && + bool(payloads_[a]) < bool(payloads_[b])); + }); + std::vector addresses; + std::vector> payloads; + addresses.reserve(addresses_.size()); + payloads.reserve(addresses_.size()); + for (auto i : indices) { + addresses.push_back(addresses_[i]); + payloads.push_back(payloads_[i]); + } + addresses_ = std::move(addresses); + payloads_ = std::move(payloads); + sorted_ = true; + } + bool sorted_ = true; + std::vector addresses_; + std::vector> payloads_; +}; +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/sections.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/sections.h new file mode 100644 index 0000000000000000000000000000000000000000..f3f4f63b2d4e92d14ff361c722df2b66f0009d73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/sections.h @@ -0,0 +1,125 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::unwind { + +static std::string demangle(const std::string& mangled_name) { + int status = 0; + char* realname = + abi::__cxa_demangle(mangled_name.c_str(), nullptr, nullptr, &status); + if (status == 0) { + std::string demangled_name(realname); + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + free(realname); + return demangled_name; + } else { + return mangled_name; + } +} + +struct Sections { + Sections() = default; + void parse(const char* name) { + library_ = std::make_unique(name); + strtab = library_->getSection(".strtab", false); + + symtab = library_->getSection(".symtab", true); + debug_info = library_->getSection(".debug_info", true); + if (debug_info.size > 0) { + debug_abbrev = library_->getSection(".debug_abbrev", false); + debug_str = library_->getSection(".debug_str", false); + debug_line = library_->getSection(".debug_line", false); + // dwarf 5 + debug_line_str = library_->getSection(".debug_line_str", true); + debug_rnglists = library_->getSection(".debug_rnglists", true); + debug_addr = library_->getSection(".debug_addr", true); + // dwarf 4 + debug_ranges = library_->getSection(".debug_ranges", true); + } + parseSymtab(); + } + + Section debug_info; + Section debug_abbrev; + Section debug_str; + Section debug_line; + Section debug_line_str; + Section debug_rnglists; + Section debug_ranges; + Section debug_addr; + Section symtab; + Section strtab; + + const char* readString(CheckedLexer& data, uint64_t encoding, bool is_64bit) { + switch (encoding) { + case DW_FORM_string: { + return data.readCString(); + } + case DW_FORM_strp: { + return debug_str.string(readSegmentOffset(data, is_64bit)); + } + case DW_FORM_line_strp: { + return debug_line_str.string(readSegmentOffset(data, is_64bit)); + } + default: + UNWIND_CHECK(false, "unsupported string encoding {:x}", encoding); + } + } + + uint64_t readSegmentOffset(CheckedLexer& data, bool is_64bit) { + return is_64bit ? data.read() : data.read(); + } + + std::optional findDebugInfoOffset(uint64_t address) { + return debug_info_offsets_.find(address); + } + size_t compilationUnitCount() { + return debug_info_offsets_.size() / 2; + } + void addDebugInfoRange( + uint64_t start, + uint64_t end, + uint64_t debug_info_offset) { + debug_info_offsets_.add(start, debug_info_offset, false); + debug_info_offsets_.add(end, std::nullopt, false); + } + std::optional findSubprogramName(uint64_t address) { + if (auto e = symbol_table_.find(address)) { + return demangle(strtab.string(*e)); + } + return std::nullopt; + } + + private: + void parseSymtab() { + auto L = symtab.lexer(0); + char* end = symtab.data + symtab.size; + while (L.loc() < end) { + auto symbol = L.read(); + if (symbol.st_shndx == SHN_UNDEF || + ELF64_ST_TYPE(symbol.st_info) != STT_FUNC) { + continue; + } + symbol_table_.add(symbol.st_value, symbol.st_name, false); + symbol_table_.add(symbol.st_value + symbol.st_size, std::nullopt, false); + } + } + + std::unique_ptr library_; + RangeTable debug_info_offsets_; + RangeTable symbol_table_; +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwind.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwind.h new file mode 100644 index 0000000000000000000000000000000000000000..5dd90ecbbebb016b28fc3c3581a5e3a4c8f36c6a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwind.h @@ -0,0 +1,48 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +namespace torch::unwind { +// gather current stack, relatively fast. +// gets faster once the cache of program counter locations is warm. +TORCH_API std::vector unwind(); + +struct Frame { + std::string filename; + std::string funcname; + uint64_t lineno; +}; + +enum class Mode { addr2line, fast, dladdr }; + +// note: symbolize is really slow +// it will launch an addr2line process that has to parse dwarf +// information from the libraries that frames point into. +// Callers should first batch up all the unique void* pointers +// across a number of unwind states and make a single call to +// symbolize. +TORCH_API std::vector symbolize( + const std::vector& frames, + Mode mode); + +// returns path to the library, and the offset of the addr inside the library +TORCH_API std::optional> libraryFor( + void* addr); + +struct Stats { + size_t hits = 0; + size_t misses = 0; + size_t unsupported = 0; + size_t resets = 0; +}; +Stats stats(); + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwind_error.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwind_error.h new file mode 100644 index 0000000000000000000000000000000000000000..9a468e702c2379d2b25d6bd1c251daa517f1cf1f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwind_error.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::unwind { + +struct UnwindError : public std::runtime_error { + using std::runtime_error::runtime_error; +}; + +#define UNWIND_CHECK(cond, fmtstring, ...) \ + do { \ + if (!(cond)) { \ + throw unwind::UnwindError(fmt::format( \ + "{}:{}: " fmtstring, __FILE__, __LINE__, ##__VA_ARGS__)); \ + } \ + } while (0) + +// #define LOG_INFO(...) fmt::print(__VA_ARGS__) +#define LOG_INFO(...) + +// #define PRINT_INST(...) LOG_INFO(__VA_ARGS__) +#define PRINT_INST(...) + +// #define PRINT_LINE_TABLE(...) LOG_INFO(__VA_ARGS__) +#define PRINT_LINE_TABLE(...) + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwinder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwinder.h new file mode 100644 index 0000000000000000000000000000000000000000..a297f44f5d54a6c1476d551e07cf33468eff6352 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwinder.h @@ -0,0 +1,86 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::unwind { + +struct UnwindState { + int64_t rip, rbp, rsp; +}; + +struct Unwinder { + Unwinder(Action rsp, Action rip, Action rbp) + : kind_(rip.kind == A_UNDEFINED ? END : STANDARD), + reg_(rsp.reg), + off_(rsp.data), + rip_off_(rip.data), + rbp_off_( + rbp.kind == A_UNDEFINED ? std::numeric_limits::max() + : rbp.data), + deref_(rsp.kind == A_REG_PLUS_DATA_DEREF) { + check(rsp.reg == D_RSP || rsp.reg == D_RBP); + check(rip.kind == A_UNDEFINED || rip.kind == A_LOAD_CFA_OFFSET); + if (rsp.kind == A_REG_PLUS_DATA) { + check(rbp.kind == A_LOAD_CFA_OFFSET || rbp.kind == A_UNDEFINED); + } else if (rsp.kind == A_REG_PLUS_DATA_DEREF) { + if (rbp.kind == A_REG_PLUS_DATA_DEREF) { + check(rbp.reg == rsp.reg); + rbp_off_ -= rsp.data; + } else { + check(rbp.kind == A_UNDEFINED); + } + } else { + check(false); + } + } + void check(bool cond) { + if (!cond) { + throw UnwindError("Unwinding actions do not follow supported patterns"); + } + } + bool terminator() const { + return kind_ != STANDARD; + } + bool isUnknown() const { + return kind_ == UNKNOWN; + } + // unwinder representing some pattern unsupported in + // current implementation + static Unwinder unknown() { + return Unwinder(); + } + UnwindState run(const UnwindState& cur) const { + UnwindState r = cur; + r.rsp = (reg_ == D_RSP ? cur.rsp : cur.rbp) + off_; + r.rbp = rbp_off_ == std::numeric_limits::max() + ? cur.rbp + // NOLINTNEXTLINE(performance-no-int-to-ptr) + : *(int64_t*)(r.rsp + rbp_off_); + if (deref_) { + // NOLINTNEXTLINE(performance-no-int-to-ptr) + r.rsp = *(int64_t*)r.rsp; + } + // NOLINTNEXTLINE(performance-no-int-to-ptr) + r.rip = *(int64_t*)(r.rsp + rip_off_); + + return r; + } + + private: + Unwinder() : kind_(UNKNOWN), reg_(0), off_(0), rip_off_(0), rbp_off_(0) {} + enum Kind { STANDARD, END, UNKNOWN } kind_; + uint32_t reg_; + int64_t off_; + int64_t rip_off_; + int64_t rbp_off_; + bool deref_{false}; +}; + +} // namespace torch::unwind + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/util.h new file mode 100644 index 0000000000000000000000000000000000000000..b1e64e56da5e31ff01d02f236c98b0f5a6919a7d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/util.h @@ -0,0 +1,213 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +// TODO: replace with pytorch/rfcs#43 when it is ready. +#define SOFT_ASSERT(cond, ...) \ + [&]() -> bool { \ + if (C10_UNLIKELY(!(cond))) { \ + torch::profiler::impl::logSoftAssert( \ + __func__, \ + __FILE__, \ + static_cast(__LINE__), \ + #cond, \ + ::c10::str(__VA_ARGS__)); \ + if (torch::profiler::impl::softAssertRaises()) { \ + TORCH_INTERNAL_ASSERT(cond, __VA_ARGS__); \ + } else { \ + TORCH_WARN_ONCE(__VA_ARGS__); \ + } \ + return false; \ + } \ + return true; \ + }() + +namespace torch::profiler::impl { +TORCH_API bool softAssertRaises(); +TORCH_API void setSoftAssertRaises(std::optional value); +TORCH_API void logSoftAssert( + const char* func, + const char* file, + uint32_t line, + const char* cond, + const char* args); +inline void logSoftAssert( + const char* func, + const char* file, + uint32_t line, + const char* cond, + ::c10::detail::CompileTimeEmptyString args) { + logSoftAssert(func, file, line, cond, (const char*)args); +} +TORCH_API void logSoftAssert( + const char* func, + const char* file, + uint32_t line, + const char* cond, + const std::string& args); + +using shape = + std::variant, std::vector>>; +constexpr int TENSOR_LIST_DISPLAY_LENGTH_LIMIT = 30; + +std::string getNvtxStr( + const char* name, + int64_t sequence_nr, + const std::vector>& shapes, + at::RecordFunctionHandle op_id = 0, + const std::list>& input_op_ids = + {}); + +struct TORCH_API FileLineFunc { + std::string filename; + size_t line; + std::string funcname; +}; + +struct TORCH_API SaveNcclMetaConfig { + bool truncate; + bool introspectMetadata; + bool introspectInputs; + bool introspectOutputs; + + // Default constructor with default values + SaveNcclMetaConfig() + : truncate(true), + introspectMetadata(true), + introspectInputs(false), + introspectOutputs(false) {} + + SaveNcclMetaConfig( + bool truncate, + bool introspectMetadata, + bool introspectInputs, + bool introspectOutputs) + : truncate(truncate), + introspectMetadata(introspectMetadata), + introspectInputs(introspectInputs), + introspectOutputs(introspectOutputs) {} +}; + +TORCH_API std::vector prepareCallstack( + const std::vector& cs); +TORCH_API std::vector callstackStr( + const std::vector& cs); +TORCH_API std::string stacksToStr( + const std::vector& stacks, + const char* delim); +TORCH_API std::vector> inputSizes( + const at::RecordFunction& fn, + const bool flatten_list_enabled = false); +TORCH_API std::string variantShapesToStr(const std::vector& shapes); +TORCH_API std::string shapesToStr( + const std::vector>& shapes); +TORCH_API std::string strListToStr(const std::vector& types); +TORCH_API std::string inputOpIdsToStr( + const std::list>& input_op_ids); +TORCH_API std::string ivalueToStr(const c10::IValue& val, bool isString); +TORCH_API std::string ivalueListToStr(const std::vector& list); +TORCH_API std::vector inputTypes(const at::RecordFunction& fn); + +std::unordered_map TORCH_API +saveExtraArgs(const at::RecordFunction& fn); +std::unordered_map TORCH_API saveNcclMeta( + const at::RecordFunction& fn, + const SaveNcclMetaConfig& config = SaveNcclMetaConfig()); +int getTensorStartHint(const at::Tensor& t); +bool checkFunctionOutputsForLogging(const at::RecordFunction& fn); +bool checkFunctionInputsForLogging(const at::RecordFunction& fn); +std::pair>> findStartAddrForTensors( + const c10::IValue& val); +uint64_t TORCH_API computeFlops( + const std::string& op_name, + const std::unordered_map& extra_args); + +std::string shapeToStr(const std::vector& shape); + +template +class TORCH_API GlobalStateManager { + public: + static GlobalStateManager& singleton() { + /* library-local */ static GlobalStateManager singleton_; + return singleton_; + } + + static void push(std::shared_ptr&& state) { + if (singleton().state_) { + LOG(WARNING) << "GlobalStatePtr already exists!"; + } else { + singleton().state_ = std::move(state); + } + } + + static auto* get() { + return singleton().state_.get(); + } + + static std::shared_ptr pop() { + auto out = singleton().state_; + singleton().state_.reset(); + return out; + } + + private: + GlobalStateManager() = default; + + std::shared_ptr state_; +}; + +struct HashCombine { + template + size_t operator()(const std::pair& i) { + return c10::get_hash((*this)(i.first), (*this)(i.second)); + } + + template + size_t operator()(const std::tuple& i) { + return c10::get_hash(i); + } + + template + size_t operator()(const T& i) { + return c10::get_hash(i); + } +}; + +#ifdef USE_DISTRIBUTED +constexpr auto kCommsName = "Collective name"; +constexpr auto kDtype = "dtype"; +constexpr auto kInMsgNelems = "In msg nelems"; +constexpr auto kOutMsgNelems = "Out msg nelems"; +constexpr auto kInSplit = "In split size"; +constexpr auto kOutSplit = "Out split size"; +constexpr auto kGlobalRankStart = "Global rank start"; +constexpr auto kGlobalRankStride = "Global rank stride"; +constexpr auto kGroupSize = "Group size"; +constexpr auto kProcessGroupName = "Process Group Name"; +constexpr auto kProcessGroupDesc = "Process Group Description"; +constexpr auto kGroupRanks = "Process Group Ranks"; +constexpr auto kRank = "Rank"; +constexpr auto kP2pSrc = "Src Rank"; +constexpr auto kP2pDst = "Dst Rank"; +constexpr auto kInTensorsStart = "Input Tensors start"; +constexpr auto kOutTensorsStart = "Output Tensors start"; +#endif // USE_DISTRIBUTED + +} // namespace torch::profiler::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/accelerator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/accelerator.h new file mode 100644 index 0000000000000000000000000000000000000000..b73b27936ea716715940c841fd245412b4eced14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/accelerator.h @@ -0,0 +1,79 @@ +#pragma once + +#include +#include +#include + +#include + +HIDDEN_NAMESPACE_BEGIN(torch, stable, accelerator) + +using DeleterFnPtr = void (*)(void*); + +namespace { +inline void delete_device_guard(void* ptr) { + TORCH_ERROR_CODE_CHECK( + aoti_torch_delete_device_guard(reinterpret_cast(ptr))); +} + +} // namespace + +// this is bigger than DeviceIndex in c10/core/Device.h but it is the type we +// can converge on in this world as DeviceIndex in libtorch is not stable. +using DeviceIndex = int32_t; +using StreamId = int64_t; // this is from c10/core/Stream.h + +class DeviceGuard { + public: + explicit DeviceGuard() = delete; + explicit DeviceGuard(DeviceIndex device_index) + : guard_(nullptr, delete_device_guard) { + DeviceGuardHandle ptr = nullptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_create_device_guard(device_index, &ptr)); + guard_.reset(ptr); + } + + void set_index(DeviceIndex device_index) { + TORCH_ERROR_CODE_CHECK( + aoti_torch_device_guard_set_index(guard_.get(), device_index)); + } + + private: + std::unique_ptr guard_; +}; + +class Stream { + public: + explicit Stream() = delete; + + // Construct a stable::Stream from a StreamHandle + // Steals ownership from the StreamHandle + explicit Stream(StreamHandle stream) + : stream_(stream, [](StreamHandle stream) { + TORCH_ERROR_CODE_CHECK(aoti_torch_delete_stream(stream)); + }) {} + + StreamId id() const { + StreamId stream_id; + TORCH_ERROR_CODE_CHECK(aoti_torch_stream_id(stream_.get(), &stream_id)); + return stream_id; + } + + private: + std::shared_ptr stream_; +}; + +inline Stream getCurrentStream(DeviceIndex device_index) { + StreamHandle stream = nullptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_stream(device_index, &stream)); + return Stream(stream); +} + +// Get the current device index +inline DeviceIndex getCurrentDeviceIndex() { + DeviceIndex device_index; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_device_index(&device_index)); + return device_index; +} + +HIDDEN_NAMESPACE_END(torch, stable, accelerator) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/c/shim.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/c/shim.h new file mode 100644 index 0000000000000000000000000000000000000000..dc82b37954f0fb28232e1f6867fc58daa7a96300 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/c/shim.h @@ -0,0 +1,162 @@ +#ifndef STABLE_TORCH_SHIM +#define STABLE_TORCH_SHIM + +#include + +#include + +// This header defines stable C API extensions for backward/forward +// compatibility when calling ATen operations through the dispatcher. +// +// This is separate from the main AOTI shim to provide versioning capabilities +// for schema changes in native ATen functions. + +#ifdef __cplusplus +extern "C" { +#endif + +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 +using StableIValue = uint64_t; + +// Has the same semantic as aoti_torch_call_dispatcher, but takes an +// additional argument for the extension build version. This is +// needed for backward compatibility when calling native functions via +// the dispatcher. The caller should pass in the libtorch version the +// extension is building with (NOT target version). +AOTI_TORCH_EXPORT AOTITorchError torch_call_dispatcher( + const char* opName, + const char* overloadName, + StableIValue* stack, + uint64_t extension_build_version); + +// Version-aware variant of aoti_torch_library_impl that takes an +// extension_build_version parameter for backward compatibility +AOTI_TORCH_EXPORT AOTITorchError torch_library_impl( + TorchLibraryHandle self, + const char* name, + void (*fn)(StableIValue*, uint64_t, uint64_t), + uint64_t extension_build_version); + +struct StableListOpaque; +using StableListHandle = StableListOpaque*; + +// returns an owning reference of a StableList. callee is responsible for +// freeing memory. +AOTI_TORCH_EXPORT AOTITorchError +torch_new_list_reserve_size(size_t size, StableListHandle* ret); + +AOTI_TORCH_EXPORT AOTITorchError +torch_list_size(StableListHandle list_handle, size_t* size); + +AOTI_TORCH_EXPORT AOTITorchError torch_list_get_item( + StableListHandle list_handle, + size_t index, + StableIValue* element); + +AOTI_TORCH_EXPORT AOTITorchError torch_list_set_item( + StableListHandle list_handle, + size_t index, + StableIValue element); + +AOTI_TORCH_EXPORT AOTITorchError +torch_list_push_back(StableListHandle list_handle, StableIValue element); + +// deletes the underlying list referenced by list_handle +AOTI_TORCH_EXPORT AOTITorchError +torch_delete_list(StableListHandle list_handle); + +// Helper function to parse device string using c10::Device +// Returns device type and index via output parameters +AOTI_TORCH_EXPORT AOTITorchError torch_parse_device_string( + const char* device_string, + uint32_t* out_device_type, + int32_t* out_device_index); + +// Parallel utility APIs for stable ABI +// Function pointer type for parallel_for callback +// The callback receives begin and end indices for a range to process +typedef void (*ParallelFunc)(int64_t begin, int64_t end, void* ctx); + +AOTI_TORCH_EXPORT AOTITorchError torch_parallel_for( + int64_t begin, + int64_t end, + int64_t grain_size, + ParallelFunc func, + void* ctx); + +// Get the current thread index in a parallel region +// Returns 0 if not in a parallel region +AOTI_TORCH_EXPORT AOTITorchError torch_get_thread_idx(uint32_t* out_thread_idx); + +// Get the number of threads for the parallel backend +AOTI_TORCH_EXPORT AOTITorchError +torch_get_num_threads(uint32_t* out_num_threads); + +// Get a pointer to the underlying storage data +AOTI_TORCH_EXPORT AOTITorchError torch_get_mutable_data_ptr( + AtenTensorHandle tensor, + void** ret_data_ptr // returns borrowed reference +); + +AOTI_TORCH_EXPORT AOTITorchError torch_get_const_data_ptr( + AtenTensorHandle tensor, + const void** ret_data_ptr // returns borrowed reference +); + +struct StringOpaque; +using StringHandle = StringOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError +torch_new_string_handle(const char* data, size_t length, StringHandle* handle); + +AOTI_TORCH_EXPORT AOTITorchError torch_delete_string(StringHandle handle); + +AOTI_TORCH_EXPORT AOTITorchError +torch_string_length(StringHandle handle, size_t* length); + +AOTI_TORCH_EXPORT AOTITorchError +torch_string_c_str(StringHandle handle, const char** data); + +#ifdef USE_CUDA + +AOTI_TORCH_EXPORT AOTITorchError +torch_get_current_cuda_blas_handle(void** ret_handle); + +AOTI_TORCH_EXPORT AOTITorchError +torch_set_current_cuda_stream(void* stream, int32_t device_index); + +AOTI_TORCH_EXPORT AOTITorchError torch_get_cuda_stream_from_pool( + bool isHighPriority, + int32_t device_index, + void** ret_stream); + +AOTI_TORCH_EXPORT AOTITorchError +torch_cuda_stream_synchronize(void* stream, int32_t device_index); + +// Wrapper around c10_cuda_check_implementation that captures the error message +// without propagating the exception. The caller must free error_msg using +// torch_c10_cuda_free_error_msg if it is non-null. +AOTI_TORCH_EXPORT AOTITorchError torch_c10_cuda_check_msg( + int32_t err, + const char* filename, + const char* function_name, + uint32_t line_number, + bool include_device_assertions, + char** error_msg); + +// Free error message allocated by torch_c10_cuda_check_msg +AOTI_TORCH_EXPORT void torch_c10_cuda_free_error_msg(char* error_msg); + +#endif // USE_CUDA + +// Set requires_grad on a tensor +AOTI_TORCH_EXPORT AOTITorchError +torch_set_requires_grad(AtenTensorHandle tensor, bool requires_grad); + +#endif // TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // STABLE_TORCH_SHIM diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device.h new file mode 100644 index 0000000000000000000000000000000000000000..223e3320a4fd341ba0b388b1dfe08ff38f2d94df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device.h @@ -0,0 +1,4 @@ +#pragma once + +#include +#include diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device_inl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..8c9685f0d7da7822ddca6fbe80eab065895b8933 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device_inl.h @@ -0,0 +1,41 @@ +#pragma once + +// This file implements device.h. We separated out the Device struct so that +// other files can depend on the Device struct (like stableivalue_conversions.h) +// and the implementations of the Device methods can depend on APIs in +// stableivalue_conversions.h without circular dependencies. + +#include +#include +#include +#include +#include +#include +#include + +#include + +HIDDEN_NAMESPACE_BEGIN(torch, stable) + +using DeviceType = torch::headeronly::DeviceType; +using DeviceIndex = torch::stable::accelerator::DeviceIndex; + +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +inline Device::Device(const std::string& device_string) { + uint32_t device_type; + int32_t device_index; + + TORCH_ERROR_CODE_CHECK(torch_parse_device_string( + device_string.c_str(), &device_type, &device_index)); + + DeviceType dt = torch::stable::detail::to( + torch::stable::detail::from(device_type)); + DeviceIndex di = static_cast(device_index); + + *this = Device(dt, di); +} + +#endif // TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +HIDDEN_NAMESPACE_END(torch, stable) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device_struct.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device_struct.h new file mode 100644 index 0000000000000000000000000000000000000000..b422d62e30c5885a987946ac23224c95e39d4827 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device_struct.h @@ -0,0 +1,107 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +HIDDEN_NAMESPACE_BEGIN(torch, stable) + +using DeviceType = torch::headeronly::DeviceType; +using DeviceIndex = torch::stable::accelerator::DeviceIndex; + +// The torch::stable::Device class is an approximate copy of c10::Device. +// It has some slight modifications: +// 1. TORCH_INTERNAL_ASSERT_DEBUG_ONLY -> STD_TORCH_CHECK +// 2. Has a string constructor that uses a shim function +// 3. does not include some is_{device} variants that we can add later +// +// We chose to copy it rather than moving it to headeronly as +// 1. Device is < 8 bytes so the *Handle approach used for tensor doesn't make +// sense +// 2. c10::Device is not header-only due to its string constructor. +// +// StableIValue conversions handle conversion between c10::Device (in libtorch) +// and torch::stable::Device (in stable user extensions) + +class Device { + private: + DeviceType type_; + DeviceIndex index_ = -1; + + void validate() { + STD_TORCH_CHECK( + index_ >= -1, + "Device index must be -1 or non-negative, got ", + static_cast(index_)); + STD_TORCH_CHECK( + type_ != DeviceType::CPU || index_ <= 0, + "CPU device index must be -1 or zero, got ", + static_cast(index_)); + } + + public: + // Construct a stable::Device from a DeviceType and optional device index + // Default index is -1 (current device) + /* implicit */ Device(DeviceType type, DeviceIndex index = -1) + : type_(type), index_(index) { + validate(); + } + +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + // Construct a stable::Device from a string description + // The string must follow the schema: (cpu|cuda|...)[:] + // Defined in device_inl.h to avoid circular dependencies + /* implicit */ Device(const std::string& device_string); +#endif // TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + + // Copy and move constructors can be default + Device(const Device& other) = default; + Device(Device&& other) noexcept = default; + + // Copy and move assignment operators can be default + Device& operator=(const Device& other) = default; + Device& operator=(Device&& other) noexcept = default; + + // Destructor can be default + ~Device() = default; + + bool operator==(const Device& other) const noexcept { + return type() == other.type() && index() == other.index(); + } + + bool operator!=(const Device& other) const noexcept { + return !(*this == other); + } + + void set_index(DeviceIndex index) { + index_ = index; + } + + DeviceType type() const noexcept { + return type_; + } + + DeviceIndex index() const noexcept { + return index_; + } + + bool has_index() const noexcept { + return index_ != -1; + } + + bool is_cuda() const noexcept { + return type_ == DeviceType::CUDA; + } + + bool is_cpu() const noexcept { + return type_ == DeviceType::CPU; + } +}; + +HIDDEN_NAMESPACE_END(torch, stable) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/library.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/library.h new file mode 100644 index 0000000000000000000000000000000000000000..9c8424ac16b6ce167acaa07d727732c19a2c4791 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/library.h @@ -0,0 +1,371 @@ +#pragma once +// this file can only have stable stuff! Akin to shim.h +// but unlike shim.h, this file can contain header-only C++ +// code for better UX. + +#include +#include +#include +#include + +// Technically, this file doesn't use anything from stableivalue_conversions.h, +// but we need to include it here as the contents of stableivalue_conversions.h +// used to live here and so we need to expose them for backwards compatibility. +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, stable, detail) + +class StableLibrary final { + private: + TorchLibraryHandle lib_; + + public: + enum class Kind { + DEF, + IMPL, + FRAGMENT, + }; + + // constructor + /// \private + /// + /// Use STABLE_TORCH_LIBRARY or STABLE_TORCH_LIBRARY_IMPL() instead of using + /// these constructors directly + StableLibrary( + Kind kind, + const char* ns, + const char* k, + const char* file, + uint32_t line) { + if (kind == Kind::IMPL) { + aoti_torch_library_init_impl(ns, k, file, line, &lib_); + } else if (kind == Kind::DEF) { + aoti_torch_library_init_def(ns, file, line, &lib_); + } else { // kind == FRAGMENT + aoti_torch_library_init_fragment(ns, file, line, &lib_); + } + } + + // do not permit copy + StableLibrary(const StableLibrary&) = delete; + StableLibrary& operator=(const StableLibrary&) = delete; + + // do not permit move + StableLibrary(StableLibrary&& other) = delete; + StableLibrary& operator=(StableLibrary&& other) = delete; + + ~StableLibrary() { + aoti_torch_delete_library_object(lib_); + } + + // corresponds to a limited, stable version of torch::library::impl() + // Inputs: + // name: the name of the function to implement + // fn: a boxed function with schema + // (StableIValue* stack, uint64_t num_inputs, uint64_t num_outputs) -> + // void + // fn should follow the calling convention of our boxed kernels that convert + // to IValues. fn will be called with a StableIValue* array of length + // max(num_inputs, num_outputs), where the first num_inputs entries are + // populated with inputs. fn is responsible for stealing the memory of the + // inputs, in effect "popping" them off the stack, and then populating the + // stack with StableIValue outputs. Concretely, fn should: + // 1. read StableIValue inputs from the given stack + // 2. convert the inputs to the proper types + // 3. call the function corresponding to name with the inputs + // 4. convert the outputs to StableIValues + // 5. populate the now empty stack with StableIValue outputs + // If the operation corresponding to name takes in 4 inputs and returns 2 + // outputs, fn should expect stack to contain 4 StableIValues: + // [stable_arg1, stable_arg2, stable_arg3, stable_arg4] + // to end, fn should fill the stack with 2 StableIValues representing outputs: + // [stable_ret1, stable_ret2, -, -] + StableLibrary& impl( + const char* name, + void (*fn)(StableIValue*, uint64_t, uint64_t)) { +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + torch_library_impl(lib_, name, fn, TORCH_ABI_VERSION); +#else + aoti_torch_library_impl(lib_, name, fn); +#endif + return *this; + } + + // corresponds to a limited, stable version of torch::library::def() + StableLibrary& def(const char* schema) { + aoti_torch_library_def(lib_, schema); + return *this; + } +}; + +class StableTorchLibraryInit final { + private: + using InitFn = void(StableLibrary&); + StableLibrary lib_; + + public: + StableTorchLibraryInit( + StableLibrary::Kind kind, + InitFn* fn, + const char* ns, + const char* k, + const char* file, + uint32_t line) + : lib_(kind, ns, k, file, line) { + fn(lib_); + } +}; + +// type mapper: since to> cannot exist, +// we map that to to> to preserve ownership semantics. +// note that unbox_type_t is used to convert ParamTypes, so that +// the tuple holding the arguments will have proper ownership too. +template +struct UnboxType { + using type = T; +}; + +template +struct UnboxType> { + using type = std::vector; +}; + +template +struct UnboxType>> { + using type = std::optional>; +}; + +template <> +struct UnboxType { + using type = std::string; +}; + +// const and reference are stripped before UnboxType is applied +// in order to avoid ambiguous template matches +template +using unbox_type_t = + typename UnboxType>>::type; + +template +std::tuple unbox_to_tuple_impl( + StableIValue* stack, + std::index_sequence) { + return std::make_tuple(to(stack[I])...); +} + +template +std::tuple unbox_to_tuple(StableIValue* stack) { + return unbox_to_tuple_impl( + stack, std::make_index_sequence()); +} + +template +void box_from_tuple_impl( + StableIValue* stack, + std::tuple vals, + std::index_sequence) { + ((stack[I] = from(std::get(vals))), ...); +} + +template +void box_from_tuple(StableIValue* stack, std::tuple vals) { + box_from_tuple_impl( + stack, vals, std::make_index_sequence()); +} + +template < + typename ReturnType, + typename ParameterTypeList, + typename FuncT, + FuncT* func> +struct boxer_impl { + static_assert( + torch::headeronly::guts::false_t::value, + "Unsupported function schema for TORCH_BOX."); +}; + +// Multiple returns +template < + typename... ReturnTypes, + typename... ParameterTypes, + typename FuncT, + FuncT* func> +struct boxer_impl< + std::tuple, + torch::headeronly::guts::typelist::typelist, + FuncT, + func> { + static void boxed_fn( + StableIValue* stack, + uint64_t num_args, + uint64_t num_outputs) { + STD_TORCH_CHECK( + num_args == sizeof...(ParameterTypes), + "Registered schema has ", + num_args, + " args, but the kernel to box has ", + sizeof...(ParameterTypes)); + STD_TORCH_CHECK( + num_outputs == sizeof...(ReturnTypes), + "Registered schema has ", + num_outputs, + " outputs, but the kernel to box has ", + sizeof...(ReturnTypes)); + std::tuple...> args = + unbox_to_tuple...>(stack); + auto res = std::apply(func, args); + box_from_tuple(stack, res); + } +}; + +// Single return +template < + typename ReturnType, + typename... ParameterTypes, + typename FuncT, + FuncT* func> +struct boxer_impl< + ReturnType, + torch::headeronly::guts::typelist::typelist, + FuncT, + func> { + static void boxed_fn( + StableIValue* stack, + uint64_t num_args, + uint64_t num_outputs) { + STD_TORCH_CHECK( + num_args == sizeof...(ParameterTypes), + "Registered schema has ", + num_args, + " args, but the kernel to box has ", + sizeof...(ParameterTypes)); + STD_TORCH_CHECK( + num_outputs == 1, + "Registered schema has ", + num_outputs, + " outputs, but the kernel to box has ", + 1); + std::tuple...> args = + unbox_to_tuple...>(stack); + auto res = std::apply(func, args); + stack[0] = from(res); + } +}; + +// No/void return +template +struct boxer_impl< + void, + torch::headeronly::guts::typelist::typelist, + FuncT, + func> { + static void boxed_fn( + StableIValue* stack, + uint64_t num_args, + uint64_t num_outputs) { + STD_TORCH_CHECK( + num_args == sizeof...(ParameterTypes), + "Registered schema has ", + num_args, + " args, but the kernel to box has ", + sizeof...(ParameterTypes)); + STD_TORCH_CHECK( + num_outputs == 0, + "Registered schema has ", + num_outputs, + " outputs, but the kernel to box has ", + 0); + std::tuple...> args = + unbox_to_tuple...>(stack); + std::apply(func, args); + } +}; + +template +struct boxer { + using FunctionTraits = + torch::headeronly::guts::infer_function_traits_t; + + static void boxed_fn( + StableIValue* stack, + uint64_t num_args, + uint64_t num_outputs) { + boxer_impl< + typename FunctionTraits::return_type, + typename FunctionTraits::parameter_types, + FuncT, + func>::boxed_fn(stack, num_args, num_outputs); + } +}; + +HIDDEN_NAMESPACE_END(torch, stable, detail) + +#define TORCH_BOX(func) \ + torch::stable::detail::boxer< \ + std::remove_pointer_t>, \ + (func)>::boxed_fn + +// macros copied from c10/macros/Macros.h +#ifdef __COUNTER__ +#define STABLE_UID __COUNTER__ +#else +#define STABLE_UID __LINE__ +#endif + +#define STABLE_CONCATENATE_IMPL(s1, s2) s1##s2 +#define STABLE_CONCATENATE(s1, s2) STABLE_CONCATENATE_IMPL(s1, s2) +// end of macros copied from c10/macros/Macros.h + +#define STABLE_TORCH_LIBRARY_IMPL(ns, k, m) \ + _STABLE_TORCH_LIBRARY_IMPL(ns, k, m, STABLE_UID) + +#define _STABLE_TORCH_LIBRARY_IMPL(ns, k, m, uid) \ + static void STABLE_CONCATENATE( \ + STABLE_TORCH_LIBRARY_IMPL_init_##ns##_##k##_, \ + uid)(torch::stable::detail::StableLibrary&); \ + static const torch::stable::detail::StableTorchLibraryInit \ + STABLE_CONCATENATE( \ + STABLE_TORCH_LIBRARY_IMPL_static_init_##ns##_##k##_, uid)( \ + torch::stable::detail::StableLibrary::Kind::IMPL, \ + &STABLE_CONCATENATE( \ + STABLE_TORCH_LIBRARY_IMPL_init_##ns##_##k##_, uid), \ + #ns, \ + #k, \ + __FILE__, \ + __LINE__); \ + void STABLE_CONCATENATE(STABLE_TORCH_LIBRARY_IMPL_init_##ns##_##k##_, uid)( \ + torch::stable::detail::StableLibrary & m) + +#define STABLE_TORCH_LIBRARY(ns, m) \ + static void STABLE_TORCH_LIBRARY_init_##ns( \ + torch::stable::detail::StableLibrary&); \ + static const torch::stable::detail::StableTorchLibraryInit \ + STABLE_TORCH_LIBRARY_static_init_##ns( \ + torch::stable::detail::StableLibrary::Kind::DEF, \ + &STABLE_TORCH_LIBRARY_init_##ns, \ + #ns, \ + nullptr, \ + __FILE__, \ + __LINE__); \ + void STABLE_TORCH_LIBRARY_init_##ns(torch::stable::detail::StableLibrary& m) + +#define STABLE_TORCH_LIBRARY_FRAGMENT(ns, m) \ + _STABLE_TORCH_LIBRARY_FRAGMENT(ns, m, STABLE_UID) + +#define _STABLE_TORCH_LIBRARY_FRAGMENT(ns, m, uid) \ + static void STABLE_CONCATENATE( \ + STABLE_TORCH_LIBRARY_FRAGMENT_init_##ns##_, \ + uid)(torch::stable::detail::StableLibrary&); \ + static const torch::stable::detail::StableTorchLibraryInit \ + STABLE_CONCATENATE( \ + STABLE_TORCH_LIBRARY_FRAGMENT_static_init_##ns##_, uid)( \ + torch::stable::detail::StableLibrary::Kind::FRAGMENT, \ + &STABLE_CONCATENATE( \ + STABLE_TORCH_LIBRARY_FRAGMENT_init_##ns##_, uid), \ + #ns, \ + nullptr, \ + __FILE__, \ + __LINE__); \ + void STABLE_CONCATENATE(STABLE_TORCH_LIBRARY_FRAGMENT_init_##ns##_, uid)( \ + torch::stable::detail::StableLibrary & m) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/macros.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..c06e9f0f541c85dd2445814e6f320b986d19c05b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/macros.h @@ -0,0 +1,26 @@ +#include + +#include +#include + +// Users of this macro are expected to include cuda_runtime.h +#define STD_CUDA_CHECK(EXPR) \ + do { \ + const cudaError_t __err = EXPR; \ + char* __error_msg = nullptr; \ + torch_c10_cuda_check_msg( \ + static_cast(__err), \ + __FILE__, \ + __func__, \ + static_cast(__LINE__), \ + true, \ + &__error_msg); \ + if (__error_msg != nullptr) { \ + std::string __msg(__error_msg); \ + torch_c10_cuda_free_error_msg(__error_msg); \ + throw std::runtime_error(__msg); \ + } \ + } while (0) + +// Users of this macro are expected to include cuda_runtime.h +#define STD_CUDA_KERNEL_LAUNCH_CHECK() STD_CUDA_CHECK(cudaGetLastError()) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/ops.h new file mode 100644 index 0000000000000000000000000000000000000000..246df3cfd8c7eb10bb67343875254259a5511252 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/ops.h @@ -0,0 +1,734 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, stable) + +// We expect this to be the stable version of the empty_like op that takes in +// no kwargs (device, dtype, layout, memory_format). We will add kwargs +// support in the future. +inline torch::stable::Tensor empty_like(const torch::stable::Tensor& self) { + const auto num_args = 6; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(std::nullopt), + torch::stable::detail::from(std::nullopt), + torch::stable::detail::from(std::nullopt), + torch::stable::detail::from(std::nullopt), + torch::stable::detail::from(std::nullopt)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::empty_like", "", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::empty_like", "", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the fill_.Scalar op +// with identical semantics to the existing fill_.Scalar op. +// A subtle nuance is that `value` is typed as a double, but it is +// actually a Scalar. This is because Scalar.h is currently not +// header-only. +inline torch::stable::Tensor fill_( + const torch::stable::Tensor& self, + double value) { + TORCH_ERROR_CODE_CHECK(aoti_torch_aten_fill__Scalar(self.get(), value)); + return self; +} + +// We expect this to be the stable version of the narrow.default op. +// narrow takes in a SymInt for start and length, but these are typed as +// int64_t as SymInt is not yet header-only. +inline torch::stable::Tensor narrow( + torch::stable::Tensor& self, + int64_t dim, + int64_t start, + int64_t length) { + AtenTensorHandle ret0 = nullptr; + + TORCH_ERROR_CODE_CHECK( + aoti_torch_aten_narrow(self.get(), dim, start, length, &ret0)); + return torch::stable::Tensor(ret0); +} + +#if TORCH_FEATURE_VERSION < TORCH_VERSION_2_10_0 +// We expect this to be a stable version of the new_empty op that takes in +// only dtype information. +// This is gated to < 2.10 to avoid ambiguity with the full new_empty overload +// in the 2.10+ block, which has the same first three parameters with defaults. +inline torch::stable::Tensor new_empty( + const torch::stable::Tensor& self, + torch::headeronly::IntHeaderOnlyArrayRef size, + std::optional dtype = std::nullopt) { + int32_t device_type; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type(self.get(), &device_type)); + + int32_t device_index; + TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_index(self.get(), &device_index)); + + int32_t target_dtype; + if (dtype.has_value()) { + target_dtype = torch::stable::detail::to( + torch::stable::detail::from(dtype.value())); + } else { + TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype(self.get(), &target_dtype)); + } + + int32_t layout; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_layout(self.get(), &layout)); + + AtenTensorHandle ret0; + TORCH_ERROR_CODE_CHECK(aoti_torch_aten_new_empty( + self.get(), + size.data(), + static_cast(size.size()), + &target_dtype, + &layout, + &device_type, + device_index, + nullptr, // pin_memory (nullptr for default) + &ret0)); + + return torch::stable::Tensor(ret0); +} + +// We expect this to be a stable version of the new_zeros op that takes in +// only dtype information. +// This is gated to < 2.10 to avoid ambiguity with the full new_zeros overload +// in the 2.10+ block, which has the same first three parameters with defaults. +inline torch::stable::Tensor new_zeros( + const torch::stable::Tensor& self, + torch::headeronly::IntHeaderOnlyArrayRef size, + std::optional dtype = std::nullopt) { + int32_t device_type; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type(self.get(), &device_type)); + + int32_t device_index; + TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_index(self.get(), &device_index)); + + int32_t target_dtype; + if (dtype.has_value()) { + target_dtype = torch::stable::detail::to( + torch::stable::detail::from(dtype.value())); + } else { + TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype(self.get(), &target_dtype)); + } + + int32_t layout; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_layout(self.get(), &layout)); + + AtenTensorHandle ath; + TORCH_ERROR_CODE_CHECK(aoti_torch_aten_new_zeros( + self.get(), + size.data(), + static_cast(size.size()), + &target_dtype, + &layout, + &device_type, + device_index, + nullptr, // pin_memory (nullptr for default) + &ath)); + + return torch::stable::Tensor(ath); +} +#endif // TORCH_FEATURE_VERSION < TORCH_VERSION_2_10_0 + +// We expect this to be the stable version of the pad.default op. +// pad.default takes in a SymInt[] as the pad argument however pad is typed as +// torch::headeronly::IntHeaderOnlyArrayRef as SymInt is not yet header-only. +inline torch::stable::Tensor pad( + const torch::stable::Tensor& self, + torch::headeronly::IntHeaderOnlyArrayRef pad, + const std::string& mode = "constant", + double value = 0.0) { + AtenTensorHandle ret0 = nullptr; + + TORCH_ERROR_CODE_CHECK(aoti_torch_aten_pad( + self.get(), pad.data(), pad.size(), mode.c_str(), &value, &ret0)); + return torch::stable::Tensor(ret0); +} + +// We expect the following two functions to be stable versions of the +// amax.default op with identical semantics to the existing amax.default op. If +// `keepdim` is true, the result will have the same number of dimensions as +// `self`, with the specified dimension having size 1. Otherwise, the result +// will have one fewer dimension than `self`, with the specified dimension +// removed. + +// This function is an overload to compute the maximum value along each slice of +// `self` along a single dimension `dim`. +inline torch::stable::Tensor amax( + const torch::stable::Tensor& self, + int64_t dim, + bool keepdim = false) { + AtenTensorHandle ret = nullptr; + TORCH_ERROR_CODE_CHECK( + aoti_torch_aten_amax(self.get(), &dim, 1, keepdim, &ret)); + return torch::stable::Tensor(ret); +} + +// This function is an overload to compute the maximum value along each slice of +// `self` reducing over all the dimensions in the vector `dims`. The +// amax.default op takes in a SymInt[] as the dims argument, however dims is +// typed as use IntHeaderOnlyArrayRef here because SymInt is not yet header-only +inline torch::stable::Tensor amax( + const torch::stable::Tensor& self, + torch::headeronly::IntHeaderOnlyArrayRef dims, + bool keepdim = false) { + AtenTensorHandle ret = nullptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_aten_amax( + self.get(), + dims.data(), + static_cast(dims.size()), + keepdim, + &ret)); + return torch::stable::Tensor(ret); +} + +// We expect this to be the stable version of the transpose op with identical +// semantics to the existing transpose.int op. +inline torch::stable::Tensor transpose( + const torch::stable::Tensor& self, + int64_t dim0, + int64_t dim1) { + const auto num_args = 3; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(dim0), + torch::stable::detail::from(dim1)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::transpose", "int", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::transpose", "int", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the zero_ op with identical +// semantics to the existing zero_ op (except that it will not be called as +// a tensor method but only as a function i.e. zero_(t) not t.zero_()). +inline torch::stable::Tensor zero_(torch::stable::Tensor& self) { + const auto num_args = 1; + std::array stack{torch::stable::detail::from(self)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::zero_", "", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::zero_", "", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the copy_ op with +// identical semantics to the existing copy_ op. +inline torch::stable::Tensor copy_( + torch::stable::Tensor& self, + const torch::stable::Tensor& src, + std::optional non_blocking = std::nullopt) { + const auto num_args = 3; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(src), + torch::stable::detail::from(non_blocking.value_or(false))}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::copy_", "", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::copy_", "", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the clone op. We will +// add optional memory_format kwarg support in the future. +inline torch::stable::Tensor clone(const torch::stable::Tensor& self) { + const auto num_args = 2; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(std::nullopt)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::clone", "", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::clone", "", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the flatten.using_ints op. +inline torch::stable::Tensor flatten( + const torch::stable::Tensor& self, + int64_t start_dim = 0, + int64_t end_dim = -1) { + const auto num_args = 3; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(start_dim), + torch::stable::detail::from(end_dim)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::flatten", "using_ints", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::flatten", "using_ints", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the unsqueeze op with identical +// semantics to the existing unsqueeze op. +inline torch::stable::Tensor unsqueeze( + const torch::stable::Tensor& self, + int64_t dim) { + const auto num_args = 2; + std::array stack{ + torch::stable::detail::from(self), torch::stable::detail::from(dim)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::unsqueeze", "", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::unsqueeze", "", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the squeeze.dim op with identical +// semantics to the existing squeeze.dim op. +inline torch::stable::Tensor squeeze( + const torch::stable::Tensor& self, + int64_t dim) { + const auto num_args = 2; + std::array stack{ + torch::stable::detail::from(self), torch::stable::detail::from(dim)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::squeeze", "dim", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::squeeze", "dim", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the select.int op with identical +// semantics to the existing select.int op. +// Note: index is typed as int64_t because SymInt is not yet header-only. +inline torch::stable::Tensor select( + const torch::stable::Tensor& self, + int64_t dim, + int64_t index) { + const auto num_args = 3; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(dim), + torch::stable::detail::from(index)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::select", "int", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::select", "int", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the matmul op with identical +// semantics to the existing matmul op. +inline torch::stable::Tensor matmul( + const torch::stable::Tensor& self, + const torch::stable::Tensor& other) { + const auto num_args = 2; + std::array stack{ + torch::stable::detail::from(self), torch::stable::detail::from(other)}; +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::matmul", "", stack.data(), TORCH_ABI_VERSION)); +#else + TORCH_ERROR_CODE_CHECK( + aoti_torch_call_dispatcher("aten::matmul", "", stack.data())); +#endif + return torch::stable::detail::to(stack[0]); +} + +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +// New ops should be added here if they use a brand new shim API + +// Parallel utility wrapper that provides a stable interface to at::parallel_for +// This function has the same signature as at::parallel_for and allows stable +// ABI code to leverage PyTorch's parallel execution capabilities. +// +// The function f will be called with (begin, end) ranges to process in +// parallel. grain_size controls the minimum work size per thread for efficient +// parallelization. +template +inline void parallel_for( + const int64_t begin, + const int64_t end, + const int64_t grain_size, + const F& f) { + auto callback = [](int64_t cb_begin, int64_t cb_end, void* ctx) { + const F* func = static_cast(ctx); + (*func)(cb_begin, cb_end); + }; + TORCH_ERROR_CODE_CHECK(torch_parallel_for( + begin, + end, + grain_size, + callback, + const_cast(static_cast(&f)))); +} + +// Get the number of threads for the parallel backend +// This provides a stable interface to at::get_num_threads +inline uint32_t get_num_threads() { + uint32_t num_threads; + TORCH_ERROR_CODE_CHECK(torch_get_num_threads(&num_threads)); + return num_threads; +} + +// We expect this to be the stable version of the empty.memory_format op that +// takes in device and dtype parameters. This function is only available in 2.10 +// because it uses the stableivalue conversion for HeaderOnlyArrayRef, which +// is only available in 2.10. +inline torch::stable::Tensor empty( + torch::headeronly::IntHeaderOnlyArrayRef size, + std::optional dtype = std::nullopt, + std::optional layout = std::nullopt, + std::optional device = std::nullopt, + std::optional pin_memory = std::nullopt, + std::optional memory_format = + std::nullopt) { + const auto num_args = 6; + std::array stack{ + torch::stable::detail::from(size), + torch::stable::detail::from(dtype), + torch::stable::detail::from(layout), + torch::stable::detail::from(device), + torch::stable::detail::from(pin_memory), + torch::stable::detail::from(memory_format)}; + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::empty", "memory_format", stack.data(), TORCH_ABI_VERSION)); + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the reshape op. +// This function is only available in 2.10 because it uses the stableivalue +// conversion for HeaderOnlyArrayRef, which is only available in 2.10. +inline torch::stable::Tensor reshape( + const torch::stable::Tensor& self, + torch::headeronly::IntHeaderOnlyArrayRef shape) { + const auto num_args = 2; + std::array stack{ + torch::stable::detail::from(self), torch::stable::detail::from(shape)}; + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::reshape", "", stack.data(), TORCH_ABI_VERSION)); + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the view op. +// This function is only available in 2.10 because it uses the stableivalue +// conversion for HeaderOnlyArrayRef, which is only available in 2.10. +inline torch::stable::Tensor view( + const torch::stable::Tensor& self, + torch::headeronly::IntHeaderOnlyArrayRef size) { + const auto num_args = 2; + std::array stack{ + torch::stable::detail::from(self), torch::stable::detail::from(size)}; + TORCH_ERROR_CODE_CHECK( + torch_call_dispatcher("aten::view", "", stack.data(), TORCH_ABI_VERSION)); + return torch::stable::detail::to(stack[0]); +} + +inline torch::stable::Tensor from_blob( + void* data, + torch::headeronly::IntHeaderOnlyArrayRef sizes, + torch::headeronly::IntHeaderOnlyArrayRef strides, + torch::stable::Device device, + torch::headeronly::ScalarType dtype, + int64_t storage_offset = 0, + torch::headeronly::Layout layout = torch::headeronly::Layout::Strided) { + auto shim_dtype = + torch::stable::detail::to(torch::stable::detail::from(dtype)); + auto shim_device_type = torch::stable::detail::to( + torch::stable::detail::from(device.type())); + auto shim_layout = + torch::stable::detail::to(torch::stable::detail::from(layout)); + AtenTensorHandle ath; + TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob_v2( + data, + sizes.size(), + sizes.data(), + strides.data(), + storage_offset, + shim_dtype, + shim_device_type, + device.index(), + &ath, + shim_layout, + nullptr, + 0)); + return torch::stable::Tensor(ath); +} + +// We expect this to be the stable version of the to.dtype_layout op. +// This function is only available in 2.10 because it uses the stableivalue +// conversion for torch::stable::Device, which is only available in 2.10. +inline torch::stable::Tensor to( + const torch::stable::Tensor& self, + std::optional dtype = std::nullopt, + std::optional layout = std::nullopt, + std::optional device = std::nullopt, + std::optional pin_memory = std::nullopt, + bool non_blocking = false, + bool copy = false, + std::optional memory_format = + std::nullopt) { + const auto num_args = 8; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(dtype), + torch::stable::detail::from(layout), + torch::stable::detail::from(device), + torch::stable::detail::from(pin_memory), + torch::stable::detail::from(non_blocking), + torch::stable::detail::from(copy), + torch::stable::detail::from(memory_format)}; + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::to", "dtype_layout", stack.data(), TORCH_ABI_VERSION)); + return torch::stable::detail::to(stack[0]); +} + +// Convenience overload for to(device) +// We add this for convenience since stable does not support .to(TensorOptions) +inline torch::stable::Tensor to( + const torch::stable::Tensor& self, + torch::stable::Device device, + bool non_blocking = false, + bool copy = false) { + return to( + self, + std::nullopt, + std::nullopt, + device, + std::nullopt, + non_blocking, + copy, + std::nullopt); +} + +// We expect this to be the stable version of the contiguous op. +// This function is only available in 2.10 because it uses the stableivalue +// conversion for MemoryFormat, which is only available in 2.10. +// Contiguous is also a method on (non-stable Tensor), for now we only +// support the function version. +inline torch::stable::Tensor contiguous( + const torch::stable::Tensor& self, + torch::headeronly::MemoryFormat memory_format = + torch::headeronly::MemoryFormat::Contiguous) { + const auto num_args = 2; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(memory_format)}; + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::contiguous", "", stack.data(), TORCH_ABI_VERSION)); + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the new_empty op with all kwargs. +// This function is only available in 2.10 because it uses the stableivalue +// conversion for Device, HeaderOnlyArrayRef, Layout which are only available +// in 2.10. In versions < 2.10, a simpler new_empty overload that only takes +// dtype is available instead. +inline torch::stable::Tensor new_empty( + const torch::stable::Tensor& self, + torch::headeronly::IntHeaderOnlyArrayRef size, + std::optional dtype = std::nullopt, + std::optional layout = std::nullopt, + std::optional device = std::nullopt, + std::optional pin_memory = std::nullopt) { + const auto num_args = 6; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(size), + torch::stable::detail::from(dtype), + torch::stable::detail::from(layout), + torch::stable::detail::from(device), + torch::stable::detail::from(pin_memory)}; + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::new_empty", "", stack.data(), TORCH_ABI_VERSION)); + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the new_zeros op with all kwargs. +// This function is only available in 2.10 because it uses the stableivalue +// conversion for Device, HeaderOnlyArrayRef, Layout which are only available +// in 2.10. In versions < 2.10, a simpler new_zeros overload that only takes +// dtype is available instead. +inline torch::stable::Tensor new_zeros( + const torch::stable::Tensor& self, + torch::headeronly::IntHeaderOnlyArrayRef size, + std::optional dtype = std::nullopt, + std::optional layout = std::nullopt, + std::optional device = std::nullopt, + std::optional pin_memory = std::nullopt) { + const auto num_args = 6; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(size), + torch::stable::detail::from(dtype), + torch::stable::detail::from(layout), + torch::stable::detail::from(device), + torch::stable::detail::from(pin_memory)}; + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::new_zeros", "", stack.data(), TORCH_ABI_VERSION)); + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the sum.dim_IntList op. +// This function computes the sum of the input tensor along the specified +// dimensions and returns a new tensor containing the result. This function is +// only available in 2.10 because it uses the stableivalue conversion for +// HeaderOnlyArrayRef, which is only available in 2.10. The dim parameter is +// optional - if not provided, sums over all dimensions. +inline torch::stable::Tensor sum( + const torch::stable::Tensor& self, + std::optional dim = std::nullopt, + bool keepdim = false, + std::optional dtype = std::nullopt) { + const auto num_args = 4; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(dim), + torch::stable::detail::from(keepdim), + torch::stable::detail::from(dtype)}; + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::sum", "dim_IntList", stack.data(), TORCH_ABI_VERSION)); + return torch::stable::detail::to(stack[0]); +} + +// We expect this to be the stable version of the sum.IntList_out op. +// This function takes an output tensor and computes the sum of the input tensor +// along the specified dimensions. The output tensor is modified in-place and +// returned. Following C++ convention, the out parameter comes first. This +// function is only available in 2.10 because it uses the stableivalue +// conversion for HeaderOnlyArrayRef, which is only available in 2.10. +inline torch::stable::Tensor& sum_out( + torch::stable::Tensor& out, + const torch::stable::Tensor& self, + std::optional dim = std::nullopt, + bool keepdim = false, + std::optional dtype = std::nullopt) { + const auto num_args = 5; + std::array stack{ + torch::stable::detail::from(self), + torch::stable::detail::from(dim), + torch::stable::detail::from(keepdim), + torch::stable::detail::from(dtype), + torch::stable::detail::from(out)}; + TORCH_ERROR_CODE_CHECK(torch_call_dispatcher( + "aten::sum", "IntList_out", stack.data(), TORCH_ABI_VERSION)); + // Clean up the handle in stack[0], discard the temporary + (void)torch::stable::detail::to(stack[0]); + return out; +} + +// We expect this to be the stable version of the subtract.Tensor op. +// Note: alpha is typed as double because the underlying C shim API +// uses double for the Scalar parameter. We don't use torch_call_dispatcher +// as the stableivalue conversion for Scalar is not yet available as of +// 2.10 +inline torch::stable::Tensor subtract( + const torch::stable::Tensor& self, + const torch::stable::Tensor& other, + double alpha = 1.0) { + AtenTensorHandle ret0; + TORCH_ERROR_CODE_CHECK( + aoti_torch_aten_subtract_Tensor(self.get(), other.get(), alpha, &ret0)); + return torch::stable::Tensor(ret0); +} + +// We expect this to be the stable version of the full.default op. +// Note: fill_value is typed as double because the underlying C shim API +// uses double for the Scalar parameter. We don't use torch_call_dispatcher +// as the stableivalue conversion for Scalar is not yet available as of +// 2.10 +inline torch::stable::Tensor full( + torch::headeronly::IntHeaderOnlyArrayRef size, + double fill_value, + std::optional dtype = std::nullopt, + std::optional layout = std::nullopt, + std::optional device = std::nullopt, + std::optional pin_memory = std::nullopt) { + int32_t* dtype_ptr = nullptr; + int32_t dtype_val; + if (dtype.has_value()) { + dtype_val = torch::stable::detail::to( + torch::stable::detail::from(dtype.value())); + dtype_ptr = &dtype_val; + } + + int32_t* layout_ptr = nullptr; + int32_t layout_val; + if (layout.has_value()) { + layout_val = torch::stable::detail::to( + torch::stable::detail::from(layout.value())); + layout_ptr = &layout_val; + } + + int32_t* device_type_ptr = nullptr; + int32_t device_type_val; + int32_t device_index = 0; + if (device.has_value()) { + device_type_val = torch::stable::detail::to( + torch::stable::detail::from(device.value().type())); + device_type_ptr = &device_type_val; + device_index = device.value().index(); + } + + int32_t* pin_memory_ptr = nullptr; + int32_t pin_memory_val; + if (pin_memory.has_value()) { + pin_memory_val = pin_memory.value() ? 1 : 0; + pin_memory_ptr = &pin_memory_val; + } + + AtenTensorHandle ret0; + TORCH_ERROR_CODE_CHECK(aoti_torch_aten_full( + size.data(), + static_cast(size.size()), + fill_value, + dtype_ptr, + layout_ptr, + device_type_ptr, + device_index, + pin_memory_ptr, + &ret0)); + + return torch::stable::Tensor(ret0); +} + +#endif // TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +HIDDEN_NAMESPACE_END(torch, stable) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/stableivalue_conversions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/stableivalue_conversions.h new file mode 100644 index 0000000000000000000000000000000000000000..c4f10486ec779c11109f9527fa2dcbfba7c6945d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/stableivalue_conversions.h @@ -0,0 +1,861 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +HIDDEN_NAMESPACE_BEGIN(torch, stable, detail) + +// Helper variable templates to detect 2.10+ types for better compile-time error +// messages +template +inline constexpr bool is_header_only_array_ref_v = false; + +template +inline constexpr bool + is_header_only_array_ref_v> = true; + +template +inline constexpr bool is_std_vector_v = false; + +template +inline constexpr bool is_std_vector_v> = true; + +// forward declare so that the from/to() implementations in the detail +// namespace of library.h where the real work is done can compile. +template +StableIValue from(T val); +template +T to(StableIValue val); + +// ============================================================================= +// Below are the helpers for converting between StableIValue and T +// ============================================================================= +// ============================================================================= +// FROM CONVERSIONS (T -> StableIValue) +// ====================================================================== + +// Specialization for general copyable types (catch-all) => StableIValue +template +struct FromImpl { + static StableIValue call( + T val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + // Ensure 2.10+ types don't accidentally use the base case - provide clear + // compile-time errors. + static_assert( + !std::is_same_v, + "torch::stable::Device requires TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0"); + static_assert( + !is_header_only_array_ref_v, + "HeaderOnlyArrayRef requires TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0"); + static_assert( + !is_std_vector_v, + "std::vector requires TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0"); + static_assert( + !std::is_same_v, + "std::string requires TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0"); + static_assert( + sizeof(T) <= sizeof(StableIValue), + "StableLibrary stack does not support parameter types larger than 64 bits."); + static_assert(std::is_trivially_copyable_v); + // Initialization should be cheap enough; let's give people well-specified + // reproducible behavior. + StableIValue result = 0; + // NOTE [ -Wclass-memaccess ]: reinterpret_cast to suppress + // overzealous -Wclass-memaccess. (see + // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107361) We have a + // static_assert above that T is trivially copyable, which should be + // enough. +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + std::memcpy(&result, reinterpret_cast(&val), sizeof(val)); +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + // if value has size less than sizeof(StableIValue), then only lowest bytes + // have to be updated + std::memcpy( + reinterpret_cast(&result) + sizeof(StableIValue) - + sizeof(val), + reinterpret_cast(&val), + sizeof(val)); +#else +#error "Unexpected or undefined __BYTE_ORDER__" +#endif + return result; + } +}; + +// Specialization for torch::headeronly::ScalarType => StableIValue +// Note that we call into the shim to translate between the user's +// ScalarType and libtorch's ScalarType, which can be different! +// Also note that the list below is not comprehensive, as it does not +// include types that are no longer really used and should probably be +// deprecated (like qint8). +using torch::headeronly::ScalarType; +template <> +struct FromImpl { + static StableIValue call( + ScalarType val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + switch (val) { + case ScalarType::Byte: + return torch::stable::detail::from(aoti_torch_dtype_uint8()); + case ScalarType::Char: + return torch::stable::detail::from(aoti_torch_dtype_int8()); + case ScalarType::Short: + return torch::stable::detail::from(aoti_torch_dtype_int16()); + case ScalarType::Int: + return torch::stable::detail::from(aoti_torch_dtype_int32()); + case ScalarType::Long: + return torch::stable::detail::from(aoti_torch_dtype_int64()); + case ScalarType::Half: + return torch::stable::detail::from(aoti_torch_dtype_float16()); + case ScalarType::Float: + return torch::stable::detail::from(aoti_torch_dtype_float32()); + case ScalarType::Double: + return torch::stable::detail::from(aoti_torch_dtype_float64()); + case ScalarType::ComplexHalf: + return torch::stable::detail::from(aoti_torch_dtype_complex32()); + case ScalarType::ComplexFloat: + return torch::stable::detail::from(aoti_torch_dtype_complex64()); + case ScalarType::ComplexDouble: + return torch::stable::detail::from(aoti_torch_dtype_complex128()); + case ScalarType::Bool: + return torch::stable::detail::from(aoti_torch_dtype_bool()); + case ScalarType::BFloat16: + return torch::stable::detail::from(aoti_torch_dtype_bfloat16()); + case ScalarType::Float8_e5m2: + return torch::stable::detail::from(aoti_torch_dtype_float8_e5m2()); + case ScalarType::Float8_e4m3fn: + return torch::stable::detail::from(aoti_torch_dtype_float8_e4m3fn()); + case ScalarType::Float8_e5m2fnuz: + return torch::stable::detail::from(aoti_torch_dtype_float8_e5m2fnuz()); + case ScalarType::Float8_e4m3fnuz: + return torch::stable::detail::from(aoti_torch_dtype_float8_e4m3fnuz()); + case ScalarType::UInt16: + return torch::stable::detail::from(aoti_torch_dtype_uint16()); + case ScalarType::UInt32: + return torch::stable::detail::from(aoti_torch_dtype_uint32()); + case ScalarType::UInt64: + return torch::stable::detail::from(aoti_torch_dtype_uint64()); + default: + STD_TORCH_CHECK( + false, + "Not yet supported ScalarType, please file an issue describing your use case."); + } + } +}; + +// [Note DeviceType version guard] +// This conversion was introduced in 2.10. However, we do not gate it +// with TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 because this +// conversion is not actually used to pass DeviceType between user +// extensions and libtorch (i.e. there is no c10::TypeKind::DeviceType). +// The purpose of gating other conversions is to ensure that user +// extensions do not try to pass a StableIValue that libtorch is +// unable to interpret. +// This conversion is only used +// (1) In the conversion for torch::stable::Device (already gated) +// (2) Within the user extension to translate between libtorch/extension's +// DeviceType (no gating needed) +// Specialization for torch::headeronly::DeviceType => StableIValue +// Note that we call into the shim to translate between the user's +// DeviceType and libtorch's DeviceType, which can be different! +using torch::headeronly::DeviceType; +template <> +struct FromImpl { + static StableIValue call( + DeviceType val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + switch (val) { + case DeviceType::CPU: + return torch::stable::detail::from(aoti_torch_device_type_cpu()); + case DeviceType::CUDA: + return torch::stable::detail::from(aoti_torch_device_type_cuda()); + case DeviceType::Meta: + return torch::stable::detail::from(aoti_torch_device_type_meta()); + case DeviceType::XPU: + return torch::stable::detail::from(aoti_torch_device_type_xpu()); + case DeviceType::MPS: + return torch::stable::detail::from(aoti_torch_device_type_mps()); + case DeviceType::PrivateUse1: + return torch::stable::detail::from( + aoti_torch_device_type_privateuse1()); + default: + STD_TORCH_CHECK( + false, + "Not yet supported DeviceType, please file an issue describing your use case."); + } + } +}; + +// Specialization for std::nullopt_t => StableIValue +template <> +struct FromImpl { + static StableIValue call( + std::nullopt_t val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + return torch::stable::detail::from(nullptr); + } +}; + +// Specialization for std::optional => StableIValue +// [Handling std::optional] +// When the schema is represented by an optional type, say int?, then we +// expect the custom extension representation to be a std::optional +// (critically NOT int!). In order for all parameters to be stably parsed and +// handled by our dispatcher, we liaison custom extension parameters through +// boxed kernels, meaning that every value will make its way to be an IValue: +// +// custom extension value --(from)-> StableIValue --(to_ivalue)-> IValue +// +// When the custom extension value is a literal that can be trivially +// casted to StableIValue, e.g., an int, a float, a pointer, this route is +// ...trivial. The below specialization is for a case when the custom +// extension value would NOT fit within a StableIValue: a std::optional. +// +// If the std::optional has no value, it is treated as std::nullopt, +// whose StableIValue representation is from(nullptr). Otherwise, we: +// 1. unwrap the std::optional +// 2. recursively convert its value of type T to a StableIValue +// 3. allocate heap space for said StableIValue +// 4. convert the resulting StableIValue* into a StableIValue +// +// note that this allocates heap memory! which we expect to be cleaned +// up in the to_ivalue() function defined in shim_common.cpp. We +// purposefully hide this implementation detail from the user so that +// all the user needs to know is: +// +// The schema requests an optional (T?) so I must call `from` on a +// std::optional or a std::nullopt. +template +struct FromImpl> { + static StableIValue call( + const std::optional& val, + uint64_t extension_build_version, + bool is_internal) { + if (!val.has_value()) { + return torch::stable::detail::from(std::nullopt); + } + return torch::stable::detail::from( + new StableIValue(detail::FromImpl::call( + val.value(), extension_build_version, is_internal))); + } +}; + +// Specialization for torch::stable::Tensor => StableIValue +// Returns a new owning reference of the underlying Tensor. +template <> +struct FromImpl { + static StableIValue call( + const torch::stable::Tensor& val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + AtenTensorHandle new_ath; + TORCH_ERROR_CODE_CHECK(aoti_torch_new_tensor_handle(val.get(), &new_ath)); + return torch::stable::detail::from(new_ath); + } +}; + +// ============================================================================= +// FROM CONVERSIONS requiring TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 +// ============================================================================= +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +// Specialization for torch::headeronly::Layout => StableIValue +// Note that we call into the shim to translate between the user's +// Layout and libtorch's Layout, which can be different! +using torch::headeronly::Layout; +template <> +struct FromImpl { + static StableIValue call( + Layout val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + switch (val) { + case Layout::Strided: + return torch::stable::detail::from(aoti_torch_layout_strided()); + case Layout::Sparse: + return torch::stable::detail::from(aoti_torch_layout_sparse_coo()); + case Layout::SparseCsr: + return torch::stable::detail::from(aoti_torch_layout_sparse_csr()); + case Layout::SparseCsc: + return torch::stable::detail::from(aoti_torch_layout_sparse_csc()); + case Layout::SparseBsr: + return torch::stable::detail::from(aoti_torch_layout_sparse_bsr()); + case Layout::SparseBsc: + return torch::stable::detail::from(aoti_torch_layout_sparse_bsc()); + case Layout::Mkldnn: + return torch::stable::detail::from(aoti_torch_layout__mkldnn()); + case Layout::Jagged: + return torch::stable::detail::from(aoti_torch_layout_jagged()); + default: + STD_TORCH_CHECK( + false, + "Not yet supported Layout, please file an issue describing your use case."); + } + } +}; + +// Specialization for torch::headeronly::MemoryFormat => StableIValue +// Note that we call into the shim to translate between the user's +// MemoryFormat and libtorch's MemoryFormat, which can be different! +using torch::headeronly::MemoryFormat; +template <> +struct FromImpl { + static StableIValue call( + MemoryFormat val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + switch (val) { + case MemoryFormat::Contiguous: + return torch::stable::detail::from( + aoti_torch_memory_format_contiguous_format()); + case MemoryFormat::Preserve: + return torch::stable::detail::from( + aoti_torch_memory_format_preserve_format()); + case MemoryFormat::ChannelsLast: + return torch::stable::detail::from( + aoti_torch_memory_format_channels_last()); + case MemoryFormat::ChannelsLast3d: + return torch::stable::detail::from( + aoti_torch_memory_format_channels_last_3d()); + default: + STD_TORCH_CHECK( + false, + "Not yet supported MemoryFormat, please file an issue describing your use case."); + } + } +}; + +// Specialization for torch::headeronly::HeaderOnlyArrayRef => StableIValue +// Returns a new owning reference of the underlying list. +template +struct FromImpl> { + static StableIValue call( + const torch::headeronly::HeaderOnlyArrayRef& val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + StableListHandle new_list_handle; + try { + TORCH_ERROR_CODE_CHECK( + torch_new_list_reserve_size(val.size(), &new_list_handle)); + for (const auto& elem : val) { + TORCH_ERROR_CODE_CHECK(torch_list_push_back( + new_list_handle, torch::stable::detail::from(elem))); + } + return torch::stable::detail::from(new_list_handle); + } catch (const std::runtime_error&) { + if (new_list_handle != nullptr) { + // clean up memory if an error was thrown + TORCH_ERROR_CODE_CHECK(torch_delete_list(new_list_handle)); + } + throw; + } + } +}; + +// Specialization for std::vector => StableIValue, which is implemented the +// same way as HeaderOnlyArrayRef => StableIValue +// Returns a new owning reference of the underlying list. +template +struct FromImpl> { + static StableIValue call( + const std::vector& val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + return torch::stable::detail::from< + torch::headeronly::HeaderOnlyArrayRef>(val); + } +}; + +// Specialization for torch::stable::Device => StableIValue +// Pack the device type and index into a StableIValue in a platform-independent +// format. We use the shim representation for DeviceType (int32_t) for ABI +// stability. StableIValue layout: DeviceIndex in lower 32 bits, +// DeviceType (shim int32_t) in upper 32 bits +template <> +struct FromImpl { + static StableIValue call( + const torch::stable::Device& val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + // Convert DeviceType to shim representation (int32_t) + StableIValue device_type_shim = torch::stable::detail::from(val.type()); + // Pack: lower 32 bits = device index, upper 32 bits = device type (shim) + uint64_t device_index_bits = + static_cast(static_cast(val.index())); + uint64_t device_type_bits = + static_cast(static_cast(device_type_shim)) << 32; + return device_index_bits | device_type_bits; + } +}; + +// Specialization for std::string, which should return a new owning reference of +// the string +template <> +struct FromImpl { + static StableIValue call( + const std::string& val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + StringHandle handle; + TORCH_ERROR_CODE_CHECK( + torch_new_string_handle(val.c_str(), val.length(), &handle)) + return torch::stable::detail::from(handle); + } +}; + +#endif // TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +// ============================================================================= +// TO CONVERSIONS (StableIValue -> T) +// ============================================================================= + +// Specialization for StableIValue => general copyable types (catch-all) +template +struct ToImpl { + static T call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + // Ensure 2.10+ types don't accidentally use the base case - provide clear + // compile-time errors. + static_assert( + !std::is_same_v, + "torch::stable::Device requires TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0"); + static_assert( + !is_header_only_array_ref_v, + "HeaderOnlyArrayRef requires TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0"); + static_assert( + !is_std_vector_v, + "std::vector requires TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0"); + static_assert( + !std::is_same_v, + "std::string requires TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0"); + static_assert(std::is_trivially_copyable_v); + // T may not have a default constructor. (For example, it might be + // c10::Device.) However, std::memcpy implicitly creates a T at the + // destination. So, we can use a union to work around this lack of + // default constructor. + union Result { + Result() {} + T t; + }; + Result result; + // See NOTE[ -Wclass-memaccess ] above. +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + std::memcpy(reinterpret_cast(&result.t), &val, sizeof(result)); +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + static_assert( + sizeof(T) <= sizeof(StableIValue), + "StableLibrary stack does not support parameter types larger than 64 bits."); + // if value has size less than sizeof(StableIValue), then only lowest bytes + // have to be updated + std::memcpy( + reinterpret_cast(&result.t), + reinterpret_cast(&val) + sizeof(StableIValue) - + sizeof(result), + sizeof(result)); +#else +#error "Unexpected or undefined __BYTE_ORDER__" +#endif + return result.t; + } +}; + +// Specialization for StableIValue => torch::headeronly::ScalarType +template <> +struct ToImpl { + static ScalarType call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + int32_t shim_scalartype = torch::stable::detail::to(val); + if (shim_scalartype == aoti_torch_dtype_uint8()) { + return ScalarType::Byte; + } else if (shim_scalartype == aoti_torch_dtype_int8()) { + return ScalarType::Char; + } else if (shim_scalartype == aoti_torch_dtype_int16()) { + return ScalarType::Short; + } else if (shim_scalartype == aoti_torch_dtype_int32()) { + return ScalarType::Int; + } else if (shim_scalartype == aoti_torch_dtype_int64()) { + return ScalarType::Long; + } else if (shim_scalartype == aoti_torch_dtype_float16()) { + return ScalarType::Half; + } else if (shim_scalartype == aoti_torch_dtype_float32()) { + return ScalarType::Float; + } else if (shim_scalartype == aoti_torch_dtype_float64()) { + return ScalarType::Double; + } else if (shim_scalartype == aoti_torch_dtype_complex32()) { + return ScalarType::ComplexHalf; + } else if (shim_scalartype == aoti_torch_dtype_complex64()) { + return ScalarType::ComplexFloat; + } else if (shim_scalartype == aoti_torch_dtype_complex128()) { + return ScalarType::ComplexDouble; + } else if (shim_scalartype == aoti_torch_dtype_bool()) { + return ScalarType::Bool; + } else if (shim_scalartype == aoti_torch_dtype_bfloat16()) { + return ScalarType::BFloat16; + } else if (shim_scalartype == aoti_torch_dtype_float8_e5m2()) { + return ScalarType::Float8_e5m2; + } else if (shim_scalartype == aoti_torch_dtype_float8_e4m3fn()) { + return ScalarType::Float8_e4m3fn; + } else if (shim_scalartype == aoti_torch_dtype_float8_e5m2fnuz()) { + return ScalarType::Float8_e5m2fnuz; + } else if (shim_scalartype == aoti_torch_dtype_float8_e4m3fnuz()) { + return ScalarType::Float8_e4m3fnuz; + } else if (shim_scalartype == aoti_torch_dtype_uint16()) { + return ScalarType::UInt16; + } else if (shim_scalartype == aoti_torch_dtype_uint32()) { + return ScalarType::UInt32; + } else if (shim_scalartype == aoti_torch_dtype_uint64()) { + return ScalarType::UInt64; + } else { + STD_TORCH_CHECK( + false, + "Not yet supported ScalarType ", + std::to_string(shim_scalartype), + ", please file an issue describing your use case."); + } + } +}; + +// See [Note DeviceType version guard] +// Specialization for StableIValue => torch::headeronly::DeviceType +template <> +struct ToImpl { + static DeviceType call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + int32_t shim_devicetype = torch::stable::detail::to(val); + if (shim_devicetype == aoti_torch_device_type_cpu()) { + return DeviceType::CPU; + } else if (shim_devicetype == aoti_torch_device_type_cuda()) { + return DeviceType::CUDA; + } else if (shim_devicetype == aoti_torch_device_type_meta()) { + return DeviceType::Meta; + } else if (shim_devicetype == aoti_torch_device_type_xpu()) { + return DeviceType::XPU; + } else if (shim_devicetype == aoti_torch_device_type_mps()) { + return DeviceType::MPS; + } else if (shim_devicetype == aoti_torch_device_type_privateuse1()) { + return DeviceType::PrivateUse1; + } else { + STD_TORCH_CHECK( + false, + "Not yet supported DeviceType ", + std::to_string(shim_devicetype), + ", please file an issue describing your use case."); + } + } +}; + +// Specialization for StableIValue => std::nullopt_t +template <> +struct ToImpl { + static std::nullopt_t call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + // val should be equivalent to from(nullptr) + return std::nullopt; + } +}; + +// Specialization for StableIValue => std::optional, see [Handling +// std::optional] as the semantic is the same but in reverse direction as we go +// from IValue --(from_ivalue)-> StableIValue --(to)-> T in custom extension +template +struct ToImpl> { + static std::optional call( + StableIValue val, + uint64_t extension_build_version, + bool is_internal) { + auto sivp = torch::stable::detail::to(val); + + // sivp is either nullptr or a pointer to a StableIValue + if (sivp == nullptr) { + return {}; + } + auto inner_val = + detail::ToImpl::call(*sivp, extension_build_version, is_internal); + + // free the memory associated with StableIValue* sivp + delete sivp; + + return std::make_optional(inner_val); + } +}; + +// Specialization for StableIValue => torch::stable::Tensor +// The resulting stable::Tensor steals ownership of the input's +// underlying AtenTensorHandle. +template <> +struct ToImpl { + static torch::stable::Tensor call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + return torch::stable::Tensor( + torch::stable::detail::to(val)); + } +}; + +// ============================================================================= +// TO CONVERSIONS requiring TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 +// ============================================================================= +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +// Specialization for StableIValue => torch::headeronly::Layout +template <> +struct ToImpl { + static Layout call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + int32_t shim_layout = torch::stable::detail::to(val); + if (shim_layout == aoti_torch_layout_strided()) { + return Layout::Strided; + } else if (shim_layout == aoti_torch_layout_sparse_coo()) { + return Layout::Sparse; + } else if (shim_layout == aoti_torch_layout_sparse_csr()) { + return Layout::SparseCsr; + } else if (shim_layout == aoti_torch_layout_sparse_csc()) { + return Layout::SparseCsc; + } else if (shim_layout == aoti_torch_layout_sparse_bsr()) { + return Layout::SparseBsr; + } else if (shim_layout == aoti_torch_layout_sparse_bsc()) { + return Layout::SparseBsc; + } else if (shim_layout == aoti_torch_layout__mkldnn()) { + return Layout::Mkldnn; + } else if (shim_layout == aoti_torch_layout_jagged()) { + return Layout::Jagged; + } else { + STD_TORCH_CHECK( + false, + "Not yet supported Layout ", + std::to_string(shim_layout), + ", please file an issue describing your use case."); + } + } +}; + +// Specialization for StableIValue => torch::headeronly::MemoryFormat +template <> +struct ToImpl { + static MemoryFormat call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + int32_t shim_memory_format = torch::stable::detail::to(val); + if (shim_memory_format == aoti_torch_memory_format_contiguous_format()) { + return MemoryFormat::Contiguous; + } else if ( + shim_memory_format == aoti_torch_memory_format_preserve_format()) { + return MemoryFormat::Preserve; + } else if (shim_memory_format == aoti_torch_memory_format_channels_last()) { + return MemoryFormat::ChannelsLast; + } else if ( + shim_memory_format == aoti_torch_memory_format_channels_last_3d()) { + return MemoryFormat::ChannelsLast3d; + } else { + STD_TORCH_CHECK( + false, + "Not yet supported MemoryFormat ", + std::to_string(shim_memory_format), + ", please file an issue describing your use case."); + } + } +}; + +// Specialization for StableIValue => std::vector +// std::vector should be represented as a StableListHandle +// filled with StableIValues +// The new std::vector steals ownership of the underlying elements +// and we free the underlying list referred by the input StableListHandle. +template +struct ToImpl> { + static std::vector call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + auto list_handle = torch::stable::detail::to(val); + size_t size; + try { + TORCH_ERROR_CODE_CHECK(torch_list_size(list_handle, &size)); + std::vector result; + result.reserve(size); + for (size_t i = 0; i < size; i++) { + StableIValue element; + TORCH_ERROR_CODE_CHECK(torch_list_get_item(list_handle, i, &element)); + result.push_back(torch::stable::detail::to(element)); + } + TORCH_ERROR_CODE_CHECK(torch_delete_list(list_handle)); + return result; + } catch (const std::runtime_error&) { + // clean up memory if an exception is thrown, and rethrow + TORCH_ERROR_CODE_CHECK(torch_delete_list(list_handle)); + throw; + } + } +}; + +// Specialization for StableIValue => torch::stable::Device +// Unpack device type and index from StableIValue in platform-independent +// format. StableIValue layout: DeviceIndex in lower 32 bits, +// DeviceType (shim int32_t) in upper 32 bits +template <> +struct ToImpl { + static torch::stable::Device call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + // Unpack: lower 32 bits = device index, upper 32 bits = device type (shim) + int32_t device_index = static_cast(val & 0xFFFFFFFF); + StableIValue device_type_shim = (val >> 32) & 0xFFFFFFFF; + DeviceType device_type = + torch::stable::detail::to(device_type_shim); + return torch::stable::Device(device_type, device_index); + } +}; + +// Specialization for std::string +// Returns a new std::string; the string in val is deleted. +template <> +struct ToImpl { + static std::string call( + StableIValue val, + [[maybe_unused]] uint64_t extension_build_version, + [[maybe_unused]] bool is_internal) { + StringHandle handle = torch::stable::detail::to(val); + size_t length; + TORCH_ERROR_CODE_CHECK(torch_string_length(handle, &length)); + const char* data; + TORCH_ERROR_CODE_CHECK(torch_string_c_str(handle, &data)); + auto strptr = new std::string(data, length); + + // delete the old string before returning new string + TORCH_ERROR_CODE_CHECK(torch_delete_string(handle)); + return *strptr; + } +}; + +#endif // TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +// ============================================================================= +// end to helpers for converting between StableIValue and T +// ============================================================================= + +// Expose the partially templated class functions through single functions +// The non-private versions will be used by the extension or headers that +// the extension includes. +template +inline StableIValue from(T val) { + return detail::FromImpl::call( + val, aoti_torch_abi_version(), /*is_internal=*/false); +} + +template +inline StableIValue from(const std::optional& val) { + return detail::FromImpl>::call( + val, aoti_torch_abi_version(), /*is_internal=*/false); +} + +// The below overload is used! See https://godbolt.org/z/859cshxrW +// We are suppressing the warning for versions clang12- and gcc11- +[[maybe_unused]] inline StableIValue from(const torch::stable::Tensor& val) { + return detail::FromImpl::call( + val, aoti_torch_abi_version(), /*is_internal=*/false); +} + +template +inline T to(StableIValue val) { + return detail::ToImpl::call( + val, aoti_torch_abi_version(), /*is_internal=*/false); +} + +// Internal conversion functions used by from_ivalue and to_ivalue. +// These are used in libtorch +template +inline StableIValue _from(T val, uint64_t extension_build_version) { + return detail::FromImpl::call( + val, extension_build_version, /*is_internal=*/true); +} + +template +inline StableIValue _from( + const std::optional& val, + uint64_t extension_build_version) { + return detail::FromImpl>::call( + val, extension_build_version, /*is_internal=*/true); +} + +[[maybe_unused]] inline StableIValue _from( + const torch::stable::Tensor& val, + uint64_t extension_build_version) { + return detail::FromImpl::call( + val, extension_build_version, /*is_internal=*/true); +} + +template +inline T _to(StableIValue val, uint64_t extension_build_version) { + return detail::ToImpl::call( + val, extension_build_version, /*is_internal=*/true); +} + +HIDDEN_NAMESPACE_END(torch, stable, detail) + +// [global from/to deprecation note] +// WARNING! the following APIs will be removed!! We deprecated global from/to +// (in 2.10) in favor of torch::stable::detail from/to to not pollute the global +// namespace. We are only including the following wrappers for backwards +// compatibility. + +// WARNING! Will be removed. Only exists for BC. See [global from/to deprecation +// note] +template +[[deprecated("Use torch::stable::detail::from instead.")]] +inline StableIValue from(T val) { + return torch::stable::detail::from(val); +} + +// WARNING! Will be removed. Only exists for BC. See [global from/to deprecation +// note] +template +[[deprecated("Use torch::stable::detail::from instead.")]] +inline StableIValue from(const std::optional& val) { + return torch::stable::detail::from(val); +} + +// WARNING! Will be removed. Only exists for BC. See [global from/to deprecation +// note] +[[deprecated( + "Use torch::stable::detail::from instead.")]] [[maybe_unused]] inline StableIValue +from(const torch::stable::Tensor& val) { + return torch::stable::detail::from(val); +} + +// WARNING! Will be removed. Only exists for BC. See [global from/to deprecation +// note] +template +[[deprecated("Use torch::stable::detail::to instead.")]] +inline T to(StableIValue val) { + return torch::stable::detail::to(val); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..8762372a415cf30f429808980e0e2f2af7942b1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor.h @@ -0,0 +1,4 @@ +#pragma once + +#include +#include diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor_inl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..8f7be7b4aabbd7a9229493203b300c5a08e9a2b3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor_inl.h @@ -0,0 +1,69 @@ +#pragma once + +// This file implements tensor.h. We separated out the Tensor struct so that +// other files can depend on the Tensor struct (like library.h) and the +// implementations of the Tensor methods can depend on APIs in library.h +// without circular dependencies. + +#include +#include +#include +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, stable) + +using torch::headeronly::ScalarType; + +inline ScalarType Tensor::scalar_type() const { + int32_t dtype; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype(ath_.get(), &dtype)); + return torch::stable::detail::to( + torch::stable::detail::from(dtype)); +} + +inline Device Tensor::device() const { + int32_t device_type; + int32_t device_index; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type(ath_.get(), &device_type)); + TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_index(ath_.get(), &device_index)); + DeviceType extension_device_type = torch::stable::detail::to( + torch::stable::detail::from(device_type)); + return Device(extension_device_type, static_cast(device_index)); +} + +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 +// The following data ptr cast methods mirror the methods defined in +// aten/src/ATen/templates/TensorMethods.cpp +#define DEFINE_DATA_PTR_CAST(T, name, PRED) \ + template <> \ + inline T* Tensor::mutable_data_ptr() const { \ + auto stype = scalar_type(); \ + STD_TORCH_CHECK( \ + PRED(stype, torch::headeronly::ScalarType::name), \ + "expected scalar type " #name " but found ", \ + torch::headeronly::toString(stype)); \ + return static_cast(mutable_data_ptr()); \ + } \ + template <> \ + inline const T* Tensor::const_data_ptr() const { \ + auto stype = scalar_type(); \ + STD_TORCH_CHECK( \ + PRED(stype, torch::headeronly::ScalarType::name), \ + "expected scalar type " #name " but found ", \ + torch::headeronly::toString(stype)); \ + return static_cast(const_data_ptr()); \ + } + +#define _PRED(S1, S2) S1 == S2 +#define DEFINE_CAST(T, name) DEFINE_DATA_PTR_CAST(T, name, _PRED) +AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_CAST) +DEFINE_CAST(uint16_t, UInt16) +DEFINE_CAST(uint32_t, UInt32) +DEFINE_CAST(uint64_t, UInt64) +#undef DEFINE_CAST +#undef _PRED +#endif // TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + +HIDDEN_NAMESPACE_END(torch, stable) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor_struct.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor_struct.h new file mode 100644 index 0000000000000000000000000000000000000000..e7b7440ea08f0a56578201c6613b29d504162174 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor_struct.h @@ -0,0 +1,244 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, stable) + +using accelerator::DeviceIndex; +using torch::headeronly::IntHeaderOnlyArrayRef; +using torch::headeronly::ScalarType; + +// The torch::stable::Tensor class is a highlevel C++ wrapper around +// the C shim Tensor APIs. We've modeled this class after TensorBase, as custom +// op kernels only really need to interact with Tensor metadata (think sizes, +// strides, device, dtype). Other functions on Tensor (like empty_like) should +// live like the ATen op that they are and exist outside of this struct. +// +// There are several goals of this class over AtenTensorHandle and +// RAIIAtenTensorHandle: +// 1. torch::stable::Tensor is a nicer UX much closer to torch::Tensor than the +// C APIs with AtenTensorHandle. Under the hood we still call to these C shim +// APIs to preserve stability. +// 2. RAIIAtenTensorHandle boils down to a uniq_ptr that forces the user to pass +// around ownership. This makes it difficult to pass one input into 2 +// different functions, e.g., doing something like c = a(t) + b(t) for +// stable::Tensor t. Thus, we use a shared_ptr here. +class Tensor { + private: + std::shared_ptr ath_; + + public: + // Construct a stable::Tensor with an uninitialized AtenTensorHandle (ATH) + // Steals ownership from the ATH + Tensor() { + AtenTensorHandle ret; + TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&ret)); + ath_ = std::shared_ptr(ret, [](AtenTensorHandle ath) { + TORCH_ERROR_CODE_CHECK(aoti_torch_delete_tensor_object(ath)); + }); + } + + // Construct a stable::Tensor from an AtenTensorHandle (ATH) + // Steals ownership from the ATH + explicit Tensor(AtenTensorHandle ath) + : ath_(ath, [](AtenTensorHandle ath) { + TORCH_ERROR_CODE_CHECK(aoti_torch_delete_tensor_object(ath)); + }) {} + + // Copy and move constructors can be default cuz the underlying handle is a + // shared_ptr + Tensor(const Tensor& other) = default; + Tensor(Tensor&& other) noexcept = default; + + // Copy and move assignment operators can be default cuz the underlying handle + // is a shared_ptr + Tensor& operator=(const Tensor& other) = default; + Tensor& operator=(Tensor&& other) noexcept = default; + + // Destructor can be default: shared ptr has custom deletion logic + ~Tensor() = default; + + // Returns a borrowed reference to the AtenTensorHandle + AtenTensorHandle get() const { + return ath_.get(); + } + + // ============================================================================= + // C-shimified TensorBase APIs: the below APIs have the same signatures and + // semantics as their counterparts in TensorBase.h. + // ============================================================================= + + // Do not add new uses of data_ptr(), use const_data_ptr() if + // possible, mutable_data_ptr() otherwise. + void* data_ptr() const { + void* data_ptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(ath_.get(), &data_ptr)); + return data_ptr; + } + +#if TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + void* mutable_data_ptr() const { + void* data_ptr{}; + TORCH_ERROR_CODE_CHECK(torch_get_mutable_data_ptr(ath_.get(), &data_ptr)); + return data_ptr; + } + + const void* const_data_ptr() const { + const void* data_ptr{}; + TORCH_ERROR_CODE_CHECK(torch_get_const_data_ptr(ath_.get(), &data_ptr)); + return data_ptr; + } + + template + T* mutable_data_ptr() const; + + template , int> = 0> + const T* const_data_ptr() const; + + const Tensor& set_requires_grad(bool requires_grad) const { + TORCH_ERROR_CODE_CHECK(torch_set_requires_grad(ath_.get(), requires_grad)); + return *this; + } +#endif // TORCH_FEATURE_VERSION >= TORCH_VERSION_2_10_0 + + int64_t dim() const { + int64_t dim; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_dim(ath_.get(), &dim)); + return dim; + } + + int64_t numel() const { + int64_t numel; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_numel(ath_.get(), &numel)); + return numel; + } + + // note: this API is, for all intents and purposes, the same as the one in + // TensorBase.h: it returns a borrowed reference of the dimension sizes of + // a Tensor. + // + // The only difference is that it returns a header-only IntHeaderOnlyArrayRef, + // which has slightly less functionality than a regular IntArrayRef. See + // [HeaderOnlyArrayRef vs ArrayRef note] for more details. + IntHeaderOnlyArrayRef sizes() const { + int64_t* sizes; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(ath_.get(), &sizes)); + return IntHeaderOnlyArrayRef(sizes, dim()); + } + + // note: this API is, for all intents and purposes, the same as the one in + // TensorBase.h: it returns a borrowed reference of the strides of a + // Tensor. + // + // The only difference is that it returns a header-only IntHeaderOnlyArrayRef, + // which has slightly less functionality than a regular IntArrayRef. See + // [HeaderOnlyArrayRef vs ArrayRef note] for more details. + IntHeaderOnlyArrayRef strides() const { + int64_t* strides; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(ath_.get(), &strides)); + return IntHeaderOnlyArrayRef(strides, dim()); + } + + // note: this is a subset of the original TensorBase API. It takes no + // arguments whereas the original API takes in a kwarg of memory format. + // Here, we assume the default contiguous memory format. + bool is_contiguous() const { + bool is_contiguous; + TORCH_ERROR_CODE_CHECK( + aoti_torch_is_contiguous(ath_.get(), &is_contiguous)); + return is_contiguous; + } + + int64_t stride(int64_t dim) const { + int64_t stride; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_stride(ath_.get(), dim, &stride)); + return stride; + } + + // This is almost the same API as the one in TensorBase.h, except + // we add a check that the returned device_index is within the + // range of int8_t. + int8_t get_device() const { + int32_t device_index; + TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_index(ath_.get(), &device_index)); + STD_TORCH_CHECK( + device_index >= std::numeric_limits::min() && + device_index <= std::numeric_limits::max(), + "Device index is out of range of return type int8_t, please use get_device_index() instead."); + return static_cast(device_index); + } + + // The same as get_device but with two differences: + // 1. it has a more suiting name + // 2. it returns a DeviceIndex, which is int32_t in this world + // that should be more stable than the likely shifting + // DeviceIndex in libtorch (it is int8_t that might become int16_t) + DeviceIndex get_device_index() const { + int32_t device_index; + TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_index(ath_.get(), &device_index)); + return device_index; + } + + bool is_cuda() const { + int32_t device_type; + TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_type(ath_.get(), &device_type)); + return device_type == aoti_torch_device_type_cuda(); + } + + bool is_cpu() const { + int32_t device_type; + TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_type(ath_.get(), &device_type)); + return device_type == aoti_torch_device_type_cpu(); + } + + int64_t size(int64_t dim) const { + int64_t size; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_size(ath_.get(), dim, &size)); + return size; + } + + bool defined() const { + bool defined; + TORCH_ERROR_CODE_CHECK(aoti_torch_is_defined(ath_.get(), &defined)); + return defined; + } + + int64_t storage_offset() const { + int64_t storage_offset; + TORCH_ERROR_CODE_CHECK( + aoti_torch_get_storage_offset(ath_.get(), &storage_offset)); + return storage_offset; + } + + size_t element_size() const { + int32_t dtype; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype(ath_.get(), &dtype)); + return aoti_torch_dtype_element_size(dtype); + } + + // defined in tensor-inl.h to avoid circular dependencies + ScalarType scalar_type() const; + + // defined in tensor-inl.h to avoid circular dependencies + Device device() const; + + // ============================================================================= + // END of C-shimified TensorBase APIs + // ============================================================================= +}; + +HIDDEN_NAMESPACE_END(torch, stable) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/version.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/version.h new file mode 100644 index 0000000000000000000000000000000000000000..22c9076a3a1b3b325c20ebd2f21be8b1df367747 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/stable/version.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +// Stable ABI Version Targeting +// +// This header provides version targeting capabilities for the PyTorch Stable +// ABI. Users can define TORCH_TARGET_VERSION to target a specific stable ABI +// version instead of using the current TORCH_ABI_VERSION of libtorch at +// compile time. +// +// Usage: +// Default behavior (uses current ABI version): +// #include +// +// Target a specific stable version (major.minor) (e.g. PyTorch 2.9): +// (1) Pass a compiler flag -DTORCH_TARGET_VERSION=0x0209000000000000 +// (2) Alternatively, define TORCH_TARGET_VERSION in the source code before +// including any header files: +// #define TORCH_TARGET_VERSION (((0ULL + 2) << 56) | ((0ULL + 9) << 48)) +// #include + +#ifdef TORCH_TARGET_VERSION +#define TORCH_FEATURE_VERSION TORCH_TARGET_VERSION +#else +#define TORCH_FEATURE_VERSION TORCH_ABI_VERSION +#endif + +#define TORCH_VERSION_2_10_0 (((0ULL + 2) << 56) | ((0ULL + 10) << 48)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/tensor/python_tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/tensor/python_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..87183f3f4eed50b44407c6df72e9e39ead754db8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/tensor/python_tensor.h @@ -0,0 +1,40 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace at { +class Tensor; +} // namespace at + +namespace torch::tensors { + +// Initializes the Python tensor type objects: torch.FloatTensor, +// torch.DoubleTensor, etc. and binds them in their containing modules. +TORCH_PYTHON_API void initialize_python_bindings(); + +// Same as set_default_tensor_type() but takes a PyObject* +TORCH_PYTHON_API void py_set_default_tensor_type(PyObject* type_obj); + +// Same as py_set_default_tensor_type, but only changes the dtype (ScalarType). +TORCH_PYTHON_API void py_set_default_dtype(PyObject* dtype_obj); + +// Gets the DispatchKey for the default tensor type. +// +// TODO: This is nuts! There is no reason to let the default tensor type id +// change. Probably only store ScalarType, as that's the only flex point +// we support. +TORCH_PYTHON_API c10::DispatchKey get_default_dispatch_key(); +TORCH_PYTHON_API at::Device get_default_device(); + +// Gets the ScalarType for the default tensor type. +TORCH_PYTHON_API at::ScalarType get_default_scalar_type(); +} // namespace torch::tensors + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/byte_order.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/byte_order.h new file mode 100644 index 0000000000000000000000000000000000000000..74ce8c0dadbe4e7baa6f9237520edce5921cb19c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/byte_order.h @@ -0,0 +1,86 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __FreeBSD__ +#include +#include +#define thp_bswap16(x) bswap16(x) +#define thp_bswap32(x) bswap32(x) +#define thp_bswap64(x) bswap64(x) +#elif defined(__APPLE__) +#include +#define thp_bswap16(x) OSSwapInt16(x) +#define thp_bswap32(x) OSSwapInt32(x) +#define thp_bswap64(x) OSSwapInt64(x) +#elif defined(__GNUC__) && !defined(__MINGW32__) +#include +#define thp_bswap16(x) bswap_16(x) +#define thp_bswap32(x) bswap_32(x) +#define thp_bswap64(x) bswap_64(x) +#elif defined _WIN32 || defined _WIN64 +#define thp_bswap16(x) _byteswap_ushort(x) +#define thp_bswap32(x) _byteswap_ulong(x) +#define thp_bswap64(x) _byteswap_uint64(x) +#endif + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define to_be16(x) thp_bswap16(x) +#define from_be16(x) thp_bswap16(x) +#define to_be32(x) thp_bswap32(x) +#define from_be32(x) thp_bswap32(x) +#define to_be64(x) thp_bswap64(x) +#define from_be64(x) thp_bswap64(x) +#define to_le16(x) (x) +#define from_le16(x) (x) +#define to_le32(x) (x) +#define from_le32(x) (x) +#define to_le64(x) (x) +#define from_le64(x) (x) +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define to_be16(x) (x) +#define from_be16(x) (x) +#define to_be32(x) (x) +#define from_be32(x) (x) +#define to_be64(x) (x) +#define from_be64(x) (x) +#define to_le16(x) thp_bswap16(x) +#define from_le16(x) thp_bswap16(x) +#define to_le32(x) thp_bswap32(x) +#define from_le32(x) thp_bswap32(x) +#define to_le64(x) thp_bswap64(x) +#define from_le64(x) thp_bswap64(x) +#else +#error Unexpected or undefined __BYTE_ORDER__ +#endif + +namespace torch::utils { + +enum THPByteOrder { THP_LITTLE_ENDIAN = 0, THP_BIG_ENDIAN = 1 }; + +TORCH_API THPByteOrder THP_nativeByteOrder(); + +template +TORCH_API void THP_decodeBuffer(T* dst, const uint8_t* src, U type, size_t len); + +template +TORCH_API void THP_encodeBuffer( + uint8_t* dst, + const T* src, + THPByteOrder order, + size_t len); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cpp_stacktraces.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cpp_stacktraces.h new file mode 100644 index 0000000000000000000000000000000000000000..2e24da7a55d82a86777253263813ff58b1264ed6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cpp_stacktraces.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch { +TORCH_API bool get_cpp_stacktraces_enabled(); +TORCH_API torch::unwind::Mode get_symbolize_mode(); +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cuda_enabled.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cuda_enabled.h new file mode 100644 index 0000000000000000000000000000000000000000..7704171f7c8e889a2680ef2815f1b2b0c04c7d92 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cuda_enabled.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::utils { + +inline constexpr bool cuda_enabled() { +#ifdef USE_CUDA + return true; +#else + return false; +#endif +} + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/device_lazy_init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/device_lazy_init.h new file mode 100644 index 0000000000000000000000000000000000000000..0f48437820daeb566418292c1de24c21b3f136b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/device_lazy_init.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +// device_lazy_init() is always compiled, even for CPU-only builds. + +namespace torch::utils { + +/** + * This mechanism of lazy initialization is designed for each device backend. + * Currently, CUDA and XPU follow this design. This function `device_lazy_init` + * MUST be called before you attempt to access any Type(CUDA or XPU) object + * from ATen, in any way. It guarantees that the device runtime status is lazily + * initialized when the first runtime API is requested. + * + * Here are some common ways that a device object may be retrieved: + * - You call getNonVariableType or getNonVariableTypeOpt + * - You call toBackend() on a Type + * + * It's important to do this correctly, because if you forget to add it you'll + * get an oblique error message seems like "Cannot initialize CUDA without + * ATen_cuda library" or "Cannot initialize XPU without ATen_xpu library" if you + * try to use CUDA or XPU functionality from a CPU-only build, which is not good + * UX. + */ +TORCH_PYTHON_API void device_lazy_init(at::DeviceType device_type); +TORCH_PYTHON_API void set_requires_device_init( + at::DeviceType device_type, + bool value); + +inline bool is_device_lazy_init_supported(at::DeviceType device_type) { + // Add more devices here to enable lazy initialization. + return ( + device_type == at::DeviceType::CUDA || + device_type == at::DeviceType::XPU || + device_type == at::DeviceType::HPU || + device_type == at::DeviceType::MTIA || + device_type == at::DeviceType::PrivateUse1); +} + +inline void maybe_initialize_device(at::Device& device) { + if (is_device_lazy_init_supported(device.type())) { + device_lazy_init(device.type()); + } +} + +inline void maybe_initialize_device(std::optional& device) { + if (!device.has_value()) { + return; + } + maybe_initialize_device(device.value()); +} + +inline void maybe_initialize_device(const at::TensorOptions& options) { + auto device = options.device(); + maybe_initialize_device(device); +} + +inline void maybe_initialize_device( + std::optional& device_type) { + if (!device_type.has_value()) { + return; + } + maybe_initialize_device(device_type.value()); +} + +bool is_device_initialized(at::DeviceType device_type); + +TORCH_PYTHON_API bool is_device_in_bad_fork(at::DeviceType device_type); + +TORCH_PYTHON_API void set_device_in_bad_fork( + at::DeviceType device_type, + bool value); + +TORCH_PYTHON_API void register_fork_handler_for_device_init( + at::DeviceType device_type); + +inline void maybe_register_fork_handler_for_device_init( + std::optional& device_type) { + if (!device_type.has_value()) { + return; + } + register_fork_handler_for_device_init(device_type.value()); +} + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/disable_torch_function.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/disable_torch_function.h new file mode 100644 index 0000000000000000000000000000000000000000..694a47e8fd6cf4af36aa1e749a26979eee1799c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/disable_torch_function.h @@ -0,0 +1,52 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch { +// Sometimes we don't want infinite recursion for subclasses, +// Or a way to achieve the old behaviour. + +// This is an internal utility, not exposed to users. +bool torch_function_enabled(); +PyObject* disabled_torch_function_impl(); +PyObject* disabled_torch_dispatch_impl(); +void set_disabled_torch_function_impl(PyObject* value); +void set_disabled_torch_dispatch_impl(PyObject* value); +// Set ignore_mode to true if you're trying to collect overloaded arguments; +// using mode here will improperly cause you to add ALL objects to the +// overloaded list even if they don't actually have __torch_function__ +bool check_has_torch_function(PyObject* obj, bool ignore_mode = false); + +struct DisableTorchDispatch { + DisableTorchDispatch() + : guard_(c10::DispatchKeySet( + {c10::DispatchKey::Python, c10::DispatchKey::PreDispatch})), + guard_tls_snapshot_(c10::DispatchKey::PythonTLSSnapshot) {} + c10::impl::ExcludeDispatchKeyGuard guard_; + c10::impl::ExcludeDispatchKeyGuard guard_tls_snapshot_; +}; + +} // namespace torch + +PyObject* THPModule_isEnabledTorchFunction(PyObject* self, PyObject* unused); +PyObject* THPModule_isAllDisabledTorchFunction( + PyObject* self, + PyObject* unused); +PyObject* THPModule_DisableTorchFunctionType(); +PyObject* THPModule_DisableTorchFunctionSubclassType(); +PyObject* THPModule_disable_torch_function(PyObject* self, PyObject* args); +PyObject* THPModule_disable_torch_dispatch(PyObject* self, PyObject* args); +PyObject* THPModule_has_torch_function(PyObject* /*unused*/, PyObject* arg); +PyObject* THPModule_has_torch_function_unary( + PyObject* /*unused*/, + PyObject* obj); +PyObject* THPModule_has_torch_function_variadic( + PyObject* /*unused*/, + PyObject* const* args, + Py_ssize_t nargs); + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/generated_serialization_types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/generated_serialization_types.h new file mode 100644 index 0000000000000000000000000000000000000000..f0bef999e2039e49772e037203aade905df03d6f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/generated_serialization_types.h @@ -0,0 +1,3877 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// @generated by update_schema.py +// checksum<> +// clang-format off + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END } +#endif + +// https://github.com/nlohmann/json/pull/2117 +NLOHMANN_JSON_NAMESPACE_BEGIN +template +struct adl_serializer> { + static void to_json(json& j, const std::optional& opt) { + if (opt == std::nullopt) { + j = nullptr; + } else { + j = *opt; // this will call adl_serializer::to_json which will + // find the free function to_json in T's namespace! + } + } + + static void from_json(const json& j, std::optional& opt) { + if (j.is_null()) { + opt = std::nullopt; + } else { + opt = j.template get(); // same as above, but with + // adl_serializer::from_json + } + } +}; +NLOHMANN_JSON_NAMESPACE_END + +namespace torch { +namespace _export { + +template +class ForwardRef { + static_assert(!std::is_reference_v, "ForwardRef cannot be a reference type"); + + public: + ForwardRef(): ptr_(std::make_unique()) {} + ForwardRef(ForwardRef&&); + ForwardRef(const ForwardRef& other): ptr_(std::make_unique(*other.ptr_)) {} + ForwardRef& operator=(ForwardRef&&); + ForwardRef& operator=(const ForwardRef& other) { + ptr_ = std::make_unique(*other.ptr_); + return *this; + } + ~ForwardRef(); + const T& operator*() const { + return *ptr_; + } + + const T* operator->() const { + return ptr_.get(); + } + + void emplace(T&& t) { + ptr_ = std::make_unique(std::move(t)); + } + + private: + std::unique_ptr ptr_; +}; + +template +void to_json(nlohmann::json& j, const ForwardRef& p) { + j = *p; +} + +template +void from_json(const nlohmann::json& j, ForwardRef& p) { + p.emplace(j.template get()); +} + +class F64 { + public: + double get() const { + return value_; + } + + void set(double value) { + value_ = value; + } + + private: + double value_; +}; + +inline void to_json(nlohmann::json& j, const F64& f) { + if (std::isinf(f.get())) { + j = "Infinity"; + } else if (std::isinf(-f.get())) { + j = "-Infinity"; + } else if (std::isnan(f.get())) { + j = "NaN"; + } else { + j = f.get(); + } +} + +inline void from_json(const nlohmann::json& j, F64& f) { + if (j == "Infinity") { + f.set(std::numeric_limits::infinity()); + } else if (j == "-Infinity") { + f.set(-std::numeric_limits::infinity()); + } else if (j == "NaN") { + f.set(std::numeric_limits::quiet_NaN()); + } else { + f.set(j.get()); + } +} + +class AOTInductorModelPickleData; +class Argument; +class BufferMutationSpec; +class ComplexValue; +class ConstantValue; +class CustomObjArgument; +class Device; +class ExportedProgram; +class ExternKernelNode; +class ExternKernelNodes; +class GradientToParameterSpec; +class GradientToUserInputSpec; +class Graph; +class GraphArgument; +class GraphModule; +class GraphSignature; +class InputSpec; +class InputToBufferSpec; +class InputToConstantInputSpec; +class InputToCustomObjSpec; +class InputToParameterSpec; +class InputToTensorConstantSpec; +class InputTokenSpec; +class LossOutputSpec; +class ModuleCallEntry; +class ModuleCallSignature; +class NamedArgument; +class NamedTupleDef; +class Node; +class OptionalTensorArgument; +class OutputSpec; +class OutputTokenSpec; +class ParameterMutationSpec; +class PayloadConfig; +class PayloadMeta; +class RangeConstraint; +class SchemaVersion; +class SymBool; +class SymBoolArgument; +class SymExpr; +class SymExprHint; +class SymFloat; +class SymFloatArgument; +class SymInt; +class SymIntArgument; +class TensorArgument; +class TensorMeta; +class TokenArgument; +class UserInputMutationSpec; +class UserInputSpec; +class UserOutputSpec; + +enum class ArgumentKind { + UNKNOWN = 0, + POSITIONAL = 1, + KEYWORD = 2, +}; + +inline std::string_view printEnum(const ArgumentKind& e) { + switch (e) { + case ArgumentKind::UNKNOWN: return "UNKNOWN"; + case ArgumentKind::POSITIONAL: return "POSITIONAL"; + case ArgumentKind::KEYWORD: return "KEYWORD"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, ArgumentKind& t) { + if (s == "UNKNOWN") { t = ArgumentKind::UNKNOWN; return; } + if (s == "POSITIONAL") { t = ArgumentKind::POSITIONAL; return; } + if (s == "KEYWORD") { t = ArgumentKind::KEYWORD; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + +enum class Layout { + Unknown = 0, + SparseCoo = 1, + SparseCsr = 2, + SparseCsc = 3, + SparseBsr = 4, + SparseBsc = 5, + _mkldnn = 6, + Strided = 7, +}; + +inline std::string_view printEnum(const Layout& e) { + switch (e) { + case Layout::Unknown: return "Unknown"; + case Layout::SparseCoo: return "SparseCoo"; + case Layout::SparseCsr: return "SparseCsr"; + case Layout::SparseCsc: return "SparseCsc"; + case Layout::SparseBsr: return "SparseBsr"; + case Layout::SparseBsc: return "SparseBsc"; + case Layout::_mkldnn: return "_mkldnn"; + case Layout::Strided: return "Strided"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, Layout& t) { + if (s == "Unknown") { t = Layout::Unknown; return; } + if (s == "SparseCoo") { t = Layout::SparseCoo; return; } + if (s == "SparseCsr") { t = Layout::SparseCsr; return; } + if (s == "SparseCsc") { t = Layout::SparseCsc; return; } + if (s == "SparseBsr") { t = Layout::SparseBsr; return; } + if (s == "SparseBsc") { t = Layout::SparseBsc; return; } + if (s == "_mkldnn") { t = Layout::_mkldnn; return; } + if (s == "Strided") { t = Layout::Strided; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + +enum class MemoryFormat { + Unknown = 0, + ContiguousFormat = 1, + ChannelsLast = 2, + ChannelsLast3d = 3, + PreserveFormat = 4, +}; + +inline std::string_view printEnum(const MemoryFormat& e) { + switch (e) { + case MemoryFormat::Unknown: return "Unknown"; + case MemoryFormat::ContiguousFormat: return "ContiguousFormat"; + case MemoryFormat::ChannelsLast: return "ChannelsLast"; + case MemoryFormat::ChannelsLast3d: return "ChannelsLast3d"; + case MemoryFormat::PreserveFormat: return "PreserveFormat"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, MemoryFormat& t) { + if (s == "Unknown") { t = MemoryFormat::Unknown; return; } + if (s == "ContiguousFormat") { t = MemoryFormat::ContiguousFormat; return; } + if (s == "ChannelsLast") { t = MemoryFormat::ChannelsLast; return; } + if (s == "ChannelsLast3d") { t = MemoryFormat::ChannelsLast3d; return; } + if (s == "PreserveFormat") { t = MemoryFormat::PreserveFormat; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + +enum class ScalarType { + UNKNOWN = 0, + BYTE = 1, + CHAR = 2, + SHORT = 3, + INT = 4, + LONG = 5, + HALF = 6, + FLOAT = 7, + DOUBLE = 8, + COMPLEXHALF = 9, + COMPLEXFLOAT = 10, + COMPLEXDOUBLE = 11, + BOOL = 12, + BFLOAT16 = 13, + UINT16 = 28, + FLOAT8E4M3FN = 29, + FLOAT8E5M2 = 30, + FLOAT8E4M3FNUZ = 31, + FLOAT8E5M2FNUZ = 32, +}; + +inline std::string_view printEnum(const ScalarType& e) { + switch (e) { + case ScalarType::UNKNOWN: return "UNKNOWN"; + case ScalarType::BYTE: return "BYTE"; + case ScalarType::CHAR: return "CHAR"; + case ScalarType::SHORT: return "SHORT"; + case ScalarType::INT: return "INT"; + case ScalarType::LONG: return "LONG"; + case ScalarType::HALF: return "HALF"; + case ScalarType::FLOAT: return "FLOAT"; + case ScalarType::DOUBLE: return "DOUBLE"; + case ScalarType::COMPLEXHALF: return "COMPLEXHALF"; + case ScalarType::COMPLEXFLOAT: return "COMPLEXFLOAT"; + case ScalarType::COMPLEXDOUBLE: return "COMPLEXDOUBLE"; + case ScalarType::BOOL: return "BOOL"; + case ScalarType::BFLOAT16: return "BFLOAT16"; + case ScalarType::UINT16: return "UINT16"; + case ScalarType::FLOAT8E4M3FN: return "FLOAT8E4M3FN"; + case ScalarType::FLOAT8E5M2: return "FLOAT8E5M2"; + case ScalarType::FLOAT8E4M3FNUZ: return "FLOAT8E4M3FNUZ"; + case ScalarType::FLOAT8E5M2FNUZ: return "FLOAT8E5M2FNUZ"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, ScalarType& t) { + if (s == "UNKNOWN") { t = ScalarType::UNKNOWN; return; } + if (s == "BYTE") { t = ScalarType::BYTE; return; } + if (s == "CHAR") { t = ScalarType::CHAR; return; } + if (s == "SHORT") { t = ScalarType::SHORT; return; } + if (s == "INT") { t = ScalarType::INT; return; } + if (s == "LONG") { t = ScalarType::LONG; return; } + if (s == "HALF") { t = ScalarType::HALF; return; } + if (s == "FLOAT") { t = ScalarType::FLOAT; return; } + if (s == "DOUBLE") { t = ScalarType::DOUBLE; return; } + if (s == "COMPLEXHALF") { t = ScalarType::COMPLEXHALF; return; } + if (s == "COMPLEXFLOAT") { t = ScalarType::COMPLEXFLOAT; return; } + if (s == "COMPLEXDOUBLE") { t = ScalarType::COMPLEXDOUBLE; return; } + if (s == "BOOL") { t = ScalarType::BOOL; return; } + if (s == "BFLOAT16") { t = ScalarType::BFLOAT16; return; } + if (s == "UINT16") { t = ScalarType::UINT16; return; } + if (s == "FLOAT8E4M3FN") { t = ScalarType::FLOAT8E4M3FN; return; } + if (s == "FLOAT8E5M2") { t = ScalarType::FLOAT8E5M2; return; } + if (s == "FLOAT8E4M3FNUZ") { t = ScalarType::FLOAT8E4M3FNUZ; return; } + if (s == "FLOAT8E5M2FNUZ") { t = ScalarType::FLOAT8E5M2FNUZ; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class Device { + private: + std::string type; + std::optional index = std::nullopt; + + public: + + const std::string& get_type() const { + return type; + } + + void set_type(std::string def) { + type = std::move(def); + } + + const std::optional& get_index() const { + return index; + } + + void set_index(std::optional def) { + index = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const Device& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, Device& nlohmann_json_t); +}; + +class SymExprHint { + struct Void {}; + + public: + enum class Tag { + AS_INT, AS_BOOL, AS_FLOAT + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const int64_t& get_as_int() const { + return std::get<1>(variant_); + } + + void set_as_int(int64_t def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_INT; + } + + const bool& get_as_bool() const { + return std::get<2>(variant_); + } + + void set_as_bool(bool def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_BOOL; + } + + const F64& get_as_float() const { + return std::get<3>(variant_); + } + + void set_as_float(F64 def) { + variant_.emplace<3>(std::move(def)); + tag_ = Tag::AS_FLOAT; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SymExprHint& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_INT) { + nlohmann_json_j["as_int"] = nlohmann_json_t.get_as_int(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_BOOL) { + nlohmann_json_j["as_bool"] = nlohmann_json_t.get_as_bool(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_FLOAT) { + nlohmann_json_j["as_float"] = nlohmann_json_t.get_as_float(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, SymExprHint& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_int")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_int").template get()); + nlohmann_json_t.tag_ = Tag::AS_INT; + return; + } + if (nlohmann_json_j.contains("as_bool")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_bool").template get()); + nlohmann_json_t.tag_ = Tag::AS_BOOL; + return; + } + if (nlohmann_json_j.contains("as_float")) { + nlohmann_json_t.variant_.emplace<3>(nlohmann_json_j.at("as_float").template get()); + nlohmann_json_t.tag_ = Tag::AS_FLOAT; + return; + } + } +}; + +inline std::string_view printEnum(const SymExprHint::Tag& e) { + switch (e) { + case SymExprHint::Tag::AS_INT: return "AS_INT"; + case SymExprHint::Tag::AS_BOOL: return "AS_BOOL"; + case SymExprHint::Tag::AS_FLOAT: return "AS_FLOAT"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, SymExprHint::Tag& t) { + if (s == "AS_INT") { t = SymExprHint::Tag::AS_INT; return; } + if (s == "AS_BOOL") { t = SymExprHint::Tag::AS_BOOL; return; } + if (s == "AS_FLOAT") { t = SymExprHint::Tag::AS_FLOAT; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class SymExpr { + private: + std::string expr_str; + std::optional hint = std::nullopt; + + public: + + const std::string& get_expr_str() const { + return expr_str; + } + + void set_expr_str(std::string def) { + expr_str = std::move(def); + } + + const std::optional& get_hint() const { + return hint; + } + + void set_hint(std::optional def) { + hint = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SymExpr& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, SymExpr& nlohmann_json_t); +}; + +class SymInt { + struct Void {}; + + public: + enum class Tag { + AS_EXPR, AS_INT + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const SymExpr& get_as_expr() const { + return std::get<1>(variant_); + } + + void set_as_expr(SymExpr def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_EXPR; + } + + const int64_t& get_as_int() const { + return std::get<2>(variant_); + } + + void set_as_int(int64_t def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_INT; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SymInt& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_EXPR) { + nlohmann_json_j["as_expr"] = nlohmann_json_t.get_as_expr(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_INT) { + nlohmann_json_j["as_int"] = nlohmann_json_t.get_as_int(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, SymInt& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_expr")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_expr").template get()); + nlohmann_json_t.tag_ = Tag::AS_EXPR; + return; + } + if (nlohmann_json_j.contains("as_int")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_int").template get()); + nlohmann_json_t.tag_ = Tag::AS_INT; + return; + } + } +}; + +inline std::string_view printEnum(const SymInt::Tag& e) { + switch (e) { + case SymInt::Tag::AS_EXPR: return "AS_EXPR"; + case SymInt::Tag::AS_INT: return "AS_INT"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, SymInt::Tag& t) { + if (s == "AS_EXPR") { t = SymInt::Tag::AS_EXPR; return; } + if (s == "AS_INT") { t = SymInt::Tag::AS_INT; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class SymFloat { + struct Void {}; + + public: + enum class Tag { + AS_EXPR, AS_FLOAT + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const SymExpr& get_as_expr() const { + return std::get<1>(variant_); + } + + void set_as_expr(SymExpr def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_EXPR; + } + + const F64& get_as_float() const { + return std::get<2>(variant_); + } + + void set_as_float(F64 def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_FLOAT; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SymFloat& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_EXPR) { + nlohmann_json_j["as_expr"] = nlohmann_json_t.get_as_expr(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_FLOAT) { + nlohmann_json_j["as_float"] = nlohmann_json_t.get_as_float(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, SymFloat& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_expr")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_expr").template get()); + nlohmann_json_t.tag_ = Tag::AS_EXPR; + return; + } + if (nlohmann_json_j.contains("as_float")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_float").template get()); + nlohmann_json_t.tag_ = Tag::AS_FLOAT; + return; + } + } +}; + +inline std::string_view printEnum(const SymFloat::Tag& e) { + switch (e) { + case SymFloat::Tag::AS_EXPR: return "AS_EXPR"; + case SymFloat::Tag::AS_FLOAT: return "AS_FLOAT"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, SymFloat::Tag& t) { + if (s == "AS_EXPR") { t = SymFloat::Tag::AS_EXPR; return; } + if (s == "AS_FLOAT") { t = SymFloat::Tag::AS_FLOAT; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class SymBool { + struct Void {}; + + public: + enum class Tag { + AS_EXPR, AS_BOOL + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const SymExpr& get_as_expr() const { + return std::get<1>(variant_); + } + + void set_as_expr(SymExpr def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_EXPR; + } + + const bool& get_as_bool() const { + return std::get<2>(variant_); + } + + void set_as_bool(bool def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_BOOL; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SymBool& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_EXPR) { + nlohmann_json_j["as_expr"] = nlohmann_json_t.get_as_expr(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_BOOL) { + nlohmann_json_j["as_bool"] = nlohmann_json_t.get_as_bool(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, SymBool& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_expr")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_expr").template get()); + nlohmann_json_t.tag_ = Tag::AS_EXPR; + return; + } + if (nlohmann_json_j.contains("as_bool")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_bool").template get()); + nlohmann_json_t.tag_ = Tag::AS_BOOL; + return; + } + } +}; + +inline std::string_view printEnum(const SymBool::Tag& e) { + switch (e) { + case SymBool::Tag::AS_EXPR: return "AS_EXPR"; + case SymBool::Tag::AS_BOOL: return "AS_BOOL"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, SymBool::Tag& t) { + if (s == "AS_EXPR") { t = SymBool::Tag::AS_EXPR; return; } + if (s == "AS_BOOL") { t = SymBool::Tag::AS_BOOL; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class TensorMeta { + private: + int64_t dtype; + std::vector sizes; + bool requires_grad; + Device device; + std::vector strides; + SymInt storage_offset; + int64_t layout; + + public: + + ScalarType get_dtype() const { + return static_cast(dtype); + } + + void set_dtype(ScalarType def) { + dtype = static_cast(def); + } + + const std::vector& get_sizes() const { + return sizes; + } + + void set_sizes(std::vector def) { + sizes = std::move(def); + } + + const bool& get_requires_grad() const { + return requires_grad; + } + + void set_requires_grad(bool def) { + requires_grad = std::move(def); + } + + const Device& get_device() const { + return device; + } + + void set_device(Device def) { + device = std::move(def); + } + + const std::vector& get_strides() const { + return strides; + } + + void set_strides(std::vector def) { + strides = std::move(def); + } + + const SymInt& get_storage_offset() const { + return storage_offset; + } + + void set_storage_offset(SymInt def) { + storage_offset = std::move(def); + } + + Layout get_layout() const { + return static_cast(layout); + } + + void set_layout(Layout def) { + layout = static_cast(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const TensorMeta& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, TensorMeta& nlohmann_json_t); +}; + +class SymIntArgument { + struct Void {}; + + public: + enum class Tag { + AS_NAME, AS_INT + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const std::string& get_as_name() const { + return std::get<1>(variant_); + } + + void set_as_name(std::string def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_NAME; + } + + const int64_t& get_as_int() const { + return std::get<2>(variant_); + } + + void set_as_int(int64_t def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_INT; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SymIntArgument& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_NAME) { + nlohmann_json_j["as_name"] = nlohmann_json_t.get_as_name(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_INT) { + nlohmann_json_j["as_int"] = nlohmann_json_t.get_as_int(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, SymIntArgument& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_name")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_name").template get()); + nlohmann_json_t.tag_ = Tag::AS_NAME; + return; + } + if (nlohmann_json_j.contains("as_int")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_int").template get()); + nlohmann_json_t.tag_ = Tag::AS_INT; + return; + } + } +}; + +inline std::string_view printEnum(const SymIntArgument::Tag& e) { + switch (e) { + case SymIntArgument::Tag::AS_NAME: return "AS_NAME"; + case SymIntArgument::Tag::AS_INT: return "AS_INT"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, SymIntArgument::Tag& t) { + if (s == "AS_NAME") { t = SymIntArgument::Tag::AS_NAME; return; } + if (s == "AS_INT") { t = SymIntArgument::Tag::AS_INT; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class SymFloatArgument { + struct Void {}; + + public: + enum class Tag { + AS_NAME, AS_FLOAT + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const std::string& get_as_name() const { + return std::get<1>(variant_); + } + + void set_as_name(std::string def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_NAME; + } + + const F64& get_as_float() const { + return std::get<2>(variant_); + } + + void set_as_float(F64 def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_FLOAT; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SymFloatArgument& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_NAME) { + nlohmann_json_j["as_name"] = nlohmann_json_t.get_as_name(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_FLOAT) { + nlohmann_json_j["as_float"] = nlohmann_json_t.get_as_float(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, SymFloatArgument& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_name")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_name").template get()); + nlohmann_json_t.tag_ = Tag::AS_NAME; + return; + } + if (nlohmann_json_j.contains("as_float")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_float").template get()); + nlohmann_json_t.tag_ = Tag::AS_FLOAT; + return; + } + } +}; + +inline std::string_view printEnum(const SymFloatArgument::Tag& e) { + switch (e) { + case SymFloatArgument::Tag::AS_NAME: return "AS_NAME"; + case SymFloatArgument::Tag::AS_FLOAT: return "AS_FLOAT"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, SymFloatArgument::Tag& t) { + if (s == "AS_NAME") { t = SymFloatArgument::Tag::AS_NAME; return; } + if (s == "AS_FLOAT") { t = SymFloatArgument::Tag::AS_FLOAT; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class SymBoolArgument { + struct Void {}; + + public: + enum class Tag { + AS_NAME, AS_BOOL + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const std::string& get_as_name() const { + return std::get<1>(variant_); + } + + void set_as_name(std::string def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_NAME; + } + + const bool& get_as_bool() const { + return std::get<2>(variant_); + } + + void set_as_bool(bool def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_BOOL; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SymBoolArgument& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_NAME) { + nlohmann_json_j["as_name"] = nlohmann_json_t.get_as_name(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_BOOL) { + nlohmann_json_j["as_bool"] = nlohmann_json_t.get_as_bool(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, SymBoolArgument& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_name")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_name").template get()); + nlohmann_json_t.tag_ = Tag::AS_NAME; + return; + } + if (nlohmann_json_j.contains("as_bool")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_bool").template get()); + nlohmann_json_t.tag_ = Tag::AS_BOOL; + return; + } + } +}; + +inline std::string_view printEnum(const SymBoolArgument::Tag& e) { + switch (e) { + case SymBoolArgument::Tag::AS_NAME: return "AS_NAME"; + case SymBoolArgument::Tag::AS_BOOL: return "AS_BOOL"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, SymBoolArgument::Tag& t) { + if (s == "AS_NAME") { t = SymBoolArgument::Tag::AS_NAME; return; } + if (s == "AS_BOOL") { t = SymBoolArgument::Tag::AS_BOOL; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class TensorArgument { + private: + std::string name; + + public: + + const std::string& get_name() const { + return name; + } + + void set_name(std::string def) { + name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const TensorArgument& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, TensorArgument& nlohmann_json_t); +}; + +class TokenArgument { + private: + std::string name; + + public: + + const std::string& get_name() const { + return name; + } + + void set_name(std::string def) { + name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const TokenArgument& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, TokenArgument& nlohmann_json_t); +}; + +class OptionalTensorArgument { + struct Void {}; + + public: + enum class Tag { + AS_TENSOR, AS_NONE + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const TensorArgument& get_as_tensor() const { + return std::get<1>(variant_); + } + + void set_as_tensor(TensorArgument def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_TENSOR; + } + + const bool& get_as_none() const { + return std::get<2>(variant_); + } + + void set_as_none(bool def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_NONE; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const OptionalTensorArgument& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_TENSOR) { + nlohmann_json_j["as_tensor"] = nlohmann_json_t.get_as_tensor(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_NONE) { + nlohmann_json_j["as_none"] = nlohmann_json_t.get_as_none(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, OptionalTensorArgument& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_tensor")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_tensor").template get()); + nlohmann_json_t.tag_ = Tag::AS_TENSOR; + return; + } + if (nlohmann_json_j.contains("as_none")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_none").template get()); + nlohmann_json_t.tag_ = Tag::AS_NONE; + return; + } + } +}; + +inline std::string_view printEnum(const OptionalTensorArgument::Tag& e) { + switch (e) { + case OptionalTensorArgument::Tag::AS_TENSOR: return "AS_TENSOR"; + case OptionalTensorArgument::Tag::AS_NONE: return "AS_NONE"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, OptionalTensorArgument::Tag& t) { + if (s == "AS_TENSOR") { t = OptionalTensorArgument::Tag::AS_TENSOR; return; } + if (s == "AS_NONE") { t = OptionalTensorArgument::Tag::AS_NONE; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class GraphArgument { + private: + std::string name; + ForwardRef graph; + + public: + + const std::string& get_name() const { + return name; + } + + void set_name(std::string def) { + name = std::move(def); + } + + const ForwardRef& get_graph() const { + return graph; + } + + void set_graph(ForwardRef def) { + graph = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const GraphArgument& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, GraphArgument& nlohmann_json_t); +}; + +class CustomObjArgument { + private: + std::string name; + std::string class_fqn; + + public: + + const std::string& get_name() const { + return name; + } + + void set_name(std::string def) { + name = std::move(def); + } + + const std::string& get_class_fqn() const { + return class_fqn; + } + + void set_class_fqn(std::string def) { + class_fqn = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const CustomObjArgument& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, CustomObjArgument& nlohmann_json_t); +}; + +class ComplexValue { + private: + F64 real; + F64 imag; + + public: + + const F64& get_real() const { + return real; + } + + void set_real(F64 def) { + real = std::move(def); + } + + const F64& get_imag() const { + return imag; + } + + void set_imag(F64 def) { + imag = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const ComplexValue& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, ComplexValue& nlohmann_json_t); +}; + +class Argument { + struct Void {}; + + public: + enum class Tag { + AS_NONE, AS_TENSOR, AS_TENSORS, AS_INT, AS_INTS, AS_FLOAT, AS_FLOATS, AS_STRING, AS_STRINGS, AS_SYM_INT, AS_SYM_INTS, AS_SCALAR_TYPE, AS_MEMORY_FORMAT, AS_LAYOUT, AS_DEVICE, AS_BOOL, AS_BOOLS, AS_SYM_BOOL, AS_SYM_BOOLS, AS_GRAPH, AS_OPTIONAL_TENSORS, AS_CUSTOM_OBJ, AS_OPERATOR, AS_SYM_FLOAT, AS_SYM_FLOATS, AS_OPTIONAL_TENSOR, AS_COMPLEX, AS_INT_LISTS, AS_STRING_TO_ARGUMENT + }; + + private: + std::variant, int64_t, std::vector, F64, std::vector, std::string, std::vector, SymIntArgument, std::vector, ScalarType, MemoryFormat, Layout, Device, bool, std::vector, SymBoolArgument, std::vector, GraphArgument, std::vector, CustomObjArgument, std::string, SymFloatArgument, std::vector, OptionalTensorArgument, ComplexValue, std::vector>, std::unordered_map>> variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const bool& get_as_none() const { + return std::get<1>(variant_); + } + + void set_as_none(bool def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_NONE; + } + + const TensorArgument& get_as_tensor() const { + return std::get<2>(variant_); + } + + void set_as_tensor(TensorArgument def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_TENSOR; + } + + const std::vector& get_as_tensors() const { + return std::get<3>(variant_); + } + + void set_as_tensors(std::vector def) { + variant_.emplace<3>(std::move(def)); + tag_ = Tag::AS_TENSORS; + } + + const int64_t& get_as_int() const { + return std::get<4>(variant_); + } + + void set_as_int(int64_t def) { + variant_.emplace<4>(std::move(def)); + tag_ = Tag::AS_INT; + } + + const std::vector& get_as_ints() const { + return std::get<5>(variant_); + } + + void set_as_ints(std::vector def) { + variant_.emplace<5>(std::move(def)); + tag_ = Tag::AS_INTS; + } + + const F64& get_as_float() const { + return std::get<6>(variant_); + } + + void set_as_float(F64 def) { + variant_.emplace<6>(std::move(def)); + tag_ = Tag::AS_FLOAT; + } + + const std::vector& get_as_floats() const { + return std::get<7>(variant_); + } + + void set_as_floats(std::vector def) { + variant_.emplace<7>(std::move(def)); + tag_ = Tag::AS_FLOATS; + } + + const std::string& get_as_string() const { + return std::get<8>(variant_); + } + + void set_as_string(std::string def) { + variant_.emplace<8>(std::move(def)); + tag_ = Tag::AS_STRING; + } + + const std::vector& get_as_strings() const { + return std::get<9>(variant_); + } + + void set_as_strings(std::vector def) { + variant_.emplace<9>(std::move(def)); + tag_ = Tag::AS_STRINGS; + } + + const SymIntArgument& get_as_sym_int() const { + return std::get<10>(variant_); + } + + void set_as_sym_int(SymIntArgument def) { + variant_.emplace<10>(std::move(def)); + tag_ = Tag::AS_SYM_INT; + } + + const std::vector& get_as_sym_ints() const { + return std::get<11>(variant_); + } + + void set_as_sym_ints(std::vector def) { + variant_.emplace<11>(std::move(def)); + tag_ = Tag::AS_SYM_INTS; + } + + const ScalarType& get_as_scalar_type() const { + return std::get<12>(variant_); + } + + void set_as_scalar_type(ScalarType def) { + variant_.emplace<12>(std::move(def)); + tag_ = Tag::AS_SCALAR_TYPE; + } + + const MemoryFormat& get_as_memory_format() const { + return std::get<13>(variant_); + } + + void set_as_memory_format(MemoryFormat def) { + variant_.emplace<13>(std::move(def)); + tag_ = Tag::AS_MEMORY_FORMAT; + } + + const Layout& get_as_layout() const { + return std::get<14>(variant_); + } + + void set_as_layout(Layout def) { + variant_.emplace<14>(std::move(def)); + tag_ = Tag::AS_LAYOUT; + } + + const Device& get_as_device() const { + return std::get<15>(variant_); + } + + void set_as_device(Device def) { + variant_.emplace<15>(std::move(def)); + tag_ = Tag::AS_DEVICE; + } + + const bool& get_as_bool() const { + return std::get<16>(variant_); + } + + void set_as_bool(bool def) { + variant_.emplace<16>(std::move(def)); + tag_ = Tag::AS_BOOL; + } + + const std::vector& get_as_bools() const { + return std::get<17>(variant_); + } + + void set_as_bools(std::vector def) { + variant_.emplace<17>(std::move(def)); + tag_ = Tag::AS_BOOLS; + } + + const SymBoolArgument& get_as_sym_bool() const { + return std::get<18>(variant_); + } + + void set_as_sym_bool(SymBoolArgument def) { + variant_.emplace<18>(std::move(def)); + tag_ = Tag::AS_SYM_BOOL; + } + + const std::vector& get_as_sym_bools() const { + return std::get<19>(variant_); + } + + void set_as_sym_bools(std::vector def) { + variant_.emplace<19>(std::move(def)); + tag_ = Tag::AS_SYM_BOOLS; + } + + const GraphArgument& get_as_graph() const { + return std::get<20>(variant_); + } + + void set_as_graph(GraphArgument def) { + variant_.emplace<20>(std::move(def)); + tag_ = Tag::AS_GRAPH; + } + + const std::vector& get_as_optional_tensors() const { + return std::get<21>(variant_); + } + + void set_as_optional_tensors(std::vector def) { + variant_.emplace<21>(std::move(def)); + tag_ = Tag::AS_OPTIONAL_TENSORS; + } + + const CustomObjArgument& get_as_custom_obj() const { + return std::get<22>(variant_); + } + + void set_as_custom_obj(CustomObjArgument def) { + variant_.emplace<22>(std::move(def)); + tag_ = Tag::AS_CUSTOM_OBJ; + } + + const std::string& get_as_operator() const { + return std::get<23>(variant_); + } + + void set_as_operator(std::string def) { + variant_.emplace<23>(std::move(def)); + tag_ = Tag::AS_OPERATOR; + } + + const SymFloatArgument& get_as_sym_float() const { + return std::get<24>(variant_); + } + + void set_as_sym_float(SymFloatArgument def) { + variant_.emplace<24>(std::move(def)); + tag_ = Tag::AS_SYM_FLOAT; + } + + const std::vector& get_as_sym_floats() const { + return std::get<25>(variant_); + } + + void set_as_sym_floats(std::vector def) { + variant_.emplace<25>(std::move(def)); + tag_ = Tag::AS_SYM_FLOATS; + } + + const OptionalTensorArgument& get_as_optional_tensor() const { + return std::get<26>(variant_); + } + + void set_as_optional_tensor(OptionalTensorArgument def) { + variant_.emplace<26>(std::move(def)); + tag_ = Tag::AS_OPTIONAL_TENSOR; + } + + const ComplexValue& get_as_complex() const { + return std::get<27>(variant_); + } + + void set_as_complex(ComplexValue def) { + variant_.emplace<27>(std::move(def)); + tag_ = Tag::AS_COMPLEX; + } + + const std::vector>& get_as_int_lists() const { + return std::get<28>(variant_); + } + + void set_as_int_lists(std::vector> def) { + variant_.emplace<28>(std::move(def)); + tag_ = Tag::AS_INT_LISTS; + } + + const std::unordered_map>& get_as_string_to_argument() const { + return std::get<29>(variant_); + } + + void set_as_string_to_argument(std::unordered_map> def) { + variant_.emplace<29>(std::move(def)); + tag_ = Tag::AS_STRING_TO_ARGUMENT; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const Argument& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_NONE) { + nlohmann_json_j["as_none"] = nlohmann_json_t.get_as_none(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_TENSOR) { + nlohmann_json_j["as_tensor"] = nlohmann_json_t.get_as_tensor(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_TENSORS) { + nlohmann_json_j["as_tensors"] = nlohmann_json_t.get_as_tensors(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_INT) { + nlohmann_json_j["as_int"] = nlohmann_json_t.get_as_int(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_INTS) { + nlohmann_json_j["as_ints"] = nlohmann_json_t.get_as_ints(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_FLOAT) { + nlohmann_json_j["as_float"] = nlohmann_json_t.get_as_float(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_FLOATS) { + nlohmann_json_j["as_floats"] = nlohmann_json_t.get_as_floats(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_STRING) { + nlohmann_json_j["as_string"] = nlohmann_json_t.get_as_string(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_STRINGS) { + nlohmann_json_j["as_strings"] = nlohmann_json_t.get_as_strings(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_SYM_INT) { + nlohmann_json_j["as_sym_int"] = nlohmann_json_t.get_as_sym_int(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_SYM_INTS) { + nlohmann_json_j["as_sym_ints"] = nlohmann_json_t.get_as_sym_ints(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_SCALAR_TYPE) { + nlohmann_json_j["as_scalar_type"] = nlohmann_json_t.get_as_scalar_type(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_MEMORY_FORMAT) { + nlohmann_json_j["as_memory_format"] = nlohmann_json_t.get_as_memory_format(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_LAYOUT) { + nlohmann_json_j["as_layout"] = nlohmann_json_t.get_as_layout(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_DEVICE) { + nlohmann_json_j["as_device"] = nlohmann_json_t.get_as_device(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_BOOL) { + nlohmann_json_j["as_bool"] = nlohmann_json_t.get_as_bool(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_BOOLS) { + nlohmann_json_j["as_bools"] = nlohmann_json_t.get_as_bools(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_SYM_BOOL) { + nlohmann_json_j["as_sym_bool"] = nlohmann_json_t.get_as_sym_bool(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_SYM_BOOLS) { + nlohmann_json_j["as_sym_bools"] = nlohmann_json_t.get_as_sym_bools(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_GRAPH) { + nlohmann_json_j["as_graph"] = nlohmann_json_t.get_as_graph(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_OPTIONAL_TENSORS) { + nlohmann_json_j["as_optional_tensors"] = nlohmann_json_t.get_as_optional_tensors(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_CUSTOM_OBJ) { + nlohmann_json_j["as_custom_obj"] = nlohmann_json_t.get_as_custom_obj(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_OPERATOR) { + nlohmann_json_j["as_operator"] = nlohmann_json_t.get_as_operator(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_SYM_FLOAT) { + nlohmann_json_j["as_sym_float"] = nlohmann_json_t.get_as_sym_float(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_SYM_FLOATS) { + nlohmann_json_j["as_sym_floats"] = nlohmann_json_t.get_as_sym_floats(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_OPTIONAL_TENSOR) { + nlohmann_json_j["as_optional_tensor"] = nlohmann_json_t.get_as_optional_tensor(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_COMPLEX) { + nlohmann_json_j["as_complex"] = nlohmann_json_t.get_as_complex(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_INT_LISTS) { + nlohmann_json_j["as_int_lists"] = nlohmann_json_t.get_as_int_lists(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_STRING_TO_ARGUMENT) { + nlohmann_json_j["as_string_to_argument"] = nlohmann_json_t.get_as_string_to_argument(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, Argument& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_none")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_none").template get()); + nlohmann_json_t.tag_ = Tag::AS_NONE; + return; + } + if (nlohmann_json_j.contains("as_tensor")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_tensor").template get()); + nlohmann_json_t.tag_ = Tag::AS_TENSOR; + return; + } + if (nlohmann_json_j.contains("as_tensors")) { + nlohmann_json_t.variant_.emplace<3>(nlohmann_json_j.at("as_tensors").template get>()); + nlohmann_json_t.tag_ = Tag::AS_TENSORS; + return; + } + if (nlohmann_json_j.contains("as_int")) { + nlohmann_json_t.variant_.emplace<4>(nlohmann_json_j.at("as_int").template get()); + nlohmann_json_t.tag_ = Tag::AS_INT; + return; + } + if (nlohmann_json_j.contains("as_ints")) { + nlohmann_json_t.variant_.emplace<5>(nlohmann_json_j.at("as_ints").template get>()); + nlohmann_json_t.tag_ = Tag::AS_INTS; + return; + } + if (nlohmann_json_j.contains("as_float")) { + nlohmann_json_t.variant_.emplace<6>(nlohmann_json_j.at("as_float").template get()); + nlohmann_json_t.tag_ = Tag::AS_FLOAT; + return; + } + if (nlohmann_json_j.contains("as_floats")) { + nlohmann_json_t.variant_.emplace<7>(nlohmann_json_j.at("as_floats").template get>()); + nlohmann_json_t.tag_ = Tag::AS_FLOATS; + return; + } + if (nlohmann_json_j.contains("as_string")) { + nlohmann_json_t.variant_.emplace<8>(nlohmann_json_j.at("as_string").template get()); + nlohmann_json_t.tag_ = Tag::AS_STRING; + return; + } + if (nlohmann_json_j.contains("as_strings")) { + nlohmann_json_t.variant_.emplace<9>(nlohmann_json_j.at("as_strings").template get>()); + nlohmann_json_t.tag_ = Tag::AS_STRINGS; + return; + } + if (nlohmann_json_j.contains("as_sym_int")) { + nlohmann_json_t.variant_.emplace<10>(nlohmann_json_j.at("as_sym_int").template get()); + nlohmann_json_t.tag_ = Tag::AS_SYM_INT; + return; + } + if (nlohmann_json_j.contains("as_sym_ints")) { + nlohmann_json_t.variant_.emplace<11>(nlohmann_json_j.at("as_sym_ints").template get>()); + nlohmann_json_t.tag_ = Tag::AS_SYM_INTS; + return; + } + if (nlohmann_json_j.contains("as_scalar_type")) { + nlohmann_json_t.variant_.emplace<12>(nlohmann_json_j.at("as_scalar_type").template get()); + nlohmann_json_t.tag_ = Tag::AS_SCALAR_TYPE; + return; + } + if (nlohmann_json_j.contains("as_memory_format")) { + nlohmann_json_t.variant_.emplace<13>(nlohmann_json_j.at("as_memory_format").template get()); + nlohmann_json_t.tag_ = Tag::AS_MEMORY_FORMAT; + return; + } + if (nlohmann_json_j.contains("as_layout")) { + nlohmann_json_t.variant_.emplace<14>(nlohmann_json_j.at("as_layout").template get()); + nlohmann_json_t.tag_ = Tag::AS_LAYOUT; + return; + } + if (nlohmann_json_j.contains("as_device")) { + nlohmann_json_t.variant_.emplace<15>(nlohmann_json_j.at("as_device").template get()); + nlohmann_json_t.tag_ = Tag::AS_DEVICE; + return; + } + if (nlohmann_json_j.contains("as_bool")) { + nlohmann_json_t.variant_.emplace<16>(nlohmann_json_j.at("as_bool").template get()); + nlohmann_json_t.tag_ = Tag::AS_BOOL; + return; + } + if (nlohmann_json_j.contains("as_bools")) { + nlohmann_json_t.variant_.emplace<17>(nlohmann_json_j.at("as_bools").template get>()); + nlohmann_json_t.tag_ = Tag::AS_BOOLS; + return; + } + if (nlohmann_json_j.contains("as_sym_bool")) { + nlohmann_json_t.variant_.emplace<18>(nlohmann_json_j.at("as_sym_bool").template get()); + nlohmann_json_t.tag_ = Tag::AS_SYM_BOOL; + return; + } + if (nlohmann_json_j.contains("as_sym_bools")) { + nlohmann_json_t.variant_.emplace<19>(nlohmann_json_j.at("as_sym_bools").template get>()); + nlohmann_json_t.tag_ = Tag::AS_SYM_BOOLS; + return; + } + if (nlohmann_json_j.contains("as_graph")) { + nlohmann_json_t.variant_.emplace<20>(nlohmann_json_j.at("as_graph").template get()); + nlohmann_json_t.tag_ = Tag::AS_GRAPH; + return; + } + if (nlohmann_json_j.contains("as_optional_tensors")) { + nlohmann_json_t.variant_.emplace<21>(nlohmann_json_j.at("as_optional_tensors").template get>()); + nlohmann_json_t.tag_ = Tag::AS_OPTIONAL_TENSORS; + return; + } + if (nlohmann_json_j.contains("as_custom_obj")) { + nlohmann_json_t.variant_.emplace<22>(nlohmann_json_j.at("as_custom_obj").template get()); + nlohmann_json_t.tag_ = Tag::AS_CUSTOM_OBJ; + return; + } + if (nlohmann_json_j.contains("as_operator")) { + nlohmann_json_t.variant_.emplace<23>(nlohmann_json_j.at("as_operator").template get()); + nlohmann_json_t.tag_ = Tag::AS_OPERATOR; + return; + } + if (nlohmann_json_j.contains("as_sym_float")) { + nlohmann_json_t.variant_.emplace<24>(nlohmann_json_j.at("as_sym_float").template get()); + nlohmann_json_t.tag_ = Tag::AS_SYM_FLOAT; + return; + } + if (nlohmann_json_j.contains("as_sym_floats")) { + nlohmann_json_t.variant_.emplace<25>(nlohmann_json_j.at("as_sym_floats").template get>()); + nlohmann_json_t.tag_ = Tag::AS_SYM_FLOATS; + return; + } + if (nlohmann_json_j.contains("as_optional_tensor")) { + nlohmann_json_t.variant_.emplace<26>(nlohmann_json_j.at("as_optional_tensor").template get()); + nlohmann_json_t.tag_ = Tag::AS_OPTIONAL_TENSOR; + return; + } + if (nlohmann_json_j.contains("as_complex")) { + nlohmann_json_t.variant_.emplace<27>(nlohmann_json_j.at("as_complex").template get()); + nlohmann_json_t.tag_ = Tag::AS_COMPLEX; + return; + } + if (nlohmann_json_j.contains("as_int_lists")) { + nlohmann_json_t.variant_.emplace<28>(nlohmann_json_j.at("as_int_lists").template get>>()); + nlohmann_json_t.tag_ = Tag::AS_INT_LISTS; + return; + } + if (nlohmann_json_j.contains("as_string_to_argument")) { + nlohmann_json_t.variant_.emplace<29>(nlohmann_json_j.at("as_string_to_argument").template get>>()); + nlohmann_json_t.tag_ = Tag::AS_STRING_TO_ARGUMENT; + return; + } + } +}; + +inline std::string_view printEnum(const Argument::Tag& e) { + switch (e) { + case Argument::Tag::AS_NONE: return "AS_NONE"; + case Argument::Tag::AS_TENSOR: return "AS_TENSOR"; + case Argument::Tag::AS_TENSORS: return "AS_TENSORS"; + case Argument::Tag::AS_INT: return "AS_INT"; + case Argument::Tag::AS_INTS: return "AS_INTS"; + case Argument::Tag::AS_FLOAT: return "AS_FLOAT"; + case Argument::Tag::AS_FLOATS: return "AS_FLOATS"; + case Argument::Tag::AS_STRING: return "AS_STRING"; + case Argument::Tag::AS_STRINGS: return "AS_STRINGS"; + case Argument::Tag::AS_SYM_INT: return "AS_SYM_INT"; + case Argument::Tag::AS_SYM_INTS: return "AS_SYM_INTS"; + case Argument::Tag::AS_SCALAR_TYPE: return "AS_SCALAR_TYPE"; + case Argument::Tag::AS_MEMORY_FORMAT: return "AS_MEMORY_FORMAT"; + case Argument::Tag::AS_LAYOUT: return "AS_LAYOUT"; + case Argument::Tag::AS_DEVICE: return "AS_DEVICE"; + case Argument::Tag::AS_BOOL: return "AS_BOOL"; + case Argument::Tag::AS_BOOLS: return "AS_BOOLS"; + case Argument::Tag::AS_SYM_BOOL: return "AS_SYM_BOOL"; + case Argument::Tag::AS_SYM_BOOLS: return "AS_SYM_BOOLS"; + case Argument::Tag::AS_GRAPH: return "AS_GRAPH"; + case Argument::Tag::AS_OPTIONAL_TENSORS: return "AS_OPTIONAL_TENSORS"; + case Argument::Tag::AS_CUSTOM_OBJ: return "AS_CUSTOM_OBJ"; + case Argument::Tag::AS_OPERATOR: return "AS_OPERATOR"; + case Argument::Tag::AS_SYM_FLOAT: return "AS_SYM_FLOAT"; + case Argument::Tag::AS_SYM_FLOATS: return "AS_SYM_FLOATS"; + case Argument::Tag::AS_OPTIONAL_TENSOR: return "AS_OPTIONAL_TENSOR"; + case Argument::Tag::AS_COMPLEX: return "AS_COMPLEX"; + case Argument::Tag::AS_INT_LISTS: return "AS_INT_LISTS"; + case Argument::Tag::AS_STRING_TO_ARGUMENT: return "AS_STRING_TO_ARGUMENT"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, Argument::Tag& t) { + if (s == "AS_NONE") { t = Argument::Tag::AS_NONE; return; } + if (s == "AS_TENSOR") { t = Argument::Tag::AS_TENSOR; return; } + if (s == "AS_TENSORS") { t = Argument::Tag::AS_TENSORS; return; } + if (s == "AS_INT") { t = Argument::Tag::AS_INT; return; } + if (s == "AS_INTS") { t = Argument::Tag::AS_INTS; return; } + if (s == "AS_FLOAT") { t = Argument::Tag::AS_FLOAT; return; } + if (s == "AS_FLOATS") { t = Argument::Tag::AS_FLOATS; return; } + if (s == "AS_STRING") { t = Argument::Tag::AS_STRING; return; } + if (s == "AS_STRINGS") { t = Argument::Tag::AS_STRINGS; return; } + if (s == "AS_SYM_INT") { t = Argument::Tag::AS_SYM_INT; return; } + if (s == "AS_SYM_INTS") { t = Argument::Tag::AS_SYM_INTS; return; } + if (s == "AS_SCALAR_TYPE") { t = Argument::Tag::AS_SCALAR_TYPE; return; } + if (s == "AS_MEMORY_FORMAT") { t = Argument::Tag::AS_MEMORY_FORMAT; return; } + if (s == "AS_LAYOUT") { t = Argument::Tag::AS_LAYOUT; return; } + if (s == "AS_DEVICE") { t = Argument::Tag::AS_DEVICE; return; } + if (s == "AS_BOOL") { t = Argument::Tag::AS_BOOL; return; } + if (s == "AS_BOOLS") { t = Argument::Tag::AS_BOOLS; return; } + if (s == "AS_SYM_BOOL") { t = Argument::Tag::AS_SYM_BOOL; return; } + if (s == "AS_SYM_BOOLS") { t = Argument::Tag::AS_SYM_BOOLS; return; } + if (s == "AS_GRAPH") { t = Argument::Tag::AS_GRAPH; return; } + if (s == "AS_OPTIONAL_TENSORS") { t = Argument::Tag::AS_OPTIONAL_TENSORS; return; } + if (s == "AS_CUSTOM_OBJ") { t = Argument::Tag::AS_CUSTOM_OBJ; return; } + if (s == "AS_OPERATOR") { t = Argument::Tag::AS_OPERATOR; return; } + if (s == "AS_SYM_FLOAT") { t = Argument::Tag::AS_SYM_FLOAT; return; } + if (s == "AS_SYM_FLOATS") { t = Argument::Tag::AS_SYM_FLOATS; return; } + if (s == "AS_OPTIONAL_TENSOR") { t = Argument::Tag::AS_OPTIONAL_TENSOR; return; } + if (s == "AS_COMPLEX") { t = Argument::Tag::AS_COMPLEX; return; } + if (s == "AS_INT_LISTS") { t = Argument::Tag::AS_INT_LISTS; return; } + if (s == "AS_STRING_TO_ARGUMENT") { t = Argument::Tag::AS_STRING_TO_ARGUMENT; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class NamedArgument { + private: + std::string name; + Argument arg; + std::optional kind = std::nullopt; + + public: + + const std::string& get_name() const { + return name; + } + + void set_name(std::string def) { + name = std::move(def); + } + + const Argument& get_arg() const { + return arg; + } + + void set_arg(Argument def) { + arg = std::move(def); + } + + const std::optional& get_kind() const { + return kind; + } + + void set_kind(std::optional def) { + kind = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const NamedArgument& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, NamedArgument& nlohmann_json_t); +}; + +class Node { + private: + std::string target; + std::vector inputs; + std::vector outputs; + std::unordered_map metadata; + std::optional is_hop_single_tensor_return = std::nullopt; + + public: + + const std::string& get_target() const { + return target; + } + + void set_target(std::string def) { + target = std::move(def); + } + + const std::vector& get_inputs() const { + return inputs; + } + + void set_inputs(std::vector def) { + inputs = std::move(def); + } + + const std::vector& get_outputs() const { + return outputs; + } + + void set_outputs(std::vector def) { + outputs = std::move(def); + } + + const std::unordered_map& get_metadata() const { + return metadata; + } + + void set_metadata(std::unordered_map def) { + metadata = std::move(def); + } + + const std::optional& get_is_hop_single_tensor_return() const { + return is_hop_single_tensor_return; + } + + void set_is_hop_single_tensor_return(std::optional def) { + is_hop_single_tensor_return = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const Node& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, Node& nlohmann_json_t); +}; + +class Graph { + private: + std::vector inputs; + std::vector outputs; + std::vector nodes; + std::unordered_map tensor_values; + std::unordered_map sym_int_values; + std::unordered_map sym_bool_values; + bool is_single_tensor_return = false; + std::unordered_map custom_obj_values = {}; + std::unordered_map sym_float_values = {}; + + public: + + const std::vector& get_inputs() const { + return inputs; + } + + void set_inputs(std::vector def) { + inputs = std::move(def); + } + + const std::vector& get_outputs() const { + return outputs; + } + + void set_outputs(std::vector def) { + outputs = std::move(def); + } + + const std::vector& get_nodes() const { + return nodes; + } + + void set_nodes(std::vector def) { + nodes = std::move(def); + } + + const std::unordered_map& get_tensor_values() const { + return tensor_values; + } + + void set_tensor_values(std::unordered_map def) { + tensor_values = std::move(def); + } + + const std::unordered_map& get_sym_int_values() const { + return sym_int_values; + } + + void set_sym_int_values(std::unordered_map def) { + sym_int_values = std::move(def); + } + + const std::unordered_map& get_sym_bool_values() const { + return sym_bool_values; + } + + void set_sym_bool_values(std::unordered_map def) { + sym_bool_values = std::move(def); + } + + const bool& get_is_single_tensor_return() const { + return is_single_tensor_return; + } + + void set_is_single_tensor_return(bool def) { + is_single_tensor_return = std::move(def); + } + + const std::unordered_map& get_custom_obj_values() const { + return custom_obj_values; + } + + void set_custom_obj_values(std::unordered_map def) { + custom_obj_values = std::move(def); + } + + const std::unordered_map& get_sym_float_values() const { + return sym_float_values; + } + + void set_sym_float_values(std::unordered_map def) { + sym_float_values = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const Graph& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, Graph& nlohmann_json_t); +}; + +class UserInputSpec { + private: + Argument arg; + + public: + + const Argument& get_arg() const { + return arg; + } + + void set_arg(Argument def) { + arg = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const UserInputSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, UserInputSpec& nlohmann_json_t); +}; + +class ConstantValue { + struct Void {}; + + public: + enum class Tag { + AS_NONE, AS_INT, AS_FLOAT, AS_STRING, AS_BOOL + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const bool& get_as_none() const { + return std::get<1>(variant_); + } + + void set_as_none(bool def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::AS_NONE; + } + + const int64_t& get_as_int() const { + return std::get<2>(variant_); + } + + void set_as_int(int64_t def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::AS_INT; + } + + const F64& get_as_float() const { + return std::get<3>(variant_); + } + + void set_as_float(F64 def) { + variant_.emplace<3>(std::move(def)); + tag_ = Tag::AS_FLOAT; + } + + const std::string& get_as_string() const { + return std::get<4>(variant_); + } + + void set_as_string(std::string def) { + variant_.emplace<4>(std::move(def)); + tag_ = Tag::AS_STRING; + } + + const bool& get_as_bool() const { + return std::get<5>(variant_); + } + + void set_as_bool(bool def) { + variant_.emplace<5>(std::move(def)); + tag_ = Tag::AS_BOOL; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const ConstantValue& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::AS_NONE) { + nlohmann_json_j["as_none"] = nlohmann_json_t.get_as_none(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_INT) { + nlohmann_json_j["as_int"] = nlohmann_json_t.get_as_int(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_FLOAT) { + nlohmann_json_j["as_float"] = nlohmann_json_t.get_as_float(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_STRING) { + nlohmann_json_j["as_string"] = nlohmann_json_t.get_as_string(); + return; + } + if (nlohmann_json_t.tag_ == Tag::AS_BOOL) { + nlohmann_json_j["as_bool"] = nlohmann_json_t.get_as_bool(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, ConstantValue& nlohmann_json_t) { + + if (nlohmann_json_j.contains("as_none")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("as_none").template get()); + nlohmann_json_t.tag_ = Tag::AS_NONE; + return; + } + if (nlohmann_json_j.contains("as_int")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("as_int").template get()); + nlohmann_json_t.tag_ = Tag::AS_INT; + return; + } + if (nlohmann_json_j.contains("as_float")) { + nlohmann_json_t.variant_.emplace<3>(nlohmann_json_j.at("as_float").template get()); + nlohmann_json_t.tag_ = Tag::AS_FLOAT; + return; + } + if (nlohmann_json_j.contains("as_string")) { + nlohmann_json_t.variant_.emplace<4>(nlohmann_json_j.at("as_string").template get()); + nlohmann_json_t.tag_ = Tag::AS_STRING; + return; + } + if (nlohmann_json_j.contains("as_bool")) { + nlohmann_json_t.variant_.emplace<5>(nlohmann_json_j.at("as_bool").template get()); + nlohmann_json_t.tag_ = Tag::AS_BOOL; + return; + } + } +}; + +inline std::string_view printEnum(const ConstantValue::Tag& e) { + switch (e) { + case ConstantValue::Tag::AS_NONE: return "AS_NONE"; + case ConstantValue::Tag::AS_INT: return "AS_INT"; + case ConstantValue::Tag::AS_FLOAT: return "AS_FLOAT"; + case ConstantValue::Tag::AS_STRING: return "AS_STRING"; + case ConstantValue::Tag::AS_BOOL: return "AS_BOOL"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, ConstantValue::Tag& t) { + if (s == "AS_NONE") { t = ConstantValue::Tag::AS_NONE; return; } + if (s == "AS_INT") { t = ConstantValue::Tag::AS_INT; return; } + if (s == "AS_FLOAT") { t = ConstantValue::Tag::AS_FLOAT; return; } + if (s == "AS_STRING") { t = ConstantValue::Tag::AS_STRING; return; } + if (s == "AS_BOOL") { t = ConstantValue::Tag::AS_BOOL; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class InputToConstantInputSpec { + private: + std::string name; + ConstantValue value; + + public: + + const std::string& get_name() const { + return name; + } + + void set_name(std::string def) { + name = std::move(def); + } + + const ConstantValue& get_value() const { + return value; + } + + void set_value(ConstantValue def) { + value = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const InputToConstantInputSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, InputToConstantInputSpec& nlohmann_json_t); +}; + +class InputToParameterSpec { + private: + TensorArgument arg; + std::string parameter_name; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + const std::string& get_parameter_name() const { + return parameter_name; + } + + void set_parameter_name(std::string def) { + parameter_name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const InputToParameterSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, InputToParameterSpec& nlohmann_json_t); +}; + +class InputToBufferSpec { + private: + TensorArgument arg; + std::string buffer_name; + bool persistent; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + const std::string& get_buffer_name() const { + return buffer_name; + } + + void set_buffer_name(std::string def) { + buffer_name = std::move(def); + } + + const bool& get_persistent() const { + return persistent; + } + + void set_persistent(bool def) { + persistent = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const InputToBufferSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, InputToBufferSpec& nlohmann_json_t); +}; + +class InputToTensorConstantSpec { + private: + TensorArgument arg; + std::string tensor_constant_name; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + const std::string& get_tensor_constant_name() const { + return tensor_constant_name; + } + + void set_tensor_constant_name(std::string def) { + tensor_constant_name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const InputToTensorConstantSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, InputToTensorConstantSpec& nlohmann_json_t); +}; + +class InputToCustomObjSpec { + private: + CustomObjArgument arg; + std::string custom_obj_name; + + public: + + const CustomObjArgument& get_arg() const { + return arg; + } + + void set_arg(CustomObjArgument def) { + arg = std::move(def); + } + + const std::string& get_custom_obj_name() const { + return custom_obj_name; + } + + void set_custom_obj_name(std::string def) { + custom_obj_name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const InputToCustomObjSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, InputToCustomObjSpec& nlohmann_json_t); +}; + +class InputTokenSpec { + private: + TokenArgument arg; + + public: + + const TokenArgument& get_arg() const { + return arg; + } + + void set_arg(TokenArgument def) { + arg = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const InputTokenSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, InputTokenSpec& nlohmann_json_t); +}; + +class InputSpec { + struct Void {}; + + public: + enum class Tag { + USER_INPUT, PARAMETER, BUFFER, TENSOR_CONSTANT, CUSTOM_OBJ, TOKEN, CONSTANT_INPUT + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const UserInputSpec& get_user_input() const { + return std::get<1>(variant_); + } + + void set_user_input(UserInputSpec def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::USER_INPUT; + } + + const InputToParameterSpec& get_parameter() const { + return std::get<2>(variant_); + } + + void set_parameter(InputToParameterSpec def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::PARAMETER; + } + + const InputToBufferSpec& get_buffer() const { + return std::get<3>(variant_); + } + + void set_buffer(InputToBufferSpec def) { + variant_.emplace<3>(std::move(def)); + tag_ = Tag::BUFFER; + } + + const InputToTensorConstantSpec& get_tensor_constant() const { + return std::get<4>(variant_); + } + + void set_tensor_constant(InputToTensorConstantSpec def) { + variant_.emplace<4>(std::move(def)); + tag_ = Tag::TENSOR_CONSTANT; + } + + const InputToCustomObjSpec& get_custom_obj() const { + return std::get<5>(variant_); + } + + void set_custom_obj(InputToCustomObjSpec def) { + variant_.emplace<5>(std::move(def)); + tag_ = Tag::CUSTOM_OBJ; + } + + const InputTokenSpec& get_token() const { + return std::get<6>(variant_); + } + + void set_token(InputTokenSpec def) { + variant_.emplace<6>(std::move(def)); + tag_ = Tag::TOKEN; + } + + const InputToConstantInputSpec& get_constant_input() const { + return std::get<7>(variant_); + } + + void set_constant_input(InputToConstantInputSpec def) { + variant_.emplace<7>(std::move(def)); + tag_ = Tag::CONSTANT_INPUT; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const InputSpec& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::USER_INPUT) { + nlohmann_json_j["user_input"] = nlohmann_json_t.get_user_input(); + return; + } + if (nlohmann_json_t.tag_ == Tag::PARAMETER) { + nlohmann_json_j["parameter"] = nlohmann_json_t.get_parameter(); + return; + } + if (nlohmann_json_t.tag_ == Tag::BUFFER) { + nlohmann_json_j["buffer"] = nlohmann_json_t.get_buffer(); + return; + } + if (nlohmann_json_t.tag_ == Tag::TENSOR_CONSTANT) { + nlohmann_json_j["tensor_constant"] = nlohmann_json_t.get_tensor_constant(); + return; + } + if (nlohmann_json_t.tag_ == Tag::CUSTOM_OBJ) { + nlohmann_json_j["custom_obj"] = nlohmann_json_t.get_custom_obj(); + return; + } + if (nlohmann_json_t.tag_ == Tag::TOKEN) { + nlohmann_json_j["token"] = nlohmann_json_t.get_token(); + return; + } + if (nlohmann_json_t.tag_ == Tag::CONSTANT_INPUT) { + nlohmann_json_j["constant_input"] = nlohmann_json_t.get_constant_input(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, InputSpec& nlohmann_json_t) { + + if (nlohmann_json_j.contains("user_input")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("user_input").template get()); + nlohmann_json_t.tag_ = Tag::USER_INPUT; + return; + } + if (nlohmann_json_j.contains("parameter")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("parameter").template get()); + nlohmann_json_t.tag_ = Tag::PARAMETER; + return; + } + if (nlohmann_json_j.contains("buffer")) { + nlohmann_json_t.variant_.emplace<3>(nlohmann_json_j.at("buffer").template get()); + nlohmann_json_t.tag_ = Tag::BUFFER; + return; + } + if (nlohmann_json_j.contains("tensor_constant")) { + nlohmann_json_t.variant_.emplace<4>(nlohmann_json_j.at("tensor_constant").template get()); + nlohmann_json_t.tag_ = Tag::TENSOR_CONSTANT; + return; + } + if (nlohmann_json_j.contains("custom_obj")) { + nlohmann_json_t.variant_.emplace<5>(nlohmann_json_j.at("custom_obj").template get()); + nlohmann_json_t.tag_ = Tag::CUSTOM_OBJ; + return; + } + if (nlohmann_json_j.contains("token")) { + nlohmann_json_t.variant_.emplace<6>(nlohmann_json_j.at("token").template get()); + nlohmann_json_t.tag_ = Tag::TOKEN; + return; + } + if (nlohmann_json_j.contains("constant_input")) { + nlohmann_json_t.variant_.emplace<7>(nlohmann_json_j.at("constant_input").template get()); + nlohmann_json_t.tag_ = Tag::CONSTANT_INPUT; + return; + } + } +}; + +inline std::string_view printEnum(const InputSpec::Tag& e) { + switch (e) { + case InputSpec::Tag::USER_INPUT: return "USER_INPUT"; + case InputSpec::Tag::PARAMETER: return "PARAMETER"; + case InputSpec::Tag::BUFFER: return "BUFFER"; + case InputSpec::Tag::TENSOR_CONSTANT: return "TENSOR_CONSTANT"; + case InputSpec::Tag::CUSTOM_OBJ: return "CUSTOM_OBJ"; + case InputSpec::Tag::TOKEN: return "TOKEN"; + case InputSpec::Tag::CONSTANT_INPUT: return "CONSTANT_INPUT"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, InputSpec::Tag& t) { + if (s == "USER_INPUT") { t = InputSpec::Tag::USER_INPUT; return; } + if (s == "PARAMETER") { t = InputSpec::Tag::PARAMETER; return; } + if (s == "BUFFER") { t = InputSpec::Tag::BUFFER; return; } + if (s == "TENSOR_CONSTANT") { t = InputSpec::Tag::TENSOR_CONSTANT; return; } + if (s == "CUSTOM_OBJ") { t = InputSpec::Tag::CUSTOM_OBJ; return; } + if (s == "TOKEN") { t = InputSpec::Tag::TOKEN; return; } + if (s == "CONSTANT_INPUT") { t = InputSpec::Tag::CONSTANT_INPUT; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class UserOutputSpec { + private: + Argument arg; + + public: + + const Argument& get_arg() const { + return arg; + } + + void set_arg(Argument def) { + arg = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const UserOutputSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, UserOutputSpec& nlohmann_json_t); +}; + +class LossOutputSpec { + private: + TensorArgument arg; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const LossOutputSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, LossOutputSpec& nlohmann_json_t); +}; + +class BufferMutationSpec { + private: + TensorArgument arg; + std::string buffer_name; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + const std::string& get_buffer_name() const { + return buffer_name; + } + + void set_buffer_name(std::string def) { + buffer_name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const BufferMutationSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, BufferMutationSpec& nlohmann_json_t); +}; + +class ParameterMutationSpec { + private: + TensorArgument arg; + std::string parameter_name; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + const std::string& get_parameter_name() const { + return parameter_name; + } + + void set_parameter_name(std::string def) { + parameter_name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const ParameterMutationSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, ParameterMutationSpec& nlohmann_json_t); +}; + +class GradientToParameterSpec { + private: + TensorArgument arg; + std::string parameter_name; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + const std::string& get_parameter_name() const { + return parameter_name; + } + + void set_parameter_name(std::string def) { + parameter_name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const GradientToParameterSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, GradientToParameterSpec& nlohmann_json_t); +}; + +class GradientToUserInputSpec { + private: + TensorArgument arg; + std::string user_input_name; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + const std::string& get_user_input_name() const { + return user_input_name; + } + + void set_user_input_name(std::string def) { + user_input_name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const GradientToUserInputSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, GradientToUserInputSpec& nlohmann_json_t); +}; + +class UserInputMutationSpec { + private: + TensorArgument arg; + std::string user_input_name; + + public: + + const TensorArgument& get_arg() const { + return arg; + } + + void set_arg(TensorArgument def) { + arg = std::move(def); + } + + const std::string& get_user_input_name() const { + return user_input_name; + } + + void set_user_input_name(std::string def) { + user_input_name = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const UserInputMutationSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, UserInputMutationSpec& nlohmann_json_t); +}; + +class OutputTokenSpec { + private: + TokenArgument arg; + + public: + + const TokenArgument& get_arg() const { + return arg; + } + + void set_arg(TokenArgument def) { + arg = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const OutputTokenSpec& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, OutputTokenSpec& nlohmann_json_t); +}; + +class OutputSpec { + struct Void {}; + + public: + enum class Tag { + USER_OUTPUT, LOSS_OUTPUT, BUFFER_MUTATION, GRADIENT_TO_PARAMETER, GRADIENT_TO_USER_INPUT, USER_INPUT_MUTATION, TOKEN, PARAMETER_MUTATION + }; + + private: + std::variant variant_; + Tag tag_; + + public: + Tag tag() const { + return tag_; + } + + const UserOutputSpec& get_user_output() const { + return std::get<1>(variant_); + } + + void set_user_output(UserOutputSpec def) { + variant_.emplace<1>(std::move(def)); + tag_ = Tag::USER_OUTPUT; + } + + const LossOutputSpec& get_loss_output() const { + return std::get<2>(variant_); + } + + void set_loss_output(LossOutputSpec def) { + variant_.emplace<2>(std::move(def)); + tag_ = Tag::LOSS_OUTPUT; + } + + const BufferMutationSpec& get_buffer_mutation() const { + return std::get<3>(variant_); + } + + void set_buffer_mutation(BufferMutationSpec def) { + variant_.emplace<3>(std::move(def)); + tag_ = Tag::BUFFER_MUTATION; + } + + const GradientToParameterSpec& get_gradient_to_parameter() const { + return std::get<4>(variant_); + } + + void set_gradient_to_parameter(GradientToParameterSpec def) { + variant_.emplace<4>(std::move(def)); + tag_ = Tag::GRADIENT_TO_PARAMETER; + } + + const GradientToUserInputSpec& get_gradient_to_user_input() const { + return std::get<5>(variant_); + } + + void set_gradient_to_user_input(GradientToUserInputSpec def) { + variant_.emplace<5>(std::move(def)); + tag_ = Tag::GRADIENT_TO_USER_INPUT; + } + + const UserInputMutationSpec& get_user_input_mutation() const { + return std::get<6>(variant_); + } + + void set_user_input_mutation(UserInputMutationSpec def) { + variant_.emplace<6>(std::move(def)); + tag_ = Tag::USER_INPUT_MUTATION; + } + + const OutputTokenSpec& get_token() const { + return std::get<7>(variant_); + } + + void set_token(OutputTokenSpec def) { + variant_.emplace<7>(std::move(def)); + tag_ = Tag::TOKEN; + } + + const ParameterMutationSpec& get_parameter_mutation() const { + return std::get<8>(variant_); + } + + void set_parameter_mutation(ParameterMutationSpec def) { + variant_.emplace<8>(std::move(def)); + tag_ = Tag::PARAMETER_MUTATION; + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const OutputSpec& nlohmann_json_t) { + + if (nlohmann_json_t.tag_ == Tag::USER_OUTPUT) { + nlohmann_json_j["user_output"] = nlohmann_json_t.get_user_output(); + return; + } + if (nlohmann_json_t.tag_ == Tag::LOSS_OUTPUT) { + nlohmann_json_j["loss_output"] = nlohmann_json_t.get_loss_output(); + return; + } + if (nlohmann_json_t.tag_ == Tag::BUFFER_MUTATION) { + nlohmann_json_j["buffer_mutation"] = nlohmann_json_t.get_buffer_mutation(); + return; + } + if (nlohmann_json_t.tag_ == Tag::GRADIENT_TO_PARAMETER) { + nlohmann_json_j["gradient_to_parameter"] = nlohmann_json_t.get_gradient_to_parameter(); + return; + } + if (nlohmann_json_t.tag_ == Tag::GRADIENT_TO_USER_INPUT) { + nlohmann_json_j["gradient_to_user_input"] = nlohmann_json_t.get_gradient_to_user_input(); + return; + } + if (nlohmann_json_t.tag_ == Tag::USER_INPUT_MUTATION) { + nlohmann_json_j["user_input_mutation"] = nlohmann_json_t.get_user_input_mutation(); + return; + } + if (nlohmann_json_t.tag_ == Tag::TOKEN) { + nlohmann_json_j["token"] = nlohmann_json_t.get_token(); + return; + } + if (nlohmann_json_t.tag_ == Tag::PARAMETER_MUTATION) { + nlohmann_json_j["parameter_mutation"] = nlohmann_json_t.get_parameter_mutation(); + return; + } + } + + friend void from_json(const nlohmann::json& nlohmann_json_j, OutputSpec& nlohmann_json_t) { + + if (nlohmann_json_j.contains("user_output")) { + nlohmann_json_t.variant_.emplace<1>(nlohmann_json_j.at("user_output").template get()); + nlohmann_json_t.tag_ = Tag::USER_OUTPUT; + return; + } + if (nlohmann_json_j.contains("loss_output")) { + nlohmann_json_t.variant_.emplace<2>(nlohmann_json_j.at("loss_output").template get()); + nlohmann_json_t.tag_ = Tag::LOSS_OUTPUT; + return; + } + if (nlohmann_json_j.contains("buffer_mutation")) { + nlohmann_json_t.variant_.emplace<3>(nlohmann_json_j.at("buffer_mutation").template get()); + nlohmann_json_t.tag_ = Tag::BUFFER_MUTATION; + return; + } + if (nlohmann_json_j.contains("gradient_to_parameter")) { + nlohmann_json_t.variant_.emplace<4>(nlohmann_json_j.at("gradient_to_parameter").template get()); + nlohmann_json_t.tag_ = Tag::GRADIENT_TO_PARAMETER; + return; + } + if (nlohmann_json_j.contains("gradient_to_user_input")) { + nlohmann_json_t.variant_.emplace<5>(nlohmann_json_j.at("gradient_to_user_input").template get()); + nlohmann_json_t.tag_ = Tag::GRADIENT_TO_USER_INPUT; + return; + } + if (nlohmann_json_j.contains("user_input_mutation")) { + nlohmann_json_t.variant_.emplace<6>(nlohmann_json_j.at("user_input_mutation").template get()); + nlohmann_json_t.tag_ = Tag::USER_INPUT_MUTATION; + return; + } + if (nlohmann_json_j.contains("token")) { + nlohmann_json_t.variant_.emplace<7>(nlohmann_json_j.at("token").template get()); + nlohmann_json_t.tag_ = Tag::TOKEN; + return; + } + if (nlohmann_json_j.contains("parameter_mutation")) { + nlohmann_json_t.variant_.emplace<8>(nlohmann_json_j.at("parameter_mutation").template get()); + nlohmann_json_t.tag_ = Tag::PARAMETER_MUTATION; + return; + } + } +}; + +inline std::string_view printEnum(const OutputSpec::Tag& e) { + switch (e) { + case OutputSpec::Tag::USER_OUTPUT: return "USER_OUTPUT"; + case OutputSpec::Tag::LOSS_OUTPUT: return "LOSS_OUTPUT"; + case OutputSpec::Tag::BUFFER_MUTATION: return "BUFFER_MUTATION"; + case OutputSpec::Tag::GRADIENT_TO_PARAMETER: return "GRADIENT_TO_PARAMETER"; + case OutputSpec::Tag::GRADIENT_TO_USER_INPUT: return "GRADIENT_TO_USER_INPUT"; + case OutputSpec::Tag::USER_INPUT_MUTATION: return "USER_INPUT_MUTATION"; + case OutputSpec::Tag::TOKEN: return "TOKEN"; + case OutputSpec::Tag::PARAMETER_MUTATION: return "PARAMETER_MUTATION"; + default: + throw std::runtime_error("Unknown enum value"); + } +} + +inline void parseEnum(std::string_view s, OutputSpec::Tag& t) { + if (s == "USER_OUTPUT") { t = OutputSpec::Tag::USER_OUTPUT; return; } + if (s == "LOSS_OUTPUT") { t = OutputSpec::Tag::LOSS_OUTPUT; return; } + if (s == "BUFFER_MUTATION") { t = OutputSpec::Tag::BUFFER_MUTATION; return; } + if (s == "GRADIENT_TO_PARAMETER") { t = OutputSpec::Tag::GRADIENT_TO_PARAMETER; return; } + if (s == "GRADIENT_TO_USER_INPUT") { t = OutputSpec::Tag::GRADIENT_TO_USER_INPUT; return; } + if (s == "USER_INPUT_MUTATION") { t = OutputSpec::Tag::USER_INPUT_MUTATION; return; } + if (s == "TOKEN") { t = OutputSpec::Tag::TOKEN; return; } + if (s == "PARAMETER_MUTATION") { t = OutputSpec::Tag::PARAMETER_MUTATION; return; } + throw std::runtime_error("Unknown enum value: " + std::string{s}); +} + + +class GraphSignature { + private: + std::vector input_specs; + std::vector output_specs; + + public: + + const std::vector& get_input_specs() const { + return input_specs; + } + + void set_input_specs(std::vector def) { + input_specs = std::move(def); + } + + const std::vector& get_output_specs() const { + return output_specs; + } + + void set_output_specs(std::vector def) { + output_specs = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const GraphSignature& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, GraphSignature& nlohmann_json_t); +}; + +class RangeConstraint { + private: + std::optional min_val; + std::optional max_val; + + public: + + const std::optional& get_min_val() const { + return min_val; + } + + void set_min_val(std::optional def) { + min_val = std::move(def); + } + + const std::optional& get_max_val() const { + return max_val; + } + + void set_max_val(std::optional def) { + max_val = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const RangeConstraint& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, RangeConstraint& nlohmann_json_t); +}; + +class ModuleCallSignature { + private: + std::vector inputs; + std::vector outputs; + std::string in_spec; + std::string out_spec; + std::optional> forward_arg_names = std::nullopt; + + public: + + const std::vector& get_inputs() const { + return inputs; + } + + void set_inputs(std::vector def) { + inputs = std::move(def); + } + + const std::vector& get_outputs() const { + return outputs; + } + + void set_outputs(std::vector def) { + outputs = std::move(def); + } + + const std::string& get_in_spec() const { + return in_spec; + } + + void set_in_spec(std::string def) { + in_spec = std::move(def); + } + + const std::string& get_out_spec() const { + return out_spec; + } + + void set_out_spec(std::string def) { + out_spec = std::move(def); + } + + const std::optional>& get_forward_arg_names() const { + return forward_arg_names; + } + + void set_forward_arg_names(std::optional> def) { + forward_arg_names = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const ModuleCallSignature& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, ModuleCallSignature& nlohmann_json_t); +}; + +class ModuleCallEntry { + private: + std::string fqn; + std::optional signature = std::nullopt; + + public: + + const std::string& get_fqn() const { + return fqn; + } + + void set_fqn(std::string def) { + fqn = std::move(def); + } + + const std::optional& get_signature() const { + return signature; + } + + void set_signature(std::optional def) { + signature = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const ModuleCallEntry& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, ModuleCallEntry& nlohmann_json_t); +}; + +class NamedTupleDef { + private: + std::vector field_names; + + public: + + const std::vector& get_field_names() const { + return field_names; + } + + void set_field_names(std::vector def) { + field_names = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const NamedTupleDef& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, NamedTupleDef& nlohmann_json_t); +}; + +class GraphModule { + private: + Graph graph; + GraphSignature signature; + std::vector module_call_graph; + std::unordered_map metadata = {}; + std::unordered_map treespec_namedtuple_fields = {}; + + public: + + const Graph& get_graph() const { + return graph; + } + + void set_graph(Graph def) { + graph = std::move(def); + } + + const GraphSignature& get_signature() const { + return signature; + } + + void set_signature(GraphSignature def) { + signature = std::move(def); + } + + const std::vector& get_module_call_graph() const { + return module_call_graph; + } + + void set_module_call_graph(std::vector def) { + module_call_graph = std::move(def); + } + + const std::unordered_map& get_metadata() const { + return metadata; + } + + void set_metadata(std::unordered_map def) { + metadata = std::move(def); + } + + const std::unordered_map& get_treespec_namedtuple_fields() const { + return treespec_namedtuple_fields; + } + + void set_treespec_namedtuple_fields(std::unordered_map def) { + treespec_namedtuple_fields = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const GraphModule& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, GraphModule& nlohmann_json_t); +}; + +class SchemaVersion { + private: + int64_t major; + int64_t minor; + + public: + + const int64_t& get_major() const { + return major; + } + + void set_major(int64_t def) { + major = std::move(def); + } + + const int64_t& get_minor() const { + return minor; + } + + void set_minor(int64_t def) { + minor = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const SchemaVersion& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, SchemaVersion& nlohmann_json_t); +}; + +class ExportedProgram { + private: + GraphModule graph_module; + std::unordered_map opset_version; + std::unordered_map range_constraints; + SchemaVersion schema_version; + std::vector verifiers = {}; + std::string torch_version = "<=2.4"; + std::vector guards_code = {}; + + public: + + const GraphModule& get_graph_module() const { + return graph_module; + } + + void set_graph_module(GraphModule def) { + graph_module = std::move(def); + } + + const std::unordered_map& get_opset_version() const { + return opset_version; + } + + void set_opset_version(std::unordered_map def) { + opset_version = std::move(def); + } + + const std::unordered_map& get_range_constraints() const { + return range_constraints; + } + + void set_range_constraints(std::unordered_map def) { + range_constraints = std::move(def); + } + + const SchemaVersion& get_schema_version() const { + return schema_version; + } + + void set_schema_version(SchemaVersion def) { + schema_version = std::move(def); + } + + const std::vector& get_verifiers() const { + return verifiers; + } + + void set_verifiers(std::vector def) { + verifiers = std::move(def); + } + + const std::string& get_torch_version() const { + return torch_version; + } + + void set_torch_version(std::string def) { + torch_version = std::move(def); + } + + const std::vector& get_guards_code() const { + return guards_code; + } + + void set_guards_code(std::vector def) { + guards_code = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const ExportedProgram& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, ExportedProgram& nlohmann_json_t); +}; + +class PayloadMeta { + private: + std::string path_name; + bool is_param; + bool use_pickle; + std::optional tensor_meta; + + public: + + const std::string& get_path_name() const { + return path_name; + } + + void set_path_name(std::string def) { + path_name = std::move(def); + } + + const bool& get_is_param() const { + return is_param; + } + + void set_is_param(bool def) { + is_param = std::move(def); + } + + const bool& get_use_pickle() const { + return use_pickle; + } + + void set_use_pickle(bool def) { + use_pickle = std::move(def); + } + + const std::optional& get_tensor_meta() const { + return tensor_meta; + } + + void set_tensor_meta(std::optional def) { + tensor_meta = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const PayloadMeta& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, PayloadMeta& nlohmann_json_t); +}; + +class PayloadConfig { + private: + std::unordered_map config; + + public: + + const std::unordered_map& get_config() const { + return config; + } + + void set_config(std::unordered_map def) { + config = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const PayloadConfig& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, PayloadConfig& nlohmann_json_t); +}; + +class AOTInductorModelPickleData { + private: + std::string library_basename; + std::vector input_names; + std::vector output_names; + std::optional floating_point_input_dtype = std::nullopt; + std::optional floating_point_output_dtype = std::nullopt; + std::optional aot_inductor_model_is_cpu = std::nullopt; + + public: + + const std::string& get_library_basename() const { + return library_basename; + } + + void set_library_basename(std::string def) { + library_basename = std::move(def); + } + + const std::vector& get_input_names() const { + return input_names; + } + + void set_input_names(std::vector def) { + input_names = std::move(def); + } + + const std::vector& get_output_names() const { + return output_names; + } + + void set_output_names(std::vector def) { + output_names = std::move(def); + } + + const std::optional& get_floating_point_input_dtype() const { + return floating_point_input_dtype; + } + + void set_floating_point_input_dtype(std::optional def) { + floating_point_input_dtype = std::move(def); + } + + const std::optional& get_floating_point_output_dtype() const { + return floating_point_output_dtype; + } + + void set_floating_point_output_dtype(std::optional def) { + floating_point_output_dtype = std::move(def); + } + + const std::optional& get_aot_inductor_model_is_cpu() const { + return aot_inductor_model_is_cpu; + } + + void set_aot_inductor_model_is_cpu(std::optional def) { + aot_inductor_model_is_cpu = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const AOTInductorModelPickleData& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, AOTInductorModelPickleData& nlohmann_json_t); +}; + +class ExternKernelNode { + private: + std::string name; + Node node; + + public: + + const std::string& get_name() const { + return name; + } + + void set_name(std::string def) { + name = std::move(def); + } + + const Node& get_node() const { + return node; + } + + void set_node(Node def) { + node = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const ExternKernelNode& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, ExternKernelNode& nlohmann_json_t); +}; + +class ExternKernelNodes { + private: + std::vector nodes; + + public: + + const std::vector& get_nodes() const { + return nodes; + } + + void set_nodes(std::vector def) { + nodes = std::move(def); + } + + friend void to_json(nlohmann::json& nlohmann_json_j, const ExternKernelNodes& nlohmann_json_t); + friend void from_json(const nlohmann::json& nlohmann_json_j, ExternKernelNodes& nlohmann_json_t); +}; + +inline void to_json(nlohmann::json& nlohmann_json_j, const AOTInductorModelPickleData& nlohmann_json_t) { + nlohmann_json_j["library_basename"] = nlohmann_json_t.library_basename; + nlohmann_json_j["input_names"] = nlohmann_json_t.input_names; + nlohmann_json_j["output_names"] = nlohmann_json_t.output_names; + nlohmann_json_j["floating_point_input_dtype"] = nlohmann_json_t.floating_point_input_dtype; + nlohmann_json_j["floating_point_output_dtype"] = nlohmann_json_t.floating_point_output_dtype; + nlohmann_json_j["aot_inductor_model_is_cpu"] = nlohmann_json_t.aot_inductor_model_is_cpu; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, AOTInductorModelPickleData& nlohmann_json_t) { + AOTInductorModelPickleData nlohmann_json_default_obj; + nlohmann_json_t.library_basename = nlohmann_json_j.value("library_basename", nlohmann_json_default_obj.library_basename); + nlohmann_json_t.input_names = nlohmann_json_j.value("input_names", nlohmann_json_default_obj.input_names); + nlohmann_json_t.output_names = nlohmann_json_j.value("output_names", nlohmann_json_default_obj.output_names); + nlohmann_json_t.floating_point_input_dtype = nlohmann_json_j.value("floating_point_input_dtype", nlohmann_json_default_obj.floating_point_input_dtype); + nlohmann_json_t.floating_point_output_dtype = nlohmann_json_j.value("floating_point_output_dtype", nlohmann_json_default_obj.floating_point_output_dtype); + nlohmann_json_t.aot_inductor_model_is_cpu = nlohmann_json_j.value("aot_inductor_model_is_cpu", nlohmann_json_default_obj.aot_inductor_model_is_cpu); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const BufferMutationSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["buffer_name"] = nlohmann_json_t.buffer_name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, BufferMutationSpec& nlohmann_json_t) { + BufferMutationSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.buffer_name = nlohmann_json_j.value("buffer_name", nlohmann_json_default_obj.buffer_name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const ComplexValue& nlohmann_json_t) { + nlohmann_json_j["real"] = nlohmann_json_t.real; + nlohmann_json_j["imag"] = nlohmann_json_t.imag; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, ComplexValue& nlohmann_json_t) { + ComplexValue nlohmann_json_default_obj; + nlohmann_json_t.real = nlohmann_json_j.value("real", nlohmann_json_default_obj.real); + nlohmann_json_t.imag = nlohmann_json_j.value("imag", nlohmann_json_default_obj.imag); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const CustomObjArgument& nlohmann_json_t) { + nlohmann_json_j["name"] = nlohmann_json_t.name; + nlohmann_json_j["class_fqn"] = nlohmann_json_t.class_fqn; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, CustomObjArgument& nlohmann_json_t) { + CustomObjArgument nlohmann_json_default_obj; + nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name); + nlohmann_json_t.class_fqn = nlohmann_json_j.value("class_fqn", nlohmann_json_default_obj.class_fqn); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const Device& nlohmann_json_t) { + nlohmann_json_j["type"] = nlohmann_json_t.type; + nlohmann_json_j["index"] = nlohmann_json_t.index; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, Device& nlohmann_json_t) { + Device nlohmann_json_default_obj; + nlohmann_json_t.type = nlohmann_json_j.value("type", nlohmann_json_default_obj.type); + nlohmann_json_t.index = nlohmann_json_j.value("index", nlohmann_json_default_obj.index); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const ExportedProgram& nlohmann_json_t) { + nlohmann_json_j["graph_module"] = nlohmann_json_t.graph_module; + nlohmann_json_j["opset_version"] = nlohmann_json_t.opset_version; + nlohmann_json_j["range_constraints"] = nlohmann_json_t.range_constraints; + nlohmann_json_j["schema_version"] = nlohmann_json_t.schema_version; + nlohmann_json_j["verifiers"] = nlohmann_json_t.verifiers; + nlohmann_json_j["torch_version"] = nlohmann_json_t.torch_version; + nlohmann_json_j["guards_code"] = nlohmann_json_t.guards_code; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, ExportedProgram& nlohmann_json_t) { + ExportedProgram nlohmann_json_default_obj; + nlohmann_json_t.graph_module = nlohmann_json_j.value("graph_module", nlohmann_json_default_obj.graph_module); + nlohmann_json_t.opset_version = nlohmann_json_j.value("opset_version", nlohmann_json_default_obj.opset_version); + nlohmann_json_t.range_constraints = nlohmann_json_j.value("range_constraints", nlohmann_json_default_obj.range_constraints); + nlohmann_json_t.schema_version = nlohmann_json_j.value("schema_version", nlohmann_json_default_obj.schema_version); + nlohmann_json_t.verifiers = nlohmann_json_j.value("verifiers", nlohmann_json_default_obj.verifiers); + nlohmann_json_t.torch_version = nlohmann_json_j.value("torch_version", nlohmann_json_default_obj.torch_version); + nlohmann_json_t.guards_code = nlohmann_json_j.value("guards_code", nlohmann_json_default_obj.guards_code); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const ExternKernelNode& nlohmann_json_t) { + nlohmann_json_j["name"] = nlohmann_json_t.name; + nlohmann_json_j["node"] = nlohmann_json_t.node; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, ExternKernelNode& nlohmann_json_t) { + ExternKernelNode nlohmann_json_default_obj; + nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name); + nlohmann_json_t.node = nlohmann_json_j.value("node", nlohmann_json_default_obj.node); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const ExternKernelNodes& nlohmann_json_t) { + nlohmann_json_j["nodes"] = nlohmann_json_t.nodes; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, ExternKernelNodes& nlohmann_json_t) { + ExternKernelNodes nlohmann_json_default_obj; + nlohmann_json_t.nodes = nlohmann_json_j.value("nodes", nlohmann_json_default_obj.nodes); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const GradientToParameterSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["parameter_name"] = nlohmann_json_t.parameter_name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, GradientToParameterSpec& nlohmann_json_t) { + GradientToParameterSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.parameter_name = nlohmann_json_j.value("parameter_name", nlohmann_json_default_obj.parameter_name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const GradientToUserInputSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["user_input_name"] = nlohmann_json_t.user_input_name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, GradientToUserInputSpec& nlohmann_json_t) { + GradientToUserInputSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.user_input_name = nlohmann_json_j.value("user_input_name", nlohmann_json_default_obj.user_input_name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const Graph& nlohmann_json_t) { + nlohmann_json_j["inputs"] = nlohmann_json_t.inputs; + nlohmann_json_j["outputs"] = nlohmann_json_t.outputs; + nlohmann_json_j["nodes"] = nlohmann_json_t.nodes; + nlohmann_json_j["tensor_values"] = nlohmann_json_t.tensor_values; + nlohmann_json_j["sym_int_values"] = nlohmann_json_t.sym_int_values; + nlohmann_json_j["sym_bool_values"] = nlohmann_json_t.sym_bool_values; + nlohmann_json_j["is_single_tensor_return"] = nlohmann_json_t.is_single_tensor_return; + nlohmann_json_j["custom_obj_values"] = nlohmann_json_t.custom_obj_values; + nlohmann_json_j["sym_float_values"] = nlohmann_json_t.sym_float_values; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, Graph& nlohmann_json_t) { + Graph nlohmann_json_default_obj; + nlohmann_json_t.inputs = nlohmann_json_j.value("inputs", nlohmann_json_default_obj.inputs); + nlohmann_json_t.outputs = nlohmann_json_j.value("outputs", nlohmann_json_default_obj.outputs); + nlohmann_json_t.nodes = nlohmann_json_j.value("nodes", nlohmann_json_default_obj.nodes); + nlohmann_json_t.tensor_values = nlohmann_json_j.value("tensor_values", nlohmann_json_default_obj.tensor_values); + nlohmann_json_t.sym_int_values = nlohmann_json_j.value("sym_int_values", nlohmann_json_default_obj.sym_int_values); + nlohmann_json_t.sym_bool_values = nlohmann_json_j.value("sym_bool_values", nlohmann_json_default_obj.sym_bool_values); + nlohmann_json_t.is_single_tensor_return = nlohmann_json_j.value("is_single_tensor_return", nlohmann_json_default_obj.is_single_tensor_return); + nlohmann_json_t.custom_obj_values = nlohmann_json_j.value("custom_obj_values", nlohmann_json_default_obj.custom_obj_values); + nlohmann_json_t.sym_float_values = nlohmann_json_j.value("sym_float_values", nlohmann_json_default_obj.sym_float_values); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const GraphArgument& nlohmann_json_t) { + nlohmann_json_j["name"] = nlohmann_json_t.name; + nlohmann_json_j["graph"] = nlohmann_json_t.graph; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, GraphArgument& nlohmann_json_t) { + GraphArgument nlohmann_json_default_obj; + nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name); + nlohmann_json_t.graph = nlohmann_json_j.value("graph", nlohmann_json_default_obj.graph); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const GraphModule& nlohmann_json_t) { + nlohmann_json_j["graph"] = nlohmann_json_t.graph; + nlohmann_json_j["signature"] = nlohmann_json_t.signature; + nlohmann_json_j["module_call_graph"] = nlohmann_json_t.module_call_graph; + nlohmann_json_j["metadata"] = nlohmann_json_t.metadata; + nlohmann_json_j["treespec_namedtuple_fields"] = nlohmann_json_t.treespec_namedtuple_fields; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, GraphModule& nlohmann_json_t) { + GraphModule nlohmann_json_default_obj; + nlohmann_json_t.graph = nlohmann_json_j.value("graph", nlohmann_json_default_obj.graph); + nlohmann_json_t.signature = nlohmann_json_j.value("signature", nlohmann_json_default_obj.signature); + nlohmann_json_t.module_call_graph = nlohmann_json_j.value("module_call_graph", nlohmann_json_default_obj.module_call_graph); + nlohmann_json_t.metadata = nlohmann_json_j.value("metadata", nlohmann_json_default_obj.metadata); + nlohmann_json_t.treespec_namedtuple_fields = nlohmann_json_j.value("treespec_namedtuple_fields", nlohmann_json_default_obj.treespec_namedtuple_fields); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const GraphSignature& nlohmann_json_t) { + nlohmann_json_j["input_specs"] = nlohmann_json_t.input_specs; + nlohmann_json_j["output_specs"] = nlohmann_json_t.output_specs; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, GraphSignature& nlohmann_json_t) { + GraphSignature nlohmann_json_default_obj; + nlohmann_json_t.input_specs = nlohmann_json_j.value("input_specs", nlohmann_json_default_obj.input_specs); + nlohmann_json_t.output_specs = nlohmann_json_j.value("output_specs", nlohmann_json_default_obj.output_specs); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const InputToBufferSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["buffer_name"] = nlohmann_json_t.buffer_name; + nlohmann_json_j["persistent"] = nlohmann_json_t.persistent; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, InputToBufferSpec& nlohmann_json_t) { + InputToBufferSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.buffer_name = nlohmann_json_j.value("buffer_name", nlohmann_json_default_obj.buffer_name); + nlohmann_json_t.persistent = nlohmann_json_j.value("persistent", nlohmann_json_default_obj.persistent); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const InputToConstantInputSpec& nlohmann_json_t) { + nlohmann_json_j["name"] = nlohmann_json_t.name; + nlohmann_json_j["value"] = nlohmann_json_t.value; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, InputToConstantInputSpec& nlohmann_json_t) { + InputToConstantInputSpec nlohmann_json_default_obj; + nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name); + nlohmann_json_t.value = nlohmann_json_j.value("value", nlohmann_json_default_obj.value); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const InputToCustomObjSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["custom_obj_name"] = nlohmann_json_t.custom_obj_name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, InputToCustomObjSpec& nlohmann_json_t) { + InputToCustomObjSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.custom_obj_name = nlohmann_json_j.value("custom_obj_name", nlohmann_json_default_obj.custom_obj_name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const InputToParameterSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["parameter_name"] = nlohmann_json_t.parameter_name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, InputToParameterSpec& nlohmann_json_t) { + InputToParameterSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.parameter_name = nlohmann_json_j.value("parameter_name", nlohmann_json_default_obj.parameter_name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const InputToTensorConstantSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["tensor_constant_name"] = nlohmann_json_t.tensor_constant_name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, InputToTensorConstantSpec& nlohmann_json_t) { + InputToTensorConstantSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.tensor_constant_name = nlohmann_json_j.value("tensor_constant_name", nlohmann_json_default_obj.tensor_constant_name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const InputTokenSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, InputTokenSpec& nlohmann_json_t) { + InputTokenSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const LossOutputSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, LossOutputSpec& nlohmann_json_t) { + LossOutputSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const ModuleCallEntry& nlohmann_json_t) { + nlohmann_json_j["fqn"] = nlohmann_json_t.fqn; + nlohmann_json_j["signature"] = nlohmann_json_t.signature; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, ModuleCallEntry& nlohmann_json_t) { + ModuleCallEntry nlohmann_json_default_obj; + nlohmann_json_t.fqn = nlohmann_json_j.value("fqn", nlohmann_json_default_obj.fqn); + nlohmann_json_t.signature = nlohmann_json_j.value("signature", nlohmann_json_default_obj.signature); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const ModuleCallSignature& nlohmann_json_t) { + nlohmann_json_j["inputs"] = nlohmann_json_t.inputs; + nlohmann_json_j["outputs"] = nlohmann_json_t.outputs; + nlohmann_json_j["in_spec"] = nlohmann_json_t.in_spec; + nlohmann_json_j["out_spec"] = nlohmann_json_t.out_spec; + nlohmann_json_j["forward_arg_names"] = nlohmann_json_t.forward_arg_names; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, ModuleCallSignature& nlohmann_json_t) { + ModuleCallSignature nlohmann_json_default_obj; + nlohmann_json_t.inputs = nlohmann_json_j.value("inputs", nlohmann_json_default_obj.inputs); + nlohmann_json_t.outputs = nlohmann_json_j.value("outputs", nlohmann_json_default_obj.outputs); + nlohmann_json_t.in_spec = nlohmann_json_j.value("in_spec", nlohmann_json_default_obj.in_spec); + nlohmann_json_t.out_spec = nlohmann_json_j.value("out_spec", nlohmann_json_default_obj.out_spec); + nlohmann_json_t.forward_arg_names = nlohmann_json_j.value("forward_arg_names", nlohmann_json_default_obj.forward_arg_names); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const NamedArgument& nlohmann_json_t) { + nlohmann_json_j["name"] = nlohmann_json_t.name; + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["kind"] = nlohmann_json_t.kind; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, NamedArgument& nlohmann_json_t) { + NamedArgument nlohmann_json_default_obj; + nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name); + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.kind = nlohmann_json_j.value("kind", nlohmann_json_default_obj.kind); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const NamedTupleDef& nlohmann_json_t) { + nlohmann_json_j["field_names"] = nlohmann_json_t.field_names; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, NamedTupleDef& nlohmann_json_t) { + NamedTupleDef nlohmann_json_default_obj; + nlohmann_json_t.field_names = nlohmann_json_j.value("field_names", nlohmann_json_default_obj.field_names); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const Node& nlohmann_json_t) { + nlohmann_json_j["target"] = nlohmann_json_t.target; + nlohmann_json_j["inputs"] = nlohmann_json_t.inputs; + nlohmann_json_j["outputs"] = nlohmann_json_t.outputs; + nlohmann_json_j["metadata"] = nlohmann_json_t.metadata; + nlohmann_json_j["is_hop_single_tensor_return"] = nlohmann_json_t.is_hop_single_tensor_return; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, Node& nlohmann_json_t) { + Node nlohmann_json_default_obj; + nlohmann_json_t.target = nlohmann_json_j.value("target", nlohmann_json_default_obj.target); + nlohmann_json_t.inputs = nlohmann_json_j.value("inputs", nlohmann_json_default_obj.inputs); + nlohmann_json_t.outputs = nlohmann_json_j.value("outputs", nlohmann_json_default_obj.outputs); + nlohmann_json_t.metadata = nlohmann_json_j.value("metadata", nlohmann_json_default_obj.metadata); + nlohmann_json_t.is_hop_single_tensor_return = nlohmann_json_j.value("is_hop_single_tensor_return", nlohmann_json_default_obj.is_hop_single_tensor_return); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const OutputTokenSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, OutputTokenSpec& nlohmann_json_t) { + OutputTokenSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const ParameterMutationSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["parameter_name"] = nlohmann_json_t.parameter_name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, ParameterMutationSpec& nlohmann_json_t) { + ParameterMutationSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.parameter_name = nlohmann_json_j.value("parameter_name", nlohmann_json_default_obj.parameter_name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const PayloadConfig& nlohmann_json_t) { + nlohmann_json_j["config"] = nlohmann_json_t.config; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, PayloadConfig& nlohmann_json_t) { + PayloadConfig nlohmann_json_default_obj; + nlohmann_json_t.config = nlohmann_json_j.value("config", nlohmann_json_default_obj.config); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const PayloadMeta& nlohmann_json_t) { + nlohmann_json_j["path_name"] = nlohmann_json_t.path_name; + nlohmann_json_j["is_param"] = nlohmann_json_t.is_param; + nlohmann_json_j["use_pickle"] = nlohmann_json_t.use_pickle; + nlohmann_json_j["tensor_meta"] = nlohmann_json_t.tensor_meta; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, PayloadMeta& nlohmann_json_t) { + PayloadMeta nlohmann_json_default_obj; + nlohmann_json_t.path_name = nlohmann_json_j.value("path_name", nlohmann_json_default_obj.path_name); + nlohmann_json_t.is_param = nlohmann_json_j.value("is_param", nlohmann_json_default_obj.is_param); + nlohmann_json_t.use_pickle = nlohmann_json_j.value("use_pickle", nlohmann_json_default_obj.use_pickle); + nlohmann_json_t.tensor_meta = nlohmann_json_j.value("tensor_meta", nlohmann_json_default_obj.tensor_meta); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const RangeConstraint& nlohmann_json_t) { + nlohmann_json_j["min_val"] = nlohmann_json_t.min_val; + nlohmann_json_j["max_val"] = nlohmann_json_t.max_val; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, RangeConstraint& nlohmann_json_t) { + RangeConstraint nlohmann_json_default_obj; + nlohmann_json_t.min_val = nlohmann_json_j.value("min_val", nlohmann_json_default_obj.min_val); + nlohmann_json_t.max_val = nlohmann_json_j.value("max_val", nlohmann_json_default_obj.max_val); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const SchemaVersion& nlohmann_json_t) { + nlohmann_json_j["major"] = nlohmann_json_t.major; + nlohmann_json_j["minor"] = nlohmann_json_t.minor; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, SchemaVersion& nlohmann_json_t) { + SchemaVersion nlohmann_json_default_obj; + nlohmann_json_t.major = nlohmann_json_j.value("major", nlohmann_json_default_obj.major); + nlohmann_json_t.minor = nlohmann_json_j.value("minor", nlohmann_json_default_obj.minor); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const SymExpr& nlohmann_json_t) { + nlohmann_json_j["expr_str"] = nlohmann_json_t.expr_str; + nlohmann_json_j["hint"] = nlohmann_json_t.hint; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, SymExpr& nlohmann_json_t) { + SymExpr nlohmann_json_default_obj; + nlohmann_json_t.expr_str = nlohmann_json_j.value("expr_str", nlohmann_json_default_obj.expr_str); + nlohmann_json_t.hint = nlohmann_json_j.value("hint", nlohmann_json_default_obj.hint); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const TensorArgument& nlohmann_json_t) { + nlohmann_json_j["name"] = nlohmann_json_t.name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, TensorArgument& nlohmann_json_t) { + TensorArgument nlohmann_json_default_obj; + nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const TensorMeta& nlohmann_json_t) { + nlohmann_json_j["dtype"] = nlohmann_json_t.dtype; + nlohmann_json_j["sizes"] = nlohmann_json_t.sizes; + nlohmann_json_j["requires_grad"] = nlohmann_json_t.requires_grad; + nlohmann_json_j["device"] = nlohmann_json_t.device; + nlohmann_json_j["strides"] = nlohmann_json_t.strides; + nlohmann_json_j["storage_offset"] = nlohmann_json_t.storage_offset; + nlohmann_json_j["layout"] = nlohmann_json_t.layout; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, TensorMeta& nlohmann_json_t) { + TensorMeta nlohmann_json_default_obj; + nlohmann_json_t.dtype = nlohmann_json_j.value("dtype", nlohmann_json_default_obj.dtype); + nlohmann_json_t.sizes = nlohmann_json_j.value("sizes", nlohmann_json_default_obj.sizes); + nlohmann_json_t.requires_grad = nlohmann_json_j.value("requires_grad", nlohmann_json_default_obj.requires_grad); + nlohmann_json_t.device = nlohmann_json_j.value("device", nlohmann_json_default_obj.device); + nlohmann_json_t.strides = nlohmann_json_j.value("strides", nlohmann_json_default_obj.strides); + nlohmann_json_t.storage_offset = nlohmann_json_j.value("storage_offset", nlohmann_json_default_obj.storage_offset); + nlohmann_json_t.layout = nlohmann_json_j.value("layout", nlohmann_json_default_obj.layout); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const TokenArgument& nlohmann_json_t) { + nlohmann_json_j["name"] = nlohmann_json_t.name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, TokenArgument& nlohmann_json_t) { + TokenArgument nlohmann_json_default_obj; + nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const UserInputMutationSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; + nlohmann_json_j["user_input_name"] = nlohmann_json_t.user_input_name; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, UserInputMutationSpec& nlohmann_json_t) { + UserInputMutationSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); + nlohmann_json_t.user_input_name = nlohmann_json_j.value("user_input_name", nlohmann_json_default_obj.user_input_name); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const UserInputSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, UserInputSpec& nlohmann_json_t) { + UserInputSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); +} + +inline void to_json(nlohmann::json& nlohmann_json_j, const UserOutputSpec& nlohmann_json_t) { + nlohmann_json_j["arg"] = nlohmann_json_t.arg; +} + +inline void from_json(const nlohmann::json& nlohmann_json_j, UserOutputSpec& nlohmann_json_t) { + UserOutputSpec nlohmann_json_default_obj; + nlohmann_json_t.arg = nlohmann_json_j.value("arg", nlohmann_json_default_obj.arg); +} + + +template ForwardRef::ForwardRef(ForwardRef&&) = default; +template ForwardRef& ForwardRef::operator=(ForwardRef&&) = default; +template ForwardRef::~ForwardRef() = default; +} // namespace _export +} // namespace torch + +// clang-format on + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/init.h new file mode 100644 index 0000000000000000000000000000000000000000..0496865beeb547590c24aa992f4484333fe02230 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/init.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::throughput_benchmark { + +void initThroughputBenchmarkBindings(PyObject* module); + +} // namespace torch::throughput_benchmark + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/invalid_arguments.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/invalid_arguments.h new file mode 100644 index 0000000000000000000000000000000000000000..d2e818adf738250bc1a707af802d2915e9711067 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/invalid_arguments.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch { + +std::string format_invalid_args( + PyObject* given_args, + PyObject* given_kwargs, + const std::string& function_name, + const std::vector& options); + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/nested.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/nested.h new file mode 100644 index 0000000000000000000000000000000000000000..0d06a65acbe2b076b72dd01d6ceed3f10cc51dc6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/nested.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::utils { + +at::Tensor nested_tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/numpy_stub.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/numpy_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..11846d0879f0b2b95c46190d997ac9a0e011e840 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/numpy_stub.h @@ -0,0 +1,26 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#ifdef USE_NUMPY + +#if !defined(NO_IMPORT_ARRAY) && !defined(WITH_NUMPY_IMPORT_ARRAY) +#define NO_IMPORT_ARRAY +#endif + +#ifndef PY_ARRAY_UNIQUE_SYMBOL +#define PY_ARRAY_UNIQUE_SYMBOL __numpy_array_api +#endif + +#ifndef NPY_NO_DEPRECATED_API +#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION +#endif + +#include + +#endif // USE_NUMPY + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/object_ptr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/object_ptr.h new file mode 100644 index 0000000000000000000000000000000000000000..aabd25e545d5df22e2480dce0cd01d9f69c68d3b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/object_ptr.h @@ -0,0 +1,86 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +template +class TORCH_PYTHON_API THPPointer { + public: + THPPointer() : ptr(nullptr) {} + explicit THPPointer(T* ptr) noexcept : ptr(ptr) {} + THPPointer(THPPointer&& p) noexcept : ptr(std::exchange(p.ptr, nullptr)) {} + THPPointer(const THPPointer& p) = delete; + THPPointer& operator=(const THPPointer&) = delete; + + ~THPPointer() { + free(); + } + T* get() { + return ptr; + } + const T* get() const { + return ptr; + } + THPPointer dup() const { + return dup(ptr); + } + static THPPointer dup(const T* ptr) { + Py_XINCREF(ptr); + return THPPointer( + const_cast(ptr)); // NOLINT(cppcoreguidelines-pro-type-const-cast) + } + static THPPointer none() { + Py_INCREF(Py_None); + return THPPointer(reinterpret_cast(Py_None)); + } + T* release() { + T* tmp = ptr; + ptr = nullptr; + return tmp; + } + operator T*() { + return ptr; + } + THPPointer& operator=(T* new_ptr) noexcept { + free(); + ptr = new_ptr; + return *this; + } + THPPointer& operator=(THPPointer&& p) noexcept { + free(); + ptr = p.ptr; + p.ptr = nullptr; + return *this; + } + T* operator->() { + return ptr; + } + explicit operator bool() const { + return ptr != nullptr; + } + + private: + void free(); + T* ptr = nullptr; +}; + +/** + * An RAII-style, owning pointer to a PyObject. You must protect + * destruction of this object with the GIL. + * + * WARNING: Think twice before putting this as a field in a C++ + * struct. This class does NOT take out the GIL on destruction, + * so if you will need to ensure that the destructor of your struct + * is either (a) always invoked when the GIL is taken or (b) takes + * out the GIL itself. Easiest way to avoid this problem is to + * not use THPPointer in this situation. + */ +using THPObjectPtr = THPPointer; +using THPCodeObjectPtr = THPPointer; +using THPFrameObjectPtr = THPPointer; + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/out_types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/out_types.h new file mode 100644 index 0000000000000000000000000000000000000000..baa59bad3c1fce24c4f8dcaca5a3a9bf2ac99d89 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/out_types.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::utils { + +TORCH_API void check_out_type_matches( + const at::Tensor& result, + std::optional scalarType, + bool scalarType_is_none, + std::optional layout, + std::optional device, + bool device_is_none); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pybind.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..4c399988a8d8a05859c9b71917e9e94c8b4147f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pybind.h @@ -0,0 +1,425 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace py = pybind11; + +#define IS_PYBIND_2_13_PLUS PYBIND11_VERSION_HEX >= 0x020D0000 + +// This makes intrusive_ptr to be available as a custom pybind11 holder type, +// see +// https://pybind11.readthedocs.io/en/stable/advanced/smart_ptrs.html#custom-smart-pointers +PYBIND11_DECLARE_HOLDER_TYPE(T, c10::intrusive_ptr, true) + +PYBIND11_DECLARE_HOLDER_TYPE(T, c10::SingletonOrSharedTypePtr) +PYBIND11_DECLARE_HOLDER_TYPE(T, c10::SingletonTypePtr, true) + +namespace pybind11::detail { + +// torch.Tensor <-> at::Tensor conversions (without unwrapping) +template <> +struct TORCH_PYTHON_API type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::Tensor, _("torch.Tensor")); + + bool load(handle src, bool /*unused*/); + + static handle cast( + const at::Tensor& src, + return_value_policy /* policy */, + handle /* parent */); +}; + +// torch._StorageBase <-> at::Storage +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::Storage, _("torch.StorageBase")); + + bool load(handle src, bool /*unused*/) { + PyObject* obj = src.ptr(); + if (torch::isStorage(obj)) { + value = torch::createStorage(obj); + return true; + } + return false; + } + + static handle cast( + const at::Storage& src, + return_value_policy /* policy */, + handle /* parent */) { + return handle(torch::createPyObject(src)); + } +}; + +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::Generator, _("torch.Generator")); + + bool load(handle src, bool /*unused*/) { + PyObject* obj = src.ptr(); + if (THPGenerator_Check(obj)) { + value = reinterpret_cast(obj)->cdata; + return true; + } + return false; + } + + static handle cast( + const at::Generator& src, + return_value_policy /* policy */, + handle /* parent */) { + return handle(THPGenerator_Wrap(src)); + } +}; + +template <> +struct TORCH_PYTHON_API type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::IntArrayRef, _("Tuple[int, ...]")); + + bool load(handle src, bool /*unused*/); + static handle cast( + at::IntArrayRef src, + return_value_policy /* policy */, + handle /* parent */); + + private: + std::vector v_value; +}; + +template <> +struct TORCH_PYTHON_API type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::SymIntArrayRef, _("List[int]")); + + bool load(handle src, bool /*unused*/); + static handle cast( + at::SymIntArrayRef src, + return_value_policy /* policy */, + handle /* parent */); + + private: + std::vector v_value; +}; + +template <> +struct TORCH_PYTHON_API type_caster> { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::ArrayRef, _("List[SymNode]")); + + bool load(handle src, bool /*unused*/); + static handle cast( + at::ArrayRef src, + return_value_policy /* policy */, + handle /* parent */); + + private: + std::vector v_value; +}; + +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::MemoryFormat, _("torch.memory_format")); + + bool load(handle src, bool /*unused*/) { + PyObject* obj = src.ptr(); + if (THPMemoryFormat_Check(obj)) { + value = reinterpret_cast(obj)->memory_format; + return true; + } + return false; + } + static handle cast( + at::MemoryFormat src, + return_value_policy /* policy */, + handle /* parent */) { + return handle(Py_NewRef(torch::utils::getTHPMemoryFormat(src))); + } +}; + +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::Device, _("torch.device")); + + // PYBIND11_TYPE_CASTER defines a member field called value. Since at::Device + // cannot be default-initialized, we provide this constructor to explicitly + // initialize that field. The value doesn't matter as it will be overwritten + // after a successful call to load. + type_caster() : value(c10::kCPU) {} + + bool load(handle src, bool /*unused*/) { + PyObject* obj = src.ptr(); + if (THPDevice_Check(obj)) { + value = reinterpret_cast(obj)->device; + return true; + } + return false; + } + + static handle cast( + const at::Device& src, + return_value_policy /* policy */, + handle /* parent */) { + return handle(THPDevice_New(src)); + } +}; + +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(at::ScalarType, _("torch.dtype")); + + // PYBIND11_TYPE_CASTER defines a member field called value. at::ScalarType + // cannot be default-initialized, we provide this constructor to explicitly + // initialize that field. The value doesn't matter as it will be overwritten + // after a successful call to load. + type_caster() : value(at::kFloat) {} + + bool load(handle src, bool /*unused*/) { + PyObject* obj = src.ptr(); + if (THPDtype_Check(obj)) { + value = reinterpret_cast(obj)->scalar_type; + return true; + } + return false; + } + + static handle cast( + const at::ScalarType& src, + return_value_policy /* policy */, + handle /* parent */) { + return Py_NewRef(torch::getTHPDtype(src)); + } +}; + +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(c10::Stream, _("torch.Stream")); + + // PYBIND11_TYPE_CASTER defines a member field called value. Since c10::Stream + // cannot be default-initialized, we provide this constructor to explicitly + // initialize that field. The value doesn't matter as it will be overwritten + // after a successful call to load. + type_caster() : value(c10::Stream::DEFAULT, c10::Device(c10::kCPU, 0)) {} + + bool load(handle src, bool /*unused*/) { + PyObject* obj = src.ptr(); + if (THPStream_Check(obj)) { + value = c10::Stream::unpack3( + ((THPStream*)obj)->stream_id, + static_cast(((THPStream*)obj)->device_index), + static_cast(((THPStream*)obj)->device_type)); + return true; + } + return false; + } + + static handle cast( + const c10::Stream& src, + return_value_policy /* policy */, + handle /* parent */) { + return handle(THPStream_Wrap(src)); + } +}; + +template <> +struct type_caster + : public type_caster_base { + using base = type_caster_base; + c10::DispatchKey tmp{}; + + public: + bool load(handle src, bool convert) { + if (base::load(src, convert)) { + return true; + } else if (py::isinstance( + src, py::module_::import("builtins").attr("str"))) { + tmp = c10::parseDispatchKey(py::cast(src)); + value = &tmp; + return true; + } + return false; + } + + static handle cast( + c10::DispatchKey src, + return_value_policy policy, + handle parent) { + return base::cast(src, policy, parent); + } +}; + +template <> +struct TORCH_PYTHON_API type_caster { + public: + PYBIND11_TYPE_CASTER( + c10::Scalar, + _("Union[Number, torch.SymInt, torch.SymFloat, torch.SymBool]")); + bool load(py::handle src, bool /*unused*/); + + static py::handle cast( + const c10::Scalar& si, + return_value_policy /* policy */, + handle /* parent */); +}; + +template <> +struct TORCH_PYTHON_API type_caster { + public: + PYBIND11_TYPE_CASTER(c10::SymInt, _("Union[int, torch.SymInt]")); + bool load(py::handle src, bool /*unused*/); + + static py::handle cast( + const c10::SymInt& si, + return_value_policy /* policy */, + handle /* parent */); +}; + +template <> +struct TORCH_PYTHON_API type_caster { + public: + PYBIND11_TYPE_CASTER(c10::SymFloat, _("float")); + bool load(py::handle src, bool /*unused*/); + + static py::handle cast( + const c10::SymFloat& si, + return_value_policy /* policy */, + handle /* parent */); +}; + +template <> +struct TORCH_PYTHON_API type_caster { + public: + PYBIND11_TYPE_CASTER(c10::SymBool, _("Union[bool, torch.SymBool]")); + bool load(py::handle src, bool /*unused*/); + + static py::handle cast( + const c10::SymBool& si, + return_value_policy /* policy */, + handle /* parent */); +}; + +template +struct type_caster> { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(c10::complex, _("complex")); + + bool load(handle src, bool /*unused*/) { + PyObject* obj = src.ptr(); + + // Referred from `THPUtils_unpackComplexDouble` + Py_complex py_complex = PyComplex_AsCComplex(obj); + if (py_complex.real == -1.0 && PyErr_Occurred()) { + return false; + } + + // Python's Complex is always double precision. + value = c10::complex(py_complex.real, py_complex.imag); + return true; + } + + static handle cast( + const c10::complex& complex, + return_value_policy /* policy */, + handle /* parent */) { + // Python only knows double precision complex. + return handle(PyComplex_FromDoubles(complex.real(), complex.imag())); + } +}; + +} // namespace pybind11::detail + +namespace torch::impl { + +// Use this function if you have a C++ object that is used from both C++ +// and Python contexts, and you need its GIL to be released when you +// destruct it in the Python context. +// +// This function is a valid shared_ptr destructor and can be used to +// conveniently allocate a shared_ptr to an object whose destructor will be run +// without the GIL. Pass it as the second argument to shared_ptr, e.g., +// +// shared_ptr(new T(), destroy_without_gil) +// +// Attaching the GIL release logic to the holder pointer rather than the +// actual destructor of T is helpful when T is Python-agnostic and +// shouldn't refer to the PYthon API. +// +// Note there are limitations to the correctness of code that makes use of this. +// In particular, if a shared_ptr is constructed from C++ code without this +// destructor and then passed to pybind11, pybind11 will happily take ownership +// of the shared_ptr (and be willing to destruct it from a context where it is +// holding the GIL). unique_ptr with a type branded deleter is less prone to +// this problem, because a stock deleter unique_ptr is not convertible with it. +// I plan to mitigate this problem by adding DEBUG-only asserts to the true C++ +// destructors that the GIL is not held (using a virtual call to get to the +// Python interpreter); alternately, we could use a virtual call to simply +// ensure we release the GIL in the C++ destructor, however, this is a layering +// violation (why does code that is ostensibly Python agnostic calling into the +// GIL). +// +// Adapted from +// https://github.com/pybind/pybind11/issues/1446#issuecomment-406341510 +template +inline void destroy_without_gil(T* ptr) { + // Because the ownership of a shared_ptr is diffuse, it's not possible to + // necessarily predict whether or not the last reference to an object will + // be destructed from Python or C++. This means that in the destructor here, + // we don't necessarily know if we actually have the GIL or not; in fact, + // we don't even know if the Python interpreter still exists! Thus, we have + // to test for it before releasing the GIL. + // + // PyGILState_Check is hopefully self explanatory. But Py_IsInitialized or + // _PyIsFinalizing? Both get set at the same time during the Python + // destruction process: + // https://github.com/python/cpython/blob/d92513390a1a0da781bb08c284136f4d7abea36d/Python/pylifecycle.c#L1716-L1717 + // so the operant question is whether or not you want to release the GIL after + // finalization has completed (and there is just no Python interpreter). + // Clearly there is no need to release GIL in that state, so we want + // Py_IsInitialized. + if (Py_IsInitialized() && PyGILState_Check()) { + pybind11::gil_scoped_release nogil; + delete ptr; + } else { + delete ptr; + } +} + +} // namespace torch::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pycfunction_helpers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pycfunction_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..a4c40edc4d326b36ef1ab8f162e08a4fa70f01be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pycfunction_helpers.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +inline PyCFunction castPyCFunctionWithKeywords(PyCFunctionWithKeywords func) { + C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wcast-function-type") + C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wcast-function-type-strict") + return reinterpret_cast(func); + C10_DIAGNOSTIC_POP() + C10_DIAGNOSTIC_POP() +} + +#if !IS_PYTHON_3_13_PLUS +using PyCFunctionFast = _PyCFunctionFast; +#endif + +inline PyCFunction castPyCFunctionFast(PyCFunctionFast func) { + C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wcast-function-type") + C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wcast-function-type-strict") + return reinterpret_cast(func); + C10_DIAGNOSTIC_POP() + C10_DIAGNOSTIC_POP() +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pyobject_preservation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pyobject_preservation.h new file mode 100644 index 0000000000000000000000000000000000000000..5c8183ae78cac120a7423a8917c9761cb9b79cf4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pyobject_preservation.h @@ -0,0 +1,36 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// This file contains utilities used for handling PyObject preservation + +namespace c10 { +class intrusive_ptr_target; +namespace impl { +struct PyObjectSlot; +} // namespace impl +} // namespace c10 + +namespace torch::utils { + +class PyObjectPreservation { + public: + // Store a PyObject wrapper on a fresh c10 wrapper. The caller must hold + // a unique reference to `target`. + static void init_fresh_nonatomic( + c10::intrusive_ptr_target* target, + c10::impl::PyObjectSlot* slot, + PyObject* pyobj); + + static PyObject* init_once( + c10::intrusive_ptr_target* target, + c10::impl::PyObjectSlot* slot, + PyObject* pyobj); +}; + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_arg_parser.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_arg_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..56de9a132b6086540a7befd769d56c1baaa627f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_arg_parser.h @@ -0,0 +1,1379 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// Parse arguments to Python functions implemented in C++ +// This is similar to PyArg_ParseTupleAndKeywords(), but specifically handles +// the types relevant to PyTorch and distinguishes between overloaded function +// signatures. +// +// Example: +// +// static PythonArgParser parser({ +// "norm(Scalar p, int64_t dim, bool keepdim=False)", +// "norm(Scalar p=2)", +// }); +// ParsedArgs<3> parsed_args; +// auto r = parser.parse(args, kwargs, parsed_args); +// if (r.idx == 0) { +// norm(r.scalar(0), r.int64(1), r.bool(0)); +// } else { +// norm(r.scalar(0)); +// } +// +// We auto-generate most uses of PythonArgParser; the generated files +// are torch/csrc/autograd/generated/python_*.cpp +// +// Some gotchas that you should watch out for: +// +// - Note [Order of overloads matters] +// Order of overloads matters. A set of input arguments may +// bind to multiple argument specs; we will always pick the +// first one in PythonArgParser. However, when you are writing +// overloads in, e.g., native_functions.yaml, you don't have to +// worry about what order you write them, because the code +// generation logic always gives the overloads a canonical +// order, where Tensor overloads come first, before Scalar overloads. +// This logic is in sort_declarations in +// tools/autograd/gen_python_functions.py +// +// - Zero-dim tensors (e.g., torch.tensor(2)) bind to both +// Scalar and Tensor, UNLESS they require grad (in which case +// they only bind to Tensor). + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +inline bool THPUtils_checkScalar(PyObject* obj) { +#ifdef USE_NUMPY + if (torch::utils::is_numpy_scalar(obj)) { + return true; + } +#endif + return PyFloat_Check(obj) || PyLong_Check(obj) || PyComplex_Check(obj) || + torch::is_symint(py::handle(obj)) || torch::is_dynint(py::handle(obj)) || + torch::is_symfloat(py::handle(obj)) || torch::is_symbool(py::handle(obj)); +} + +namespace torch { + +TORCH_PYTHON_API bool should_allow_numbers_as_tensors(const std::string& name); + +enum class ParameterType { + TENSOR, + SCALAR, + INT64, + SYM_INT, + DOUBLE, + COMPLEX, + TENSOR_LIST, + INT_LIST, + GENERATOR, + BOOL, + STORAGE, + PYOBJECT, + SCALARTYPE, + LAYOUT, + MEMORY_FORMAT, + DEVICE, + STREAM, + STRING, + DIMNAME, + DIMNAME_LIST, + QSCHEME, + FLOAT_LIST, + SCALAR_LIST, + SYM_INT_LIST, + DISPATCH_KEY_SET +}; + +struct FunctionParameter; +struct FunctionSignature; +struct PythonArgs; + +// Contains bound Python arguments in declaration order +template +struct ParsedArgs { + ParsedArgs() : args() {} + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + PyObject* args[N]; +}; + +// A PythonArgParser contains a list of valid signatures. Instances are +// typically global variables and should be immutable. +struct PYBIND11_EXPORT PythonArgParser { + explicit PythonArgParser( + const std::vector& fmts, + bool traceable = false); + + // meant only for `torch` functions. + template + inline PythonArgs parse( + PyObject* self, + PyObject* args, + PyObject* kwargs, + ParsedArgs& dst); + + template + inline PythonArgs parse(PyObject* args, PyObject* kwargs, ParsedArgs& dst); + + inline PythonArgs parse(PyObject* self, ParsedArgs<0>& dst); + + // Formatted strings of non-hidden signatures + std::vector get_signatures() const; + + private: + [[noreturn]] void print_error( + PyObject* self, + PyObject* args, + PyObject* kwargs, + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + PyObject* parsed_args[]); + void check_deprecated(const FunctionSignature& signature); + PythonArgs raw_parse( + PyObject* self, + PyObject* args, + PyObject* kwargs, + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + PyObject* parsed_args[]); + + std::vector signatures_; + std::string function_name; + size_t max_args; + bool traceable; +}; + +// FunctionSignature represents a single valid signature for a Python function. +// It is immutable once constructed. The contained data can be concurrently +// accessed by multiple calls. +struct FunctionSignature { + explicit FunctionSignature(const std::string& fmt, int index); + + bool parse( + PyObject* self, + PyObject* args, + PyObject* kwargs, + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + PyObject* dst[], + std::vector& overloaded_args, + bool raise_exception); + + std::string toString() const; + + std::string name; + std::vector params; + size_t min_args; + size_t max_args; + size_t max_pos_args; + int index; + bool hidden; + bool deprecated; +}; + +// PythonArgs contains bound Python arguments for an actual invocation +// along with references to the matched signature. +struct TORCH_PYTHON_API PythonArgs { + PythonArgs( + bool traceable, + const FunctionSignature& signature, + PyObject** args, + std::vector overloaded_args) + : idx(signature.index), + traceable(traceable), + signature(signature), + args(args), + overloaded_args(std::move(overloaded_args)) {} + + int idx; + bool traceable; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const FunctionSignature& signature; + PyObject** args; + std::vector overloaded_args; // NOTE: borrowed references + + inline bool has_torch_function(); + inline std::string get_func_name(); + inline at::Tensor tensor(int i); + inline std::optional optionalTensor(int i); + inline at::Scalar scalar(int i); + inline at::Scalar scalarWithDefault(int i, const at::Scalar& default_scalar); + inline std::vector scalarlist(int i); + inline std::vector tensorlist(int i); + inline torch::List> list_of_optional_tensors(int i); + template + inline std::array tensorlist_n(int i); + inline std::vector intlist(int i); + inline std::vector symintlist(int i); + inline c10::OptionalArray intlistOptional(int i); + inline c10::OptionalArray symintlistOptional(int i); + inline std::vector intlistWithDefault( + int i, + std::vector default_intlist); + inline std::optional generator(int i); + inline at::Storage storage(int i); + inline at::Storage storage( + int i, + at::ScalarType& storage_scalar_type, + bool& is_typed_storage); + inline c10::Stream stream(int i); + inline at::ScalarType scalartype(int i); + inline at::ScalarType scalartypeWithDefault( + int i, + at::ScalarType default_scalartype); + inline std::optional scalartypeOptional(int i); + inline std::optional scalarOptional(int i); + inline std::optional toInt64Optional(int i); + inline std::optional toSymIntOptional(int i); + inline std::optional toBoolOptional(int i); + inline std::optional toDoubleOptional(int i); + inline c10::OptionalArray doublelistOptional(int i); + inline std::vector doublelist(int i); + inline std::vector getDoublelist(int i); + inline at::Layout layout(int i); + inline at::Layout layoutWithDefault(int i, at::Layout default_layout); + inline std::optional layoutOptional(int i); + inline at::Device device(int i); + inline at::Device deviceWithDefault(int i, const at::Device& default_device); + inline std::optional deviceOptional(int i); + inline at::Dimname dimname(int i); + inline std::vector dimnamelist(int i); + inline std::optional> toDimnameListOptional(int i); + inline at::MemoryFormat memoryformat(int i); + inline std::optional memoryformatOptional(int i); + inline at::QScheme toQScheme(int i); + inline std::string string(int i); + inline std::string stringWithDefault(int i, const std::string& default_str); + inline std::optional stringOptional(int i); + inline std::string_view stringView(int i); + inline std::string_view stringViewWithDefault( + int i, + const std::string_view default_str); + inline std::optional stringViewOptional(int i); + inline PyObject* pyobject(int i); + inline int64_t toInt64(int i); + inline c10::SymInt toSymInt(int i); + inline c10::SymBool toSymBool(int i); + inline int64_t toInt64WithDefault(int i, int64_t default_int); + inline double toDouble(int i); + inline double toDoubleWithDefault(int i, double default_double); + inline c10::complex toComplex(int i); + inline c10::complex toComplexWithDefault( + int i, + c10::complex default_complex); + inline bool toBool(int i); + inline bool toBoolWithDefault(int i, bool default_bool); + inline bool isNone(int i); + inline std::optional toDispatchKeySetOptional(int i); + + private: + // Non-inline functions' symbols are exposed to torch_python DLL + // via TORCH_PYTHON_API tag at struct level. + at::Tensor tensor_slow(int i); + at::Scalar scalar_slow(int i); + at::Scalar scalar_slow(PyObject* arg); +}; + +// FunctionParameter is a single formal parameter of a Python function. +// It is immutable once constructed. +struct FunctionParameter { + FunctionParameter(const std::string& fmt, bool keyword_only); + + bool check( + PyObject* obj, + std::vector& overloaded_args, + int argnum, + int64_t* failed_idx = nullptr); + + bool _check( + PyObject* obj, + std::vector& overloaded_args, + int argnum, + int64_t* failed_idx = nullptr); + + void set_default_str(const std::string& str); + TORCH_PYTHON_API std::string type_name() const; + + ParameterType type_; + bool optional; + bool allow_none; + bool keyword_only; + bool allow_numbers_as_tensors = false; + int size; + std::string name; + // having this as a raw PyObject * will presumably leak it, but these are only + // held by static objects anyway, and Py_Finalize can already be called when + // this is destructed. + PyObject* python_name; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) + at::SmallVector numpy_python_names; + at::Scalar default_scalar; + std::vector default_intlist; + std::string default_string; + union { + bool default_bool; + int64_t default_int; + double default_double; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + double default_complex[2]; // see Scalar + at::ScalarType default_scalartype; + at::Layout default_layout; + }; + std::string default_value; +}; + +template +inline PythonArgs PythonArgParser::parse( + PyObject* self, + PyObject* args, + PyObject* kwargs, + ParsedArgs& dst) { + TORCH_CHECK_VALUE( + N >= max_args, + "PythonArgParser: dst ParsedArgs buffer does not have enough capacity, expected ", + max_args, + " (got ", + N, + ")"); + return raw_parse(self, args, kwargs, dst.args); +} + +template +inline PythonArgs PythonArgParser::parse( + PyObject* args, + PyObject* kwargs, + ParsedArgs& dst) { + return parse(nullptr, args, kwargs, dst); +} + +inline PythonArgs PythonArgParser::parse(PyObject* self, ParsedArgs<0>& dst) { + return parse(self, nullptr, nullptr, dst); +} + +inline bool PythonArgs::has_torch_function() { + return !overloaded_args.empty() || at::impl::torch_function_mode_enabled(); +} + +inline std::string PythonArgs::get_func_name() { + return signature.name; +} + +// TODO: this can return MaybeOwned +inline at::Tensor PythonArgs::tensor(int i) { + if (args[i] && THPVariable_CheckExact(args[i])) { + return THPVariable_Unpack(args[i]); + } + return tensor_slow(i); +} + +inline std::optional PythonArgs::optionalTensor(int i) { + at::Tensor t = tensor(i); + // NOLINTNEXTLINE(bugprone-branch-clone) + if (t.defined()) { + return t; + } else { + return std::nullopt; + } +} + +inline at::Scalar PythonArgs::scalar(int i) { + if (!args[i]) + return signature.params[i].default_scalar; + return scalar_slow(i); +} + +inline std::vector PythonArgs::scalarlist(int i) { + if (!args[i]) + return std::vector(); + auto tuple = six::isTuple(args[i]); + THPObjectPtr arg = six::maybeAsTuple(args[i]); + // NOLINTNEXTLINE(bugprone-branch-clone) + auto size = tuple ? PyTuple_GET_SIZE(arg.get()) : PyList_GET_SIZE(arg.get()); + std::vector res(size); + for (const auto idx : c10::irange(size)) { + PyObject* obj = tuple ? PyTuple_GET_ITEM(arg.get(), idx) + : PyList_GET_ITEM(arg.get(), idx); + res[idx] = scalar_slow(obj); + } + return res; +} + +inline at::Scalar PythonArgs::scalarWithDefault( + int i, + const at::Scalar& default_scalar) { + if (!args[i]) + return default_scalar; + return scalar_slow(i); +} + +inline std::optional PythonArgs::scalarOptional(int i) { + if (!args[i]) + return std::nullopt; + return scalar_slow(i); +} + +inline std::vector PythonArgs::tensorlist(int i) { + if (!args[i]) + return std::vector(); + auto tuple = six::isTuple(args[i]); + THPObjectPtr arg = six::maybeAsTuple(args[i]); + // NOLINTNEXTLINE(bugprone-branch-clone) + auto size = tuple ? PyTuple_GET_SIZE(arg.get()) : PyList_GET_SIZE(arg.get()); + std::vector res(size); + for (const auto idx : c10::irange(size)) { + PyObject* obj = tuple ? PyTuple_GET_ITEM(arg.get(), idx) + : PyList_GET_ITEM(arg.get(), idx); + // This is checked by the argument parser so it's safe to cast without + // checking if this is a tensor first + res[idx] = THPVariable_Unpack(obj); + } + return res; +} + +inline torch::List> PythonArgs:: + list_of_optional_tensors(int i) { + if (!args[i]) + return torch::List>(); + auto tuple = six::isTuple(args[i]); + THPObjectPtr arg = six::maybeAsTuple(args[i]); + // NOLINTNEXTLINE(bugprone-branch-clone) + auto size = tuple ? PyTuple_GET_SIZE(arg.get()) : PyList_GET_SIZE(arg.get()); + torch::List> res; + res.reserve(size); + for (const auto idx : c10::irange(size)) { + PyObject* obj = tuple ? PyTuple_GET_ITEM(arg.get(), idx) + : PyList_GET_ITEM(arg.get(), idx); + // This is checked by the argument parser so it's safe to cast without + // checking if this is a tensor first + res.push_back(THPVariable_Unpack(obj)); + } + return res; +} + +template +inline std::array PythonArgs::tensorlist_n(int i) { + auto res = std::array(); + if (!args[i]) + return res; + auto tuple = six::isTuple(args[i]); + THPObjectPtr arg = six::maybeAsTuple(args[i]); + // NOLINTNEXTLINE(bugprone-branch-clone) + auto size = tuple ? PyTuple_GET_SIZE(arg.get()) : PyList_GET_SIZE(arg.get()); + if (size != N) { + TORCH_CHECK_TYPE( + false, + fmt::format("expected tuple of {} elements but got {}", N, size)); + } + for (const auto idx : c10::irange(size)) { + PyObject* obj = tuple ? PyTuple_GET_ITEM(arg.get(), idx) + : PyList_GET_ITEM(arg.get(), idx); + // This is checked by the argument parser so it's safe to cast without + // checking if this is a tensor first + res[idx] = THPVariable_Unpack(obj); + } + return res; +} + +inline std::vector PythonArgs::intlist(int i) { + return intlistWithDefault(i, signature.params[i].default_intlist); +} + +inline PyObject* toPyObject(const c10::SymInt& symint) { + if (symint.is_symbolic()) { + auto r = py::cast(symint).release().ptr(); + TORCH_INTERNAL_ASSERT(r); + return r; + } else { + auto m = symint.maybe_as_int(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return THPUtils_packInt64(m.value()); + } +} + +inline void throw_intlist_exception( + const torch::PythonArgs* args, + size_t i, + PyObject* obj, + size_t idx, + const std::exception& e = python_error()) { + std::string error = strlen(e.what()) + ? e.what() + : std::string("type must be ") + args->signature.params[i].type_name() + + ",but got " + Py_TYPE(obj)->tp_name; + TORCH_CHECK_TYPE( + false, + fmt::format( + "{}(): argument '{}' failed to unpack the object at pos {} with error \"{}\"", + args->signature.name, + args->signature.params[i].name, + idx + 1, + error)); +} + +inline std::vector PythonArgs::symintlist(int i) { + if (!args[i]) { + return c10::fmap(signature.params[i].default_intlist, [](int64_t di) { + return c10::SymInt(di); + }); + } + + const auto size1 = signature.params[i].size; + if (size1 > 0 && THPUtils_checkLong(args[i])) { + return std::vector( + size1, c10::SymInt(THPUtils_unpackLong(args[i]))); + } + + if (size1 > 0 && torch::is_symint(py::handle(args[i]))) { + auto si = py::handle(args[i]).cast(); + return std::vector(size1, si); + } + + if (size1 > 0 && THPVariable_Check(args[i])) { + return std::vector( + size1, THPVariable_Unpack(args[i]).item().toSymInt()); + } + + PyObject* arg = args[i]; + auto tuple = PyTuple_Check(arg); + if (!tuple) { + TORCH_INTERNAL_ASSERT(PyList_Check(arg), "expected tuple or list"); + } + // NOLINTNEXTLINE(bugprone-branch-clone) + const auto size2 = tuple ? PyTuple_GET_SIZE(arg) : PyList_GET_SIZE(arg); + std::vector res; + res.reserve(size2); + for (const auto idx : c10::irange(size2)) { + PyObject* obj = + tuple ? PyTuple_GET_ITEM(arg, idx) : PyList_GET_ITEM(arg, idx); + + // Elements of torch.Size are tensors during tracing, and we need to + // record extra information before they are turned into an IntArrayRef + if (traceable && jit::tracer::isTracing() && THPVariable_Check(obj)) { + auto& var = THPVariable_Unpack(obj); + jit::tracer::ArgumentStash::stashIntArrayRefElem( + signature.params[i].name, size2, idx, var); + try { + res.emplace_back(var.item()); + continue; + } catch (std::exception& e) { + throw_intlist_exception(this, i, obj, idx, e); + } + continue; + } else { + // convert tensor to scalar outside of try / catch, + // so that Tensor subclass exceptions will not be caught. + if (THPUtils_checkLongExact(obj)) { + // Fast path for plain numbers + try { + res.emplace_back(THPUtils_unpackLong(obj)); + } catch (std::exception& e) { + throw_intlist_exception(this, i, obj, idx, e); + } + } else if (THPVariable_Check(obj)) { + auto& var = THPVariable_Unpack(obj); + if (var.numel() != 1 || + !at::isIntegralType( + var.dtype().toScalarType(), /*include_bool*/ true)) { + throw_intlist_exception(this, i, obj, idx); + } + auto scalar = var.item(); + TORCH_CHECK(scalar.isIntegral(/*include bool*/ false)); + res.push_back(scalar.toSymInt()); + } else { + try { + if (is_symint(py::handle(obj))) { + res.push_back(py::handle(obj).cast()); + } else if (is_dynint(py::handle(obj))) { + res.push_back(py::handle(obj).cast()); + } else { + res.emplace_back(THPUtils_unpackIndex(obj)); + } + } catch (std::exception& e) { + throw_intlist_exception(this, i, obj, idx, e); + } + } + } + } + + return res; +} + +inline std::vector PythonArgs::intlistWithDefault( + int i, + std::vector default_intlist) { + if (!args[i]) + return default_intlist; + PyObject* arg = args[i]; + const auto size1 = signature.params[i].size; + if (size1 > 0 && THPUtils_checkLong(arg)) { + return std::vector(size1, THPUtils_unpackLong(arg)); + } + if (size1 > 0 && torch::is_symint(py::handle(arg))) { + return std::vector( + size1, + py::handle(arg).cast().guard_int(__FILE__, __LINE__)); + } + if (size1 > 0 && torch::is_dynint(py::handle(arg))) { + return std::vector(size1, py::handle(arg).cast()); + } + if (size1 > 0 && THPVariable_Check(arg)) { + return std::vector(size1, THPVariable_Unpack(arg).item()); + } + auto tuple = PyTuple_Check(arg); + if (!tuple) { + TORCH_INTERNAL_ASSERT(PyList_Check(arg), "expected tuple or list"); + } + // NOLINTNEXTLINE(bugprone-branch-clone) + const auto size2 = tuple ? PyTuple_GET_SIZE(arg) : PyList_GET_SIZE(arg); + std::vector res(size2); + for (const auto idx : c10::irange(size2)) { + PyObject* obj = + tuple ? PyTuple_GET_ITEM(arg, idx) : PyList_GET_ITEM(arg, idx); + // Elements of torch.Size are tensors during tracing, and we need to + // record extra information before they are turned into an IntArrayRef + if (traceable && jit::tracer::isTracing() && THPVariable_Check(obj)) { + auto& var = THPVariable_Unpack(obj); + jit::tracer::ArgumentStash::stashIntArrayRefElem( + signature.params[i].name, size2, idx, var); + try { + res[idx] = var.item(); + continue; + } catch (std::exception& e) { + throw_intlist_exception(this, i, obj, idx, e); + } + } else { + // convert tensor to scalar outside of try / catch, + // so that Tensor subclass exceptions will not be caught. + if (THPUtils_checkLongExact(obj)) { + // Fast path for plain numbers + try { + res[idx] = THPUtils_unpackLong(obj); + } catch (std::exception& e) { + throw_intlist_exception(this, i, obj, idx, e); + } + } else if (torch::is_symint(py::handle(obj))) { + res[idx] = py::cast(py::handle(obj)) + .guard_int(__FILE__, __LINE__); + } else if (torch::is_dynint(py::handle(obj))) { + res[idx] = py::handle(obj).cast(); + } else if (THPVariable_Check(obj)) { + auto& var = THPVariable_Unpack(obj); + if (var.numel() != 1 || + !at::isIntegralType( + var.dtype().toScalarType(), /*include_bool*/ true)) { + throw_intlist_exception(this, i, obj, idx); + } + res[idx] = var.item(); + } else { + try { + res[idx] = THPUtils_unpackIndex(obj); + } catch (std::exception& e) { + throw_intlist_exception(this, i, obj, idx, e); + } + } + } + } + return res; +} + +inline c10::OptionalArray PythonArgs::intlistOptional(int i) { + if (!args[i]) { + return {}; + } + return intlist(i); +} + +inline c10::OptionalArray PythonArgs::symintlistOptional(int i) { + if (!args[i]) { + return {}; + } + return symintlist(i); +} + +inline std::vector PythonArgs::getDoublelist(int i) { + PyObject* arg = args[i]; + auto tuple = PyTuple_Check(arg); + if (!tuple) { + TORCH_INTERNAL_ASSERT(PyList_Check(arg), "expected tuple or list"); + } + // NOLINTNEXTLINE(bugprone-branch-clone) + auto size = tuple ? PyTuple_GET_SIZE(arg) : PyList_GET_SIZE(arg); + std::vector res(size); + for (const auto idx : c10::irange(size)) { + PyObject* obj = + tuple ? PyTuple_GET_ITEM(arg, idx) : PyList_GET_ITEM(arg, idx); + try { + if (torch::is_symfloat(py::handle(obj))) { + res[idx] = py::cast(py::handle(obj)) + .guard_float(__FILE__, __LINE__); + } else { + res[idx] = THPUtils_unpackDouble(obj); + } + } catch (const std::exception&) { + TORCH_CHECK_TYPE( + false, + fmt::format( + "{}(): argument '{}' must be {}, but found element of type {} at pos {}", + signature.name, + signature.params[i].name, + signature.params[i].type_name(), + Py_TYPE(obj)->tp_name, + idx + 1)); + } + } + return res; +} + +inline c10::OptionalArray PythonArgs::doublelistOptional(int i) { + if (!args[i]) { + return {}; + } + return this->getDoublelist(i); +} + +inline std::vector PythonArgs::doublelist(int i) { + if (!args[i]) { + return {}; + } + return this->getDoublelist(i); +} + +inline std::optional PythonArgs::toDispatchKeySetOptional( + int i) { + if (!args[i]) { + return {}; + } + return py::cast(py::handle(args[i])); +} + +inline at::ScalarType PythonArgs::scalartypeWithDefault( + int i, + at::ScalarType default_scalartype) { + if (!args[i]) + return default_scalartype; + return scalartype(i); +} + +inline at::ScalarType toScalarType(PyObject* obj) { + if (obj == (PyObject*)&PyFloat_Type) { + return at::ScalarType::Double; + } + if (obj == (PyObject*)&PyBool_Type) { + return at::ScalarType::Bool; + } + if (obj == (PyObject*)&PyLong_Type) { + return at::ScalarType::Long; + } + if (obj == (PyObject*)&PyComplex_Type) { + return at::ScalarType::ComplexDouble; + } + return reinterpret_cast(obj)->scalar_type; +} + +inline at::ScalarType PythonArgs::scalartype(int i) { + if (!args[i]) { + auto scalartype = signature.params[i].default_scalartype; + return (scalartype == at::ScalarType::Undefined) + ? torch::tensors::get_default_scalar_type() + : scalartype; + } + PyObject* obj = args[i]; + return toScalarType(obj); +} + +inline std::optional PythonArgs::scalartypeOptional(int i) { + if (!args[i]) + return std::nullopt; + return scalartype(i); +} + +inline at::Layout toLayout(PyObject* obj) { + const auto layout = reinterpret_cast(obj); + return layout->layout; +} + +inline at::Layout PythonArgs::layout(int i) { + if (!args[i]) + return signature.params[i].default_layout; + return toLayout(args[i]); +} + +inline at::Layout PythonArgs::layoutWithDefault( + int i, + at::Layout default_layout) { + if (!args[i]) + return default_layout; + return layout(i); +} + +inline std::optional PythonArgs::layoutOptional(int i) { + if (!args[i]) + return std::nullopt; + return layout(i); +} + +inline at::Device deviceFromLong(int64_t device_index) { + TORCH_CHECK(device_index >= 0, "Device index must not be negative"); + return at::Device( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + at::getAccelerator(true).value(), + static_cast(device_index)); +} + +inline at::Device toDevice(PyObject* obj) { + if (THPDevice_Check(obj)) { + const auto device = reinterpret_cast(obj); + return device->device; + } + if (THPUtils_checkLong(obj)) { + return deviceFromLong(THPUtils_unpackLong(obj)); + } + if (torch::is_symint(py::handle(obj))) { + auto device_index = + py::cast(py::handle(obj)).guard_int(__FILE__, __LINE__); + return deviceFromLong(device_index); + } + if (torch::is_dynint(py::handle(obj))) { + auto device_index = py::cast(py::handle(obj)); + return deviceFromLong(device_index); + } + const std::string& device_str = THPUtils_unpackString(obj); + return at::Device(device_str); +} + +inline at::Device PythonArgs::device(int i) { + if (!args[i]) { + return torch::tensors::get_default_device(); + } + return toDevice(args[i]); +} + +inline at::Device PythonArgs::deviceWithDefault( + int i, + const at::Device& default_device) { + if (!args[i]) + return default_device; + return device(i); +} + +inline std::optional PythonArgs::deviceOptional(int i) { + if (!args[i]) + return std::nullopt; + return device(i); +} + +inline at::Dimname PythonArgs::dimname(int i) { + TORCH_INTERNAL_ASSERT(args[i] != nullptr); + return THPDimname_parse(args[i]); +} + +inline std::vector parseDimnameList(PyObject* arg) { + auto tuple = PyTuple_Check(arg); + if (!tuple) { + TORCH_INTERNAL_ASSERT(PyList_Check(arg), "expected tuple or list"); + } + // NOLINTNEXTLINE(bugprone-branch-clone) + auto size = tuple ? PyTuple_GET_SIZE(arg) : PyList_GET_SIZE(arg); + std::vector res; + res.reserve(size); + for (const auto idx : c10::irange(size)) { + PyObject* obj = + tuple ? PyTuple_GET_ITEM(arg, idx) : PyList_GET_ITEM(arg, idx); + res.push_back(THPDimname_parse(obj)); + } + return res; +} + +inline std::optional> PythonArgs:: + toDimnameListOptional(int i) { + if (!args[i]) + return std::nullopt; + return parseDimnameList(args[i]); +} + +inline std::vector PythonArgs::dimnamelist(int i) { + TORCH_INTERNAL_ASSERT(args[i]); + PyObject* arg = args[i]; + auto size = signature.params[i].size; + TORCH_INTERNAL_ASSERT(size == 0 || size == 1); + if (size == 1 && THPUtils_checkDimname(arg)) { + return {THPDimname_parse(arg)}; + } + return parseDimnameList(arg); +} + +inline at::MemoryFormat PythonArgs::memoryformat(int i) { + if (!args[i]) + return at::MemoryFormat::Contiguous; + TORCH_CHECK( + THPMemoryFormat_Check(args[i]), + "memory_format arg must be an instance of the torch.memory_format"); + const auto memory_format = reinterpret_cast(args[i]); + return memory_format->memory_format; +} + +inline std::optional PythonArgs::memoryformatOptional(int i) { + if (!args[i]) + return std::nullopt; + return memoryformat(i); +} + +inline at::QScheme PythonArgs::toQScheme(int i) { + if (!args[i]) + return at::kPerTensorAffine; + TORCH_CHECK( + THPQScheme_Check(args[i]), + "qscheme arg must be an instance of the torch.qscheme"); + const auto qscheme = reinterpret_cast(args[i]); + return qscheme->qscheme; +} + +inline std::string PythonArgs::string(int i) { + return stringWithDefault(i, signature.params[i].default_string); +} + +inline std::string PythonArgs::stringWithDefault( + int i, + const std::string& default_str) { + if (!args[i]) + return default_str; + return THPUtils_unpackString(args[i]); +} + +inline std::optional PythonArgs::stringOptional(int i) { + if (!args[i]) + return std::nullopt; + return THPUtils_unpackString(args[i]); +} + +inline std::string_view PythonArgs::stringView(int i) { + return stringViewWithDefault(i, signature.params[i].default_string); +} + +inline std::string_view PythonArgs::stringViewWithDefault( + int i, + const std::string_view default_str) { + if (!args[i]) + return default_str; + return THPUtils_unpackStringView(args[i]); +} + +inline std::optional PythonArgs::stringViewOptional(int i) { + if (!args[i]) + return std::nullopt; + return THPUtils_unpackStringView(args[i]); +} + +inline int64_t PythonArgs::toInt64(int i) { + if (!args[i]) + return signature.params[i].default_int; + if (traceable && jit::tracer::isTracing() && THPVariable_Check(args[i])) { + auto& var = THPVariable_Unpack(args[i]); + jit::tracer::ArgumentStash::stashValue( + signature.params[i].name, idx, var, c10::IntType::get()); + } + if (torch::is_symint(py::handle(args[i]))) { + return py::cast(py::handle(args[i])) + .guard_int(__FILE__, __LINE__); + } + if (torch::is_dynint(py::handle(args[i]))) { + return py::cast(py::handle(args[i])); + } + return THPUtils_unpackLong(args[i]); +} + +inline c10::SymInt PythonArgs::toSymInt(int i) { + if (!args[i]) { + return c10::SymInt(signature.params[i].default_int); + } + + if (traceable && jit::tracer::isTracing() && THPVariable_Check(args[i])) { + auto& var = THPVariable_Unpack(args[i]); + jit::tracer::ArgumentStash::stashValue( + signature.params[i].name, idx, var, c10::IntType::get()); + } + + return py::cast(py::handle(args[i])); +} + +inline c10::SymBool PythonArgs::toSymBool(int i) { + if (!args[i]) { + return c10::SymBool(signature.params[i].default_bool); + } + if (traceable && jit::tracer::isTracing() && THPVariable_Check(args[i])) { + auto& var = THPVariable_Unpack(args[i]); + jit::tracer::ArgumentStash::stashValue( + signature.params[i].name, idx, var, c10::BoolType::get()); + } + + return py::cast(py::handle(args[i])); +} + +inline int64_t PythonArgs::toInt64WithDefault(int i, int64_t default_int) { + if (!args[i]) + return default_int; + return toInt64(i); +} + +inline std::optional PythonArgs::toInt64Optional(int i) { + if (!args[i]) + return std::nullopt; + return toInt64(i); +} + +inline std::optional PythonArgs::toSymIntOptional(int i) { + if (!args[i]) + return std::nullopt; + return toSymInt(i); +} + +inline std::optional PythonArgs::toBoolOptional(int i) { + if (!args[i]) { + return std::nullopt; + } + return toBool(i); +} + +inline std::optional PythonArgs::toDoubleOptional(int i) { + if (!args[i]) { + return std::nullopt; + } + return toDouble(i); +} + +inline double PythonArgs::toDouble(int i) { + if (!args[i]) + return signature.params[i].default_double; + if (torch::is_symfloat(py::handle(args[i]))) { + return py::cast(py::handle(args[i])) + .guard_float(__FILE__, __LINE__); + } + if (torch::is_symint(py::handle(args[i]))) { + return static_cast(py::cast(py::handle(args[i])) + .guard_int(__FILE__, __LINE__)); + } + if (torch::is_dynint(py::handle(args[i]))) { + return static_cast(py::cast(py::handle(args[i]))); + } + return THPUtils_unpackDouble(args[i]); +} + +inline bool PythonArgs::toBool(int i) { + if (!args[i]) { + return signature.params[i].default_bool; + } + if (args[i] == Py_True) { + return true; + } + if (args[i] == Py_False) { + return false; + } + if (torch::is_symbool(py::handle(args[i]))) { + return py::cast(py::handle(args[i])) + .guard_bool(__FILE__, __LINE__); + } + return false; +} + +inline double PythonArgs::toDoubleWithDefault(int i, double default_double) { + if (!args[i]) + return default_double; + return toDouble(i); +} + +inline c10::complex PythonArgs::toComplex(int i) { + if (!args[i]) + return *(reinterpret_cast*>( + signature.params[i].default_complex)); + return THPUtils_unpackComplexDouble(args[i]); +} + +inline c10::complex PythonArgs::toComplexWithDefault( + int i, + c10::complex default_complex) { + if (!args[i]) + return default_complex; + return toComplex(i); +} + +inline bool PythonArgs::toBoolWithDefault(int i, bool default_bool) { + if (!args[i]) + return default_bool; + return toBool(i); +} + +inline bool PythonArgs::isNone(int i) { + return args[i] == nullptr; +} + +inline std::optional PythonArgs::generator(int i) { + if (!args[i]) + return std::nullopt; + return reinterpret_cast(args[i])->cdata; +} + +inline at::Storage PythonArgs::storage(int i) { + if (!args[i]) + return at::Storage(); + return createStorage(args[i]); +} + +inline at::Storage PythonArgs::storage( + int i, + at::ScalarType& storage_scalar_type, + bool& is_typed_storage) { + at::Storage storage; + if (!args[i]) { + storage = at::Storage(); + is_typed_storage = false; + storage_scalar_type = at::ScalarType::Undefined; + } else { + std::tie(storage, storage_scalar_type, is_typed_storage) = + createStorageGetType(args[i]); + } + return storage; +} + +inline c10::Stream PythonArgs::stream(int i) { + if (!args[i]) + return c10::Stream( + c10::Stream::Default::DEFAULT, c10::Device(c10::DeviceType::CPU, -1)); + if (!THPStream_Check(args[i])) { + TORCH_CHECK_TYPE( + false, + fmt::format( + "expected Stream object. Got '{}'", Py_TYPE(args[i])->tp_name)); + } + return c10::Stream::unpack3( + ((THPStream*)args[i])->stream_id, + static_cast(((THPStream*)args[i])->device_index), + static_cast(((THPStream*)args[i])->device_type)); +} + +inline PyObject* PythonArgs::pyobject(int i) { + if (!args[i]) + return Py_None; + return args[i]; +} + +/* + * + * Handle __torch_function__ overrides if we know that there are overloaded + * arguments. All objects stored in r.overloaded_args must have a + * __torch_function__ implementation and the arguments must be ordered in order + * of precedence. Precedence goes from left to right in the order of the + * signature of the function the overloaded arguments were passed to, except + * subclasses are always considered before superclasses. + * + * If the result of calling __torch_function__ is NotImplemented, the + * next implementation in the precedence order is called. If all + * arguments return NotImplemented from their __torch_function__ + * implementation, a TypeError is raised in Python. + * + * Assumes overloaded_args has at least one entry. All entries must have + * a __torch_function__ attribute that resolves to a callable that + * accepts a torch API function, a tuple of arguments, and a dict of + * keyword arguments for the torch API function. + * + * It is sufficient to call PythonArgs::has_torch_function before + * calling this function to verify that there are valid arguments + * present. If that is not done then special care must be taken to + * ensure there are arguments that are overloaded with + * __torch_function__. + * + * See torch._overrides.handle_torch_function for the equivalent + * code in the pure-python implementation. + * + * 'r' is a parsed PythonArgs instance, returned from + * PythonArgParser::parse. + * + * 'args' is a reference to the python tuple of arguments to the torch + * API function. + * + * 'kwargs' is a reference to the python dict of keyword arguments to + * the torch API function. + * + * 'torch_api' is a reference to a python torch API namespace. + * + * 'torch_api_function' is the reference to the original torch method, usually, + * we can use torch_api and func_name to get torch_api_function. In some cases, + * e.g., torch custom op, we create the function in C++, if we still use + * torch_api and func_name to fetch original api, a cyclic call will happen. + * + * 'overloaded_args' is the args which have overloaded __torch_function__. + * + * 'func_name' is the named of the original torch method. + * + * TODO: we could use different names for the following 'handle_torch_function' + * instead of overloading. + * + */ +// Used for Tensor methods with arguments. +auto handle_torch_function( + PythonArgs& r, + PyObject* self, + PyObject* args, + PyObject* kwargs, + PyObject* torch_api, + const char* module_name, + const char* func_name_override = nullptr) -> PyObject*; + +// Used for functions which needs to parse python args. +auto handle_torch_function( + PythonArgs& r, + PyObject* args, + PyObject* kwargs, + PyObject* torch_api, + const char* module_name, + const char* func_name_override = nullptr) -> PyObject*; + +// Used for functions that have no argument parsing. +auto handle_torch_function( + PyObject* self, + const std::string& func_name, + PyObject* args = nullptr, + PyObject* kwargs = nullptr, + PyObject* torch_api = THPVariableClass, + const std::string& module_name = "torch.Tensor") -> PyObject*; + +// Used for functions created in C++, e.g., C++ custom op, which doesn't use +// PythonArgParser to get overloaded_args. +enum class TorchFunctionName { TorchFunction, TorchDispatch }; + +auto TORCH_PYTHON_API handle_torch_function_no_python_arg_parser( + at::ArrayRef overloaded_args, + PyObject* args, + PyObject* kwargs, + const char* func_name, + PyObject* torch_api_function, + const char* module_name, + TorchFunctionName torch_function_name = TorchFunctionName::TorchFunction) + -> PyObject*; + +auto handle_torch_function_no_python_arg_parser( + at::ArrayRef overloaded_args, + PyObject* args, + PyObject* kwargs, + const char* func_name, + PyObject* torch_api_function, + const char* module_name, + const c10::OperatorHandle* opt_op, + torch::jit::Stack* opt_stack, + TorchFunctionName torch_function_name = TorchFunctionName::TorchFunction) + -> PyObject*; + +// Used for getters of Tensor properties +auto handle_torch_function_getter( + THPVariable* self, + const std::string& property_name) -> PyObject*; + +// Used for setters of Tensor properties. +auto handle_torch_function_setter( + THPVariable* self, + const std::string& property_name, + PyObject* value) -> int; + +// Used for __getitem__ and __setitem__ +auto handle_torch_function_indexing( + PyObject* self, + PyObject* index, + PyObject* val = nullptr) -> PyObject*; + +/* + * Check if the input obj is Tensor type, including its subclass, or overloaded + * type. If the type defines __torch_function__, it also returns true. + * Otherwise returns false. If the class is not torch.Tensor, and it defines + * __torch_function__, we append obj to overloaded_args. + * + * 'obj': the input argument to be checked + * 'overloaded_args': the vector to append the overloaded args. + */ +bool is_tensor_and_append_overloaded( + PyObject* obj, + std::vector* overloaded_args); + +/* + * Check if the input obj is Tensor List or Tensor Tuple type. First check + * whether obj is Tuple or List type, if true, iterate over each element and + * check whether it is Tensor type, including its subclass or overloaded type. + * At the same time, the overloaded arg is appended to the overloaded_args. + * + * 'obj': the input argument to be checked + * 'overloaded_args': the vector to append the overloaded args. + * 'argnum': the number of total arguments of the function being checked. + * 'throw_error': whether throw error if any element in the list or tuple is + * not tensor type or overloaded. + */ +bool is_tensor_list_and_append_overloaded( + PyObject* obj, + std::vector* overloaded_args, + size_t argnum, + bool throw_error); + +/* Given an argument that is definitely a tensor and is definitely overloaded, + * append it to the overloaded arguments list. Use this instead of + * is_tensor_and_append_overloaded in situations where you have a PyObject + * and you know it definitely is a Tensor and it is definitely overloaded. + * + * 'overloaded_args': the vector to append the overloaded args + * 'obj': the input tensor that is overloaded + */ +void append_overloaded_tensor( + std::vector* overloaded_args, + PyObject* obj); + +/* Given an argument that is definitely a type and is definitely overloaded, + * append it to the overloaded arguments list. Use this only with + * __torch_dispatch__, where we operate on classes that have a + * __torch_dispatch__ classmethod. + * + * 'overloaded_args': the vector to append the overloaded type + * 'obj': the input class that has a __torch_dispatch__ classmethod. + */ +void append_overloaded_type( + std::vector* overloaded_args, + PyObject* obj); + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_compat.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_compat.h new file mode 100644 index 0000000000000000000000000000000000000000..fe047faa9c15bf044dd80f1045a845b36c1878de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_compat.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#ifndef PYTHON_COMPAT +#define PYTHON_COMPAT + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// PyTorch-only compat functions + +#define IS_PYTHON_3_11_PLUS (PY_VERSION_HEX >= 0x030B00C1) +#define IS_PYTHON_3_12_PLUS (PY_VERSION_HEX >= 0x030C0000) +#define IS_PYTHON_3_13_PLUS (PY_VERSION_HEX >= 0x030D0000) +#define IS_PYTHON_3_14_PLUS (PY_VERSION_HEX >= 0x030E0000) +#define IS_PYTHON_3_15_PLUS (PY_VERSION_HEX >= 0x030F0000) + +static inline int PyCode_GetNCellvars(PyCodeObject* code) { +// gh-26364 added co_ncellvars to Python 3.11.0rc1 +#if IS_PYTHON_3_11_PLUS + return code->co_ncellvars; +#else + return PyTuple_GET_SIZE(code->co_cellvars); +#endif +} + +static inline int PyCode_GetNFreevars(PyCodeObject* code) { +// gh-26364 added co_nfreevars to Python 3.11.0rc1 +#if IS_PYTHON_3_11_PLUS + return code->co_nfreevars; +#else + return PyTuple_GET_SIZE(code->co_freevars); +#endif +} + +#ifdef __cplusplus +} +#endif +#endif // PYTHON_COMPAT + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_dispatch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3106c43acf60806568929f9e56338d7493ea32a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_dispatch.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#include + +namespace torch::impl::dispatch { + +void initDispatchBindings(PyObject* module); + +void python_op_registration_trampoline_impl( + const c10::OperatorHandle& op, + c10::DispatchKey key, + c10::DispatchKeySet keyset, + torch::jit::Stack* stack, + bool with_keyset, + bool with_op); + +} // namespace torch::impl::dispatch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_numbers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_numbers.h new file mode 100644 index 0000000000000000000000000000000000000000..371e793c508109be654ece27230f0603fab4f266 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_numbers.h @@ -0,0 +1,232 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// largest integer that can be represented consecutively in a double +const int64_t DOUBLE_INT_MAX = 9007199254740992; + +inline PyObject* THPUtils_packDeviceIndex(c10::DeviceIndex value) { + return PyLong_FromLong(value); +} + +inline PyObject* THPUtils_packInt32(int32_t value) { + return PyLong_FromLong(value); +} + +inline PyObject* THPUtils_packInt64(int64_t value) { + return PyLong_FromLongLong(value); +} + +inline PyObject* THPUtils_packUInt32(uint32_t value) { + return PyLong_FromUnsignedLong(value); +} + +inline PyObject* THPUtils_packUInt64(uint64_t value) { + return PyLong_FromUnsignedLongLong(value); +} + +inline PyObject* THPUtils_packDoubleAsInt(double value) { + return PyLong_FromDouble(value); +} + +inline bool THPUtils_checkLongExact(PyObject* obj) { + return PyLong_CheckExact(obj) && !PyBool_Check(obj); +} + +inline bool THPUtils_checkLong(PyObject* obj) { + // Fast path + if (THPUtils_checkLongExact(obj)) { + return true; + } + +#ifdef USE_NUMPY + if (torch::utils::is_numpy_int(obj)) { + return true; + } +#endif + + return PyLong_Check(obj) && !PyBool_Check(obj); +} + +inline int32_t THPUtils_unpackInt(PyObject* obj) { + int overflow = 0; + long value = PyLong_AsLongAndOverflow(obj, &overflow); + if (value == -1 && PyErr_Occurred()) { + throw python_error(); + } + TORCH_CHECK_VALUE(overflow == 0, "Overflow when unpacking long long"); + TORCH_CHECK_VALUE( + value <= std::numeric_limits::max() && + value >= std::numeric_limits::min(), + "Overflow when unpacking long"); + return (int32_t)value; +} + +inline int64_t THPUtils_unpackLong(PyObject* obj) { + int overflow = 0; + long long value = PyLong_AsLongLongAndOverflow(obj, &overflow); + if (value == -1 && PyErr_Occurred()) { + throw python_error(); + } + TORCH_CHECK_VALUE(overflow == 0, "Overflow when unpacking long long"); + return (int64_t)value; +} + +inline uint32_t THPUtils_unpackUInt32(PyObject* obj) { + unsigned long value = PyLong_AsUnsignedLong(obj); + if (PyErr_Occurred()) { + throw python_error(); + } + TORCH_CHECK_VALUE( + value <= std::numeric_limits::max(), + "Overflow when unpacking long long"); + return (uint32_t)value; +} + +inline uint64_t THPUtils_unpackUInt64(PyObject* obj) { + unsigned long long value = PyLong_AsUnsignedLongLong(obj); + if (PyErr_Occurred()) { + throw python_error(); + } + return (uint64_t)value; +} + +bool THPUtils_checkIndex(PyObject* obj); + +inline int64_t THPUtils_unpackIndex(PyObject* obj) { + if (!THPUtils_checkLong(obj)) { + auto index = THPObjectPtr(PyNumber_Index(obj)); + if (index == nullptr) { + throw python_error(); + } + // NB: This needs to be called before `index` goes out of scope and the + // underlying object's refcount is decremented + return THPUtils_unpackLong(index.get()); + } + return THPUtils_unpackLong(obj); +} + +inline bool THPUtils_unpackBool(PyObject* obj) { + if (obj == Py_True) { + return true; + } else if (obj == Py_False) { + return false; + } else { + TORCH_CHECK(false, "couldn't convert python object to boolean"); + } +} + +inline bool THPUtils_checkBool(PyObject* obj) { +#ifdef USE_NUMPY + if (torch::utils::is_numpy_bool(obj)) { + return true; + } +#endif + return PyBool_Check(obj); +} + +inline bool THPUtils_checkDouble(PyObject* obj) { +#ifdef USE_NUMPY + if (torch::utils::is_numpy_scalar(obj)) { + return true; + } +#endif + return PyFloat_Check(obj) || PyLong_Check(obj); +} + +inline double THPUtils_unpackDouble(PyObject* obj) { + if (PyFloat_Check(obj)) { + return PyFloat_AS_DOUBLE(obj); + } + double value = PyFloat_AsDouble(obj); + if (value == -1 && PyErr_Occurred()) { + throw python_error(); + } + return value; +} + +inline c10::complex THPUtils_unpackComplexDouble(PyObject* obj) { + Py_complex value = PyComplex_AsCComplex(obj); + if (value.real == -1.0 && PyErr_Occurred()) { + throw python_error(); + } + + return c10::complex(value.real, value.imag); +} + +inline bool THPUtils_unpackNumberAsBool(PyObject* obj) { +#ifdef USE_NUMPY + // Handle NumPy boolean scalars (np.bool_) + if (torch::utils::is_numpy_bool(obj)) { + int truth = PyObject_IsTrue(obj); + if (truth == -1) { + throw python_error(); + } + return truth != 0; + } +#endif + if (PyFloat_Check(obj)) { + return (bool)PyFloat_AS_DOUBLE(obj); + } + + if (PyComplex_Check(obj)) { + double real_val = PyComplex_RealAsDouble(obj); + double imag_val = PyComplex_ImagAsDouble(obj); + return !(real_val == 0 && imag_val == 0); + } + + int overflow = 0; + long long value = PyLong_AsLongLongAndOverflow(obj, &overflow); + if (value == -1 && PyErr_Occurred()) { + throw python_error(); + } + // No need to check overflow, because when overflow occurred, it should + // return true in order to keep the same behavior of numpy. + return (bool)value; +} + +inline c10::DeviceIndex THPUtils_unpackDeviceIndex(PyObject* obj) { + int overflow = 0; + long value = PyLong_AsLongAndOverflow(obj, &overflow); + if (value == -1 && PyErr_Occurred()) { + throw python_error(); + } + TORCH_CHECK(overflow == 0, "Overflow when unpacking DeviceIndex"); + TORCH_CHECK( + value <= std::numeric_limits::max() && + value >= std::numeric_limits::min(), + "Overflow when unpacking DeviceIndex"); + return (c10::DeviceIndex)value; +} + +template +inline T THPUtils_unpackInteger(PyObject* obj) { + int overflow = -1; + const auto value = PyLong_AsLongLongAndOverflow(obj, &overflow); + if (value == -1 && PyErr_Occurred()) { + throw python_error(); + } + if (!overflow) { + return static_cast(value); + } + // try unsigned + const auto uvalue = PyLong_AsUnsignedLongLong(obj); + if (uvalue == static_cast>(-1) && + PyErr_Occurred()) { + throw python_error(); + } + return static_cast(uvalue); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_raii.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_raii.h new file mode 100644 index 0000000000000000000000000000000000000000..25d0b62bf6fa77adc2c19cfe7cb921de7830a90c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_raii.h @@ -0,0 +1,89 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#include +#include + +namespace torch::impl { + +template +struct RAIIContextManager { + explicit RAIIContextManager(Args&&... args) + : args_(std::forward(args)...) {} + + void enter() { + auto emplace = [&](Args... args) { + guard_.emplace(std::forward(args)...); + }; + std::apply(std::move(emplace), args_); + } + + void exit() { + guard_ = std::nullopt; + } + + private: + std::optional guard_; + std::tuple args_; +}; + +// Turns a C++ RAII guard into a Python context manager. +// See _ExcludeDispatchKeyGuard in python_dispatch.cpp for example. +template +void py_context_manager(const py::module& m, const char* name) { + using ContextManagerT = RAIIContextManager; + py::class_(m, name) + .def(py::init()) + .def("__enter__", [](ContextManagerT& guard) { guard.enter(); }) + .def( + "__exit__", + [](ContextManagerT& guard, + const py::object& exc_type, + const py::object& exc_value, + const py::object& traceback) { guard.exit(); }); +} + +template +struct DeprecatedRAIIContextManager { + explicit DeprecatedRAIIContextManager(Args&&... args) { + guard_.emplace(std::forward(args)...); + } + + void enter() {} + + void exit() { + guard_ = std::nullopt; + } + + private: + std::optional guard_; + std::tuple args_; +}; + +// Definition: a "Python RAII guard" is an object in Python that acquires +// a resource on init and releases the resource on deletion. +// +// This API turns a C++ RAII guard into an object can be used either as a +// Python context manager or as a "Python RAII guard". +// +// Please prefer `py_context_manager` to this API if you are binding a new +// RAII guard into Python because "Python RAII guards" don't work as expected +// in Python (Python makes no guarantees about when an object gets deleted) +template +void py_context_manager_DEPRECATED(const py::module& m, const char* name) { + using ContextManagerT = DeprecatedRAIIContextManager; + py::class_(m, name) + .def(py::init()) + .def("__enter__", [](ContextManagerT& guard) { guard.enter(); }) + .def( + "__exit__", + [](ContextManagerT& guard, + const py::object& exc_type, + const py::object& exc_value, + const py::object& traceback) { guard.exit(); }); +} + +} // namespace torch::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_scalars.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_scalars.h new file mode 100644 index 0000000000000000000000000000000000000000..29ac9daf6016667b4143153dd637163bafa19f31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_scalars.h @@ -0,0 +1,173 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch::utils { + +template +inline T unpackIntegral(PyObject* obj, const char* type) { + // In Python-3.10 floats can no longer be silently converted to integers + // Keep backward compatible behavior for now + if (PyFloat_Check(obj)) { + return c10::checked_convert(THPUtils_unpackDouble(obj), type); + } + return c10::checked_convert(THPUtils_unpackLong(obj), type); +} + +inline void store_scalar(void* data, at::ScalarType scalarType, PyObject* obj) { + switch (scalarType) { + case at::kByte: + *(uint8_t*)data = unpackIntegral(obj, "uint8"); + break; + case at::kUInt16: + *(uint16_t*)data = unpackIntegral(obj, "uint16"); + break; + case at::kUInt32: + *(uint32_t*)data = unpackIntegral(obj, "uint32"); + break; + case at::kUInt64: + // NB: This doesn't allow implicit conversion of float to int + *(uint64_t*)data = THPUtils_unpackUInt64(obj); + break; + case at::kChar: + *(int8_t*)data = unpackIntegral(obj, "int8"); + break; + case at::kShort: + *(int16_t*)data = unpackIntegral(obj, "int16"); + break; + case at::kInt: + *(int32_t*)data = unpackIntegral(obj, "int32"); + break; + case at::kLong: + *(int64_t*)data = unpackIntegral(obj, "int64"); + break; + case at::kHalf: + *(at::Half*)data = + at::convert(THPUtils_unpackDouble(obj)); + break; + case at::kFloat: + *(float*)data = (float)THPUtils_unpackDouble(obj); + break; + case at::kDouble: + *(double*)data = THPUtils_unpackDouble(obj); + break; + case at::kComplexHalf: + *(c10::complex*)data = + (c10::complex)static_cast>( + THPUtils_unpackComplexDouble(obj)); + break; + case at::kComplexFloat: + *(c10::complex*)data = + (c10::complex)THPUtils_unpackComplexDouble(obj); + break; + case at::kComplexDouble: + *(c10::complex*)data = THPUtils_unpackComplexDouble(obj); + break; + case at::kBool: + *(bool*)data = THPUtils_unpackNumberAsBool(obj); + break; + case at::kBFloat16: + *(at::BFloat16*)data = + at::convert(THPUtils_unpackDouble(obj)); + break; + // TODO(#146647): simplify below with macros + case at::kFloat8_e5m2: + *(at::Float8_e5m2*)data = + at::convert(THPUtils_unpackDouble(obj)); + break; + case at::kFloat8_e5m2fnuz: + *(at::Float8_e5m2fnuz*)data = + at::convert(THPUtils_unpackDouble(obj)); + break; + case at::kFloat8_e4m3fn: + *(at::Float8_e4m3fn*)data = + at::convert(THPUtils_unpackDouble(obj)); + break; + case at::kFloat8_e4m3fnuz: + *(at::Float8_e4m3fnuz*)data = + at::convert(THPUtils_unpackDouble(obj)); + break; + case at::kFloat8_e8m0fnu: + *(at::Float8_e8m0fnu*)data = + at::convert(THPUtils_unpackDouble(obj)); + break; + default: + TORCH_CHECK(false, "store_scalar: invalid type"); + } +} + +inline PyObject* load_scalar(const void* data, at::ScalarType scalarType) { + switch (scalarType) { + case at::kByte: + return THPUtils_packInt64(*(uint8_t*)data); + case at::kUInt16: + return THPUtils_packInt64(*(uint16_t*)data); + case at::kUInt32: + return THPUtils_packUInt32(*(uint32_t*)data); + case at::kUInt64: + return THPUtils_packUInt64(*(uint64_t*)data); + case at::kChar: + return THPUtils_packInt64(*(int8_t*)data); + case at::kShort: + return THPUtils_packInt64(*(int16_t*)data); + case at::kInt: + return THPUtils_packInt64(*(int32_t*)data); + case at::kLong: + return THPUtils_packInt64(*(int64_t*)data); + case at::kHalf: + return PyFloat_FromDouble( + at::convert(*(at::Half*)data)); + case at::kFloat: + return PyFloat_FromDouble(*(float*)data); + case at::kDouble: + return PyFloat_FromDouble(*(double*)data); + case at::kComplexHalf: { + auto data_ = reinterpret_cast*>(data); + return PyComplex_FromDoubles(data_->real(), data_->imag()); + } + case at::kComplexFloat: { + auto data_ = reinterpret_cast*>(data); + return PyComplex_FromDoubles(data_->real(), data_->imag()); + } + case at::kComplexDouble: + return PyComplex_FromCComplex( + *reinterpret_cast((c10::complex*)data)); + case at::kBool: + // Don't use bool*, since it may take out-of-range byte as bool. + // Instead, we cast explicitly to avoid ASAN error. + return PyBool_FromLong(static_cast(*(uint8_t*)data)); + case at::kBFloat16: + return PyFloat_FromDouble( + at::convert(*(at::BFloat16*)data)); + // TODO(#146647): simplify below with macros + case at::kFloat8_e5m2: + return PyFloat_FromDouble( + at::convert(*(at::Float8_e5m2*)data)); + case at::kFloat8_e4m3fn: + return PyFloat_FromDouble( + at::convert(*(at::Float8_e4m3fn*)data)); + case at::kFloat8_e5m2fnuz: + return PyFloat_FromDouble(at::convert( + *(at::Float8_e5m2fnuz*)data)); + case at::kFloat8_e4m3fnuz: + return PyFloat_FromDouble(at::convert( + *(at::Float8_e4m3fnuz*)data)); + case at::kFloat8_e8m0fnu: + return PyFloat_FromDouble( + at::convert(*(at::Float8_e8m0fnu*)data)); + default: + TORCH_CHECK(false, "load_scalar: invalid type"); + } +} + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_strings.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_strings.h new file mode 100644 index 0000000000000000000000000000000000000000..bd4f0c88607cc0ad66f35162efe4433a7eb2ee99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_strings.h @@ -0,0 +1,140 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +// Utilities for handling Python strings. Note that PyString, when defined, is +// the same as PyBytes. + +// Returns true if obj is a bytes/str or unicode object +// As of Python 3.6, this does not require the GIL +inline bool THPUtils_checkString(PyObject* obj) { + return PyBytes_Check(obj) || PyUnicode_Check(obj); +} + +// Unpacks PyBytes (PyString) or PyUnicode as std::string +// PyBytes are unpacked as-is. PyUnicode is unpacked as UTF-8. +// NOTE: this method requires the GIL +inline std::string THPUtils_unpackString(PyObject* obj) { + if (PyBytes_Check(obj)) { + size_t size = PyBytes_GET_SIZE(obj); + return std::string(PyBytes_AS_STRING(obj), size); + } + if (PyUnicode_Check(obj)) { + Py_ssize_t size = 0; + const char* data = PyUnicode_AsUTF8AndSize(obj, &size); + TORCH_CHECK(data, "error unpacking string as utf-8"); + return std::string(data, (size_t)size); + } + TORCH_CHECK(false, "unpackString: expected bytes or unicode object"); +} + +// Unpacks PyBytes (PyString) or PyUnicode as std::string_view +// PyBytes are unpacked as-is. PyUnicode is unpacked as UTF-8. +// NOTE: If `obj` is destroyed, then the non-owning std::string_view will +// become invalid. If the string needs to be accessed at any point after +// `obj` is destroyed, then the std::string_view should be copied into +// a std::string, or another owning object, and kept alive. For an example, +// look at how IValue and autograd nodes handle std::string_view arguments. +// NOTE: this method requires the GIL +inline std::string_view THPUtils_unpackStringView(PyObject* obj) { + if (PyBytes_Check(obj)) { + size_t size = PyBytes_GET_SIZE(obj); + return std::string_view(PyBytes_AS_STRING(obj), size); + } + if (PyUnicode_Check(obj)) { + Py_ssize_t size = 0; + const char* data = PyUnicode_AsUTF8AndSize(obj, &size); + TORCH_CHECK(data, "error unpacking string as utf-8"); + return std::string_view(data, (size_t)size); + } + TORCH_CHECK(false, "unpackString: expected bytes or unicode object"); +} + +inline PyObject* THPUtils_packString(const char* str) { + return PyUnicode_FromString(str); +} + +inline PyObject* THPUtils_packString(const std::string& str) { + return PyUnicode_FromStringAndSize( + str.c_str(), static_cast(str.size())); +} + +inline PyObject* THPUtils_internString(const std::string& str) { + return PyUnicode_InternFromString(str.c_str()); +} + +// Precondition: THPUtils_checkString(obj) must be true +inline bool THPUtils_isInterned(PyObject* obj) { + return PyUnicode_CHECK_INTERNED(obj); +} + +// Precondition: THPUtils_checkString(obj) must be true +inline void THPUtils_internStringInPlace(PyObject** obj) { + PyUnicode_InternInPlace(obj); +} + +/* + * Reference: + * https://github.com/numpy/numpy/blob/f4c497c768e0646df740b647782df463825bfd27/numpy/core/src/common/get_attr_string.h#L42 + * + * Stripped down version of PyObject_GetAttrString, + * avoids lookups for None, tuple, and List objects, + * and doesn't create a PyErr since this code ignores it. + * + * This can be much faster then PyObject_GetAttrString where + * exceptions are not used by caller. + * + * 'obj' is the object to search for attribute. + * + * 'name' is the attribute to search for. + * + * Returns a py::object wrapping the return value. If the attribute lookup + * failed the value will be NULL. + * + */ + +inline py::object PyObject_FastGetAttrString(PyObject* obj, const char* name) { +#if IS_PYTHON_3_13_PLUS + PyObject* res = (PyObject*)nullptr; + int result_code = PyObject_GetOptionalAttrString(obj, name, &res); + if (result_code == -1) { + PyErr_Clear(); + } + return py::reinterpret_steal(res); +#else + PyTypeObject* tp = Py_TYPE(obj); + PyObject* res = (PyObject*)nullptr; + + /* Attribute referenced by (char *)name */ + if (tp->tp_getattr != nullptr) { + // This is OK per https://bugs.python.org/issue39620 + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + res = (*tp->tp_getattr)(obj, const_cast(name)); + if (res == nullptr) { + PyErr_Clear(); + } + } + /* Attribute referenced by (PyObject *)name */ + else if (tp->tp_getattro != nullptr) { + auto w = py::reinterpret_steal(PyUnicode_FromString(name)); + if (w.ptr() == nullptr) { + return py::object(); + } + res = (*tp->tp_getattro)(obj, w.ptr()); + if (res == nullptr) { + PyErr_Clear(); + } + } + return py::reinterpret_steal(res); +#endif +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_stub.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..f457be5949a775e9ce3f4b8b39d8c4bbe95985b8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_stub.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +struct _object; +using PyObject = _object; + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_symnode.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_symnode.h new file mode 100644 index 0000000000000000000000000000000000000000..793f050d3c1ec3faaab1ee97c4e8b2c5e8f38192 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_symnode.h @@ -0,0 +1,332 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch { + +TORCH_PYTHON_API py::handle get_symint_class(); +TORCH_PYTHON_API py::handle get_symfloat_class(); +TORCH_PYTHON_API py::handle get_symbool_class(); +TORCH_PYTHON_API py::handle get_dynint_class(); + +// NB: These functions must not be called too early, otherwise torch not setup. +// Alternate design is to have torch "register" the object to us +inline bool is_symint(py::handle obj) { + return py::isinstance(obj, get_symint_class()); +} +inline bool is_symfloat(py::handle obj) { + return py::isinstance(obj, get_symfloat_class()); +} +inline bool is_symbool(py::handle obj) { + return py::isinstance(obj, get_symbool_class()); +} +inline bool is_dynint(py::handle obj) { + return py::isinstance(obj, get_dynint_class()); +} + +namespace impl { + +// This c10::SymNodeImpl simply backends to a Python object that +// implements the API. The Python object is the source of truth, +// this is just an adapter so C++ calls can get to the object. +class PythonSymNodeImpl : public c10::SymNodeImpl { + public: + PythonSymNodeImpl(py::object pyobj) : c10::SymNodeImpl() { + pyobj_ = std::make_shared( + pyobj.release().ptr(), getPyInterpreter()); + } + + c10::SymNode wrap_int(int64_t num) override { + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr("wrap_int")(num); + return c10::make_intrusive(std::move(r)); + } + + c10::SymNode wrap_float(double num) override { + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr("wrap_float")(num); + return c10::make_intrusive(std::move(r)); + } + + c10::SymNode wrap_bool(bool num) override { + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr("wrap_bool")(num); + return c10::make_intrusive(std::move(r)); + } + +#define TORCH_SYMNODE_SIZES_STRIDES(n) \ + c10::SymNode n( \ + c10::ArrayRef sizes, c10::ArrayRef strides) \ + override { \ + py::gil_scoped_acquire acquire; \ + auto r = getPyObj().attr(#n)(sizes, strides); \ + return c10::make_intrusive(std::move(r)); \ + } + + // clang-format off + TORCH_SYMNODE_SIZES_STRIDES(is_contiguous) + TORCH_SYMNODE_SIZES_STRIDES(is_channels_last_contiguous_2d) + TORCH_SYMNODE_SIZES_STRIDES(is_channels_last_contiguous_3d) + TORCH_SYMNODE_SIZES_STRIDES(is_channels_last_strides_2d) + TORCH_SYMNODE_SIZES_STRIDES(is_channels_last_strides_3d) + TORCH_SYMNODE_SIZES_STRIDES(is_non_overlapping_and_dense) + // clang-format on + +#undef TORCH_SYMNODE_SIZES_STRIDES + + bool bool_() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("bool_")().is(py::handle(Py_True)); + } + + bool is_int() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("is_int")().is(py::handle(Py_True)); + } + + bool is_float() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("is_float")().is(py::handle(Py_True)); + } + + bool is_bool() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("is_bool")().is(py::handle(Py_True)); + } + + bool is_nested_int() const override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("is_nested_int")().is(py::handle(Py_True)); + } + + bool has_hint() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("has_hint")().is(py::handle(Py_True)); + } + + int64_t guard_int(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_int")(file, line).cast(); + } + + double guard_float(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_float")(file, line).cast(); + } + + bool guard_bool(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_bool")(file, line).cast(); + } + + bool expect_true(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("expect_true")(file, line).cast(); + } + + bool guard_size_oblivious(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_size_oblivious")(file, line).cast(); + } + + bool guard_or_false(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_or_false")(file, line).cast(); + } + + bool statically_known_true(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("statically_known_true")(file, line).cast(); + } + + bool guard_or_true(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_or_true")(file, line).cast(); + } + + int64_t int_() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("int_")().cast(); + } + + std::optional maybe_as_int() override { + py::gil_scoped_acquire acquire; + const auto& r = getPyObj().attr("maybe_as_int")(); + if (r.is_none()) { + return std::nullopt; + } else { + return r.cast(); + } + } + + std::string str() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("str")().cast(); + } + + std::string _graph_repr() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("_graph_repr")().cast(); + } + + c10::SymNode dispatch_sym_ite_( + const char* fname, + const c10::SymNode& other, + const c10::SymNode& third) { + auto pother = dynamic_cast(other.get()); + auto pthird = dynamic_cast(third.get()); + TORCH_CHECK(pother); + TORCH_CHECK(pthird); + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr(fname)(pother->getPyObj(), pthird->getPyObj()); + return c10::make_intrusive(r); + } + + c10::SymNode dispatch_common_(const char* fname, const c10::SymNode& other) { + auto pother = dynamic_cast(other.get()); + TORCH_CHECK(pother); + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr(fname)(pother->getPyObj()); + return c10::make_intrusive(r); + } + + c10::SymNode dispatch_common_(const char* fname) { + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr(fname)(); + return c10::make_intrusive(r); + } + + c10::SymNode add(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sub(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode mul(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode truediv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode float_truediv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode int_truediv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode pow(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode float_pow(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode pow_by_natural(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode floordiv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode int_floordiv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode mod(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode eq(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode ne(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode gt(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode lt(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode le(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode ge(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sym_min(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + c10::SymNode sym_max(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sym_and(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sym_or(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sym_ite(const c10::SymNode& other, const c10::SymNode& third) + override { + return dispatch_sym_ite_(__func__, other, third); + } + + c10::SymNode sym_not() override { + return dispatch_common_(__func__); + } + + c10::SymNode ceil() override { + return dispatch_common_(__func__); + } + + c10::SymNode floor() override { + return dispatch_common_(__func__); + } + + c10::SymNode neg() override { + return dispatch_common_(__func__); + } + + c10::SymNode clone() override { + return dispatch_common_(__func__); + } + + c10::SymNode sym_float() override { + return dispatch_common_(__func__); + } + + py::handle getPyObj() const { + return py::handle(pyobj_->ptr(getPyInterpreter())); + } + std::shared_ptr pyobj_ = nullptr; +}; + +} // namespace impl +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_torch_function_mode.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_torch_function_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..32fbbeb84b814e0c13d1203efa80d4d5362d14eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_torch_function_mode.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::overrides { + +struct StashTorchFunctionModeGuard { + StashTorchFunctionModeGuard() { + cur_mode_ = at::impl::PythonTorchFunctionTLS::pop_stack(); + } + ~StashTorchFunctionModeGuard() { + at::impl::PythonTorchFunctionTLS::push_onto_stack(cur_mode_); + } + StashTorchFunctionModeGuard(const StashTorchFunctionModeGuard&) = delete; + StashTorchFunctionModeGuard(StashTorchFunctionModeGuard&&) = delete; + StashTorchFunctionModeGuard& operator=(const StashTorchFunctionModeGuard&) = + delete; + StashTorchFunctionModeGuard& operator=(StashTorchFunctionModeGuard&&) = + delete; + + const std::shared_ptr& get_cur_mode() { + return cur_mode_; + } + + private: + std::shared_ptr cur_mode_; +}; + +} // namespace torch::overrides + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_tuples.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_tuples.h new file mode 100644 index 0000000000000000000000000000000000000000..8a35c34d5d9ed11af34d2871b906a1f2582ff47c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_tuples.h @@ -0,0 +1,32 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +inline void THPUtils_packInt64Array( + PyObject* tuple, + size_t size, + const int64_t* sizes) { + for (size_t i = 0; i != size; ++i) { + PyObject* i64 = THPUtils_packInt64(sizes[i]); + if (!i64) { + throw python_error(); + } + PyTuple_SET_ITEM(tuple, i, i64); + } +} + +inline PyObject* THPUtils_packInt64Array(size_t size, const int64_t* sizes) { + THPObjectPtr tuple(PyTuple_New(static_cast(size))); + if (!tuple) + throw python_error(); + THPUtils_packInt64Array(tuple.get(), size, sizes); + return tuple.release(); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pythoncapi_compat.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pythoncapi_compat.h new file mode 100644 index 0000000000000000000000000000000000000000..59f61c5514198f4defaaa01d9f1300712c0a8845 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pythoncapi_compat.h @@ -0,0 +1,2671 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Header file providing new C API functions to old Python versions. +// +// File distributed under the Zero Clause BSD (0BSD) license. +// Copyright Contributors to the pythoncapi_compat project. +// +// Homepage: +// https://github.com/python/pythoncapi_compat +// +// Latest version: +// https://raw.githubusercontent.com/python/pythoncapi-compat/main/pythoncapi_compat.h +// +// SPDX-License-Identifier: 0BSD + +#ifndef PYTHONCAPI_COMPAT +#define PYTHONCAPI_COMPAT + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include // offsetof() + +// Python 3.11.0b4 added PyFrame_Back() to Python.h +#if PY_VERSION_HEX < 0x030b00B4 && !defined(PYPY_VERSION) +# include "frameobject.h" // PyFrameObject, PyFrame_GetBack() +#endif + + +#ifndef _Py_CAST +# define _Py_CAST(type, expr) ((type)(expr)) +#endif + +// Static inline functions should use _Py_NULL rather than using directly NULL +// to prevent C++ compiler warnings. On C23 and newer and on C++11 and newer, +// _Py_NULL is defined as nullptr. +#ifndef _Py_NULL +# if (defined (__STDC_VERSION__) && __STDC_VERSION__ > 201710L) \ + || (defined(__cplusplus) && __cplusplus >= 201103) +# define _Py_NULL nullptr +# else +# define _Py_NULL NULL +# endif +#endif + +// Cast argument to PyObject* type. +#ifndef _PyObject_CAST +# define _PyObject_CAST(op) _Py_CAST(PyObject*, op) +#endif + +#ifndef Py_BUILD_ASSERT +# define Py_BUILD_ASSERT(cond) \ + do { \ + (void)sizeof(char [1 - 2 * !(cond)]); \ + } while(0) +#endif + + +// bpo-42262 added Py_NewRef() to Python 3.10.0a3 +#if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_NewRef) +static inline PyObject* _Py_NewRef(PyObject *obj) +{ + Py_INCREF(obj); + return obj; +} +#define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj)) +#endif + + +// bpo-42262 added Py_XNewRef() to Python 3.10.0a3 +#if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_XNewRef) +static inline PyObject* _Py_XNewRef(PyObject *obj) +{ + Py_XINCREF(obj); + return obj; +} +#define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj)) +#endif + + +// bpo-39573 added Py_SET_REFCNT() to Python 3.9.0a4 +#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_REFCNT) +static inline void _Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) +{ + ob->ob_refcnt = refcnt; +} +#define Py_SET_REFCNT(ob, refcnt) _Py_SET_REFCNT(_PyObject_CAST(ob), refcnt) +#endif + + +// Py_SETREF() and Py_XSETREF() were added to Python 3.5.2. +// It is excluded from the limited C API. +#if (PY_VERSION_HEX < 0x03050200 && !defined(Py_SETREF)) && !defined(Py_LIMITED_API) +#define Py_SETREF(dst, src) \ + do { \ + PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \ + PyObject *_tmp_dst = (*_tmp_dst_ptr); \ + *_tmp_dst_ptr = _PyObject_CAST(src); \ + Py_DECREF(_tmp_dst); \ + } while (0) + +#define Py_XSETREF(dst, src) \ + do { \ + PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \ + PyObject *_tmp_dst = (*_tmp_dst_ptr); \ + *_tmp_dst_ptr = _PyObject_CAST(src); \ + Py_XDECREF(_tmp_dst); \ + } while (0) +#endif + + +// bpo-43753 added Py_Is(), Py_IsNone(), Py_IsTrue() and Py_IsFalse() +// to Python 3.10.0b1. +#if PY_VERSION_HEX < 0x030A00B1 && !defined(Py_Is) +# define Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX < 0x030A00B1 && !defined(Py_IsNone) +# define Py_IsNone(x) Py_Is(x, Py_None) +#endif +#if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && !defined(Py_IsTrue) +# define Py_IsTrue(x) Py_Is(x, Py_True) +#endif +#if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && !defined(Py_IsFalse) +# define Py_IsFalse(x) Py_Is(x, Py_False) +#endif + + +// bpo-39573 added Py_SET_TYPE() to Python 3.9.0a4 +#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE) +static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type) +{ + ob->ob_type = type; +} +#define Py_SET_TYPE(ob, type) _Py_SET_TYPE(_PyObject_CAST(ob), type) +#endif + + +// bpo-39573 added Py_SET_SIZE() to Python 3.9.0a4 +#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE) +static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) +{ + ob->ob_size = size; +} +#define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size) +#endif + + +// bpo-40421 added PyFrame_GetCode() to Python 3.9.0b1 +#if PY_VERSION_HEX < 0x030900B1 || defined(PYPY_VERSION) +static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame) +{ + assert(frame != _Py_NULL); + assert(frame->f_code != _Py_NULL); + return _Py_CAST(PyCodeObject*, Py_NewRef(frame->f_code)); +} +#endif + +static inline PyCodeObject* _PyFrame_GetCodeBorrow(PyFrameObject *frame) +{ + PyCodeObject *code = PyFrame_GetCode(frame); + Py_DECREF(code); + return code; +} + + +// bpo-40421 added PyFrame_GetBack() to Python 3.9.0b1 +#if PY_VERSION_HEX < 0x030900B1 && !defined(PYPY_VERSION) +static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame) +{ + assert(frame != _Py_NULL); + return _Py_CAST(PyFrameObject*, Py_XNewRef(frame->f_back)); +} +#endif + +#if !defined(PYPY_VERSION) +static inline PyFrameObject* _PyFrame_GetBackBorrow(PyFrameObject *frame) +{ + PyFrameObject *back = PyFrame_GetBack(frame); + Py_XDECREF(back); + return back; +} +#endif + + +// bpo-40421 added PyFrame_GetLocals() to Python 3.11.0a7 +#if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION) +static inline PyObject* PyFrame_GetLocals(PyFrameObject *frame) +{ +#if PY_VERSION_HEX >= 0x030400B1 + if (PyFrame_FastToLocalsWithError(frame) < 0) { + return NULL; + } +#else + PyFrame_FastToLocals(frame); +#endif + return Py_NewRef(frame->f_locals); +} +#endif + + +// bpo-40421 added PyFrame_GetGlobals() to Python 3.11.0a7 +#if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION) +static inline PyObject* PyFrame_GetGlobals(PyFrameObject *frame) +{ + return Py_NewRef(frame->f_globals); +} +#endif + + +// bpo-40421 added PyFrame_GetBuiltins() to Python 3.11.0a7 +#if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION) +static inline PyObject* PyFrame_GetBuiltins(PyFrameObject *frame) +{ + return Py_NewRef(frame->f_builtins); +} +#endif + + +// bpo-40421 added PyFrame_GetLasti() to Python 3.11.0b1 +#if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION) +static inline int PyFrame_GetLasti(PyFrameObject *frame) +{ +#if PY_VERSION_HEX >= 0x030A00A7 + // bpo-27129: Since Python 3.10.0a7, f_lasti is an instruction offset, + // not a bytes offset anymore. Python uses 16-bit "wordcode" (2 bytes) + // instructions. + if (frame->f_lasti < 0) { + return -1; + } + return frame->f_lasti * 2; +#else + return frame->f_lasti; +#endif +} +#endif + + +// gh-91248 added PyFrame_GetVar() to Python 3.12.0a2 +#if PY_VERSION_HEX < 0x030C00A2 && !defined(PYPY_VERSION) +static inline PyObject* PyFrame_GetVar(PyFrameObject *frame, PyObject *name) +{ + PyObject *locals, *value; + + locals = PyFrame_GetLocals(frame); + if (locals == NULL) { + return NULL; + } +#if PY_VERSION_HEX >= 0x03000000 + value = PyDict_GetItemWithError(locals, name); +#else + value = _PyDict_GetItemWithError(locals, name); +#endif + Py_DECREF(locals); + + if (value == NULL) { + if (PyErr_Occurred()) { + return NULL; + } +#if PY_VERSION_HEX >= 0x03000000 + PyErr_Format(PyExc_NameError, "variable %R does not exist", name); +#else + PyErr_SetString(PyExc_NameError, "variable does not exist"); +#endif + return NULL; + } + return Py_NewRef(value); +} +#endif + + +// gh-91248 added PyFrame_GetVarString() to Python 3.12.0a2 +#if PY_VERSION_HEX < 0x030C00A2 && !defined(PYPY_VERSION) +static inline PyObject* +PyFrame_GetVarString(PyFrameObject *frame, const char *name) +{ + PyObject *name_obj, *value; +#if PY_VERSION_HEX >= 0x03000000 + name_obj = PyUnicode_FromString(name); +#else + name_obj = PyString_FromString(name); +#endif + if (name_obj == NULL) { + return NULL; + } + value = PyFrame_GetVar(frame, name_obj); + Py_DECREF(name_obj); + return value; +} +#endif + + +// bpo-39947 added PyThreadState_GetInterpreter() to Python 3.9.0a5 +#if PY_VERSION_HEX < 0x030900A5 || (defined(PYPY_VERSION) && PY_VERSION_HEX < 0x030B0000) +static inline PyInterpreterState * +PyThreadState_GetInterpreter(PyThreadState *tstate) +{ + assert(tstate != _Py_NULL); + return tstate->interp; +} +#endif + + +// bpo-40429 added PyThreadState_GetFrame() to Python 3.9.0b1 +#if PY_VERSION_HEX < 0x030900B1 && !defined(PYPY_VERSION) +static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate) +{ + assert(tstate != _Py_NULL); + return _Py_CAST(PyFrameObject *, Py_XNewRef(tstate->frame)); +} +#endif + +#if !defined(PYPY_VERSION) +static inline PyFrameObject* +_PyThreadState_GetFrameBorrow(PyThreadState *tstate) +{ + PyFrameObject *frame = PyThreadState_GetFrame(tstate); + Py_XDECREF(frame); + return frame; +} +#endif + + +// bpo-39947 added PyInterpreterState_Get() to Python 3.9.0a5 +#if PY_VERSION_HEX < 0x030900A5 || defined(PYPY_VERSION) +static inline PyInterpreterState* PyInterpreterState_Get(void) +{ + PyThreadState *tstate; + PyInterpreterState *interp; + + tstate = PyThreadState_GET(); + if (tstate == _Py_NULL) { + Py_FatalError("GIL released (tstate is NULL)"); + } + interp = tstate->interp; + if (interp == _Py_NULL) { + Py_FatalError("no current interpreter"); + } + return interp; +} +#endif + + +// bpo-39947 added PyInterpreterState_Get() to Python 3.9.0a6 +#if 0x030700A1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030900A6 && !defined(PYPY_VERSION) +static inline uint64_t PyThreadState_GetID(PyThreadState *tstate) +{ + assert(tstate != _Py_NULL); + return tstate->id; +} +#endif + +// bpo-43760 added PyThreadState_EnterTracing() to Python 3.11.0a2 +#if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION) +static inline void PyThreadState_EnterTracing(PyThreadState *tstate) +{ + tstate->tracing++; +#if PY_VERSION_HEX >= 0x030A00A1 + tstate->cframe->use_tracing = 0; +#else + tstate->use_tracing = 0; +#endif +} +#endif + +// bpo-43760 added PyThreadState_LeaveTracing() to Python 3.11.0a2 +#if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION) +static inline void PyThreadState_LeaveTracing(PyThreadState *tstate) +{ + int use_tracing = (tstate->c_tracefunc != _Py_NULL + || tstate->c_profilefunc != _Py_NULL); + tstate->tracing--; +#if PY_VERSION_HEX >= 0x030A00A1 + tstate->cframe->use_tracing = use_tracing; +#else + tstate->use_tracing = use_tracing; +#endif +} +#endif + + +// bpo-37194 added PyObject_CallNoArgs() to Python 3.9.0a1 +// PyObject_CallNoArgs() added to PyPy 3.9.16-v7.3.11 +#if !defined(PyObject_CallNoArgs) && PY_VERSION_HEX < 0x030900A1 +static inline PyObject* PyObject_CallNoArgs(PyObject *func) +{ + return PyObject_CallFunctionObjArgs(func, NULL); +} +#endif + + +// bpo-39245 made PyObject_CallOneArg() public (previously called +// _PyObject_CallOneArg) in Python 3.9.0a4 +// PyObject_CallOneArg() added to PyPy 3.9.16-v7.3.11 +#if !defined(PyObject_CallOneArg) && PY_VERSION_HEX < 0x030900A4 +static inline PyObject* PyObject_CallOneArg(PyObject *func, PyObject *arg) +{ + return PyObject_CallFunctionObjArgs(func, arg, NULL); +} +#endif + + +// bpo-1635741 added PyModule_AddObjectRef() to Python 3.10.0a3 +#if PY_VERSION_HEX < 0x030A00A3 +static inline int +PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value) +{ + int res; + + if (!value && !PyErr_Occurred()) { + // PyModule_AddObject() raises TypeError in this case + PyErr_SetString(PyExc_SystemError, + "PyModule_AddObjectRef() must be called " + "with an exception raised if value is NULL"); + return -1; + } + + Py_XINCREF(value); + res = PyModule_AddObject(module, name, value); + if (res < 0) { + Py_XDECREF(value); + } + return res; +} +#endif + + +// bpo-40024 added PyModule_AddType() to Python 3.9.0a5 +#if PY_VERSION_HEX < 0x030900A5 +static inline int PyModule_AddType(PyObject *module, PyTypeObject *type) +{ + const char *name, *dot; + + if (PyType_Ready(type) < 0) { + return -1; + } + + // inline _PyType_Name() + name = type->tp_name; + assert(name != _Py_NULL); + dot = strrchr(name, '.'); + if (dot != _Py_NULL) { + name = dot + 1; + } + + return PyModule_AddObjectRef(module, name, _PyObject_CAST(type)); +} +#endif + + +// bpo-40241 added PyObject_GC_IsTracked() to Python 3.9.0a6. +// bpo-4688 added _PyObject_GC_IS_TRACKED() to Python 2.7.0a2. +#if PY_VERSION_HEX < 0x030900A6 && !defined(PYPY_VERSION) +static inline int PyObject_GC_IsTracked(PyObject* obj) +{ + return (PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj)); +} +#endif + +// bpo-40241 added PyObject_GC_IsFinalized() to Python 3.9.0a6. +// bpo-18112 added _PyGCHead_FINALIZED() to Python 3.4.0 final. +#if PY_VERSION_HEX < 0x030900A6 && PY_VERSION_HEX >= 0x030400F0 && !defined(PYPY_VERSION) +static inline int PyObject_GC_IsFinalized(PyObject *obj) +{ + PyGC_Head *gc = _Py_CAST(PyGC_Head*, obj) - 1; + return (PyObject_IS_GC(obj) && _PyGCHead_FINALIZED(gc)); +} +#endif + + +// bpo-39573 added Py_IS_TYPE() to Python 3.9.0a4 +#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_IS_TYPE) +static inline int _Py_IS_TYPE(PyObject *ob, PyTypeObject *type) { + return Py_TYPE(ob) == type; +} +#define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST(ob), type) +#endif + + +// bpo-46906 added PyFloat_Pack2() and PyFloat_Unpack2() to Python 3.11a7. +// bpo-11734 added _PyFloat_Pack2() and _PyFloat_Unpack2() to Python 3.6.0b1. +// Python 3.11a2 moved _PyFloat_Pack2() and _PyFloat_Unpack2() to the internal +// C API: Python 3.11a2-3.11a6 versions are not supported. +#if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION) +static inline int PyFloat_Pack2(double x, char *p, int le) +{ return _PyFloat_Pack2(x, (unsigned char*)p, le); } + +static inline double PyFloat_Unpack2(const char *p, int le) +{ return _PyFloat_Unpack2((const unsigned char *)p, le); } +#endif + + +// bpo-46906 added PyFloat_Pack4(), PyFloat_Pack8(), PyFloat_Unpack4() and +// PyFloat_Unpack8() to Python 3.11a7. +// Python 3.11a2 moved _PyFloat_Pack4(), _PyFloat_Pack8(), _PyFloat_Unpack4() +// and _PyFloat_Unpack8() to the internal C API: Python 3.11a2-3.11a6 versions +// are not supported. +#if PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION) +static inline int PyFloat_Pack4(double x, char *p, int le) +{ return _PyFloat_Pack4(x, (unsigned char*)p, le); } + +static inline int PyFloat_Pack8(double x, char *p, int le) +{ return _PyFloat_Pack8(x, (unsigned char*)p, le); } + +static inline double PyFloat_Unpack4(const char *p, int le) +{ return _PyFloat_Unpack4((const unsigned char *)p, le); } + +static inline double PyFloat_Unpack8(const char *p, int le) +{ return _PyFloat_Unpack8((const unsigned char *)p, le); } +#endif + + +// gh-92154 added PyCode_GetCode() to Python 3.11.0b1 +#if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION) +static inline PyObject* PyCode_GetCode(PyCodeObject *code) +{ + return Py_NewRef(code->co_code); +} +#endif + + +// gh-95008 added PyCode_GetVarnames() to Python 3.11.0rc1 +#if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION) +static inline PyObject* PyCode_GetVarnames(PyCodeObject *code) +{ + return Py_NewRef(code->co_varnames); +} +#endif + +// gh-95008 added PyCode_GetFreevars() to Python 3.11.0rc1 +#if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION) +static inline PyObject* PyCode_GetFreevars(PyCodeObject *code) +{ + return Py_NewRef(code->co_freevars); +} +#endif + +// gh-95008 added PyCode_GetCellvars() to Python 3.11.0rc1 +#if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION) +static inline PyObject* PyCode_GetCellvars(PyCodeObject *code) +{ + return Py_NewRef(code->co_cellvars); +} +#endif + + +// Py_UNUSED() was added to Python 3.4.0b2. +#if PY_VERSION_HEX < 0x030400B2 && !defined(Py_UNUSED) +# if defined(__GNUC__) || defined(__clang__) +# define Py_UNUSED(name) _unused_ ## name __attribute__((unused)) +# else +# define Py_UNUSED(name) _unused_ ## name +# endif +#endif + + +// gh-105922 added PyImport_AddModuleRef() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A0 +static inline PyObject* PyImport_AddModuleRef(const char *name) +{ + return Py_XNewRef(PyImport_AddModule(name)); +} +#endif + + +// gh-105927 added PyWeakref_GetRef() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D0000 +static inline int PyWeakref_GetRef(PyObject *ref, PyObject **pobj) +{ + PyObject *obj; + if (ref != NULL && !PyWeakref_Check(ref)) { + *pobj = NULL; + PyErr_SetString(PyExc_TypeError, "expected a weakref"); + return -1; + } + obj = PyWeakref_GetObject(ref); + if (obj == NULL) { + // SystemError if ref is NULL + *pobj = NULL; + return -1; + } + if (obj == Py_None) { + *pobj = NULL; + return 0; + } + *pobj = Py_NewRef(obj); + return 1; +} +#endif + + +// bpo-36974 added PY_VECTORCALL_ARGUMENTS_OFFSET to Python 3.8b1 +#ifndef PY_VECTORCALL_ARGUMENTS_OFFSET +# define PY_VECTORCALL_ARGUMENTS_OFFSET (_Py_CAST(size_t, 1) << (8 * sizeof(size_t) - 1)) +#endif + +// bpo-36974 added PyVectorcall_NARGS() to Python 3.8b1 +#if PY_VERSION_HEX < 0x030800B1 +static inline Py_ssize_t PyVectorcall_NARGS(size_t n) +{ + return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET; +} +#endif + + +// gh-105922 added PyObject_Vectorcall() to Python 3.9.0a4 +#if PY_VERSION_HEX < 0x030900A4 +static inline PyObject* +PyObject_Vectorcall(PyObject *callable, PyObject *const *args, + size_t nargsf, PyObject *kwnames) +{ +#if PY_VERSION_HEX >= 0x030800B1 && !defined(PYPY_VERSION) + // bpo-36974 added _PyObject_Vectorcall() to Python 3.8.0b1 + return _PyObject_Vectorcall(callable, args, nargsf, kwnames); +#else + PyObject *posargs = NULL, *kwargs = NULL; + PyObject *res; + Py_ssize_t nposargs, nkwargs, i; + + if (nargsf != 0 && args == NULL) { + PyErr_BadInternalCall(); + goto error; + } + if (kwnames != NULL && !PyTuple_Check(kwnames)) { + PyErr_BadInternalCall(); + goto error; + } + + nposargs = (Py_ssize_t)PyVectorcall_NARGS(nargsf); + if (kwnames) { + nkwargs = PyTuple_GET_SIZE(kwnames); + } + else { + nkwargs = 0; + } + + posargs = PyTuple_New(nposargs); + if (posargs == NULL) { + goto error; + } + if (nposargs) { + for (i=0; i < nposargs; i++) { + PyTuple_SET_ITEM(posargs, i, Py_NewRef(*args)); + args++; + } + } + + if (nkwargs) { + kwargs = PyDict_New(); + if (kwargs == NULL) { + goto error; + } + + for (i = 0; i < nkwargs; i++) { + PyObject *key = PyTuple_GET_ITEM(kwnames, i); + PyObject *value = *args; + args++; + if (PyDict_SetItem(kwargs, key, value) < 0) { + goto error; + } + } + } + else { + kwargs = NULL; + } + + res = PyObject_Call(callable, posargs, kwargs); + Py_DECREF(posargs); + Py_XDECREF(kwargs); + return res; + +error: + Py_DECREF(posargs); + Py_XDECREF(kwargs); + return NULL; +#endif +} +#endif + + +// gh-106521 added PyObject_GetOptionalAttr() and +// PyObject_GetOptionalAttrString() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int +PyObject_GetOptionalAttr(PyObject *obj, PyObject *attr_name, PyObject **result) +{ + // bpo-32571 added _PyObject_LookupAttr() to Python 3.7.0b1 +#if PY_VERSION_HEX >= 0x030700B1 && !defined(PYPY_VERSION) + return _PyObject_LookupAttr(obj, attr_name, result); +#else + *result = PyObject_GetAttr(obj, attr_name); + if (*result != NULL) { + return 1; + } + if (!PyErr_Occurred()) { + return 0; + } + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + return 0; + } + return -1; +#endif +} + +static inline int +PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result) +{ + PyObject *name_obj; + int rc; +#if PY_VERSION_HEX >= 0x03000000 + name_obj = PyUnicode_FromString(attr_name); +#else + name_obj = PyString_FromString(attr_name); +#endif + if (name_obj == NULL) { + *result = NULL; + return -1; + } + rc = PyObject_GetOptionalAttr(obj, name_obj, result); + Py_DECREF(name_obj); + return rc; +} +#endif + + +// gh-106307 added PyObject_GetOptionalAttr() and +// PyMapping_GetOptionalItemString() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int +PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result) +{ + *result = PyObject_GetItem(obj, key); + if (*result) { + return 1; + } + if (!PyErr_ExceptionMatches(PyExc_KeyError)) { + return -1; + } + PyErr_Clear(); + return 0; +} + +static inline int +PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result) +{ + PyObject *key_obj; + int rc; +#if PY_VERSION_HEX >= 0x03000000 + key_obj = PyUnicode_FromString(key); +#else + key_obj = PyString_FromString(key); +#endif + if (key_obj == NULL) { + *result = NULL; + return -1; + } + rc = PyMapping_GetOptionalItem(obj, key_obj, result); + Py_DECREF(key_obj); + return rc; +} +#endif + +// gh-108511 added PyMapping_HasKeyWithError() and +// PyMapping_HasKeyStringWithError() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int +PyMapping_HasKeyWithError(PyObject *obj, PyObject *key) +{ + PyObject *res; + int rc = PyMapping_GetOptionalItem(obj, key, &res); + Py_XDECREF(res); + return rc; +} + +static inline int +PyMapping_HasKeyStringWithError(PyObject *obj, const char *key) +{ + PyObject *res; + int rc = PyMapping_GetOptionalItemString(obj, key, &res); + Py_XDECREF(res); + return rc; +} +#endif + + +// gh-108511 added PyObject_HasAttrWithError() and +// PyObject_HasAttrStringWithError() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int +PyObject_HasAttrWithError(PyObject *obj, PyObject *attr) +{ + PyObject *res; + int rc = PyObject_GetOptionalAttr(obj, attr, &res); + Py_XDECREF(res); + return rc; +} + +static inline int +PyObject_HasAttrStringWithError(PyObject *obj, const char *attr) +{ + PyObject *res; + int rc = PyObject_GetOptionalAttrString(obj, attr, &res); + Py_XDECREF(res); + return rc; +} +#endif + + +// gh-106004 added PyDict_GetItemRef() and PyDict_GetItemStringRef() +// to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int +PyDict_GetItemRef(PyObject *mp, PyObject *key, PyObject **result) +{ +#if PY_VERSION_HEX >= 0x03000000 + PyObject *item = PyDict_GetItemWithError(mp, key); +#else + PyObject *item = _PyDict_GetItemWithError(mp, key); +#endif + if (item != NULL) { + *result = Py_NewRef(item); + return 1; // found + } + if (!PyErr_Occurred()) { + *result = NULL; + return 0; // not found + } + *result = NULL; + return -1; +} + +static inline int +PyDict_GetItemStringRef(PyObject *mp, const char *key, PyObject **result) +{ + int res; +#if PY_VERSION_HEX >= 0x03000000 + PyObject *key_obj = PyUnicode_FromString(key); +#else + PyObject *key_obj = PyString_FromString(key); +#endif + if (key_obj == NULL) { + *result = NULL; + return -1; + } + res = PyDict_GetItemRef(mp, key_obj, result); + Py_DECREF(key_obj); + return res; +} +#endif + + +// gh-106307 added PyModule_Add() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int +PyModule_Add(PyObject *mod, const char *name, PyObject *value) +{ + int res = PyModule_AddObjectRef(mod, name, value); + Py_XDECREF(value); + return res; +} +#endif + + +// gh-108014 added Py_IsFinalizing() to Python 3.13.0a1 +// bpo-1856 added _Py_Finalizing to Python 3.2.1b1. +// _Py_IsFinalizing() was added to PyPy 7.3.0. +#if (0x030201B1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030D00A1) \ + && (!defined(PYPY_VERSION_NUM) || PYPY_VERSION_NUM >= 0x7030000) +static inline int Py_IsFinalizing(void) +{ +#if PY_VERSION_HEX >= 0x030700A1 + // _Py_IsFinalizing() was added to Python 3.7.0a1. + return _Py_IsFinalizing(); +#else + return (_Py_Finalizing != NULL); +#endif +} +#endif + + +// gh-108323 added PyDict_ContainsString() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int PyDict_ContainsString(PyObject *op, const char *key) +{ + PyObject *key_obj = PyUnicode_FromString(key); + if (key_obj == NULL) { + return -1; + } + int res = PyDict_Contains(op, key_obj); + Py_DECREF(key_obj); + return res; +} +#endif + + +// gh-108445 added PyLong_AsInt() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int PyLong_AsInt(PyObject *obj) +{ +#ifdef PYPY_VERSION + long value = PyLong_AsLong(obj); + if (value == -1 && PyErr_Occurred()) { + return -1; + } + if (value < (long)INT_MIN || (long)INT_MAX < value) { + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C int"); + return -1; + } + return (int)value; +#else + return _PyLong_AsInt(obj); +#endif +} +#endif + + +// gh-107073 added PyObject_VisitManagedDict() to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int +PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg) +{ + PyObject **dict = _PyObject_GetDictPtr(obj); + if (dict == NULL || *dict == NULL) { + return -1; + } + Py_VISIT(*dict); + return 0; +} + +static inline void +PyObject_ClearManagedDict(PyObject *obj) +{ + PyObject **dict = _PyObject_GetDictPtr(obj); + if (dict == NULL || *dict == NULL) { + return; + } + Py_CLEAR(*dict); +} +#endif + +// gh-108867 added PyThreadState_GetUnchecked() to Python 3.13.0a1 +// Python 3.5.2 added _PyThreadState_UncheckedGet(). +#if PY_VERSION_HEX >= 0x03050200 && PY_VERSION_HEX < 0x030D00A1 +static inline PyThreadState* +PyThreadState_GetUnchecked(void) +{ + return _PyThreadState_UncheckedGet(); +} +#endif + +// gh-110289 added PyUnicode_EqualToUTF8() and PyUnicode_EqualToUTF8AndSize() +// to Python 3.13.0a1 +#if PY_VERSION_HEX < 0x030D00A1 +static inline int +PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t str_len) +{ + Py_ssize_t len; + const void *utf8; + PyObject *exc_type, *exc_value, *exc_tb; + int res; + + // API cannot report errors so save/restore the exception + PyErr_Fetch(&exc_type, &exc_value, &exc_tb); + + // Python 3.3.0a1 added PyUnicode_AsUTF8AndSize() +#if PY_VERSION_HEX >= 0x030300A1 + if (PyUnicode_IS_ASCII(unicode)) { + utf8 = PyUnicode_DATA(unicode); + len = PyUnicode_GET_LENGTH(unicode); + } + else { + utf8 = PyUnicode_AsUTF8AndSize(unicode, &len); + if (utf8 == NULL) { + // Memory allocation failure. The API cannot report error, + // so ignore the exception and return 0. + res = 0; + goto done; + } + } + + if (len != str_len) { + res = 0; + goto done; + } + res = (memcmp(utf8, str, (size_t)len) == 0); +#else + PyObject *bytes = PyUnicode_AsUTF8String(unicode); + if (bytes == NULL) { + // Memory allocation failure. The API cannot report error, + // so ignore the exception and return 0. + res = 0; + goto done; + } + +#if PY_VERSION_HEX >= 0x03000000 + len = PyBytes_GET_SIZE(bytes); + utf8 = PyBytes_AS_STRING(bytes); +#else + len = PyString_GET_SIZE(bytes); + utf8 = PyString_AS_STRING(bytes); +#endif + if (len != str_len) { + Py_DECREF(bytes); + res = 0; + goto done; + } + + res = (memcmp(utf8, str, (size_t)len) == 0); + Py_DECREF(bytes); +#endif + +done: + PyErr_Restore(exc_type, exc_value, exc_tb); + return res; +} + +static inline int +PyUnicode_EqualToUTF8(PyObject *unicode, const char *str) +{ + return PyUnicode_EqualToUTF8AndSize(unicode, str, (Py_ssize_t)strlen(str)); +} +#endif + + +// gh-111138 added PyList_Extend() and PyList_Clear() to Python 3.13.0a2 +#if PY_VERSION_HEX < 0x030D00A2 +static inline int +PyList_Extend(PyObject *list, PyObject *iterable) +{ + return PyList_SetSlice(list, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable); +} + +static inline int +PyList_Clear(PyObject *list) +{ + return PyList_SetSlice(list, 0, PY_SSIZE_T_MAX, NULL); +} +#endif + +// gh-111262 added PyDict_Pop() and PyDict_PopString() to Python 3.13.0a2 +#if PY_VERSION_HEX < 0x030D00A2 +static inline int +PyDict_Pop(PyObject *dict, PyObject *key, PyObject **result) +{ + PyObject *value; + + if (!PyDict_Check(dict)) { + PyErr_BadInternalCall(); + if (result) { + *result = NULL; + } + return -1; + } + + // bpo-16991 added _PyDict_Pop() to Python 3.5.0b2. + // Python 3.6.0b3 changed _PyDict_Pop() first argument type to PyObject*. + // Python 3.13.0a1 removed _PyDict_Pop(). +#if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x030500b2 || PY_VERSION_HEX >= 0x030D0000 + value = PyObject_CallMethod(dict, "pop", "O", key); +#elif PY_VERSION_HEX < 0x030600b3 + value = _PyDict_Pop(_Py_CAST(PyDictObject*, dict), key, NULL); +#else + value = _PyDict_Pop(dict, key, NULL); +#endif + if (value == NULL) { + if (result) { + *result = NULL; + } + if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_KeyError)) { + return -1; + } + PyErr_Clear(); + return 0; + } + if (result) { + *result = value; + } + else { + Py_DECREF(value); + } + return 1; +} + +static inline int +PyDict_PopString(PyObject *dict, const char *key, PyObject **result) +{ + PyObject *key_obj = PyUnicode_FromString(key); + if (key_obj == NULL) { + if (result != NULL) { + *result = NULL; + } + return -1; + } + + int res = PyDict_Pop(dict, key_obj, result); + Py_DECREF(key_obj); + return res; +} +#endif + + +#if PY_VERSION_HEX < 0x030200A4 +// Python 3.2.0a4 added Py_hash_t type +typedef Py_ssize_t Py_hash_t; +#endif + + +// gh-111545 added Py_HashPointer() to Python 3.13.0a3 +#if PY_VERSION_HEX < 0x030D00A3 +static inline Py_hash_t Py_HashPointer(const void *ptr) +{ +#if PY_VERSION_HEX >= 0x030900A4 && !defined(PYPY_VERSION) + return _Py_HashPointer(ptr); +#else + return _Py_HashPointer(_Py_CAST(void*, ptr)); +#endif +} +#endif + + +// Python 3.13a4 added a PyTime API. +// Use the private API added to Python 3.5. +#if PY_VERSION_HEX < 0x030D00A4 && PY_VERSION_HEX >= 0x03050000 +typedef _PyTime_t PyTime_t; +#define PyTime_MIN _PyTime_MIN +#define PyTime_MAX _PyTime_MAX + +static inline double PyTime_AsSecondsDouble(PyTime_t t) +{ return _PyTime_AsSecondsDouble(t); } + +static inline int PyTime_Monotonic(PyTime_t *result) +{ return _PyTime_GetMonotonicClockWithInfo(result, NULL); } + +static inline int PyTime_Time(PyTime_t *result) +{ return _PyTime_GetSystemClockWithInfo(result, NULL); } + +static inline int PyTime_PerfCounter(PyTime_t *result) +{ +#if PY_VERSION_HEX >= 0x03070000 && !defined(PYPY_VERSION) + return _PyTime_GetPerfCounterWithInfo(result, NULL); +#elif PY_VERSION_HEX >= 0x03070000 + // Call time.perf_counter_ns() and convert Python int object to PyTime_t. + // Cache time.perf_counter_ns() function for best performance. + static PyObject *func = NULL; + if (func == NULL) { + PyObject *mod = PyImport_ImportModule("time"); + if (mod == NULL) { + return -1; + } + + func = PyObject_GetAttrString(mod, "perf_counter_ns"); + Py_DECREF(mod); + if (func == NULL) { + return -1; + } + } + + PyObject *res = PyObject_CallNoArgs(func); + if (res == NULL) { + return -1; + } + long long value = PyLong_AsLongLong(res); + Py_DECREF(res); + + if (value == -1 && PyErr_Occurred()) { + return -1; + } + + Py_BUILD_ASSERT(sizeof(value) >= sizeof(PyTime_t)); + *result = (PyTime_t)value; + return 0; +#else + // Call time.perf_counter() and convert C double to PyTime_t. + // Cache time.perf_counter() function for best performance. + static PyObject *func = NULL; + if (func == NULL) { + PyObject *mod = PyImport_ImportModule("time"); + if (mod == NULL) { + return -1; + } + + func = PyObject_GetAttrString(mod, "perf_counter"); + Py_DECREF(mod); + if (func == NULL) { + return -1; + } + } + + PyObject *res = PyObject_CallNoArgs(func); + if (res == NULL) { + return -1; + } + double d = PyFloat_AsDouble(res); + Py_DECREF(res); + + if (d == -1.0 && PyErr_Occurred()) { + return -1; + } + + // Avoid floor() to avoid having to link to libm + *result = (PyTime_t)(d * 1e9); + return 0; +#endif +} + +#endif + +// gh-111389 added hash constants to Python 3.13.0a5. These constants were +// added first as private macros to Python 3.4.0b1 and PyPy 7.3.8. +#if (!defined(PyHASH_BITS) \ + && ((!defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x030400B1) \ + || (defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x03070000 \ + && PYPY_VERSION_NUM >= 0x07030800))) +# define PyHASH_BITS _PyHASH_BITS +# define PyHASH_MODULUS _PyHASH_MODULUS +# define PyHASH_INF _PyHASH_INF +# define PyHASH_IMAG _PyHASH_IMAG +#endif + + +// gh-111545 added Py_GetConstant() and Py_GetConstantBorrowed() +// to Python 3.13.0a6 +#if PY_VERSION_HEX < 0x030D00A6 && !defined(Py_CONSTANT_NONE) + +#define Py_CONSTANT_NONE 0 +#define Py_CONSTANT_FALSE 1 +#define Py_CONSTANT_TRUE 2 +#define Py_CONSTANT_ELLIPSIS 3 +#define Py_CONSTANT_NOT_IMPLEMENTED 4 +#define Py_CONSTANT_ZERO 5 +#define Py_CONSTANT_ONE 6 +#define Py_CONSTANT_EMPTY_STR 7 +#define Py_CONSTANT_EMPTY_BYTES 8 +#define Py_CONSTANT_EMPTY_TUPLE 9 + +static inline PyObject* Py_GetConstant(unsigned int constant_id) +{ + static PyObject* constants[Py_CONSTANT_EMPTY_TUPLE + 1] = {NULL}; + + if (constants[Py_CONSTANT_NONE] == NULL) { + constants[Py_CONSTANT_NONE] = Py_None; + constants[Py_CONSTANT_FALSE] = Py_False; + constants[Py_CONSTANT_TRUE] = Py_True; + constants[Py_CONSTANT_ELLIPSIS] = Py_Ellipsis; + constants[Py_CONSTANT_NOT_IMPLEMENTED] = Py_NotImplemented; + + constants[Py_CONSTANT_ZERO] = PyLong_FromLong(0); + if (constants[Py_CONSTANT_ZERO] == NULL) { + goto fatal_error; + } + + constants[Py_CONSTANT_ONE] = PyLong_FromLong(1); + if (constants[Py_CONSTANT_ONE] == NULL) { + goto fatal_error; + } + + constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_FromStringAndSize("", 0); + if (constants[Py_CONSTANT_EMPTY_STR] == NULL) { + goto fatal_error; + } + + constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize("", 0); + if (constants[Py_CONSTANT_EMPTY_BYTES] == NULL) { + goto fatal_error; + } + + constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0); + if (constants[Py_CONSTANT_EMPTY_TUPLE] == NULL) { + goto fatal_error; + } + // goto dance to avoid compiler warnings about Py_FatalError() + goto init_done; + +fatal_error: + // This case should never happen + Py_FatalError("Py_GetConstant() failed to get constants"); + } + +init_done: + if (constant_id <= Py_CONSTANT_EMPTY_TUPLE) { + return Py_NewRef(constants[constant_id]); + } + else { + PyErr_BadInternalCall(); + return NULL; + } +} + +static inline PyObject* Py_GetConstantBorrowed(unsigned int constant_id) +{ + PyObject *obj = Py_GetConstant(constant_id); + Py_XDECREF(obj); + return obj; +} +#endif + + +// gh-114329 added PyList_GetItemRef() to Python 3.13.0a4 +#if PY_VERSION_HEX < 0x030D00A4 +static inline PyObject * +PyList_GetItemRef(PyObject *op, Py_ssize_t index) +{ + PyObject *item = PyList_GetItem(op, index); + Py_XINCREF(item); + return item; +} +#endif + + +// gh-114329 added PyList_GetItemRef() to Python 3.13.0a4 +#if PY_VERSION_HEX < 0x030D00A4 +static inline int +PyDict_SetDefaultRef(PyObject *d, PyObject *key, PyObject *default_value, + PyObject **result) +{ + PyObject *value; + if (PyDict_GetItemRef(d, key, &value) < 0) { + // get error + if (result) { + *result = NULL; + } + return -1; + } + if (value != NULL) { + // present + if (result) { + *result = value; + } + else { + Py_DECREF(value); + } + return 1; + } + + // missing: set the item + if (PyDict_SetItem(d, key, default_value) < 0) { + // set error + if (result) { + *result = NULL; + } + return -1; + } + if (result) { + *result = Py_NewRef(default_value); + } + return 0; +} +#endif + +#if PY_VERSION_HEX < 0x030D00B3 +# define Py_BEGIN_CRITICAL_SECTION(op) { +# define Py_END_CRITICAL_SECTION() } +# define Py_BEGIN_CRITICAL_SECTION2(a, b) { +# define Py_END_CRITICAL_SECTION2() } +#endif + +#if PY_VERSION_HEX < 0x030E0000 && PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION) +typedef struct PyUnicodeWriter PyUnicodeWriter; + +static inline void PyUnicodeWriter_Discard(PyUnicodeWriter *writer) +{ + _PyUnicodeWriter_Dealloc((_PyUnicodeWriter*)writer); + PyMem_Free(writer); +} + +static inline PyUnicodeWriter* PyUnicodeWriter_Create(Py_ssize_t length) +{ + if (length < 0) { + PyErr_SetString(PyExc_ValueError, + "length must be positive"); + return NULL; + } + + const size_t size = sizeof(_PyUnicodeWriter); + PyUnicodeWriter *pub_writer = (PyUnicodeWriter *)PyMem_Malloc(size); + if (pub_writer == _Py_NULL) { + PyErr_NoMemory(); + return _Py_NULL; + } + _PyUnicodeWriter *writer = (_PyUnicodeWriter *)pub_writer; + + _PyUnicodeWriter_Init(writer); + if (_PyUnicodeWriter_Prepare(writer, length, 127) < 0) { + PyUnicodeWriter_Discard(pub_writer); + return NULL; + } + writer->overallocate = 1; + return pub_writer; +} + +static inline PyObject* PyUnicodeWriter_Finish(PyUnicodeWriter *writer) +{ + PyObject *str = _PyUnicodeWriter_Finish((_PyUnicodeWriter*)writer); + assert(((_PyUnicodeWriter*)writer)->buffer == NULL); + PyMem_Free(writer); + return str; +} + +static inline int +PyUnicodeWriter_WriteChar(PyUnicodeWriter *writer, Py_UCS4 ch) +{ + if (ch > 0x10ffff) { + PyErr_SetString(PyExc_ValueError, + "character must be in range(0x110000)"); + return -1; + } + + return _PyUnicodeWriter_WriteChar((_PyUnicodeWriter*)writer, ch); +} + +static inline int +PyUnicodeWriter_WriteStr(PyUnicodeWriter *writer, PyObject *obj) +{ + PyObject *str = PyObject_Str(obj); + if (str == NULL) { + return -1; + } + + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str); + Py_DECREF(str); + return res; +} + +static inline int +PyUnicodeWriter_WriteRepr(PyUnicodeWriter *writer, PyObject *obj) +{ + PyObject *str = PyObject_Repr(obj); + if (str == NULL) { + return -1; + } + + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str); + Py_DECREF(str); + return res; +} + +static inline int +PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer, + const char *str, Py_ssize_t size) +{ + if (size < 0) { + size = (Py_ssize_t)strlen(str); + } + + PyObject *str_obj = PyUnicode_FromStringAndSize(str, size); + if (str_obj == _Py_NULL) { + return -1; + } + + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj); + Py_DECREF(str_obj); + return res; +} + +static inline int +PyUnicodeWriter_WriteASCII(PyUnicodeWriter *writer, + const char *str, Py_ssize_t size) +{ + if (size < 0) { + size = (Py_ssize_t)strlen(str); + } + + return _PyUnicodeWriter_WriteASCIIString((_PyUnicodeWriter*)writer, + str, size); +} + +static inline int +PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer, + const wchar_t *str, Py_ssize_t size) +{ + if (size < 0) { + size = (Py_ssize_t)wcslen(str); + } + + PyObject *str_obj = PyUnicode_FromWideChar(str, size); + if (str_obj == _Py_NULL) { + return -1; + } + + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj); + Py_DECREF(str_obj); + return res; +} + +static inline int +PyUnicodeWriter_WriteSubstring(PyUnicodeWriter *writer, PyObject *str, + Py_ssize_t start, Py_ssize_t end) +{ + if (!PyUnicode_Check(str)) { + PyErr_Format(PyExc_TypeError, "expect str, not %s", + Py_TYPE(str)->tp_name); + return -1; + } + if (start < 0 || start > end) { + PyErr_Format(PyExc_ValueError, "invalid start argument"); + return -1; + } + if (end > PyUnicode_GET_LENGTH(str)) { + PyErr_Format(PyExc_ValueError, "invalid end argument"); + return -1; + } + + return _PyUnicodeWriter_WriteSubstring((_PyUnicodeWriter*)writer, str, + start, end); +} + +static inline int +PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...) +{ + va_list vargs; + va_start(vargs, format); + PyObject *str = PyUnicode_FromFormatV(format, vargs); + va_end(vargs); + if (str == _Py_NULL) { + return -1; + } + + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str); + Py_DECREF(str); + return res; +} +#endif // PY_VERSION_HEX < 0x030E0000 + +// gh-116560 added PyLong_GetSign() to Python 3.14.0a0 +#if PY_VERSION_HEX < 0x030E00A0 +static inline int PyLong_GetSign(PyObject *obj, int *sign) +{ + if (!PyLong_Check(obj)) { + PyErr_Format(PyExc_TypeError, "expect int, got %s", Py_TYPE(obj)->tp_name); + return -1; + } + + *sign = _PyLong_Sign(obj); + return 0; +} +#endif + +// gh-126061 added PyLong_IsPositive/Negative/Zero() to Python in 3.14.0a2 +#if PY_VERSION_HEX < 0x030E00A2 +static inline int PyLong_IsPositive(PyObject *obj) +{ + if (!PyLong_Check(obj)) { + PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); + return -1; + } + return _PyLong_Sign(obj) == 1; +} + +static inline int PyLong_IsNegative(PyObject *obj) +{ + if (!PyLong_Check(obj)) { + PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); + return -1; + } + return _PyLong_Sign(obj) == -1; +} + +static inline int PyLong_IsZero(PyObject *obj) +{ + if (!PyLong_Check(obj)) { + PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); + return -1; + } + return _PyLong_Sign(obj) == 0; +} +#endif + + +// gh-124502 added PyUnicode_Equal() to Python 3.14.0a0 +#if PY_VERSION_HEX < 0x030E00A0 +static inline int PyUnicode_Equal(PyObject *str1, PyObject *str2) +{ + if (!PyUnicode_Check(str1)) { + PyErr_Format(PyExc_TypeError, "first argument must be str, not %s", + Py_TYPE(str1)->tp_name); + return -1; + } + if (!PyUnicode_Check(str2)) { + PyErr_Format(PyExc_TypeError, "second argument must be str, not %s", + Py_TYPE(str2)->tp_name); + return -1; + } + +#if PY_VERSION_HEX >= 0x030d0000 && !defined(PYPY_VERSION) + PyAPI_FUNC(int) _PyUnicode_Equal(PyObject *str1, PyObject *str2); + + return _PyUnicode_Equal(str1, str2); +#elif PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION) + return _PyUnicode_EQ(str1, str2); +#elif PY_VERSION_HEX >= 0x03090000 && defined(PYPY_VERSION) + return _PyUnicode_EQ(str1, str2); +#else + return (PyUnicode_Compare(str1, str2) == 0); +#endif +} +#endif + + +// gh-121645 added PyBytes_Join() to Python 3.14.0a0 +#if PY_VERSION_HEX < 0x030E00A0 +static inline PyObject* PyBytes_Join(PyObject *sep, PyObject *iterable) +{ + return _PyBytes_Join(sep, iterable); +} +#endif + + +#if PY_VERSION_HEX < 0x030E00A0 +static inline Py_hash_t Py_HashBuffer(const void *ptr, Py_ssize_t len) +{ +#if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION) + PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void *src, Py_ssize_t len); + + return _Py_HashBytes(ptr, len); +#else + Py_hash_t hash; + PyObject *bytes = PyBytes_FromStringAndSize((const char*)ptr, len); + if (bytes == NULL) { + return -1; + } + hash = PyObject_Hash(bytes); + Py_DECREF(bytes); + return hash; +#endif +} +#endif + + +#if PY_VERSION_HEX < 0x030E00A0 +static inline int PyIter_NextItem(PyObject *iter, PyObject **item) +{ + iternextfunc tp_iternext; + + assert(iter != NULL); + assert(item != NULL); + + tp_iternext = Py_TYPE(iter)->tp_iternext; + if (tp_iternext == NULL) { + *item = NULL; + PyErr_Format(PyExc_TypeError, "expected an iterator, got '%s'", + Py_TYPE(iter)->tp_name); + return -1; + } + + if ((*item = tp_iternext(iter))) { + return 1; + } + if (!PyErr_Occurred()) { + return 0; + } + if (PyErr_ExceptionMatches(PyExc_StopIteration)) { + PyErr_Clear(); + return 0; + } + return -1; +} +#endif + + +#if PY_VERSION_HEX < 0x030E00A0 +static inline PyObject* PyLong_FromInt32(int32_t value) +{ + Py_BUILD_ASSERT(sizeof(long) >= 4); + return PyLong_FromLong(value); +} + +static inline PyObject* PyLong_FromInt64(int64_t value) +{ + Py_BUILD_ASSERT(sizeof(long long) >= 8); + return PyLong_FromLongLong(value); +} + +static inline PyObject* PyLong_FromUInt32(uint32_t value) +{ + Py_BUILD_ASSERT(sizeof(unsigned long) >= 4); + return PyLong_FromUnsignedLong(value); +} + +static inline PyObject* PyLong_FromUInt64(uint64_t value) +{ + Py_BUILD_ASSERT(sizeof(unsigned long long) >= 8); + return PyLong_FromUnsignedLongLong(value); +} + +static inline int PyLong_AsInt32(PyObject *obj, int32_t *pvalue) +{ + Py_BUILD_ASSERT(sizeof(int) == 4); + int value = PyLong_AsInt(obj); + if (value == -1 && PyErr_Occurred()) { + return -1; + } + *pvalue = (int32_t)value; + return 0; +} + +static inline int PyLong_AsInt64(PyObject *obj, int64_t *pvalue) +{ + Py_BUILD_ASSERT(sizeof(long long) == 8); + long long value = PyLong_AsLongLong(obj); + if (value == -1 && PyErr_Occurred()) { + return -1; + } + *pvalue = (int64_t)value; + return 0; +} + +static inline int PyLong_AsUInt32(PyObject *obj, uint32_t *pvalue) +{ + Py_BUILD_ASSERT(sizeof(long) >= 4); + unsigned long value = PyLong_AsUnsignedLong(obj); + if (value == (unsigned long)-1 && PyErr_Occurred()) { + return -1; + } +#if SIZEOF_LONG > 4 + if ((unsigned long)UINT32_MAX < value) { + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C uint32_t"); + return -1; + } +#endif + *pvalue = (uint32_t)value; + return 0; +} + +static inline int PyLong_AsUInt64(PyObject *obj, uint64_t *pvalue) +{ + Py_BUILD_ASSERT(sizeof(long long) == 8); + unsigned long long value = PyLong_AsUnsignedLongLong(obj); + if (value == (unsigned long long)-1 && PyErr_Occurred()) { + return -1; + } + *pvalue = (uint64_t)value; + return 0; +} +#endif + + +// gh-102471 added import and export API for integers to 3.14.0a2. +#if PY_VERSION_HEX < 0x030E00A2 && PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION) +// Helpers to access PyLongObject internals. +static inline void +_PyLong_SetSignAndDigitCount(PyLongObject *op, int sign, Py_ssize_t size) +{ +#if PY_VERSION_HEX >= 0x030C0000 + op->long_value.lv_tag = (uintptr_t)(1 - sign) | ((uintptr_t)(size) << 3); +#elif PY_VERSION_HEX >= 0x030900A4 + Py_SET_SIZE(op, sign * size); +#else + Py_SIZE(op) = sign * size; +#endif +} + +static inline Py_ssize_t +_PyLong_DigitCount(const PyLongObject *op) +{ +#if PY_VERSION_HEX >= 0x030C0000 + return (Py_ssize_t)(op->long_value.lv_tag >> 3); +#else + return _PyLong_Sign((PyObject*)op) < 0 ? -Py_SIZE(op) : Py_SIZE(op); +#endif +} + +static inline digit* +_PyLong_GetDigits(const PyLongObject *op) +{ +#if PY_VERSION_HEX >= 0x030C0000 + return (digit*)(op->long_value.ob_digit); +#else + return (digit*)(op->ob_digit); +#endif +} + +typedef struct PyLongLayout { + uint8_t bits_per_digit; + uint8_t digit_size; + int8_t digits_order; + int8_t digit_endianness; +} PyLongLayout; + +typedef struct PyLongExport { + int64_t value; + uint8_t negative; + Py_ssize_t ndigits; + const void *digits; + Py_uintptr_t _reserved; +} PyLongExport; + +typedef struct PyLongWriter PyLongWriter; + +static inline const PyLongLayout* +PyLong_GetNativeLayout(void) +{ + static const PyLongLayout PyLong_LAYOUT = { + PyLong_SHIFT, + sizeof(digit), + -1, // least significant first + PY_LITTLE_ENDIAN ? -1 : 1, + }; + + return &PyLong_LAYOUT; +} + +static inline int +PyLong_Export(PyObject *obj, PyLongExport *export_long) +{ + if (!PyLong_Check(obj)) { + memset(export_long, 0, sizeof(*export_long)); + PyErr_Format(PyExc_TypeError, "expected int, got %s", + Py_TYPE(obj)->tp_name); + return -1; + } + + // Fast-path: try to convert to a int64_t + PyLongObject *self = (PyLongObject*)obj; + int overflow; +#if SIZEOF_LONG == 8 + long value = PyLong_AsLongAndOverflow(obj, &overflow); +#else + // Windows has 32-bit long, so use 64-bit long long instead + long long value = PyLong_AsLongLongAndOverflow(obj, &overflow); +#endif + Py_BUILD_ASSERT(sizeof(value) == sizeof(int64_t)); + // the function cannot fail since obj is a PyLongObject + assert(!(value == -1 && PyErr_Occurred())); + + if (!overflow) { + export_long->value = value; + export_long->negative = 0; + export_long->ndigits = 0; + export_long->digits = 0; + export_long->_reserved = 0; + } + else { + export_long->value = 0; + export_long->negative = _PyLong_Sign(obj) < 0; + export_long->ndigits = _PyLong_DigitCount(self); + if (export_long->ndigits == 0) { + export_long->ndigits = 1; + } + export_long->digits = _PyLong_GetDigits(self); + export_long->_reserved = (Py_uintptr_t)Py_NewRef(obj); + } + return 0; +} + +static inline void +PyLong_FreeExport(PyLongExport *export_long) +{ + PyObject *obj = (PyObject*)export_long->_reserved; + + if (obj) { + export_long->_reserved = 0; + Py_DECREF(obj); + } +} + +static inline PyLongWriter* +PyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits) +{ + if (ndigits <= 0) { + PyErr_SetString(PyExc_ValueError, "ndigits must be positive"); + return NULL; + } + assert(digits != NULL); + + PyLongObject *obj = _PyLong_New(ndigits); + if (obj == NULL) { + return NULL; + } + _PyLong_SetSignAndDigitCount(obj, negative?-1:1, ndigits); + + *digits = _PyLong_GetDigits(obj); + return (PyLongWriter*)obj; +} + +static inline void +PyLongWriter_Discard(PyLongWriter *writer) +{ + PyLongObject *obj = (PyLongObject *)writer; + + assert(Py_REFCNT(obj) == 1); + Py_DECREF(obj); +} + +static inline PyObject* +PyLongWriter_Finish(PyLongWriter *writer) +{ + PyObject *obj = (PyObject *)writer; + PyLongObject *self = (PyLongObject*)obj; + Py_ssize_t j = _PyLong_DigitCount(self); + Py_ssize_t i = j; + int sign = _PyLong_Sign(obj); + + assert(Py_REFCNT(obj) == 1); + + // Normalize and get singleton if possible + while (i > 0 && _PyLong_GetDigits(self)[i-1] == 0) { + --i; + } + if (i != j) { + if (i == 0) { + sign = 0; + } + _PyLong_SetSignAndDigitCount(self, sign, i); + } + if (i <= 1) { + long val = sign * (long)(_PyLong_GetDigits(self)[0]); + Py_DECREF(obj); + return PyLong_FromLong(val); + } + + return obj; +} +#endif + + +#if PY_VERSION_HEX < 0x030C00A3 +# define Py_T_SHORT 0 +# define Py_T_INT 1 +# define Py_T_LONG 2 +# define Py_T_FLOAT 3 +# define Py_T_DOUBLE 4 +# define Py_T_STRING 5 +# define _Py_T_OBJECT 6 +# define Py_T_CHAR 7 +# define Py_T_BYTE 8 +# define Py_T_UBYTE 9 +# define Py_T_USHORT 10 +# define Py_T_UINT 11 +# define Py_T_ULONG 12 +# define Py_T_STRING_INPLACE 13 +# define Py_T_BOOL 14 +# define Py_T_OBJECT_EX 16 +# define Py_T_LONGLONG 17 +# define Py_T_ULONGLONG 18 +# define Py_T_PYSSIZET 19 + +# if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION) +# define _Py_T_NONE 20 +# endif + +# define Py_READONLY 1 +# define Py_AUDIT_READ 2 +# define _Py_WRITE_RESTRICTED 4 +#endif + + +// gh-127350 added Py_fopen() and Py_fclose() to Python 3.14a4 +#if PY_VERSION_HEX < 0x030E00A4 +static inline FILE* Py_fopen(PyObject *path, const char *mode) +{ +#if 0x030400A2 <= PY_VERSION_HEX && !defined(PYPY_VERSION) + PyAPI_FUNC(FILE*) _Py_fopen_obj(PyObject *path, const char *mode); + + return _Py_fopen_obj(path, mode); +#else + FILE *f; + PyObject *bytes; +#if PY_VERSION_HEX >= 0x03000000 + if (!PyUnicode_FSConverter(path, &bytes)) { + return NULL; + } +#else + if (!PyString_Check(path)) { + PyErr_SetString(PyExc_TypeError, "except str"); + return NULL; + } + bytes = Py_NewRef(path); +#endif + const char *path_bytes = PyBytes_AS_STRING(bytes); + + f = fopen(path_bytes, mode); + Py_DECREF(bytes); + + if (f == NULL) { + PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path); + return NULL; + } + return f; +#endif +} + +static inline int Py_fclose(FILE *file) +{ + return fclose(file); +} +#endif + + +#if 0x03080000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030E0000 && !defined(PYPY_VERSION) +PyAPI_FUNC(const PyConfig*) _Py_GetConfig(void); + +static inline PyObject* +PyConfig_Get(const char *name) +{ + typedef enum { + _PyConfig_MEMBER_INT, + _PyConfig_MEMBER_UINT, + _PyConfig_MEMBER_ULONG, + _PyConfig_MEMBER_BOOL, + _PyConfig_MEMBER_WSTR, + _PyConfig_MEMBER_WSTR_OPT, + _PyConfig_MEMBER_WSTR_LIST, + } PyConfigMemberType; + + typedef struct { + const char *name; + size_t offset; + PyConfigMemberType type; + const char *sys_attr; + } PyConfigSpec; + +#define PYTHONCAPI_COMPAT_SPEC(MEMBER, TYPE, sys_attr) \ + {#MEMBER, offsetof(PyConfig, MEMBER), \ + _PyConfig_MEMBER_##TYPE, sys_attr} + + static const PyConfigSpec config_spec[] = { + PYTHONCAPI_COMPAT_SPEC(argv, WSTR_LIST, "argv"), + PYTHONCAPI_COMPAT_SPEC(base_exec_prefix, WSTR_OPT, "base_exec_prefix"), + PYTHONCAPI_COMPAT_SPEC(base_executable, WSTR_OPT, "_base_executable"), + PYTHONCAPI_COMPAT_SPEC(base_prefix, WSTR_OPT, "base_prefix"), + PYTHONCAPI_COMPAT_SPEC(bytes_warning, UINT, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(exec_prefix, WSTR_OPT, "exec_prefix"), + PYTHONCAPI_COMPAT_SPEC(executable, WSTR_OPT, "executable"), + PYTHONCAPI_COMPAT_SPEC(inspect, BOOL, _Py_NULL), +#if 0x030C0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(int_max_str_digits, UINT, _Py_NULL), +#endif + PYTHONCAPI_COMPAT_SPEC(interactive, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(module_search_paths, WSTR_LIST, "path"), + PYTHONCAPI_COMPAT_SPEC(optimization_level, UINT, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(parser_debug, BOOL, _Py_NULL), +#if 0x03090000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(platlibdir, WSTR, "platlibdir"), +#endif + PYTHONCAPI_COMPAT_SPEC(prefix, WSTR_OPT, "prefix"), + PYTHONCAPI_COMPAT_SPEC(pycache_prefix, WSTR_OPT, "pycache_prefix"), + PYTHONCAPI_COMPAT_SPEC(quiet, BOOL, _Py_NULL), +#if 0x030B0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(stdlib_dir, WSTR_OPT, "_stdlib_dir"), +#endif + PYTHONCAPI_COMPAT_SPEC(use_environment, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(verbose, UINT, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(warnoptions, WSTR_LIST, "warnoptions"), + PYTHONCAPI_COMPAT_SPEC(write_bytecode, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(xoptions, WSTR_LIST, "_xoptions"), + PYTHONCAPI_COMPAT_SPEC(buffered_stdio, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(check_hash_pycs_mode, WSTR, _Py_NULL), +#if 0x030B0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(code_debug_ranges, BOOL, _Py_NULL), +#endif + PYTHONCAPI_COMPAT_SPEC(configure_c_stdio, BOOL, _Py_NULL), +#if 0x030D0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(cpu_count, INT, _Py_NULL), +#endif + PYTHONCAPI_COMPAT_SPEC(dev_mode, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(dump_refs, BOOL, _Py_NULL), +#if 0x030B0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(dump_refs_file, WSTR_OPT, _Py_NULL), +#endif +#ifdef Py_GIL_DISABLED + PYTHONCAPI_COMPAT_SPEC(enable_gil, INT, _Py_NULL), +#endif + PYTHONCAPI_COMPAT_SPEC(faulthandler, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(filesystem_encoding, WSTR, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(filesystem_errors, WSTR, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(hash_seed, ULONG, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(home, WSTR_OPT, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(import_time, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(install_signal_handlers, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(isolated, BOOL, _Py_NULL), +#ifdef MS_WINDOWS + PYTHONCAPI_COMPAT_SPEC(legacy_windows_stdio, BOOL, _Py_NULL), +#endif + PYTHONCAPI_COMPAT_SPEC(malloc_stats, BOOL, _Py_NULL), +#if 0x030A0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(orig_argv, WSTR_LIST, "orig_argv"), +#endif + PYTHONCAPI_COMPAT_SPEC(parse_argv, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(pathconfig_warnings, BOOL, _Py_NULL), +#if 0x030C0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(perf_profiling, UINT, _Py_NULL), +#endif + PYTHONCAPI_COMPAT_SPEC(program_name, WSTR, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(run_command, WSTR_OPT, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(run_filename, WSTR_OPT, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(run_module, WSTR_OPT, _Py_NULL), +#if 0x030B0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(safe_path, BOOL, _Py_NULL), +#endif + PYTHONCAPI_COMPAT_SPEC(show_ref_count, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(site_import, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(skip_source_first_line, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(stdio_encoding, WSTR, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(stdio_errors, WSTR, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(tracemalloc, UINT, _Py_NULL), +#if 0x030B0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(use_frozen_modules, BOOL, _Py_NULL), +#endif + PYTHONCAPI_COMPAT_SPEC(use_hash_seed, BOOL, _Py_NULL), + PYTHONCAPI_COMPAT_SPEC(user_site_directory, BOOL, _Py_NULL), +#if 0x030A0000 <= PY_VERSION_HEX + PYTHONCAPI_COMPAT_SPEC(warn_default_encoding, BOOL, _Py_NULL), +#endif + }; + +#undef PYTHONCAPI_COMPAT_SPEC + + const PyConfigSpec *spec; + int found = 0; + for (size_t i=0; i < sizeof(config_spec) / sizeof(config_spec[0]); i++) { + spec = &config_spec[i]; + if (strcmp(spec->name, name) == 0) { + found = 1; + break; + } + } + if (found) { + if (spec->sys_attr != NULL) { + PyObject *value = PySys_GetObject(spec->sys_attr); + if (value == NULL) { + PyErr_Format(PyExc_RuntimeError, "lost sys.%s", spec->sys_attr); + return NULL; + } + return Py_NewRef(value); + } + + const PyConfig *config = _Py_GetConfig(); + void *member = (char *)config + spec->offset; + switch (spec->type) { + case _PyConfig_MEMBER_INT: + case _PyConfig_MEMBER_UINT: + { + int value = *(int *)member; + return PyLong_FromLong(value); + } + case _PyConfig_MEMBER_BOOL: + { + int value = *(int *)member; + return PyBool_FromLong(value != 0); + } + case _PyConfig_MEMBER_ULONG: + { + unsigned long value = *(unsigned long *)member; + return PyLong_FromUnsignedLong(value); + } + case _PyConfig_MEMBER_WSTR: + case _PyConfig_MEMBER_WSTR_OPT: + { + wchar_t *wstr = *(wchar_t **)member; + if (wstr != NULL) { + return PyUnicode_FromWideChar(wstr, -1); + } + else { + return Py_NewRef(Py_None); + } + } + case _PyConfig_MEMBER_WSTR_LIST: + { + const PyWideStringList *list = (const PyWideStringList *)member; + PyObject *tuple = PyTuple_New(list->length); + if (tuple == NULL) { + return NULL; + } + + for (Py_ssize_t i = 0; i < list->length; i++) { + PyObject *item = PyUnicode_FromWideChar(list->items[i], -1); + if (item == NULL) { + Py_DECREF(tuple); + return NULL; + } + PyTuple_SET_ITEM(tuple, i, item); + } + return tuple; + } + default: + Py_UNREACHABLE(); + } + } + + PyErr_Format(PyExc_ValueError, "unknown config option name: %s", name); + return NULL; +} + +static inline int +PyConfig_GetInt(const char *name, int *value) +{ + PyObject *obj = PyConfig_Get(name); + if (obj == NULL) { + return -1; + } + + if (!PyLong_Check(obj)) { + Py_DECREF(obj); + PyErr_Format(PyExc_TypeError, "config option %s is not an int", name); + return -1; + } + + int as_int = PyLong_AsInt(obj); + Py_DECREF(obj); + if (as_int == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_OverflowError, + "config option %s value does not fit into a C int", name); + return -1; + } + + *value = as_int; + return 0; +} +#endif // PY_VERSION_HEX > 0x03090000 && !defined(PYPY_VERSION) + +// gh-133144 added PyUnstable_Object_IsUniquelyReferenced() to Python 3.14.0b1. +// Adapted from _PyObject_IsUniquelyReferenced() implementation. +#if PY_VERSION_HEX < 0x030E00B0 +static inline int PyUnstable_Object_IsUniquelyReferenced(PyObject *obj) +{ +#if !defined(Py_GIL_DISABLED) + return Py_REFCNT(obj) == 1; +#else + // NOTE: the entire ob_ref_shared field must be zero, including flags, to + // ensure that other threads cannot concurrently create new references to + // this object. + return (_Py_IsOwnedByCurrentThread(obj) && + _Py_atomic_load_uint32_relaxed(&obj->ob_ref_local) == 1 && + _Py_atomic_load_ssize_relaxed(&obj->ob_ref_shared) == 0); +#endif +} +#endif + +// gh-128926 added PyUnstable_TryIncRef() and PyUnstable_EnableTryIncRef() to +// Python 3.14.0a5. Adapted from _Py_TryIncref() and _PyObject_SetMaybeWeakref(). +#if PY_VERSION_HEX < 0x030E00A5 +static inline int PyUnstable_TryIncRef(PyObject *op) +{ +#ifndef Py_GIL_DISABLED + if (Py_REFCNT(op) > 0) { + Py_INCREF(op); + return 1; + } + return 0; +#else + // _Py_TryIncrefFast() + uint32_t local = _Py_atomic_load_uint32_relaxed(&op->ob_ref_local); + local += 1; + if (local == 0) { + // immortal + return 1; + } + if (_Py_IsOwnedByCurrentThread(op)) { + _Py_INCREF_STAT_INC(); + _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, local); +#ifdef Py_REF_DEBUG + _Py_INCREF_IncRefTotal(); +#endif + return 1; + } + + // _Py_TryIncRefShared() + Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&op->ob_ref_shared); + for (;;) { + // If the shared refcount is zero and the object is either merged + // or may not have weak references, then we cannot incref it. + if (shared == 0 || shared == _Py_REF_MERGED) { + return 0; + } + + if (_Py_atomic_compare_exchange_ssize( + &op->ob_ref_shared, + &shared, + shared + (1 << _Py_REF_SHARED_SHIFT))) { +#ifdef Py_REF_DEBUG + _Py_INCREF_IncRefTotal(); +#endif + _Py_INCREF_STAT_INC(); + return 1; + } + } +#endif +} + +static inline void PyUnstable_EnableTryIncRef(PyObject *op) +{ +#ifdef Py_GIL_DISABLED + // _PyObject_SetMaybeWeakref() + if (_Py_IsImmortal(op)) { + return; + } + for (;;) { + Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&op->ob_ref_shared); + if ((shared & _Py_REF_SHARED_FLAG_MASK) != 0) { + // Nothing to do if it's in WEAKREFS, QUEUED, or MERGED states. + return; + } + if (_Py_atomic_compare_exchange_ssize( + &op->ob_ref_shared, &shared, shared | _Py_REF_MAYBE_WEAKREF)) { + return; + } + } +#else + (void)op; // unused argument +#endif +} +#endif + + +#if PY_VERSION_HEX < 0x030F0000 +static inline PyObject* +PySys_GetAttrString(const char *name) +{ +#if PY_VERSION_HEX >= 0x03000000 + PyObject *value = Py_XNewRef(PySys_GetObject(name)); +#else + PyObject *value = Py_XNewRef(PySys_GetObject((char*)name)); +#endif + if (value != NULL) { + return value; + } + if (!PyErr_Occurred()) { + PyErr_Format(PyExc_RuntimeError, "lost sys.%s", name); + } + return NULL; +} + +static inline PyObject* +PySys_GetAttr(PyObject *name) +{ +#if PY_VERSION_HEX >= 0x03000000 + const char *name_str = PyUnicode_AsUTF8(name); +#else + const char *name_str = PyString_AsString(name); +#endif + if (name_str == NULL) { + return NULL; + } + + return PySys_GetAttrString(name_str); +} + +static inline int +PySys_GetOptionalAttrString(const char *name, PyObject **value) +{ +#if PY_VERSION_HEX >= 0x03000000 + *value = Py_XNewRef(PySys_GetObject(name)); +#else + *value = Py_XNewRef(PySys_GetObject((char*)name)); +#endif + if (*value != NULL) { + return 1; + } + return 0; +} + +static inline int +PySys_GetOptionalAttr(PyObject *name, PyObject **value) +{ +#if PY_VERSION_HEX >= 0x03000000 + const char *name_str = PyUnicode_AsUTF8(name); +#else + const char *name_str = PyString_AsString(name); +#endif + if (name_str == NULL) { + *value = NULL; + return -1; + } + + return PySys_GetOptionalAttrString(name_str, value); +} +#endif // PY_VERSION_HEX < 0x030F00A1 + + +#if PY_VERSION_HEX < 0x030F00A1 +typedef struct PyBytesWriter { + char small_buffer[256]; + PyObject *obj; + Py_ssize_t size; +} PyBytesWriter; + +static inline Py_ssize_t +_PyBytesWriter_GetAllocated(PyBytesWriter *writer) +{ + if (writer->obj == NULL) { + return sizeof(writer->small_buffer); + } + else { + return PyBytes_GET_SIZE(writer->obj); + } +} + + +static inline int +_PyBytesWriter_Resize_impl(PyBytesWriter *writer, Py_ssize_t size, + int resize) +{ + int overallocate = resize; + assert(size >= 0); + + if (size <= _PyBytesWriter_GetAllocated(writer)) { + return 0; + } + + if (overallocate) { +#ifdef MS_WINDOWS + /* On Windows, overallocate by 50% is the best factor */ + if (size <= (PY_SSIZE_T_MAX - size / 2)) { + size += size / 2; + } +#else + /* On Linux, overallocate by 25% is the best factor */ + if (size <= (PY_SSIZE_T_MAX - size / 4)) { + size += size / 4; + } +#endif + } + + if (writer->obj != NULL) { + if (_PyBytes_Resize(&writer->obj, size)) { + return -1; + } + assert(writer->obj != NULL); + } + else { + writer->obj = PyBytes_FromStringAndSize(NULL, size); + if (writer->obj == NULL) { + return -1; + } + + if (resize) { + assert((size_t)size > sizeof(writer->small_buffer)); + memcpy(PyBytes_AS_STRING(writer->obj), + writer->small_buffer, + sizeof(writer->small_buffer)); + } + } + return 0; +} + +static inline void* +PyBytesWriter_GetData(PyBytesWriter *writer) +{ + if (writer->obj == NULL) { + return writer->small_buffer; + } + else { + return PyBytes_AS_STRING(writer->obj); + } +} + +static inline Py_ssize_t +PyBytesWriter_GetSize(PyBytesWriter *writer) +{ + return writer->size; +} + +static inline void +PyBytesWriter_Discard(PyBytesWriter *writer) +{ + if (writer == NULL) { + return; + } + + Py_XDECREF(writer->obj); + PyMem_Free(writer); +} + +static inline PyBytesWriter* +PyBytesWriter_Create(Py_ssize_t size) +{ + if (size < 0) { + PyErr_SetString(PyExc_ValueError, "size must be >= 0"); + return NULL; + } + + PyBytesWriter *writer = (PyBytesWriter*)PyMem_Malloc(sizeof(PyBytesWriter)); + if (writer == NULL) { + PyErr_NoMemory(); + return NULL; + } + + writer->obj = NULL; + writer->size = 0; + + if (size >= 1) { + if (_PyBytesWriter_Resize_impl(writer, size, 0) < 0) { + PyBytesWriter_Discard(writer); + return NULL; + } + writer->size = size; + } + return writer; +} + +static inline PyObject* +PyBytesWriter_FinishWithSize(PyBytesWriter *writer, Py_ssize_t size) +{ + PyObject *result; + if (size == 0) { + result = PyBytes_FromStringAndSize("", 0); + } + else if (writer->obj != NULL) { + if (size != PyBytes_GET_SIZE(writer->obj)) { + if (_PyBytes_Resize(&writer->obj, size)) { + goto error; + } + } + result = writer->obj; + writer->obj = NULL; + } + else { + result = PyBytes_FromStringAndSize(writer->small_buffer, size); + } + PyBytesWriter_Discard(writer); + return result; + +error: + PyBytesWriter_Discard(writer); + return NULL; +} + +static inline PyObject* +PyBytesWriter_Finish(PyBytesWriter *writer) +{ + return PyBytesWriter_FinishWithSize(writer, writer->size); +} + +static inline PyObject* +PyBytesWriter_FinishWithPointer(PyBytesWriter *writer, void *buf) +{ + Py_ssize_t size = (char*)buf - (char*)PyBytesWriter_GetData(writer); + if (size < 0 || size > _PyBytesWriter_GetAllocated(writer)) { + PyBytesWriter_Discard(writer); + PyErr_SetString(PyExc_ValueError, "invalid end pointer"); + return NULL; + } + + return PyBytesWriter_FinishWithSize(writer, size); +} + +static inline int +PyBytesWriter_Resize(PyBytesWriter *writer, Py_ssize_t size) +{ + if (size < 0) { + PyErr_SetString(PyExc_ValueError, "size must be >= 0"); + return -1; + } + if (_PyBytesWriter_Resize_impl(writer, size, 1) < 0) { + return -1; + } + writer->size = size; + return 0; +} + +static inline int +PyBytesWriter_Grow(PyBytesWriter *writer, Py_ssize_t size) +{ + if (size < 0 && writer->size + size < 0) { + PyErr_SetString(PyExc_ValueError, "invalid size"); + return -1; + } + if (size > PY_SSIZE_T_MAX - writer->size) { + PyErr_NoMemory(); + return -1; + } + size = writer->size + size; + + if (_PyBytesWriter_Resize_impl(writer, size, 1) < 0) { + return -1; + } + writer->size = size; + return 0; +} + +static inline void* +PyBytesWriter_GrowAndUpdatePointer(PyBytesWriter *writer, + Py_ssize_t size, void *buf) +{ + Py_ssize_t pos = (char*)buf - (char*)PyBytesWriter_GetData(writer); + if (PyBytesWriter_Grow(writer, size) < 0) { + return NULL; + } + return (char*)PyBytesWriter_GetData(writer) + pos; +} + +static inline int +PyBytesWriter_WriteBytes(PyBytesWriter *writer, + const void *bytes, Py_ssize_t size) +{ + if (size < 0) { + size_t len = strlen((const char*)bytes); + if (len > (size_t)PY_SSIZE_T_MAX) { + PyErr_NoMemory(); + return -1; + } + size = (Py_ssize_t)len; + } + + Py_ssize_t pos = writer->size; + if (PyBytesWriter_Grow(writer, size) < 0) { + return -1; + } + char *buf = (char*)PyBytesWriter_GetData(writer); + memcpy(buf + pos, bytes, (size_t)size); + return 0; +} + +static inline int +PyBytesWriter_Format(PyBytesWriter *writer, const char *format, ...) + Py_GCC_ATTRIBUTE((format(printf, 2, 3))); + +static inline int +PyBytesWriter_Format(PyBytesWriter *writer, const char *format, ...) +{ + va_list vargs; + va_start(vargs, format); + PyObject *str = PyBytes_FromFormatV(format, vargs); + va_end(vargs); + + if (str == NULL) { + return -1; + } + int res = PyBytesWriter_WriteBytes(writer, + PyBytes_AS_STRING(str), + PyBytes_GET_SIZE(str)); + Py_DECREF(str); + return res; +} +#endif // PY_VERSION_HEX < 0x030F00A1 + + +#if PY_VERSION_HEX < 0x030F00A1 +static inline PyObject* +PyTuple_FromArray(PyObject *const *array, Py_ssize_t size) +{ + PyObject *tuple = PyTuple_New(size); + if (tuple == NULL) { + return NULL; + } + for (Py_ssize_t i=0; i < size; i++) { + PyObject *item = array[i]; + PyTuple_SET_ITEM(tuple, i, Py_NewRef(item)); + } + return tuple; +} +#endif + + +#if PY_VERSION_HEX < 0x030F00A1 +static inline Py_hash_t +PyUnstable_Unicode_GET_CACHED_HASH(PyObject *op) +{ +#ifdef PYPY_VERSION + (void)op; // unused argument + return -1; +#elif PY_VERSION_HEX >= 0x03000000 + return ((PyASCIIObject*)op)->hash; +#else + return ((PyUnicodeObject*)op)->hash; +#endif +} +#endif + + +#ifdef __cplusplus +} +#endif +#endif // PYTHONCAPI_COMPAT + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/schema_info.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/schema_info.h new file mode 100644 index 0000000000000000000000000000000000000000..e022af2a2a585fabe2c8b8867f0e6034d22fbf84 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/schema_info.h @@ -0,0 +1,121 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::utils { + +using SchemaSpecialCasePair = + std::pair>; +/** + * class SchemaInfo + * + * FunctionSchema wrapper that publicizes argument value specific operator + * behavior (mutation, aliasing, special cases, etc...) + */ + +struct TORCH_API SchemaInfo { + public: + explicit SchemaInfo(c10::FunctionSchema schema) + : schema_(std::move(schema)), + alias_maps_current_(false), + has_init_(false) {} + explicit SchemaInfo(const char* signature) + : schema_(torch::jit::parseSchema(signature)), + alias_maps_current_(false), + has_init_(false) {} + + bool is_mutable(); + + bool is_mutable(const c10::SchemaArgument& argument); + + bool is_mutable(std::string_view name); + + bool has_argument(std::string_view name); + + bool is_nondeterministic() const; + + // Returns whether lhs and rhs may alias directly. + // This does not account for cases where lhs or rhs are a container that + // may contain elements that alias the other argument. + // Besides the checks already included in FunctionSchema::may_alias, this + // method also accounts special aliasing cases causes by aliasing argument + // values supplied from addArgumentValue. + bool may_alias( + const c10::SchemaArgument& lhs, + const c10::SchemaArgument& rhs); + + // Returns whether lhs and rhs may alias directly or whether lhs/rhs are a + // container that may contain elements that alias the other argument. Besides + // the checks already included in FunctionSchema::may_contain_alias, this + // method also accounts for special aliasing cases causes by aliasing argument + // values supplied from addArgumentValue. bidirectional = false only returns + // whether lhs may contain an alias of rhs while bidirectional = true returns + // both directions. + bool may_contain_alias( + const c10::SchemaArgument& lhs, + const c10::SchemaArgument& rhs, + bool bidirectional = true); + + void addArgumentValue(const std::string& name, const at::IValue& value); + + void addArgumentValues( + const std::vector>& value_list); + + void addArgumentValues( + const std::unordered_map& values); + + bool hasInputArgumentNamed(const std::string& name) const; + + private: + // This function enforces more conservative results when the TORCH_WARN is + // triggered from above due to duplicates in an argument list + void ensureConservativity( + const std::unordered_set& duplicates, + const std::vector& arguments_list, + c10::SchemaArgType type); + + void initSchemaInfo(); + + void generateAliasMaps(); + + bool mayContainAliasImpl( + const c10::SchemaArgument& lhs, + const c10::SchemaArgument& rhs); + + static std::vector getNonDeterministicOps(); + + static std::vector getTrainingOps(); + + const std::unordered_set& wildcardSet(); + + const std::unordered_set& containerSet(); + + // Set of all wildcard arguments + std::unordered_set wildcard_set_; + + // Set of all container arguments + std::unordered_set container_set_; + + // Map of argument IValues + std::unordered_map value_map_; + + // Alias map of inputs with each other + std::vector> input_alias_map_; + + // Alias map of outputs to inputs + std::vector> output_alias_map_; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const c10::FunctionSchema schema_; + + bool alias_maps_current_; + + bool has_init_; +}; +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/six.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/six.h new file mode 100644 index 0000000000000000000000000000000000000000..85cceb07dcc70d7cce1fe1d67631a64ca3fe2bf8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/six.h @@ -0,0 +1,57 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace six { + +// Usually instances of PyStructSequence is also an instance of tuple +// but in some py2 environment it is not, so we have to manually check +// the name of the type to determine if it is a namedtupled returned +// by a pytorch operator. + +inline bool isStructSeq(pybind11::handle input) { + return pybind11::cast(pybind11::type::handle_of(input).attr( + "__module__")) == "torch.return_types"; +} + +inline bool isStructSeq(PyObject* obj) { + return isStructSeq(pybind11::handle(obj)); +} + +inline bool isTuple(pybind11::handle input) { + if (PyTuple_Check(input.ptr())) { + return true; + } + return false; +} + +inline bool isTuple(PyObject* obj) { + return isTuple(pybind11::handle(obj)); +} + +// maybeAsTuple: if the input is a structseq, then convert it to a tuple +// +// On Python 3, structseq is a subtype of tuple, so these APIs could be used +// directly. But on Python 2, structseq is not a subtype of tuple, so we need to +// manually create a new tuple object from structseq. +inline THPObjectPtr maybeAsTuple(PyStructSequence* obj) { + Py_INCREF(obj); + return THPObjectPtr((PyObject*)obj); +} + +inline THPObjectPtr maybeAsTuple(PyObject* obj) { + if (isStructSeq(obj)) + return maybeAsTuple((PyStructSequence*)obj); + Py_INCREF(obj); + return THPObjectPtr(obj); +} + +} // namespace six + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/structseq.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/structseq.h new file mode 100644 index 0000000000000000000000000000000000000000..8d40d6bf4adc54ded2638bf0c67062a733ce9f5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/structseq.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::utils { + +PyObject* returned_structseq_repr(PyStructSequence* obj); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_apply.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_apply.h new file mode 100644 index 0000000000000000000000000000000000000000..062e093f123e11ee7492cf297b83c8087b336178 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_apply.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::utils { + +const at::Tensor& apply_(const at::Tensor& self, PyObject* fn); +const at::Tensor& map_( + const at::Tensor& self, + const at::Tensor& other_, + PyObject* fn); +const at::Tensor& map2_( + const at::Tensor& self, + const at::Tensor& x_, + const at::Tensor& y_, + PyObject* fn); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_dtypes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_dtypes.h new file mode 100644 index 0000000000000000000000000000000000000000..978bc25e12052f95b40120ba8c097c0940a955f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_dtypes.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::utils { + +std::pair getDtypeNames(at::ScalarType scalarType); + +void initializeDtypes(); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_flatten.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_flatten.h new file mode 100644 index 0000000000000000000000000000000000000000..ea7652eede79d5e40858224f096da4242b8ef41b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_flatten.h @@ -0,0 +1,89 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::utils { + +/// Generate an ID for a combination of tensor backend + scalar type to be used +/// when ordering tensors ('like' tensors are grouped by pulling out their +/// backend + scalar type, so this function combines that into a single number) +inline size_t type_id(const at::Tensor& tensor) { + return static_cast(tensor.options().backend()) * + static_cast(at::ScalarType::NumOptions) + + static_cast(tensor.scalar_type()); +} + +inline at::Tensor flatten_dense_tensors(at::TensorList tensors) { + return at::flatten_dense_tensors(tensors); +} + +inline std::vector unflatten_dense_tensors( + const at::Tensor& flat, + at::TensorList tensors) { + return at::unflatten_dense_tensors(flat, tensors); +} + +struct TensorGroup { + std::vector tensors; + size_t size = 0; + + size_t type_id() { + AT_ASSERT(!tensors.empty()); + return ::torch::utils::type_id(tensors[0]); + } + + const at::TensorOptions options() { + AT_ASSERT(!tensors.empty()); + return tensors[0].options(); + } +}; + +// Helper function that takes a list of tensors and splits them into tensor +// groups by the size limit and outputs these tensor groups. If the input +// tensors are of different tensor types, they will be split into different +// groups as well. +// +// Two options of splitting provided to the user, +// +// Imagine the size_limit is 256 and the list of input tensors are: +// tensor_a(fp16 - 128 bytes), +// tensor_b(fp32 - 256 bytes), +// tensor_c(fp16 - 128 bytes), +// +// when fine_grained == false: +// The function will read the list of tensors sequentially and accumulate +// enough tensors for each data type until the size_limit, therefore: +// it will output: {{tensor_a, tensor_c}, {tensor_b}} +// +// when fine_grained == true: +// The function will read the list of tensors sequentially and accumulate +// enough tensors for all data types until the size_limit, and then split +// the accumulated tensors into different groups by data types, therefore: +// it will output: {{tensor_a}, {tensor_b}, {tensor_c}} +TORCH_API std::vector take_tensors( + at::TensorList tensors, + size_t size_limit, + bool fine_grained = false); + +TORCH_API void reorder_tensors_like( + std::vector& tensors, + at::TensorList order); + +TORCH_API std::pair flatten_sparse_tensors( + at::TensorList tensors); + +TORCH_API std::vector unflatten_sparse_tensors( + const at::Tensor& flat_indices, + const at::Tensor& flat_values, + at::TensorList tensors); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_layouts.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_layouts.h new file mode 100644 index 0000000000000000000000000000000000000000..5521d1c4e0b8875c063e1ee14dae951c58e32bba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_layouts.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::utils { + +void initializeLayouts(); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_list.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_list.h new file mode 100644 index 0000000000000000000000000000000000000000..8705ab13d1483cb270536d660217527e0c21b308 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_list.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace at { +class Tensor; +} + +namespace torch::utils { + +PyObject* tensor_to_list(const at::Tensor& tensor); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_memoryformats.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_memoryformats.h new file mode 100644 index 0000000000000000000000000000000000000000..489033081dd89b705f048aba9fbb7f228851868a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_memoryformats.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::utils { + +void initializeMemoryFormats(); + +// This methods returns a borrowed reference! +TORCH_PYTHON_API PyObject* getTHPMemoryFormat( + c10::MemoryFormat /*memory_format*/); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_new.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_new.h new file mode 100644 index 0000000000000000000000000000000000000000..0f17085276e2fda34ba4c02cb82d327da495048a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_new.h @@ -0,0 +1,141 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::utils { + +// NOTE: [torch.tensor, lift_fresh, and device movement] +// +// The `only_lift_cpu_tensors` flag controls what happens on torch.tensor([1, 2, +// 3], device="cuda") (or any non-CPU devices). +// +// If false (default): +// - the data gets moved into a CPU Tensor +// - then, it gets moved to cuda (via .to) +// - finally, we call lift_fresh() on it. +// Steps 1 and 2 happen with all modes disabled. +// +// If true: +// - the data gets moved into a CPU Tensor (with correct dtype) +// - we call lift_fresh() on it +// - finally, we move it to cuda (via .to) +// Step 1 happens with all modes disabled. +// +// `only_lift_cpu_tensors=true` is useful to prevent CUDA initialization under +// FakeTensorMode because it avoids moving concrete data to CUDA. +TORCH_API bool only_lift_cpu_tensors(); +TORCH_API void set_only_lift_cpu_tensors(bool value); + +at::Tensor base_tensor_ctor(PyObject* args, PyObject* kwargs); +TORCH_PYTHON_API at::Tensor legacy_tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); +at::Tensor legacy_tensor_new( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); +at::Tensor indexing_tensor_from_data( + c10::TensorOptions options, + at::ScalarType scalar_type, + std::optional device, + PyObject* data); +at::Tensor sparse_coo_tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); +void _validate_sparse_coo_tensor_args( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); + +at::Tensor sparse_compressed_tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); +at::Tensor sparse_csr_tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); +at::Tensor sparse_csc_tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); +at::Tensor sparse_bsr_tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); +at::Tensor sparse_bsc_tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); + +void _validate_sparse_compressed_tensor_args( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); +void _validate_sparse_csr_tensor_args( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); +void _validate_sparse_csc_tensor_args( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); +void _validate_sparse_bsr_tensor_args( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); +void _validate_sparse_bsc_tensor_args( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); + +at::Tensor tensor_ctor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); +at::Tensor as_tensor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PythonArgs& r); +at::Tensor new_tensor( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); +at::Tensor new_ones( + c10::DispatchKey dispatch_key, + at::ScalarType scalar_type, + PyObject* args, + PyObject* kwargs); +at::Tensor tensor_frombuffer( + PyObject* buffer, + at::ScalarType dtype, + int64_t count, + int64_t offset, + bool requires_grad); +at::Tensor tensor_fromDLPack(PyObject* data); +at::Tensor asarray( + PyObject* obj, + std::optional dtype, + std::optional device, + std::optional copy, + bool requires_grad); +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_numpy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_numpy.h new file mode 100644 index 0000000000000000000000000000000000000000..b43522b8708452c5847be2873908d5c0f57ae6ad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_numpy.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::utils { + +TORCH_API PyObject* tensor_to_numpy( + const at::Tensor& tensor, + bool force = false); + +TORCH_API at::Tensor tensor_from_numpy( + PyObject* obj, + bool warn_if_not_writeable = true); + +TORCH_API int aten_to_numpy_dtype(const at::ScalarType scalar_type); +TORCH_API at::ScalarType numpy_dtype_to_aten(int dtype); + +TORCH_API bool is_numpy_available(); +TORCH_API bool is_numpy_int(PyObject* obj); +TORCH_API bool is_numpy_bool(PyObject* obj); +TORCH_API bool is_numpy_scalar(PyObject* obj); + +void warn_numpy_not_writeable(); +at::Tensor tensor_from_cuda_array_interface( + PyObject* obj, + std::optional device_opt = std::nullopt); + +void validate_numpy_for_dlpack_deleter_bug(); +bool is_numpy_dlpack_deleter_bugged(); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_qschemes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_qschemes.h new file mode 100644 index 0000000000000000000000000000000000000000..d7b24333ad63eab535b31d529754b3a4d3b30b82 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_qschemes.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::utils { + +PyObject* getTHPQScheme(at::QScheme qscheme); +void initializeQSchemes(); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_types.h new file mode 100644 index 0000000000000000000000000000000000000000..d7891fedb997e32d9481613e9cce8c1754c8bd11 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_types.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::utils { + +std::string options_to_string(const at::TensorOptions& options); +std::string type_to_string(const at::DeprecatedTypeProperties& type); +at::TensorOptions options_from_string(const std::string& str); + +// return a vector of all "declared" types, even those that weren't compiled +std::vector> all_declared_types(); + +// return python module name of backend, like torch.cuda, torch.foo +const char* backend_to_string(const at::Backend& backend); + +} // namespace torch::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/throughput_benchmark-inl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/throughput_benchmark-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..fa267bc1fc3a8ef59b60e5cee3777f696bd6b509 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/throughput_benchmark-inl.h @@ -0,0 +1,176 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::throughput_benchmark::detail { + +template +BenchmarkExecutionStats BenchmarkHelper::benchmark( + const BenchmarkConfig& config) const { + CHECK(initialized_); + TORCH_CHECK( + config.num_worker_threads == 1, + "Only parallelization by callers is supported"); + + LOG(INFO) << at::get_parallel_info(); + + // We pre-generate inputs here for each of the threads. This allows us to + // safely move inputs out for each of the threads independently and thus avoid + // overhead from the benchmark runner itself + std::vector> thread_inputs(config.num_calling_threads); + std::vector input_iters(config.num_calling_threads); + { + std::random_device seeder; + std::mt19937 engine(seeder()); + TORCH_CHECK( + !inputs_.empty(), + "Please provide benchmark inputs." + "Did you forget to call add_input()? "); + std::uniform_int_distribution dist(0, inputs_.size() - 1); + + for (const auto thread_id : c10::irange(config.num_calling_threads)) { + // Just in case we generate num_iters inputs for each of the threads + // This was if one thread does all the work we will be fine + for (const auto i [[maybe_unused]] : + c10::irange(config.num_iters + config.num_warmup_iters)) { + thread_inputs[thread_id].push_back(cloneInput(inputs_[dist(engine)])); + } + input_iters[thread_id] = 0; + } + } + + std::mutex m; + std::condition_variable worker_main_cv; + std::condition_variable main_worker_cv; + // TODO: add GUARDED_BY once it is available + int64_t initialized{0}; + int64_t finished{0}; + bool start{false}; + std::atomic num_attempted_iters{0}; + std::vector callers; + + callers.reserve(config.num_calling_threads); + + static constexpr auto& DEVICES = at::autocast::_AUTOCAST_SUPPORTED_DEVICES; + std::array autocast_enabled; + std::array autocast_dtype; + for (size_t i = 0; i < DEVICES.size(); i++) { + autocast_enabled[i] = at::autocast::is_autocast_enabled(DEVICES[i]); + autocast_dtype[i] = at::autocast::get_autocast_dtype(DEVICES[i]); + } + bool autocast_cache_enabled = at::autocast::is_autocast_cache_enabled(); + bool tls_grad_enabled = c10::GradMode::is_enabled(); + c10::impl::LocalDispatchKeySet tls_key_set = + c10::impl::tls_local_dispatch_key_set(); + + for (const auto thread_id : c10::irange(config.num_calling_threads)) { + callers.emplace_back([&, thread_id]() { + // We use conditional variable as a barrier to make sure each thread + // performs required warmeup iterations before we start measuring + c10::GradMode::set_enabled(tls_grad_enabled); + c10::impl::_force_tls_local_dispatch_key_set(tls_key_set); + for (size_t i = 0; i < DEVICES.size(); i++) { + at::autocast::set_autocast_enabled(DEVICES[i], autocast_enabled[i]); + at::autocast::set_autocast_dtype(DEVICES[i], autocast_dtype[i]); + } + at::autocast::set_autocast_cache_enabled(autocast_cache_enabled); + + for (const auto j : c10::irange(config.num_warmup_iters)) { + (void)j; + runOnce(std::move(thread_inputs[thread_id][input_iters[thread_id]])); + ++input_iters[thread_id]; + } + { + std::unique_lock lock(m); + ++initialized; + worker_main_cv.notify_one(); + // NOLINTNEXTLINE(bugprone-infinite-loop) + while (!start) { + main_worker_cv.wait(lock); + } + } + LOG(INFO) << "Starting forward thread " << thread_id; + while (num_attempted_iters.fetch_add(1) < config.num_iters) { + runOnce(std::move(thread_inputs[thread_id][input_iters[thread_id]])); + ++input_iters[thread_id]; + } + + { + std::unique_lock lock(m); + ++finished; + worker_main_cv.notify_one(); + LOG(INFO) << "Shutting down forward thread " << thread_id + << ". Total number of finished threads: " << finished; + } + }); + } + + using Clock = std::chrono::high_resolution_clock; + using RecordProfile = torch::autograd::profiler::RecordProfile; + using TimePoint = std::chrono::time_point; + TimePoint start_time; + + std::unique_ptr profiler_guard; + { + std::unique_lock lock(m); + while (initialized != config.num_calling_threads) { + worker_main_cv.wait(lock); + } + if (!config.profiler_output_path.empty()) { + LOG(INFO) << "Using Autograd profiler. Trace will be saved to " + << config.profiler_output_path; + profiler_guard = + std::make_unique(config.profiler_output_path); + } + LOG(INFO) << "Starting threads"; + start = true; + start_time = Clock::now(); + } + + main_worker_cv.notify_all(); + { + std::unique_lock lock(m); + worker_main_cv.wait( + lock, [&]() { return finished == config.num_calling_threads; }); + } + auto end_time = std::chrono::high_resolution_clock::now(); + profiler_guard.reset(); + LOG(INFO) << "Finished benchmark"; + + BenchmarkExecutionStats stats; + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + float total_time_ms = std::chrono::duration_cast( + end_time - start_time) + .count() / + 1000.0 / 1000.0; + // We use config.num_iters instead of num_attempted_iters as it is + // repsesatative of the real work done. Last attempted iteration on each + // calling threads doesn't represent the real work (i.e. running the model) + stats.latency_avg_ms = + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + total_time_ms * config.num_calling_threads / config.num_iters; + stats.num_iters = config.num_iters; + + for (auto& t : callers) { + t.join(); + } + return stats; +} + +} // namespace torch::throughput_benchmark::detail + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/throughput_benchmark.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/throughput_benchmark.h new file mode 100644 index 0000000000000000000000000000000000000000..4206d38fa32a08ff661e4686ac6a41a822993770 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/throughput_benchmark.h @@ -0,0 +1,204 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace py = pybind11; + +namespace torch::throughput_benchmark { + +/** + * The struct is used to provide results of a benchmark to the caller + * In the future all additional statistics should be added here. + */ +struct BenchmarkExecutionStats { + float latency_avg_ms{-1}; + int64_t num_iters{-1}; +}; + +std::ostream& operator<<( + std::ostream& os, + const BenchmarkExecutionStats& value); + +/** + * Use this struct in order to configure a throughput benchmark run. + * This struct should include parameters related to threading, batching, number + * of iterations, warm-up, etc. More configs can be added as needed. + * General rule here is that only things that c++ must(!) to be aware of should + * be here. If we can keep other parts in python, we should keep them there. + * This is typical for things that are not perf critical and don't affect + * execution statistics benchmark returns. + */ +struct BenchmarkConfig { + public: + // Calling threads are those threads that are calling into a module in + // parallel. + int num_calling_threads{1}; + // Worker threads are not supported yet. This is just an example that we plan + // to support some sort of multi-threaded forward calls. We may change this + // setting in the future to support different intra and inter op parallelism + // which is not available in PyTorch yet + int num_worker_threads{1}; + // Warmup iters are used to make sure we run a module a few times before + // actually measuring things. This way we avoid cold caches and any other + // similar problems + int num_warmup_iters{1}; + // Number of iterations the benchmark should run with. This number is separate + // from the warmup iterations + int64_t num_iters{100}; + // If set autograd profiler will be enabled. I.e. this variable would be + // created before the main benchmark loop (but after the warmup): + // RecordProfile guard(profiler_output_path); + std::string profiler_output_path; +}; + +namespace detail { + +/** + * A helper class to abstract out different models we test throughput of + */ +template +class BenchmarkHelper { + public: + BenchmarkHelper(); + explicit BenchmarkHelper(Model model) + : model_(std::move(model)), initialized_(true) {} + + // This method to be used in benchmark() method + // Note that there is no result. This way we don't have to call this under GIL + // even when running in the nn.Module mode. Otherwise destructor of the result + // would race with Python + void runOnce(Input&&) const; + // This method is to be used when calling from Python directly + Output runOnce(const py::args&, const py::kwargs&) const; + // Aggregate input in the format Model expects in order to avoid further + // conversions at the benchmark time + void addInput(py::args&&, py::kwargs&&); + void addInput(Input&&); + BenchmarkExecutionStats benchmark(const BenchmarkConfig& config) const; + + bool initialized() const { + return initialized_; + } + + // Destructor doesn't require the GIL because it is going to be executed on + // the PyThon thread + std::vector inputs_; + Model model_; + bool initialized_{false}; +}; + +struct C10_HIDDEN ModuleInput { + ModuleInput(ModuleInput&& other) = default; + + ModuleInput(const ModuleInput&) = delete; + ModuleInput& operator=(ModuleInput& other) = delete; + ModuleInput& operator=(ModuleInput&& other) = delete; + ~ModuleInput() = default; + + ModuleInput(py::args&& args, py::kwargs&& kwargs) + : args(std::move(args)), kwargs(std::move(kwargs)) {} + + py::args args; + py::kwargs kwargs; +}; +typedef py::object ModuleOutput; +typedef std::vector ScriptModuleInput; +typedef at::IValue ScriptModuleOutput; + +template +Input cloneInput(const Input& input); + +typedef BenchmarkHelper + ScriptModuleBenchmark; +template <> +inline BenchmarkHelper:: + BenchmarkHelper() + : model_("Module", std::make_shared()), + initialized_(false) {} +typedef BenchmarkHelper ModuleBenchmark; +template <> +inline BenchmarkHelper::BenchmarkHelper() + : initialized_(false) {} + +template <> +void ScriptModuleBenchmark::runOnce(ScriptModuleInput&& input) const; + +template <> +ScriptModuleOutput ScriptModuleBenchmark::runOnce( + const py::args& args, + const py::kwargs& kwargs) const; + +template <> +void ModuleBenchmark::runOnce(ModuleInput&& input) const; + +template <> +ModuleOutput ModuleBenchmark::runOnce( + const py::args& args, + const py::kwargs& kwargs) const; + +template <> +void ScriptModuleBenchmark::addInput(py::args&& args, py::kwargs&& kwargs); +template <> +void ScriptModuleBenchmark::addInput(ScriptModuleInput&& input); + +template <> +void ModuleBenchmark::addInput(py::args&& args, py::kwargs&& kwargs); + +} // namespace detail + +/** + * This class is a small c++ component responsible for executing a PyTorch + * module under an inference server like load. It can emulate multiple calling + * threads to a single module provided. In the future we plan to enhance this + * component to support inter and intra-op parallelism as well as multiple + * models running in a single process. + * + * For current available configurations refer to the BenchmarkConfig + * documentation + * + * The class supports working with either nn.Module or ScriptModule. + * Under the hood it just dispatches to corresponding specialization of + * class BenchmarkHelper + */ +class C10_HIDDEN ThroughputBenchmark { + public: + explicit ThroughputBenchmark(const jit::Module& module); + explicit ThroughputBenchmark(py::object module); + + // Add one more input example. This input example should be in the exact + // format the module under test expects. It is responsibility of the module to + // perform any such format checks, the benchmark doesn't perform any + // validation of its own + void addInput(py::args args, py::kwargs kwargs); + + // Equivalent to just running the model directly on the given input + py::object runOnce(const py::args& args, const py::kwargs& kwargs); + + // The main method of the class allows to perform a multi-threaded benchmark + // It returns BenchmarkExecutionStats object with a lot of useful statistics + // about runtime execution. We can enhance this class in the future to provide + // more information to the user + BenchmarkExecutionStats benchmark(const BenchmarkConfig& config) const; + + private: + detail::ScriptModuleBenchmark script_module_; + detail::ModuleBenchmark module_; +}; +} // namespace torch::throughput_benchmark + +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/torch_dispatch_mode.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/torch_dispatch_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..1fd554d248bd3b430bf4e54dc8dd74f14e78c64f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/torch_dispatch_mode.h @@ -0,0 +1,73 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::torch_dispatch_mode { + +struct StashTorchDispatchModeGuard { + public: + StashTorchDispatchModeGuard() { + if (c10::impl::TorchDispatchModeTLS::any_modes_set( + /*skip_infra_modes=*/true)) { + saved_mode_ = c10::impl::TorchDispatchModeTLS::pop_stack(); + } else { + auto mode_and_key = + c10::impl::TorchDispatchModeTLS::pop_highest_infra_mode(); + saved_mode_ = std::move(std::get<0>(mode_and_key)); + saved_mode_key_ = std::get<1>(mode_and_key); + } + } + + ~StashTorchDispatchModeGuard() { + if (saved_mode_key_.has_value()) { + c10::impl::TorchDispatchModeTLS::set_mode( + saved_mode_, saved_mode_key_.value()); + } else { + c10::impl::TorchDispatchModeTLS::push_non_infra_mode_onto_stack( + std::move(saved_mode_)); + } + } + StashTorchDispatchModeGuard(const StashTorchDispatchModeGuard&) = delete; + StashTorchDispatchModeGuard(StashTorchDispatchModeGuard&&) = delete; + StashTorchDispatchModeGuard& operator=(const StashTorchDispatchModeGuard&) = + delete; + StashTorchDispatchModeGuard& operator=(StashTorchDispatchModeGuard&&) = + delete; + + const std::shared_ptr& get_cur_mode() { + return saved_mode_; + } + + private: + std::shared_ptr saved_mode_; + std::optional saved_mode_key_; +}; + +struct StashTorchDispatchStackGuard { + public: + StashTorchDispatchStackGuard() { + auto old = c10::impl::TorchDispatchModeTLS::get_state(); + c10::impl::TorchDispatchModeTLS::set_state(std::move(saved_state_)); + saved_state_ = std::move(old); + } + StashTorchDispatchStackGuard(const StashTorchDispatchStackGuard&) = delete; + StashTorchDispatchStackGuard(StashTorchDispatchStackGuard&&) = delete; + StashTorchDispatchStackGuard& operator=(const StashTorchDispatchStackGuard&) = + delete; + StashTorchDispatchStackGuard& operator=(StashTorchDispatchStackGuard&&) = + delete; + + ~StashTorchDispatchStackGuard() { + c10::impl::TorchDispatchModeTLS::set_state(std::move(saved_state_)); + } + + private: + c10::impl::TorchDispatchModeTLS saved_state_; +}; + +} // namespace torch::torch_dispatch_mode + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/variadic.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/variadic.h new file mode 100644 index 0000000000000000000000000000000000000000..e080abdbeb64ab85591aad79431f683743f0aed9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/variadic.h @@ -0,0 +1,116 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch { + +using at::IterArgs; + +struct CountTensors : IterArgs { + size_t out = 0; + void operator()(const at::Tensor& x) { + out += 1; + } + void operator()(const std::optional& x) { + out += x.has_value(); + } + void operator()(at::ArrayRef xs) { + out += xs.size(); + } +}; + +template +size_t count_tensors(Args&&... args) { + return CountTensors().apply(std::forward(args)...).out; +} + +struct CountVariables : IterArgs { + size_t out = 0; + void operator()(const autograd::Variable& x) { + out += 1; + } + void operator()(at::ArrayRef xs) { + out += xs.size(); + } +}; + +template +inline size_t count_variables(Args&&... args) { + return CountVariables().apply(std::forward(args)...).out; +} + +//===----------------------------------------------------------------------===// +// std::index_sequence shim for C++11 +//===----------------------------------------------------------------------===// + +// A container of type-template parameter indices. +template +struct Indices {}; + +// Decrements the index N, adds N-1 to the list of indices and forwards +// whatever we already have. +template +struct MakeIndices : MakeIndices {}; + +// Partial specialization that forms our base case. When N is zero, we stop +// and define a typedef that will be visible to earlier classes due to +// inheritance. The typedef we define is an index list containing the numbers +// 0 through N-1. +template +struct MakeIndices<0, Is...> { + using indices = Indices; +}; + +//===----------------------------------------------------------------------===// +// Utilities +//===----------------------------------------------------------------------===// + +template +void apply(Function function, Ts&&... ts) { + // https://stackoverflow.com/questions/13978916/inserting-a-variadic-argument-list-into-a-vector + // Creates a dummy array, so that each function call is evaluated in order. + // `(function(), 0)` is because `function` should (!) return `void`, so + // according to the comma operator, it is evaluated and its result (`void`) + // is discarded. Then the zero is evaluated and used as an element in the + // array. The first zero ensures the array is not empty. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + int _[]{0, (function(std::forward(ts)), 0)...}; + (void)_; +} + +template < + typename ReturnType, + typename... Ts, + typename Function, + typename Accessor> +ReturnType unpack(Function function, Accessor accessor) { + return ReturnType(unpack( + std::move(function), + std::move(accessor), + typename MakeIndices::indices())); +} + +template < + typename ReturnType, + typename... Ts, + typename Function, + typename Accessor, + size_t... Is> +ReturnType unpack( + Function function, + Accessor accessor, + Indices /*unused*/) { + return ReturnType(function(accessor.template operator()(Is)...)); +} + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/verbose.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/verbose.h new file mode 100644 index 0000000000000000000000000000000000000000..54a879f7d456e18a73eade463c9b5b5188f19f33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/utils/verbose.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch { + +void initVerboseBindings(PyObject* module); + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Event.h new file mode 100644 index 0000000000000000000000000000000000000000..3dc8e69a8758a86e38775d94db140eab22198d8d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Event.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +struct THXPEvent : THPEvent { + at::xpu::XPUEvent xpu_event; +}; +extern PyObject* THXPEventClass; + +void THXPEvent_init(PyObject* module); + +inline bool THXPEvent_Check(PyObject* obj) { + return THXPEventClass && PyObject_IsInstance(obj, THXPEventClass); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..1f2eb36ed24981065ffdf7614eb9512f94bb2094 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Module.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +PyMethodDef* THXPModule_methods(); + +namespace torch::xpu { + +void initModule(PyObject* module); + +} // namespace torch::xpu + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Stream.h new file mode 100644 index 0000000000000000000000000000000000000000..de7e8366741469a70ceebb33215e0e13eb7119e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/Stream.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) +struct THXPStream : THPStream { + at::xpu::XPUStream xpu_stream; +}; +extern PyObject* THXPStreamClass; + +void THXPStream_init(PyObject* module); + +inline bool THXPStream_Check(PyObject* obj) { + return THXPStreamClass && PyObject_IsInstance(obj, THXPStreamClass); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/XPUPluggableAllocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/XPUPluggableAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..8a34baba3b47a204e44eb037e0125047487d3aba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/xpu/XPUPluggableAllocator.h @@ -0,0 +1,85 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::xpu::XPUPluggableAllocator { + +struct _AllocationMetadata { + _AllocationMetadata() {} + _AllocationMetadata( + size_t size, + c10::DeviceIndex device_idx, + sycl::queue* queue) + : size(size), device_idx(device_idx), queue(queue) {} + size_t size{0}; + c10::DeviceIndex device_idx{-1}; + sycl::queue* queue{}; +}; + +struct TORCH_PYTHON_API XPUPluggableAllocator + : public c10::xpu::XPUCachingAllocator::XPUAllocator { + XPUPluggableAllocator( + std::function alloc_fn, + std::function free_fn) + : alloc_fn_(std::move(alloc_fn)), free_fn_(std::move(free_fn)) {} + + C10_DISABLE_COPY_AND_ASSIGN(XPUPluggableAllocator); + + ~XPUPluggableAllocator() override = default; + + void* malloc(size_t size, c10::DeviceIndex device, sycl::queue* stream); + + c10::DataPtr allocate(size_t size) override; + c10::DeleterFnPtr raw_deleter() const override; + + void* raw_alloc(size_t nbytes) override; + void raw_delete(void* ptr) override; + void init(c10::DeviceIndex device_count) override; + bool initialized() override; + void copy_data(void* dest, const void* src, std::size_t count) const final; + + void recordStream(const c10::DataPtr&, c10::Stream stream) override; + void emptyCache(c10::MempoolId_t mempool_id = {0, 0}) override; + c10::CachingDeviceAllocator::DeviceStats getDeviceStats( + c10::DeviceIndex device) override; + void resetAccumulatedStats(c10::DeviceIndex device) override; + void resetPeakStats(c10::DeviceIndex device) override; + + void set_init_fn(std::function init_fn) { + init_fn_ = std::move(init_fn); + } + void set_record_stream_fn( + std::function record_stream_fn) { + record_stream_fn_ = std::move(record_stream_fn); + } + + protected: + std::function alloc_fn_; + std::function free_fn_; + std::function init_fn_; + std::function record_stream_fn_; + std::mutex allocator_mutex_; + // We do the bookkeeping here in order to simplify custom allocators + std::unordered_map allocation_metadata_; + bool initialized_ = false; +}; + +TORCH_XPU_API std::shared_ptr +getCurrentAllocator(); + +TORCH_XPU_API std::shared_ptr +createCustomAllocator( + std::function alloc_fn, + std::function free_fn); + +TORCH_XPU_API void changeCurrentAllocator( + const std::shared_ptr& + allocator); + +} // namespace torch::xpu::XPUPluggableAllocator + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/DeviceType.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/DeviceType.h new file mode 100644 index 0000000000000000000000000000000000000000..9db3ef2568d341fb9a341a36c02ac91c4dcca30f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/DeviceType.h @@ -0,0 +1,128 @@ +#pragma once + +// This is directly synchronized with caffe2/proto/caffe2.proto, but +// doesn't require me to figure out how to get Protobuf headers into +// ATen/core (which would require a lot more build system hacking.) +// If you modify me, keep me synchronized with that file. + +#include +#include + +#include +#include +#include + +namespace c10 { + +// These contains all device types that also have a BackendComponent +// and therefore participate in per-backend functionality dispatch keys. +// This is most backends except PrivateUse2 and PrivateUse3 +#define C10_FORALL_BACKEND_DEVICE_TYPES(_, extra) \ + _(CPU, extra) \ + _(CUDA, extra) \ + _(HIP, extra) \ + _(XLA, extra) \ + _(MPS, extra) \ + _(IPU, extra) \ + _(XPU, extra) \ + _(HPU, extra) \ + _(VE, extra) \ + _(Lazy, extra) \ + _(Meta, extra) \ + _(MTIA, extra) \ + _(PrivateUse1, extra) + +enum class DeviceType : int8_t { + CPU = 0, + CUDA = 1, // CUDA. + MKLDNN = 2, // Reserved for explicit MKLDNN + OPENGL = 3, // OpenGL + OPENCL = 4, // OpenCL + IDEEP = 5, // IDEEP. + HIP = 6, // AMD HIP + FPGA = 7, // FPGA + MAIA = 8, // ONNX Runtime / Microsoft + XLA = 9, // XLA / TPU + Vulkan = 10, // Vulkan + Metal = 11, // Metal + XPU = 12, // XPU + MPS = 13, // MPS + Meta = 14, // Meta (tensors with no data) + HPU = 15, // HPU / HABANA + VE = 16, // SX-Aurora / NEC + Lazy = 17, // Lazy Tensors + IPU = 18, // Graphcore IPU + MTIA = 19, // Meta training and inference devices + PrivateUse1 = 20, // PrivateUse1 device + // NB: If you add more devices: + // - Change the implementations of DeviceTypeName and isValidDeviceType + // in c10/core/DeviceType.cpp + // - Change the number below + COMPILE_TIME_MAX_DEVICE_TYPES = 21, +}; + +constexpr DeviceType kCPU = DeviceType::CPU; +constexpr DeviceType kCUDA = DeviceType::CUDA; +constexpr DeviceType kHIP = DeviceType::HIP; +constexpr DeviceType kFPGA = DeviceType::FPGA; +constexpr DeviceType kMAIA = DeviceType::MAIA; +constexpr DeviceType kXLA = DeviceType::XLA; +constexpr DeviceType kMPS = DeviceType::MPS; +constexpr DeviceType kMeta = DeviceType::Meta; +constexpr DeviceType kVulkan = DeviceType::Vulkan; +constexpr DeviceType kMetal = DeviceType::Metal; +constexpr DeviceType kXPU = DeviceType::XPU; +constexpr DeviceType kHPU = DeviceType::HPU; +constexpr DeviceType kVE = DeviceType::VE; +constexpr DeviceType kLazy = DeviceType::Lazy; +constexpr DeviceType kIPU = DeviceType::IPU; +constexpr DeviceType kMTIA = DeviceType::MTIA; +constexpr DeviceType kPrivateUse1 = DeviceType::PrivateUse1; + +// define explicit int constant +constexpr int COMPILE_TIME_MAX_DEVICE_TYPES = + static_cast(DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES); + +static_assert( + COMPILE_TIME_MAX_DEVICE_TYPES <= 21, + "Hey! You seem to be adding a lot of new DeviceTypes. The intent was " + "for this constant to reflect the actual number of DeviceTypes we support " + "in PyTorch; it's important that this number is not too large as we " + "use this to allocate stack arrays in some places in our code. If you " + "are indeed just adding the 20th device type, feel free to change " + "the check to 32; but if you are adding some sort of extensible device " + "types registration, please be aware that you are affecting code that " + "this number is small. Try auditing uses of this constant."); + +} // namespace c10 + +namespace std { +template <> +struct hash { + std::size_t operator()(c10::DeviceType k) const { + return std::hash()(static_cast(k)); + } +}; +} // namespace std + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::COMPILE_TIME_MAX_DEVICE_TYPES; +using c10::DeviceType; +using c10::kCPU; +using c10::kCUDA; +using c10::kFPGA; +using c10::kHIP; +using c10::kHPU; +using c10::kIPU; +using c10::kLazy; +using c10::kMAIA; +using c10::kMeta; +using c10::kMetal; +using c10::kMPS; +using c10::kMTIA; +using c10::kPrivateUse1; +using c10::kVE; +using c10::kVulkan; +using c10::kXLA; +using c10::kXPU; +HIDDEN_NAMESPACE_END(torch, headeronly) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Dispatch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..43293ef701ddac509c51abd9a4c1f923e61118f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Dispatch.h @@ -0,0 +1,73 @@ +#pragma once + +#include +#include + +// THO_PRIVATE_CASE_TYPE_USING_HINT_TMPL is same as +// AT_PRIVATE_CASE_TYPE_USING_HINT but with a custom PRELUDE macro: +#define THO_PRIVATE_CASE_TYPE_USING_HINT_TMPL(PRELUDE, enum_type, HINT, ...) \ + case enum_type: { \ + PRELUDE(enum_type); \ + using HINT [[maybe_unused]] = \ + torch::headeronly::impl::ScalarTypeToCPPTypeT; \ + return __VA_ARGS__(); \ + } + +// THO_DISPATCH_CASE_TMPL is same as AT_DISPATCH_CASE but with a +// custom CASE_TYPE_USING_HINT macro: +#define THO_DISPATCH_CASE_TMPL(CASE_TYPE_USING_HINT, enum_type, ...) \ + CASE_TYPE_USING_HINT(enum_type, scalar_t, __VA_ARGS__) + +namespace detail { +inline torch::headeronly::ScalarType scalar_type( + torch::headeronly::ScalarType s) { + return s; +} +} // namespace detail + +// THO_DISPATCH_SWITCH_TMPL is same as AT_DISPATCH_SWITCH but with +// custom PRELUDE and CHECK_NOT_IMPLEMENTED macros: +#define THO_DISPATCH_SWITCH_TMPL( \ + PRELUDE, CHECK_NOT_IMPLEMENTED, TYPE, NAME, ...) \ + [&] { \ + const auto& the_type = TYPE; \ + constexpr const char* at_dispatch_name = NAME; \ + /* don't use TYPE again in case it is an expensive or side-effect op */ \ + torch::headeronly::ScalarType _st = ::detail::scalar_type(the_type); \ + PRELUDE(at_dispatch_name, _st); \ + C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wswitch-enum") \ + switch (_st) { \ + __VA_ARGS__ \ + default: \ + CHECK_NOT_IMPLEMENTED( \ + false, \ + '"', \ + at_dispatch_name, \ + "\" not implemented for '", \ + torch::headeronly::toString(_st), \ + "'"); \ + } \ + C10_DIAGNOSTIC_POP() \ + }() + +// THO_EMPTY is a helper macro that discards its arguments. +#define THO_EMPTY(...) + +// THO_PRIVATE_CASE_TYPE_USING_HINT is same as +// AT_PRIVATE_CASE_TYPE_USING_HINT with call to macro +// AT_PRIVATE_CHECK_SELECTIVE_BUILD removed. +#define THO_PRIVATE_CASE_TYPE_USING_HINT(enum_type, HINT, ...) \ + THO_PRIVATE_CASE_TYPE_USING_HINT_TMPL(THO_EMPTY, enum_type, HINT, __VA_ARGS__) + +// THO_DISPATCH_SWITCH is same as AT_DISPATCH_SWITCH with call to +// macro RECORD_KERNEL_FUNCTION_DTYPE removed and using +// STD_TORCH_CHECK instead of TORCH_CHECK_NOT_IMPLEMENTED. +#define THO_DISPATCH_SWITCH(TYPE, NAME, ...) \ + THO_DISPATCH_SWITCH_TMPL(THO_EMPTY, STD_TORCH_CHECK, TYPE, NAME, __VA_ARGS__) + +// THO_DISPATCH_CASE is same as AT_DISPATCH_CASE but using +// THO_PRIVATE_CASE_TYPE_USING_HINT instead of +// AT_PRIVATE_CASE_TYPE_USING_HINT. +#define THO_DISPATCH_CASE(enum_type, ...) \ + THO_DISPATCH_CASE_TMPL( \ + THO_PRIVATE_CASE_TYPE_USING_HINT, enum_type, __VA_ARGS__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Dispatch_v2.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Dispatch_v2.h new file mode 100644 index 0000000000000000000000000000000000000000..13cbd2ee85e5f8aca7f672b7802d2dd47ae9cf19 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Dispatch_v2.h @@ -0,0 +1,170 @@ +#pragma once + +#include +#include + +// This file provides THO_DISPATCH_V2_TMPL macro that is a generalized +// version of the original AT_DISPATCH_V2 (see ATen/Dispatch_v2.h for +// documentation): THO_DISPATCH_V2_TMPL extends AT_DISPATCH_V2 with +// extra DISPATCH_SWITCH and DISPATCH_CASE arguments for specifying +// custom implementations of the original AT_DISPATCH_SWITCH and +// AT_DISPATCH_CASE macros. Use the provided macros +// THO_DISPATCH_SWITCH_TMPL and THO_DISPATCH_CASE_TMPL to define the +// custom implementations of the switch and case macros, respectively. + +// Public API macros + +// THO_DISPATCH_V2_TMPL is same as AT_DISPATCH_V2 but with custom +// DISPATCH_SWITCH and DISPATCH_CASE macro arguments: +#define THO_DISPATCH_V2_TMPL( \ + DISPATCH_SWITCH, DISPATCH_CASE, TYPE, NAME, BODY, ...) \ + DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + THO_AP_VAR_TMPL(DISPATCH_CASE, AT_WRAP(BODY), TYPE, __VA_ARGS__)) + +// THO_DISPATCH_V2 is same as AT_DISPATCH_V2 but using +// THO_DISPATCH_SWITCH and THO_DISPATCH_CASE instead of +// AT_DISPATCH_SWITCH and AT_DISPATCH_CASE, respectively. +#define THO_DISPATCH_V2(TYPE, NAME, BODY, ...) \ + THO_DISPATCH_V2_TMPL( \ + THO_DISPATCH_SWITCH, THO_DISPATCH_CASE, TYPE, NAME, BODY, __VA_ARGS__) + +// Type collection macros + +// This macro lets you pass an arbitrary expression that may contain internal +// commas to another macro without having the commas causing the expression +// to be interpreted as being multiple arguments +#define AT_WRAP(...) __VA_ARGS__ + +#define AT_FLOAT8_TYPES \ + torch::headeronly::ScalarType::Float8_e5m2, \ + torch::headeronly::ScalarType::Float8_e5m2fnuz, \ + torch::headeronly::ScalarType::Float8_e4m3fn, \ + torch::headeronly::ScalarType::Float8_e4m3fnuz, \ + torch::headeronly::ScalarType::Float8_e8m0fnu + +#define AT_INTEGRAL_TYPES \ + torch::headeronly::ScalarType::Byte, torch::headeronly::ScalarType::Char, \ + torch::headeronly::ScalarType::Int, torch::headeronly::ScalarType::Long, \ + torch::headeronly::ScalarType::Short +#define AT_FLOATING_TYPES \ + torch::headeronly::ScalarType::Double, torch::headeronly::ScalarType::Float +#define AT_BAREBONES_UNSIGNED_TYPES \ + torch::headeronly::ScalarType::UInt16, \ + torch::headeronly::ScalarType::UInt32, \ + torch::headeronly::ScalarType::UInt64 +#define AT_INTEGRAL_TYPES_V2 \ + AT_EXPAND(AT_INTEGRAL_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES) +#define AT_COMPLEX_TYPES \ + torch::headeronly::ScalarType::ComplexDouble, \ + torch::headeronly::ScalarType::ComplexFloat +#define AT_QINT_TYPES \ + torch::headeronly::ScalarType::QInt8, torch::headeronly::ScalarType::QUInt8, \ + torch::headeronly::ScalarType::QInt32 +// NB: not *actually* all types +#define AT_ALL_TYPES AT_EXPAND(AT_INTEGRAL_TYPES), AT_EXPAND(AT_FLOATING_TYPES) +#define AT_ALL_TYPES_AND_COMPLEX \ + AT_EXPAND(AT_ALL_TYPES), AT_EXPAND(AT_COMPLEX_TYPES) + +// Helper macros + +// THO_AP_VAR_TMPL is same as AT_AP_VAR but with a custom +// DISPATCH_CASE macro argument: +#define THO_AP_VAR_TMPL(C, N, T, ...) \ + AT_EXPAND( \ + AT_CONCAT(THO_AP, AT_NUM_ARGS(__VA_ARGS__))(C, AT_WRAP(N), __VA_ARGS__)) +#define AT_CONCAT(a, b) AT_CONCAT_AUX(a, b) +#define AT_CONCAT_AUX(a, b) a##b +#define AT_EXPAND(X) X + +// Ensure we never have too many scalar types for the expansion here to +// support. To bump this, you must regenerate the macros below. +static_assert(static_cast(torch::headeronly::ScalarType::NumOptions) < 60); + +// Python code to regenerate generate code below: +#if 0 + +num_args = 60 + +nums = ', '.join(str(i) for i in reversed(range(num_args+1))) +args = ', '.join(f'_{i}' for i in range(1, num_args+1)) + +print(f'#define AT_NUM_ARGS(...) AT_EXPAND(AT_NUM_ARGS_AUX(__VA_ARGS__, {nums}))') +print(f'#define AT_NUM_ARGS_AUX({args}, N, ...) N') + +for i in range(1, num_args+1): + args = ', '.join(f'_{i}' for i in range(1, i+1)) + cases = ' '.join([f'C(_{j}, N)' for j in range(1, i+1)]) + print(f'#define THO_AP{i}(C, N, {args}) {cases}') + +#endif + +// Begin generated code +// clang-format off + +#define AT_NUM_ARGS(...) AT_EXPAND(AT_NUM_ARGS_AUX(__VA_ARGS__, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) +#define AT_NUM_ARGS_AUX(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, N, ...) N +#define THO_AP1(C, N, _1) C(_1, N) +#define THO_AP2(C, N, _1, _2) C(_1, N) C(_2, N) +#define THO_AP3(C, N, _1, _2, _3) C(_1, N) C(_2, N) C(_3, N) +#define THO_AP4(C, N, _1, _2, _3, _4) C(_1, N) C(_2, N) C(_3, N) C(_4, N) +#define THO_AP5(C, N, _1, _2, _3, _4, _5) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) +#define THO_AP6(C, N, _1, _2, _3, _4, _5, _6) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) +#define THO_AP7(C, N, _1, _2, _3, _4, _5, _6, _7) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) +#define THO_AP8(C, N, _1, _2, _3, _4, _5, _6, _7, _8) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) +#define THO_AP9(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) +#define THO_AP10(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) +#define THO_AP11(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) +#define THO_AP12(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) +#define THO_AP13(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) +#define THO_AP14(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) +#define THO_AP15(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) +#define THO_AP16(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) +#define THO_AP17(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) +#define THO_AP18(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) +#define THO_AP19(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) +#define THO_AP20(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) +#define THO_AP21(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) +#define THO_AP22(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) +#define THO_AP23(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) +#define THO_AP24(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) +#define THO_AP25(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) +#define THO_AP26(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) +#define THO_AP27(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) +#define THO_AP28(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) +#define THO_AP29(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) +#define THO_AP30(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) +#define THO_AP31(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) +#define THO_AP32(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) +#define THO_AP33(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) +#define THO_AP34(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) +#define THO_AP35(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) +#define THO_AP36(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) +#define THO_AP37(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) +#define THO_AP38(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) +#define THO_AP39(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) +#define THO_AP40(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) +#define THO_AP41(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) +#define THO_AP42(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) +#define THO_AP43(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) +#define THO_AP44(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) +#define THO_AP45(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) +#define THO_AP46(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) +#define THO_AP47(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) +#define THO_AP48(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) +#define THO_AP49(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) +#define THO_AP50(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) +#define THO_AP51(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) +#define THO_AP52(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) +#define THO_AP53(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) C(_53, N) +#define THO_AP54(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) C(_53, N) C(_54, N) +#define THO_AP55(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) C(_53, N) C(_54, N) C(_55, N) +#define THO_AP56(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) C(_53, N) C(_54, N) C(_55, N) C(_56, N) +#define THO_AP57(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) C(_53, N) C(_54, N) C(_55, N) C(_56, N) C(_57, N) +#define THO_AP58(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) C(_53, N) C(_54, N) C(_55, N) C(_56, N) C(_57, N) C(_58, N) +#define THO_AP59(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) C(_53, N) C(_54, N) C(_55, N) C(_56, N) C(_57, N) C(_58, N) C(_59, N) +#define THO_AP60(C, N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60) C(_1, N) C(_2, N) C(_3, N) C(_4, N) C(_5, N) C(_6, N) C(_7, N) C(_8, N) C(_9, N) C(_10, N) C(_11, N) C(_12, N) C(_13, N) C(_14, N) C(_15, N) C(_16, N) C(_17, N) C(_18, N) C(_19, N) C(_20, N) C(_21, N) C(_22, N) C(_23, N) C(_24, N) C(_25, N) C(_26, N) C(_27, N) C(_28, N) C(_29, N) C(_30, N) C(_31, N) C(_32, N) C(_33, N) C(_34, N) C(_35, N) C(_36, N) C(_37, N) C(_38, N) C(_39, N) C(_40, N) C(_41, N) C(_42, N) C(_43, N) C(_44, N) C(_45, N) C(_46, N) C(_47, N) C(_48, N) C(_49, N) C(_50, N) C(_51, N) C(_52, N) C(_53, N) C(_54, N) C(_55, N) C(_56, N) C(_57, N) C(_58, N) C(_59, N) C(_60, N) + +// End generated code +// clang-format on diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Layout.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Layout.h new file mode 100644 index 0000000000000000000000000000000000000000..62e34ff67b457ae3b6fb5ff4d804d85b3da9cb7a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/Layout.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include + +#include +#include + +namespace c10 { + +enum class Layout : int8_t { + Strided, + Sparse, + SparseCsr, + Mkldnn, + SparseCsc, + SparseBsr, + SparseBsc, + Jagged, + NumOptions +}; + +constexpr auto kStrided = Layout::Strided; +constexpr auto kSparse = Layout::Sparse; +constexpr auto kSparseCsr = Layout::SparseCsr; +constexpr auto kMkldnn = Layout::Mkldnn; +constexpr auto kSparseCsc = Layout::SparseCsc; +constexpr auto kSparseBsr = Layout::SparseBsr; +constexpr auto kSparseBsc = Layout::SparseBsc; +constexpr auto kJagged = Layout::Jagged; + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::kJagged; +using c10::kMkldnn; +using c10::kSparse; +using c10::kSparseBsc; +using c10::kSparseBsr; +using c10::kSparseCsc; +using c10::kSparseCsr; +using c10::kStrided; +using c10::Layout; +HIDDEN_NAMESPACE_END(torch, headeronly) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/MemoryFormat.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/MemoryFormat.h new file mode 100644 index 0000000000000000000000000000000000000000..ad02a901e0169ad6c2e2169a90c72c88fb609097 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/MemoryFormat.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +#include +#include + +// Memory format is not the property of a Tensor. It is the way to tell an +// operator how the result should be organized in memory and nothing more. That +// means memory format should never be used as return value for any tensor state +// interrogation functions (internally and externally). +// +// Possible options are: +// Preserve: +// If any of the input tensors is in channels_last format, operator output +// should be in channels_last format +// +// Contiguous: +// Regardless of input tensors format, the output should be contiguous +// Tensor. +// +// ChannelsLast: +// Regardless of input tensors format, the output should be in channels_last +// format. + +namespace c10 { + +enum class MemoryFormat : int8_t { + Contiguous, + Preserve, + ChannelsLast, + ChannelsLast3d, + NumOptions +}; + +inline MemoryFormat get_contiguous_memory_format() { + return MemoryFormat::Contiguous; +} + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::get_contiguous_memory_format; +using c10::MemoryFormat; +HIDDEN_NAMESPACE_END(torch, headeronly) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/ScalarType.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/ScalarType.h new file mode 100644 index 0000000000000000000000000000000000000000..ce43ce6866cd954adc778cec54c3405d2d1569a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/ScalarType.h @@ -0,0 +1,381 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wswitch-enum") + +namespace c10 { + +// dummy struct for uint1 to uint7, actual functionality +// of these dtypes will be implemented in python with Tensor subclass +template +struct dummy_uint1_7_t {}; + +// dummy struct for int1 to int7, actual functionality +// of these dtypes will be implemented in python with Tensor subclass +template +struct dummy_int1_7_t {}; + +// [dtype Macros note] For the macros below: +// +// For users: If you want to macro some code for all non-QInt scalar types +// (i.e. types with complete information, you probably want one of the +// AT_FORALL_SCALAR_TYPES / AT_FORALL_SCALAR_TYPES_AND macros below, which are +// designed to behave similarly to the Dispatch macros with the same name. +// +// For adding a new dtype: In the beginning, we had an idea that there was a +// list of all scalar types, and you could use AT_FORALL_SCALAR_TYPES to +// iterate over them. But over the years we added weird types which couldn't +// be handled uniformly everywhere and so in the end we ended up with some +// mish-mosh of some helper macros, but mostly use sites making a call about +// what dtypes they can or can't support. So if you want to add a new dtype, +// the preferred resolution is to find a dtype similar to what you want, +// grep for it and edit all the sites you find this way. If you need to add +// a completely new kind of dtype, you're going to have to laboriously audit +// all of the sites everywhere to figure out how it should work. Consulting +// some old PRs where we added new dtypes (check history of this file) can +// help give you an idea where to start. + +// If you want to support ComplexHalf for real, add ComplexHalf +// into this macro (and change the name). But beware: convert() +// doesn't work for all the conversions you need... +// +// TODO: To add unsigned int types here, we must define accumulate type. +// But uint8 currently accumulates into int64, so we would have to make +// an inconsistent choice for the larger types. Difficult. +#define AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_EXCEPT_COMPLEX_HALF_F8NZ(_) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int, Int) \ + _(int64_t, Long) \ + _(c10::Half, Half) \ + _(float, Float) \ + _(double, Double) \ + _(c10::complex, ComplexFloat) \ + _(c10::complex, ComplexDouble) \ + _(bool, Bool) \ + _(c10::BFloat16, BFloat16) \ + _(c10::Float8_e5m2, Float8_e5m2) \ + _(c10::Float8_e4m3fn, Float8_e4m3fn) + +// This macro controls many of our C++ APIs, including constructors +// for Scalar as well as the data() and item() accessors on Tensor +#define AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(_) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int, Int) \ + _(int64_t, Long) \ + _(c10::Half, Half) \ + _(float, Float) \ + _(double, Double) \ + _(c10::complex, ComplexHalf) \ + _(c10::complex, ComplexFloat) \ + _(c10::complex, ComplexDouble) \ + _(bool, Bool) \ + _(c10::BFloat16, BFloat16) \ + _(c10::Float8_e5m2, Float8_e5m2) \ + _(c10::Float8_e4m3fn, Float8_e4m3fn) \ + _(c10::Float8_e5m2fnuz, Float8_e5m2fnuz) \ + _(c10::Float8_e4m3fnuz, Float8_e4m3fnuz) \ + _(c10::Float8_e8m0fnu, Float8_e8m0fnu) + +// NB: Order matters for this macro; it is relied upon in +// _promoteTypesLookup and the serialization format. +#define AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS(_) \ + _(uint8_t, Byte) /* 0 */ \ + _(int8_t, Char) /* 1 */ \ + _(int16_t, Short) /* 2 */ \ + _(int, Int) /* 3 */ \ + _(int64_t, Long) /* 4 */ \ + _(c10::Half, Half) /* 5 */ \ + _(float, Float) /* 6 */ \ + _(double, Double) /* 7 */ \ + _(c10::complex, ComplexHalf) /* 8 */ \ + _(c10::complex, ComplexFloat) /* 9 */ \ + _(c10::complex, ComplexDouble) /* 10 */ \ + _(bool, Bool) /* 11 */ \ + _(c10::qint8, QInt8) /* 12 */ \ + _(c10::quint8, QUInt8) /* 13 */ \ + _(c10::qint32, QInt32) /* 14 */ \ + _(c10::BFloat16, BFloat16) /* 15 */ \ + _(c10::quint4x2, QUInt4x2) /* 16 */ \ + _(c10::quint2x4, QUInt2x4) /* 17 */ \ + _(c10::bits1x8, Bits1x8) /* 18 */ \ + _(c10::bits2x4, Bits2x4) /* 19 */ \ + _(c10::bits4x2, Bits4x2) /* 20 */ \ + _(c10::bits8, Bits8) /* 21 */ \ + _(c10::bits16, Bits16) /* 22 */ \ + _(c10::Float8_e5m2, Float8_e5m2) /* 23 */ \ + _(c10::Float8_e4m3fn, Float8_e4m3fn) /* 24 */ \ + _(c10::Float8_e5m2fnuz, Float8_e5m2fnuz) /* 25 */ \ + _(c10::Float8_e4m3fnuz, Float8_e4m3fnuz) /* 26 */ \ + _(uint16_t, UInt16) /* 27 */ \ + _(uint32_t, UInt32) /* 28 */ \ + _(uint64_t, UInt64) /* 29 */ \ + _(c10::dummy_uint1_7_t<1>, UInt1) /* 30 */ \ + _(c10::dummy_uint1_7_t<2>, UInt2) /* 31 */ \ + _(c10::dummy_uint1_7_t<3>, UInt3) /* 32 */ \ + _(c10::dummy_uint1_7_t<4>, UInt4) /* 33 */ \ + _(c10::dummy_uint1_7_t<5>, UInt5) /* 34 */ \ + _(c10::dummy_uint1_7_t<6>, UInt6) /* 35 */ \ + _(c10::dummy_uint1_7_t<7>, UInt7) /* 36 */ \ + _(c10::dummy_int1_7_t<1>, Int1) /* 37 */ \ + _(c10::dummy_int1_7_t<2>, Int2) /* 38 */ \ + _(c10::dummy_int1_7_t<3>, Int3) /* 39 */ \ + _(c10::dummy_int1_7_t<4>, Int4) /* 40 */ \ + _(c10::dummy_int1_7_t<5>, Int5) /* 41 */ \ + _(c10::dummy_int1_7_t<6>, Int6) /* 42 */ \ + _(c10::dummy_int1_7_t<7>, Int7) /* 43 */ \ + _(c10::Float8_e8m0fnu, Float8_e8m0fnu) /* 44 */ \ + _(c10::Float4_e2m1fn_x2, Float4_e2m1fn_x2) /* 45 */ + +// NB: despite its generic sounding name, the macros that don't take _AND +// are mostly only used by tensorexpr +#define AT_FORALL_INT_TYPES(_) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int, Int) \ + _(int64_t, Long) + +#define AT_FORALL_SCALAR_TYPES(_) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) + +// These macros are often controlling how many template instantiations we +// create for kernels. It is typically inappropriate to add new dtypes here, +// instead, new types should be added to use sites on a case-by-case basis. +// We generally are not accepting new dtypes due to binary size concerns. + +#define AT_FORALL_SCALAR_TYPES_AND(SCALARTYPE, _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) \ + _(c10::impl::ScalarTypeToCPPTypeT, SCALARTYPE) + +#define AT_FORALL_SCALAR_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE1) \ + _(c10::impl::ScalarTypeToCPPTypeT, SCALARTYPE2) + +#define AT_FORALL_SCALAR_TYPES_AND3(SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE1) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE2) \ + _(c10::impl::ScalarTypeToCPPTypeT, SCALARTYPE3) + +#define AT_FORALL_SCALAR_TYPES_AND7( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + SCALARTYPE7, \ + _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE1) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE2) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE3) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE4) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE5) \ + _(c10::impl::ScalarTypeToCPPTypeT, \ + SCALARTYPE6) \ + _(c10::impl::ScalarTypeToCPPTypeT, SCALARTYPE7) + +#define AT_FORALL_QINT_TYPES(_) \ + _(c10::qint8, QInt8) \ + _(c10::quint8, QUInt8) \ + _(c10::qint32, QInt32) \ + _(c10::quint4x2, QUInt4x2) \ + _(c10::quint2x4, QUInt2x4) + +#define AT_FORALL_FLOAT8_TYPES(_) \ + _(c10::Float8_e5m2, Float8_e5m2) \ + _(c10::Float8_e4m3fn, Float8_e4m3fn) \ + _(c10::Float8_e5m2fnuz, Float8_e5m2fnuz) \ + _(c10::Float8_e4m3fnuz, Float8_e4m3fnuz) \ + _(c10::Float8_e8m0fnu, Float8_e8m0fnu) + +#define AT_FORALL_COMPLEX_TYPES(_) \ + _(c10::complex, ComplexFloat) \ + _(c10::complex, ComplexDouble) + +enum class ScalarType : int8_t { +#define DEFINE_ST_ENUM_VAL_(_1, n) n, + AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS(DEFINE_ST_ENUM_VAL_) +#undef DEFINE_ENUM_ST_ENUM_VAL_ + Undefined, + NumOptions +}; + +constexpr uint16_t NumScalarTypes = + static_cast(ScalarType::NumOptions); + +// Map from C++ type to ScalarType enum +template +struct CppTypeToScalarType; + +#define SPECIALIZE_CppTypeToScalarType(cpp_type, scalar_type) \ + template <> \ + struct CppTypeToScalarType \ + : std:: \ + integral_constant { \ + }; + +AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS(SPECIALIZE_CppTypeToScalarType) + +#undef SPECIALIZE_CppTypeToScalarType + +namespace impl { + +// These are used to map ScalarTypes to C++ types. + +template +struct ScalarTypeToCPPType; + +#define SPECIALIZE_ScalarTypeToCPPType(cpp_type, scalar_type) \ + template <> \ + struct ScalarTypeToCPPType { \ + using type = cpp_type; \ + \ + /* This is a workaround for the CUDA bug which prevents */ \ + /* ::detail::ScalarTypeToCType::type being used directly due to */ \ + /* ambiguous reference which can't to be resolved. For some reason it */ \ + /* can't pick between at::detail and at::cuda::detail. */ \ + /* For repro example, please see: */ \ + /* https://gist.github.com/izdeby/952ae7cf256ddb740a73776d39a7e7ba */ \ + /* UPDATE: while the CUDA bug is fixed, we cannot remove the */ \ + /* workaround as it is BC breaking. However, it is recommended to */ \ + /* update any code that contains */ \ + /* decltype(ScalarTypeToCPPType::t) */ \ + /* with */ \ + /* ScalarTypeToCPPTypeT */ \ + static type t; \ + }; + +AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS(SPECIALIZE_ScalarTypeToCPPType) + +#undef SPECIALIZE_ScalarTypeToCPPType + +template +using ScalarTypeToCPPTypeT = typename ScalarTypeToCPPType::type; + +} // namespace impl + +inline const char* toString(ScalarType t) { +#define DEFINE_CASE(_, name) \ + case ScalarType::name: \ + return #name; + + switch (t) { + AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS(DEFINE_CASE) + default: + return "UNKNOWN_SCALAR"; + } +#undef DEFINE_CASE +} + +inline std::ostream& operator<<( + std::ostream& stream, + c10::ScalarType scalar_type) { + return stream << toString(scalar_type); +} + +inline bool isQIntType(ScalarType t) { + // Don't forget to extend this when adding new QInt types + return t == ScalarType::QInt8 || t == ScalarType::QUInt8 || + t == ScalarType::QInt32 || t == ScalarType::QUInt4x2 || + t == ScalarType::QUInt2x4; +} + +inline ScalarType toUnderlying(ScalarType t) { + switch (t) { + case ScalarType::QUInt8: + case ScalarType::QUInt4x2: + [[fallthrough]]; + case ScalarType::QUInt2x4: + return ScalarType::Byte; + case ScalarType::QInt8: + return ScalarType::Char; + case ScalarType::QInt32: + return ScalarType::Int; + default: + return t; + } +} + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::CppTypeToScalarType; +using c10::dummy_int1_7_t; +using c10::dummy_uint1_7_t; +using c10::NumScalarTypes; +using c10::ScalarType; +using c10::toString; +using c10::operator<<; +using c10::isQIntType; +using c10::toUnderlying; + +namespace impl { +using c10::impl::ScalarTypeToCPPTypeT; +} // namespace impl + +HIDDEN_NAMESPACE_END(torch, headeronly) + +C10_DIAGNOSTIC_POP() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/TensorAccessor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/TensorAccessor.h new file mode 100644 index 0000000000000000000000000000000000000000..9019c7ac3104dd90e78b89631e4f011d07786ffd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/core/TensorAccessor.h @@ -0,0 +1,462 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace torch::headeronly { + +// The PtrTraits argument to the TensorAccessor/GenericPackedTensorAccessor +// is used to enable the __restrict__ keyword/modifier for the data +// passed to cuda. +template +struct DefaultPtrTraits { + typedef T* PtrType; +}; + +#if defined(__CUDACC__) || defined(__HIPCC__) +template +struct RestrictPtrTraits { + typedef T* __restrict__ PtrType; +}; +#endif + +namespace detail { +// Template classes in torch::headeronly::detail namespace are used +// to construct accessor template classes with custom ArrayRef and +// index bound check implementations. For instance, +// at::TensorAccessor and torch::headeronly::TensorAccessor template +// classes use c10::IntArrayRef and +// torch::headeronly::IntHeaderOnlyArrayRef classes, respectively, +// as return value types of sizes() and strides() methods. + +// TensorAccessorBase and TensorAccessor are used for both CPU and CUDA tensors. +// For CUDA tensors it is used in device code (only). This means that we +// restrict ourselves to functions and types available there (e.g. IntArrayRef +// isn't). + +// The PtrTraits argument is only relevant to cuda to support `__restrict__` +// pointers. +template < + class ArrayRefCls, + typename T, + size_t N, + template class PtrTraits = DefaultPtrTraits, + typename index_t = int64_t> +class TensorAccessorBase { + public: + typedef typename PtrTraits::PtrType PtrType; + + C10_HOST_DEVICE TensorAccessorBase( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : data_(data_), sizes_(sizes_), strides_(strides_) {} + C10_HOST ArrayRefCls sizes() const { + return ArrayRefCls(sizes_, N); + } + C10_HOST ArrayRefCls strides() const { + return ArrayRefCls(strides_, N); + } + C10_HOST_DEVICE index_t stride(index_t i) const { + return strides_[i]; + } + C10_HOST_DEVICE index_t size(index_t i) const { + return sizes_[i]; + } + C10_HOST_DEVICE PtrType data() { + return data_; + } + C10_HOST_DEVICE const PtrType data() const { + return data_; + } + + protected: + PtrType data_; + const index_t* sizes_; + const index_t* strides_; +}; + +// The `TensorAccessor` is typically instantiated for CPU `Tensor`s using +// `Tensor.accessor()`. +// For CUDA `Tensor`s, `GenericPackedTensorAccessor` is used on the host and +// only indexing on the device uses `TensorAccessor`s. +template < + class ArrayRefCls, + typename T, + size_t N, + template class PtrTraits = DefaultPtrTraits, + typename index_t = int64_t> +class TensorAccessor + : public TensorAccessorBase { + public: + typedef typename PtrTraits::PtrType PtrType; + + C10_HOST_DEVICE TensorAccessor( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : TensorAccessorBase( + data_, + sizes_, + strides_) {} + + C10_HOST_DEVICE TensorAccessor + operator[](index_t i) { + return TensorAccessor( + this->data_ + this->strides_[0] * i, + this->sizes_ + 1, + this->strides_ + 1); + } + + C10_HOST_DEVICE const TensorAccessor< + ArrayRefCls, + T, + N - 1, + PtrTraits, + index_t> + operator[](index_t i) const { + return TensorAccessor( + this->data_ + this->strides_[0] * i, + this->sizes_ + 1, + this->strides_ + 1); + } +}; + +template < + class ArrayRefCls, + typename T, + template class PtrTraits, + typename index_t> +class TensorAccessor + : public TensorAccessorBase { + public: + typedef typename PtrTraits::PtrType PtrType; + + C10_HOST_DEVICE TensorAccessor( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : TensorAccessorBase( + data_, + sizes_, + strides_) {} + C10_HOST_DEVICE T& operator[](index_t i) { + // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) + return this->data_[this->strides_[0] * i]; + } + C10_HOST_DEVICE const T& operator[](index_t i) const { + return this->data_[this->strides_[0] * i]; + } +}; + +// GenericPackedTensorAccessorBase and GenericPackedTensorAccessor are used on +// for CUDA `Tensor`s on the host and as in contrast to `TensorAccessor`s, they +// copy the strides and sizes on instantiation (on the host) in order to +// transfer them on the device when calling kernels. On the device, indexing of +// multidimensional tensors gives to `TensorAccessor`s. Use RestrictPtrTraits as +// PtrTraits if you want the tensor's data pointer to be marked as __restrict__. +// Instantiation from data, sizes, strides is only needed on the host and +// std::copy isn't available on the device, so those functions are host only. +template < + typename IndexBoundsCheck, + typename T, + size_t N, + template class PtrTraits = DefaultPtrTraits, + typename index_t = int64_t> +class GenericPackedTensorAccessorBase { + public: + typedef typename PtrTraits::PtrType PtrType; + C10_HOST GenericPackedTensorAccessorBase( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : data_(data_) { + std::copy(sizes_, sizes_ + N, std::begin(this->sizes_)); + std::copy(strides_, strides_ + N, std::begin(this->strides_)); + } + + // if index_t is not int64_t, we want to have an int64_t constructor + template < + typename source_index_t, + class = std::enable_if_t>> + C10_HOST GenericPackedTensorAccessorBase( + PtrType data_, + const source_index_t* sizes_, + const source_index_t* strides_) + : data_(data_) { + for (size_t i = 0; i < N; ++i) { + this->sizes_[i] = sizes_[i]; + this->strides_[i] = strides_[i]; + } + } + + C10_HOST_DEVICE index_t stride(index_t i) const { + return strides_[i]; + } + C10_HOST_DEVICE index_t size(index_t i) const { + return sizes_[i]; + } + C10_HOST_DEVICE PtrType data() { + return data_; + } + C10_HOST_DEVICE const PtrType data() const { + return data_; + } + + protected: + PtrType data_; + // NOLINTNEXTLINE(*c-arrays*) + index_t sizes_[N]; + // NOLINTNEXTLINE(*c-arrays*) + index_t strides_[N]; + C10_HOST void bounds_check_(index_t i) const { + IndexBoundsCheck _(i); + } +}; + +template < + typename ItemAccessor, + typename IndexBoundsCheck, + typename T, + size_t N, + template class PtrTraits = DefaultPtrTraits, + typename index_t = int64_t> +class GenericPackedTensorAccessor : public GenericPackedTensorAccessorBase< + IndexBoundsCheck, + T, + N, + PtrTraits, + index_t> { + public: + typedef typename PtrTraits::PtrType PtrType; + + C10_HOST GenericPackedTensorAccessor( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : GenericPackedTensorAccessorBase< + IndexBoundsCheck, + T, + N, + PtrTraits, + index_t>(data_, sizes_, strides_) {} + + // if index_t is not int64_t, we want to have an int64_t constructor + template < + typename source_index_t, + class = std::enable_if_t>> + C10_HOST GenericPackedTensorAccessor( + PtrType data_, + const source_index_t* sizes_, + const source_index_t* strides_) + : GenericPackedTensorAccessorBase< + IndexBoundsCheck, + T, + N, + PtrTraits, + index_t>(data_, sizes_, strides_) {} + + C10_DEVICE ItemAccessor operator[](index_t i) { + index_t* new_sizes = this->sizes_ + 1; + index_t* new_strides = this->strides_ + 1; + return ItemAccessor( + this->data_ + this->strides_[0] * i, new_sizes, new_strides); + } + + C10_DEVICE const ItemAccessor operator[](index_t i) const { + const index_t* new_sizes = this->sizes_ + 1; + const index_t* new_strides = this->strides_ + 1; + return ItemAccessor( + this->data_ + this->strides_[0] * i, new_sizes, new_strides); + } + + /// Returns a PackedTensorAccessor of the same dimension after transposing the + /// two dimensions given. Does not actually move elements; transposition is + /// made by permuting the size/stride arrays. If the dimensions are not valid, + /// asserts. + C10_HOST GenericPackedTensorAccessor< + ItemAccessor, + IndexBoundsCheck, + T, + N, + PtrTraits, + index_t> + transpose(index_t dim1, index_t dim2) const { + this->bounds_check_(dim1); + this->bounds_check_(dim2); + GenericPackedTensorAccessor< + ItemAccessor, + IndexBoundsCheck, + T, + N, + PtrTraits, + index_t> + result(this->data_, this->sizes_, this->strides_); + std::swap(result.strides_[dim1], result.strides_[dim2]); + std::swap(result.sizes_[dim1], result.sizes_[dim2]); + return result; + } +}; + +template < + typename ItemAccessor, + typename IndexBoundsCheck, + typename T, + template class PtrTraits, + typename index_t> +class GenericPackedTensorAccessor< + ItemAccessor, + IndexBoundsCheck, + T, + 1, + PtrTraits, + index_t> + : public GenericPackedTensorAccessorBase< + IndexBoundsCheck, + T, + 1, + PtrTraits, + index_t> { + public: + typedef typename PtrTraits::PtrType PtrType; + C10_HOST GenericPackedTensorAccessor( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : GenericPackedTensorAccessorBase< + IndexBoundsCheck, + T, + 1, + PtrTraits, + index_t>(data_, sizes_, strides_) {} + + // if index_t is not int64_t, we want to have an int64_t constructor + template < + typename source_index_t, + class = std::enable_if_t>> + C10_HOST GenericPackedTensorAccessor( + PtrType data_, + const source_index_t* sizes_, + const source_index_t* strides_) + : GenericPackedTensorAccessorBase< + IndexBoundsCheck, + T, + 1, + PtrTraits, + index_t>(data_, sizes_, strides_) {} + + C10_DEVICE T& operator[](index_t i) { + return this->data_[this->strides_[0] * i]; + } + C10_DEVICE const T& operator[](index_t i) const { + return this->data_[this->strides_[0] * i]; + } + + // Same as in the general N-dimensional case, but note that in the + // 1-dimensional case the returned PackedTensorAccessor will always be an + // identical copy of the original + C10_HOST GenericPackedTensorAccessor< + ItemAccessor, + IndexBoundsCheck, + T, + 1, + PtrTraits, + index_t> + transpose(index_t dim1, index_t dim2) const { + this->bounds_check_(dim1); + this->bounds_check_(dim2); + return GenericPackedTensorAccessor< + ItemAccessor, + IndexBoundsCheck, + T, + 1, + PtrTraits, + index_t>(this->data_, this->sizes_, this->strides_); + } +}; + +template +struct HeaderOnlyIndexBoundsCheck { + HeaderOnlyIndexBoundsCheck(index_t i) { + STD_TORCH_CHECK( + 0 <= i && i < index_t{N}, + "Index ", + i, + " is not within bounds of a tensor of dimension ", + N); + } +}; + +} // namespace detail + +// HeaderOnlyTensorAccessorBase is same as at::TensorAccessorBase +// except sizes() and strides() return IntHeaderOnlyArrayRef instead +// of IntArrayRef. +template < + typename T, + size_t N, + template class PtrTraits = DefaultPtrTraits, + typename index_t = int64_t> +using HeaderOnlyTensorAccessorBase = detail::TensorAccessorBase< + torch::headeronly::IntHeaderOnlyArrayRef, + T, + N, + PtrTraits, + index_t>; + +// HeaderOnlyTensorAccessor is same as at::TensorAccessor except +// sizes() and strides() return IntHeaderOnlyArrayRef instead of +// IntArrayRef. +template < + typename T, + size_t N, + template class PtrTraits = DefaultPtrTraits, + typename index_t = int64_t> +using HeaderOnlyTensorAccessor = detail::TensorAccessor< + torch::headeronly::IntHeaderOnlyArrayRef, + T, + N, + PtrTraits, + index_t>; + +// HeaderOnlyGenericPackedTensorAccessorBase is same as +// at::GenericPackedTensorAccessorBase except sizes() and strides() +// return IntHeaderOnlyArrayRef instead of IntArrayRef. +template < + typename T, + size_t N, + template class PtrTraits = DefaultPtrTraits, + typename index_t = int64_t> +using HeaderOnlyGenericPackedTensorAccessorBase = + detail::GenericPackedTensorAccessorBase< + detail::HeaderOnlyIndexBoundsCheck, + T, + N, + PtrTraits, + index_t>; + +// HeaderOnlyGenericPackedTensorAccessor is same as +// at::GenericPackedTensorAccessor except sizes() and strides() return +// IntHeaderOnlyArrayRef instead of IntArrayRef, and bounds check uses +// STD_TORCH_CHECK instead of TORCH_CHECK_INDEX. +template < + typename T, + size_t N, + template class PtrTraits = DefaultPtrTraits, + typename index_t = int64_t> +using HeaderOnlyGenericPackedTensorAccessor = + detail::GenericPackedTensorAccessor< + HeaderOnlyTensorAccessor, + detail::HeaderOnlyIndexBoundsCheck, + T, + N, + PtrTraits, + index_t>; + +} // namespace torch::headeronly diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/cpu/vec/intrinsics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/cpu/vec/intrinsics.h new file mode 100644 index 0000000000000000000000000000000000000000..3cf427dae64bce378f9c284e0db6dd452cb0e3d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/cpu/vec/intrinsics.h @@ -0,0 +1,50 @@ +#pragma once +#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) +/* GCC or clang-compatible compiler, targeting x86/x86-64 */ +#include +#elif defined(__clang__) && (defined(__ARM_NEON__) || defined(__aarch64__)) +/* Clang-compatible compiler, targeting arm neon */ +#include +#if defined(__ARM_FEATURE_SVE) +/* CLANG-compatible compiler, targeting ARM with SVE */ +#include +#endif +#elif defined(_MSC_VER) +/* Microsoft C/C++-compatible compiler */ +#include +#if _MSC_VER <= 1900 +#define _mm256_extract_epi64(X, Y) \ + (_mm_extract_epi64(_mm256_extractf128_si256(X, Y >> 1), Y % 2)) +#define _mm256_extract_epi32(X, Y) \ + (_mm_extract_epi32(_mm256_extractf128_si256(X, Y >> 2), Y % 4)) +#define _mm256_extract_epi16(X, Y) \ + (_mm_extract_epi16(_mm256_extractf128_si256(X, Y >> 3), Y % 8)) +#define _mm256_extract_epi8(X, Y) \ + (_mm_extract_epi8(_mm256_extractf128_si256(X, Y >> 4), Y % 16)) +#endif +#elif defined(__GNUC__) && (defined(__ARM_NEON__) || defined(__aarch64__)) +/* GCC-compatible compiler, targeting ARM with NEON */ +#include +#if defined(__ARM_FEATURE_SVE) +/* GCC-compatible compiler, targeting ARM with SVE */ +#include +#endif +#elif defined(__GNUC__) && defined(__IWMMXT__) +/* GCC-compatible compiler, targeting ARM with WMMX */ +#include +#elif defined(__s390x__) +// targets Z/architecture +// we will include vecintrin later +#elif (defined(__GNUC__) || defined(__xlC__)) && \ + (defined(__VEC__) || defined(__ALTIVEC__)) +/* XLC or GCC-compatible compiler, targeting PowerPC with VMX/VSX */ +#include +/* We need to undef those tokens defined by to avoid conflicts + with the C++ types. => Can still use __bool/__vector */ +#undef bool +#undef vector +#undef pixel +#elif defined(__GNUC__) && defined(__SPE__) +/* GCC-compatible compiler, targeting PowerPC with SPE */ +#include +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/cpu/vec/vec_half.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/cpu/vec/vec_half.h new file mode 100644 index 0000000000000000000000000000000000000000..6ad37b1948306903ea4f92c64d8402ffa3423b23 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/cpu/vec/vec_half.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly, vec) +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) +static inline uint16_t float2half_scalar(float val) { +#if defined(CPU_CAPABILITY_AVX2) +#if defined(_MSC_VER) + __m256 v = _mm256_set1_ps(val); + __m128i o = + _mm256_cvtps_ph(v, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + return static_cast(_mm_cvtsi128_si32(o)); +#else + return _cvtss_sh(val, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); +#endif +#elif defined(CPU_CAPABILITY_AVX512) + __m512 v = _mm512_set1_ps(val); + __m256i o = + _mm512_cvtps_ph(v, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + return static_cast( + _mm_cvtsi128_si32(_mm256_castsi256_si128(o))); +#endif +} + +static inline float half2float_scalar(uint16_t val) { +#if defined(CPU_CAPABILITY_AVX2) +#if defined(_MSC_VER) + __m128i v = _mm_cvtsi32_si128(val); + __m256 o = _mm256_cvtph_ps(v); + return _mm256_cvtss_f32(o); +#else + return _cvtsh_ss(val); +#endif +#elif defined(CPU_CAPABILITY_AVX512) + __m256i v = + _mm256_setr_epi16(val, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + __m512 o = _mm512_cvtph_ps(v); + return _mm512_cvtss_f32(o); +#endif +} + +#endif + +} // namespace CPU_CAPABILITY +HIDDEN_NAMESPACE_END(torch, headeronly, vec) + +namespace at::vec { +#if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) +using torch::headeronly::vec::float2half_scalar; +using torch::headeronly::vec::half2float_scalar; +#endif +} // namespace at::vec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/Export.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/Export.h new file mode 100644 index 0000000000000000000000000000000000000000..8dd25419efb4e0040e1731f7ff0b799ec58fa877 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/Export.h @@ -0,0 +1,153 @@ +#pragma once + +#ifndef C10_MACROS_EXPORT_H_ +#define C10_MACROS_EXPORT_H_ + +#ifndef C10_USING_CUSTOM_GENERATED_MACROS +#include +#endif // C10_USING_CUSTOM_GENERATED_MACROS + +/* Header file to define the common scaffolding for exported symbols. + * + * Export is by itself a quite tricky situation to deal with, and if you are + * hitting this file, make sure you start with the background here: + * - Linux: https://gcc.gnu.org/wiki/Visibility + * - Windows: + * https://docs.microsoft.com/en-us/cpp/cpp/dllexport-dllimport?view=vs-2017 + * + * Do NOT include this file directly. Instead, use c10/macros/Macros.h + */ + +// You do not need to edit this part of file unless you are changing the core +// pytorch export abstractions. +// +// This part defines the C10 core export and import macros. This is controlled +// by whether we are building shared libraries or not, which is determined +// during build time and codified in c10/core/cmake_macros.h. +// When the library is built as a shared lib, EXPORT and IMPORT will contain +// visibility attributes. If it is being built as a static lib, then EXPORT +// and IMPORT basically have no effect. + +// As a rule of thumb, you should almost NEVER mix static and shared builds for +// libraries that depend on c10. AKA, if c10 is built as a static library, we +// recommend everything dependent on c10 to be built statically. If c10 is built +// as a shared library, everything dependent on it should be built as shared. In +// the PyTorch project, all native libraries shall use the macro +// C10_BUILD_SHARED_LIB to check whether pytorch is building shared or static +// libraries. + +// For build systems that do not directly depend on CMake and directly build +// from the source directory (such as Buck), one may not have a cmake_macros.h +// file at all. In this case, the build system is responsible for providing +// correct macro definitions corresponding to the cmake_macros.h.in file. +// +// In such scenarios, one should define the macro +// C10_USING_CUSTOM_GENERATED_MACROS +// to inform this header that it does not need to include the cmake_macros.h +// file. + +#ifdef _WIN32 +#define C10_HIDDEN +#if defined(C10_BUILD_SHARED_LIBS) +#define C10_EXPORT __declspec(dllexport) +#define C10_IMPORT __declspec(dllimport) +#else +#define C10_EXPORT +#define C10_IMPORT +#endif +#else // _WIN32 +#if defined(__GNUC__) +#define C10_EXPORT __attribute__((__visibility__("default"))) +#define C10_HIDDEN __attribute__((__visibility__("hidden"))) +#else // defined(__GNUC__) +#define C10_EXPORT +#define C10_HIDDEN +#endif // defined(__GNUC__) +#define C10_IMPORT C10_EXPORT +#endif // _WIN32 + +#ifdef NO_EXPORT +#undef C10_EXPORT +#define C10_EXPORT +#endif + +// Definition of an adaptive XX_API macro, that depends on whether you are +// building the library itself or not, routes to XX_EXPORT and XX_IMPORT. +// Basically, you will need to do this for each shared library that you are +// building, and the instruction is as follows: assuming that you are building +// a library called libawesome.so. You should: +// (1) for your cmake target (usually done by "add_library(awesome, ...)"), +// define a macro called AWESOME_BUILD_MAIN_LIB using +// target_compile_options. +// (2) define the AWESOME_API macro similar to the one below. +// And in the source file of your awesome library, use AWESOME_API to +// annotate public symbols. + +// Here, for the C10 library, we will define the macro C10_API for both import +// and export. + +// This one is being used by libc10.so +#ifdef C10_BUILD_MAIN_LIB +#define C10_API C10_EXPORT +#else +#define C10_API C10_IMPORT +#endif + +// This one is being used by libtorch.so +#ifdef CAFFE2_BUILD_MAIN_LIB +#define TORCH_API C10_EXPORT +#else +#define TORCH_API C10_IMPORT +#endif + +// You may be wondering why we have TORCH_CUDA_CPP_API and TORCH_CUDA_CU_API +// belonging to the same library instead of just one TORCH_CUDA_API. Well, it +// can indeed just be one TORCH_CUDA_API (and used to be)! TORCH_CUDA_CPP_API +// and TORCH_CUDA_CU_API are artifacts of when we needed a split build to +// avoid relocation marker linking errors. The context is as follows: +// +// Once upon a time, there _was_ only TORCH_CUDA_API. All was happy until we +// tried to compile PyTorch for CUDA 11.1, which ran into relocation marker +// issues when linking big binaries. +// (https://github.com/pytorch/pytorch/issues/39968) We had two choices: +// (1) Stop supporting so many GPU architectures +// (2) Do something else +// We chose #2 and decided to split the behemoth that was torch_cuda into two +// smaller libraries, one with most of the core kernel functions (torch_cuda_cu) +// and the other that had..well..everything else (torch_cuda_cpp). The idea was +// this: instead of linking our static libraries (like the hefty +// libcudnn_static.a) with another huge library, torch_cuda, and run into pesky +// relocation marker issues, we could link our static libraries to a smaller +// part of torch_cuda (torch_cuda_cpp) and avoid the issues. + +// libtorch_cuda.so (where torch_cuda_cu and torch_cuda_cpp are a part of the +// same api) +#ifdef TORCH_CUDA_BUILD_MAIN_LIB +#define TORCH_CUDA_CPP_API C10_EXPORT +#define TORCH_CUDA_CU_API C10_EXPORT +#else +#define TORCH_CUDA_CPP_API C10_IMPORT +#define TORCH_CUDA_CU_API C10_IMPORT +#endif + +#if defined(TORCH_HIP_BUILD_MAIN_LIB) +#define TORCH_HIP_CPP_API C10_EXPORT +#define TORCH_HIP_API C10_EXPORT +#else +#define TORCH_HIP_CPP_API C10_IMPORT +#define TORCH_HIP_API C10_IMPORT +#endif + +#if defined(TORCH_XPU_BUILD_MAIN_LIB) +#define TORCH_XPU_API C10_EXPORT +#else +#define TORCH_XPU_API C10_IMPORT +#endif + +// Enums only need to be exported on windows for non-CUDA files +#if defined(_WIN32) && defined(__CUDACC__) +#define C10_API_ENUM C10_API +#else +#define C10_API_ENUM +#endif +#endif // C10_MACROS_EXPORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/Macros.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/Macros.h new file mode 100644 index 0000000000000000000000000000000000000000..63aa0d20d8e5450e232204c073b34744c9ed2e3f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/Macros.h @@ -0,0 +1,694 @@ +#ifndef C10_MACROS_MACROS_H_ +#define C10_MACROS_MACROS_H_ + +#ifdef __cplusplus +#include +#else +#include +#endif + +/* Main entry for torch/headeronly/macros (used to be c10/macros). + * + * In your code, include torch/headeronly/macros/Macros.h directly, instead of + * individual files in this folder. + */ + +// For build systems that do not directly depend on CMake and directly build +// from the source directory (such as Buck), one may not have a cmake_macros.h +// file at all. In this case, the build system is responsible for providing +// correct macro definitions corresponding to the cmake_macros.h.in file. +// +// In such scenarios, one should define the macro +// C10_USING_CUSTOM_GENERATED_MACROS +// to inform this header that it does not need to include the cmake_macros.h +// file. + +#ifndef C10_USING_CUSTOM_GENERATED_MACROS +#include +#endif // C10_USING_CUSTOM_GENERATED_MACROS + +#include + +#if defined(__clang__) +#define __ubsan_ignore_float_divide_by_zero__ \ + __attribute__((no_sanitize("float-divide-by-zero"))) +#define __ubsan_ignore_undefined__ __attribute__((no_sanitize("undefined"))) +#define __ubsan_ignore_signed_int_overflow__ \ + __attribute__((no_sanitize("signed-integer-overflow"))) +#define __ubsan_ignore_pointer_overflow__ \ + __attribute__((no_sanitize("pointer-overflow"))) +#define __ubsan_ignore_function__ __attribute__((no_sanitize("function"))) +#define __ubsan_ignore_float_cast_overflow__ \ + __attribute__((no_sanitize("float-cast-overflow"))) +#else +#define __ubsan_ignore_float_divide_by_zero__ +#define __ubsan_ignore_undefined__ +#define __ubsan_ignore_signed_int_overflow__ +#define __ubsan_ignore_pointer_overflow__ +#define __ubsan_ignore_function__ +#define __ubsan_ignore_float_cast_overflow__ +#endif + +// Detect address sanitizer as some stuff doesn't work with it +#undef C10_ASAN_ENABLED + +// for clang +#if defined(__has_feature) +#if ((__has_feature(address_sanitizer))) +#define C10_ASAN_ENABLED 1 +#endif +#endif + +// for gcc +#if defined(__SANITIZE_ADDRESS__) +#if __SANITIZE_ADDRESS__ +#if !defined(C10_ASAN_ENABLED) +#define C10_ASAN_ENABLED 1 +#endif +#endif +#endif + +#if !defined(C10_ASAN_ENABLED) +#define C10_ASAN_ENABLED 0 +#endif + +// Detect undefined-behavior sanitizer (UBSAN) +#undef C10_UBSAN_ENABLED + +// for clang or gcc >= 14 +// NB: gcc 14 adds support for Clang's __has_feature +// https://gcc.gnu.org/gcc-14/changes.html +// gcc < 14 doesn't have a macro for UBSAN +// (e.g. __SANITIZE_UNDEFINED__ does not exist in gcc) +// https://github.com/google/sanitizers/issues/765 +#if defined(__has_feature) +#if ((__has_feature(undefined_behavior_sanitizer))) +#define C10_UBSAN_ENABLED 1 +#endif +#endif + +#if !defined(C10_UBSAN_ENABLED) +#define C10_UBSAN_ENABLED 0 +#endif + +// Disable the copy and assignment operator for a class. Note that this will +// disable the usage of the class in std containers. +#define C10_DISABLE_COPY_AND_ASSIGN(classname) \ + classname(const classname&) = delete; \ + classname& operator=(const classname&) = delete + +#define C10_CONCATENATE_IMPL(s1, s2) s1##s2 +#define C10_CONCATENATE(s1, s2) C10_CONCATENATE_IMPL(s1, s2) + +#define C10_MACRO_EXPAND(args) args + +#define C10_STRINGIZE_IMPL(x) #x +#define C10_STRINGIZE(x) C10_STRINGIZE_IMPL(x) + +/** + * C10_ANONYMOUS_VARIABLE(str) introduces a new identifier which starts with + * str and ends with a unique number. + */ +#ifdef __COUNTER__ +#define C10_UID __COUNTER__ +#define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __COUNTER__) +#else +#define C10_UID __LINE__ +#define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __LINE__) +#endif + +#ifdef __has_cpp_attribute +#define C10_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +#define C10_HAS_CPP_ATTRIBUTE(x) (0) +#endif + +#ifndef FBCODE_CAFFE2 +/// DEPRECATED: Warn if a type or return value is discarded. +#define C10_NODISCARD [[nodiscard]] + +/// DEPRECATED: Suppress an unused variable. +#define C10_UNUSED [[maybe_unused]] +#endif + +#if !defined(__has_attribute) +#define __has_attribute(x) 0 +#endif + +// Direct port of LLVM_ATTRIBUTE_USED. +#if __has_attribute(used) +#define C10_USED __attribute__((__used__)) +#else +#define C10_USED +#endif + +#define C10_RESTRICT __restrict + +#ifdef __cplusplus + +// Simply define the namespace, in case a dependent library want to refer to +// the c10 namespace but not any nontrivial files. +namespace c10 {} +namespace c10::cuda {} +namespace c10::hip {} +namespace c10::xpu {} + +// Since C10 is the core library for caffe2 (and aten), we will simply reroute +// all abstractions defined in c10 to be available in caffe2 as well. +// This is only for backwards compatibility. Please use the symbols from the +// c10 namespace where possible. +namespace caffe2 { +using namespace c10; +} +namespace at { +using namespace c10; +} +namespace at::cuda { +using namespace c10::cuda; +} // namespace at::cuda + +// WARNING!!! THIS IS A GIANT HACK!!! +// This line means you cannot simultaneously include c10/hip +// and c10/cuda and then use them from the at::cuda namespace. +// This is true in practice, because HIPIFY works inplace on +// files in ATen/cuda, so it assumes that c10::hip is available +// from at::cuda. This namespace makes that happen. When +// HIPIFY is no longer out-of-place, we can switch the cuda +// here to hip and everyone is happy. +namespace at::cuda { +using namespace c10::hip; +} // namespace at::cuda + +namespace at::xpu { +using namespace c10::xpu; +} // namespace at::xpu + +#endif // __cplusplus + +// C10_LIKELY/C10_UNLIKELY +// +// These macros provide parentheses, so you can use these macros as: +// +// if C10_LIKELY(some_expr) { +// ... +// } +// +// NB: static_cast to boolean is mandatory in C++, because __builtin_expect +// takes a long argument, which means you may trigger the wrong conversion +// without it. +// +#if defined(__GNUC__) || defined(__ICL) || defined(__clang__) +#define C10_LIKELY(expr) (__builtin_expect(static_cast(expr), 1)) +#define C10_UNLIKELY(expr) (__builtin_expect(static_cast(expr), 0)) +#else +#define C10_LIKELY(expr) (expr) +#define C10_UNLIKELY(expr) (expr) +#endif + +/// C10_NOINLINE - Functions whose declaration is annotated with this will not +/// be inlined. +#ifdef __GNUC__ +#define C10_NOINLINE __attribute__((noinline)) +#elif _MSC_VER +#define C10_NOINLINE __declspec(noinline) +#else +#define C10_NOINLINE +#endif + +#if defined(_MSC_VER) +#define C10_ALWAYS_INLINE __forceinline +#elif __has_attribute(always_inline) || defined(__GNUC__) +#define C10_ALWAYS_INLINE __attribute__((__always_inline__)) inline +#else +#define C10_ALWAYS_INLINE inline +#endif + +// Unlike C10_ALWAYS_INLINE, C10_ALWAYS_INLINE_ATTRIBUTE can be used +// on a lambda. +#if defined(_MSC_VER) +// MSVC 14.39 is reasonably recent and doesn't like +// [[msvc::forceinline]] on a lambda, so don't try to use it. +#define C10_ALWAYS_INLINE_ATTRIBUTE +#elif __has_attribute(always_inline) || defined(__GNUC__) +#define C10_ALWAYS_INLINE_ATTRIBUTE __attribute__((__always_inline__)) +#else +#define C10_ALWAYS_INLINE_ATTRIBUTE +#endif + +#if defined(_MSC_VER) +#define C10_ATTR_VISIBILITY_HIDDEN +#elif defined(__GNUC__) +#define C10_ATTR_VISIBILITY_HIDDEN __attribute__((__visibility__("hidden"))) +#else +#define C10_ATTR_VISIBILITY_HIDDEN +#endif + +#define C10_ERASE C10_ALWAYS_INLINE C10_ATTR_VISIBILITY_HIDDEN + +#ifdef __cplusplus +#include +#else +#include +#endif + +#ifdef __HIPCC__ +// Unlike CUDA, HIP requires a HIP header to be included for __host__ to work. +// We do this #include here so that C10_HOST_DEVICE and friends will Just Work. +// See https://github.com/ROCm/hip/issues/441 +#include +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) +// Designates functions callable from the host (CPU) and the device (GPU) +#define C10_HOST_DEVICE __host__ __device__ +#define C10_DEVICE __device__ +#define C10_HOST __host__ +// constants from +// (https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications) +// The maximum number of threads per multiprocessor is 1024 for Turing +// architecture (7.5), 1536 for Geforce Ampere (8.6)/Jetson Orin (8.7), and +// 2048 for all other architectures. You'll get warnings if you exceed these +// constants. Hence, the following macros adjust the input values from the user +// to resolve potential warnings. +#if __CUDA_ARCH__ == 750 +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1024; +#elif __CUDA_ARCH__ == 860 || __CUDA_ARCH__ == 870 || __CUDA_ARCH__ == 890 || \ + __CUDA_ARCH__ == 1200 +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1536; +#else +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 2048; +#endif +// CUDA_MAX_THREADS_PER_BLOCK is same for all architectures currently +constexpr uint32_t CUDA_MAX_THREADS_PER_BLOCK = 1024; +// CUDA_THREADS_PER_BLOCK_FALLBACK is the "canonical fallback" choice of block +// size. 256 is a good number for this fallback and should give good occupancy +// and versatility across all architectures. +constexpr uint32_t CUDA_THREADS_PER_BLOCK_FALLBACK = 256; +// NOTE: if you are thinking of constexpr-ify the inputs to launch bounds, it +// turns out that although __launch_bounds__ can take constexpr, it +// can't take a constexpr that has anything to do with templates. +// Currently we use launch_bounds that depend on template arguments in +// Loops.cuh, Reduce.cuh and LossCTC.cuh. Hence, C10_MAX_THREADS_PER_BLOCK +// and C10_MIN_BLOCKS_PER_SM are kept as macros. +// Suppose you were planning to write __launch_bounds__(a, b), based on your +// performance tuning on a modern GPU. Instead, you should write +// __launch_bounds__(C10_MAX_THREADS_PER_BLOCK(a), C10_MIN_BLOCKS_PER_SM(a, b)), +// which will also properly respect limits on old architectures. +#define C10_MAX_THREADS_PER_BLOCK(val) \ + (((val) <= CUDA_MAX_THREADS_PER_BLOCK) ? (val) \ + : CUDA_THREADS_PER_BLOCK_FALLBACK) +#define C10_MIN_BLOCKS_PER_SM(threads_per_block, blocks_per_sm) \ + ((((threads_per_block) * (blocks_per_sm) <= CUDA_MAX_THREADS_PER_SM) \ + ? (blocks_per_sm) \ + : ((CUDA_MAX_THREADS_PER_SM + (threads_per_block) - 1) / \ + (threads_per_block)))) +// C10_LAUNCH_BOUNDS is analogous to __launch_bounds__ +#define C10_LAUNCH_BOUNDS_0 \ + __launch_bounds__( \ + 256, 4) // default launch bounds that should give good occupancy and + // versatility across all architectures. +#define C10_LAUNCH_BOUNDS_1(max_threads_per_block) \ + __launch_bounds__((C10_MAX_THREADS_PER_BLOCK((max_threads_per_block)))) +#define C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm) \ + __launch_bounds__( \ + (C10_MAX_THREADS_PER_BLOCK((max_threads_per_block))), \ + (C10_MIN_BLOCKS_PER_SM((max_threads_per_block), (min_blocks_per_sm)))) +#else +#define C10_HOST_DEVICE +#define C10_HOST +#define C10_DEVICE +#endif + +#if defined(USE_ROCM) +#define C10_HIP_HOST_DEVICE __host__ __device__ +#else +#define C10_HIP_HOST_DEVICE +#endif + +#if defined(USE_ROCM) +// C10_WARP_SIZE is only allowed for device code. +// Host code _must_ use at::cuda::warp_size() +// HIP header used to define warpSize as a constexpr that was either 32 or 64 +// depending on the target device, and then always set it to 64 for host code. +// Host pass of HIP compiler needs C10_WARP_SIZE defined to _something_ so we +// set it to something unreasonable to trigger obvious host code errors. + +namespace at::cuda { +TORCH_CUDA_CPP_API int warp_size(); +} +#ifdef __HIPCC__ +static inline int __host__ C10_WARP_SIZE_INTERNAL() { + return at::cuda::warp_size(); +} + +static inline constexpr int __device__ C10_WARP_SIZE_INTERNAL() { +#if defined(__GFX9__) + return 64; +#else // __GFX9__ + return 32; +#endif // __GFX9__ +} +#else // __HIPCC__ +static inline int C10_WARP_SIZE_INTERNAL() { + return at::cuda::warp_size(); +} +#endif // __HIPCC__ + +#define C10_WARP_SIZE (C10_WARP_SIZE_INTERNAL()) +#define C10_WARP_SIZE_STATIC 64 + +#else // defined(USE_ROCM) +#define C10_WARP_SIZE 32 +#endif + +#if defined(_MSC_VER) && _MSC_VER <= 1900 +#define __func__ __FUNCTION__ +#endif + +// CUDA_KERNEL_ASSERT checks the assertion +// even when NDEBUG is defined. This is useful for important assertions in CUDA +// code that would otherwise be suppressed when building Release. +#if defined(__ANDROID__) || defined(__APPLE__) || defined(__FreeBSD__) +// Those platforms do not support assert() +#define CUDA_KERNEL_ASSERT(cond) +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) +#define SYCL_KERNEL_ASSERT(cond) +#elif defined(_MSC_VER) +#if defined(NDEBUG) +extern "C" { +C10_IMPORT +#if defined(__SYCL_DEVICE_ONLY__) +extern SYCL_EXTERNAL void _wassert( + const wchar_t* wexpr, + const wchar_t* wfile, + unsigned line); +#else +#if defined(__CUDA_ARCH__) +__host__ __device__ +#endif // __CUDA_ARCH__ + void + _wassert(wchar_t const* _Message, wchar_t const* _File, unsigned _Line); +#endif // __SYCL_DEVICE_ONLY__ +} +#endif // NDEBUG +#define CUDA_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +// TODO: This doesn't assert the message because I (chilli) couldn't figure out +// a nice way to convert a char* to a wchar_t* +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(printf( \ + "[CUDA_KERNEL_ASSERT] " __FILE__ ":" C10_STRINGIZE( \ + __LINE__) ": %s: block: [%d,%d,%d], thread: [%d,%d,%d]: " \ + "Assertion failed: `" #cond "`: " msg "\n", \ + __func__, \ + blockIdx.x, \ + blockIdx.y, \ + blockIdx.z, \ + threadIdx.x, \ + threadIdx.y, \ + threadIdx.z, \ + ##__VA_ARGS__)); \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#else // __APPLE__, _MSC_VER +#if defined(NDEBUG) +extern "C" { +#if defined(__SYCL_DEVICE_ONLY__) +extern SYCL_EXTERNAL void __assert_fail( + const char* expr, + const char* file, + unsigned int line, + const char* func); +#elif (defined(__EMSCRIPTEN__)) +// As defined in assert.h in the Emscripten stdlib +_Noreturn void __assert_fail( + const char* expr, + const char* file, + int line, + const char* func); +#else // __SYCL_DEVICE_ONLY__ +#if (defined(__CUDA_ARCH__) && !(defined(__clang__) && defined(__CUDA__))) +// CUDA supports __assert_fail function which are common for both device +// and host side code. +__host__ __device__ +#endif + + // This forward declaration matching the declaration of __assert_fail + // exactly how it is in glibc in case parts of the program are compiled with + // different NDEBUG settings. Otherwise we might get 'ambiguous declaration' + // error. Note: On ROCm - this declaration serves for host side compilation. + void + __assert_fail( + const char* assertion, + const char* file, + unsigned int line, + const char* function) noexcept __attribute__((__noreturn__)); + +#endif // __SYCL_DEVICE_ONLY__ +} +#endif // NDEBUG +// ROCm disables kernel assert by default for performance considerations. +// Though ROCm supports __assert_fail, it uses kernel printf which has +// a non-negligible performance impact even if the assert condition is +// never triggered. We choose to use abort() instead which will still +// terminate the application but without a more useful error message. +#if !defined(C10_USE_ROCM_KERNEL_ASSERT) && defined(USE_ROCM) +#define CUDA_KERNEL_ASSERT(cond) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#else +#define CUDA_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + msg, __FILE__, static_cast(__LINE__), __func__); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if (C10_UNLIKELY(!(cond))) { \ + printf( \ + "[CUDA_KERNEL_ASSERT] " __FILE__ ":" C10_STRINGIZE( \ + __LINE__) ": %s: block: [%d,%d,%d], thread: [%d,%d,%d]: " \ + "Assertion failed: `" #cond "`: " msg "\n", \ + __func__, \ + blockIdx.x, \ + blockIdx.y, \ + blockIdx.z, \ + threadIdx.x, \ + threadIdx.y, \ + threadIdx.z, \ + ##__VA_ARGS__); \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#endif // C10_USE_ROCM_KERNEL_ASSERT && USE_ROCM +#endif // __APPLE__ + +// Compile-time switch to control how assertions are logged inside CUDA kernels. +// If C10_CUDA_VERBOSE_ASSERT is defined, CUDA_KERNEL_ASSERT_VERBOSE will +// take addition information passed to the macro and forward them to +// CUDA_KERNEL_ASSERT_PRINTF If C10_CUDA_VERBOSE_ASSERT is not defined, +// CUDA_KERNEL_ASSERT_VERBOSE will behave the same as CUDA_KERNEL_ASSERT. +#ifdef C10_ENABLE_VERBOSE_ASSERT +#define CUDA_KERNEL_ASSERT_VERBOSE(cond, ...) \ + CUDA_KERNEL_ASSERT_PRINTF(cond, __VA_ARGS__) +#else +#define CUDA_KERNEL_ASSERT_VERBOSE(cond, ...) CUDA_KERNEL_ASSERT(cond) +#endif + +#ifdef __APPLE__ +#include +#endif + +#if defined(__ANDROID__) +#define C10_ANDROID 1 +#define C10_MOBILE 1 +#elif ( \ + defined(__APPLE__) && \ + (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE)) +#define C10_IOS 1 +#define C10_MOBILE 1 +#endif // ANDROID / IOS + +#if defined(C10_MOBILE) && C10_MOBILE +#define C10_ALWAYS_INLINE_UNLESS_MOBILE inline +#else +#define C10_ALWAYS_INLINE_UNLESS_MOBILE C10_ALWAYS_INLINE +#endif + +#if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) +#define CONSTEXPR_EXCEPT_WIN_CUDA constexpr +#define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA constexpr + +#define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \ + static constexpr const char field[] = val; +#define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val) +#endif // !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) + +#ifndef HAS_DEMANGLE +#if defined(__ANDROID__) || defined(_WIN32) || defined(__EMSCRIPTEN__) +#define HAS_DEMANGLE 0 +#elif defined(__APPLE__) && \ + (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE) +#define HAS_DEMANGLE 0 +#else +#define HAS_DEMANGLE 1 +#endif +#endif // HAS_DEMANGLE + +#define _C10_PRAGMA__(string) _Pragma(#string) +#define _C10_PRAGMA_(string) _C10_PRAGMA__(string) + +#ifdef __clang__ +#define C10_CLANG_DIAGNOSTIC_PUSH() _Pragma("clang diagnostic push") +#define C10_CLANG_DIAGNOSTIC_POP() _Pragma("clang diagnostic pop") +#define C10_CLANG_DIAGNOSTIC_IGNORE(flag) \ + _C10_PRAGMA_(clang diagnostic ignored flag) +#define C10_CLANG_HAS_WARNING(flag) __has_warning(flag) +#else +#define C10_CLANG_DIAGNOSTIC_PUSH() +#define C10_CLANG_DIAGNOSTIC_POP() +#define C10_CLANG_DIAGNOSTIC_IGNORE(flag) +#define C10_CLANG_HAS_WARNING(flag) 0 +#endif + +#ifdef __clang__ + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \ + _C10_PRAGMA_(clang diagnostic push) \ + _C10_PRAGMA_(clang diagnostic ignored "-Wunknown-warning-option") \ + _C10_PRAGMA_(clang diagnostic ignored warning) + +#define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(clang diagnostic pop) + +#elif __GNUC__ + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \ + _C10_PRAGMA_(GCC diagnostic push) \ + _C10_PRAGMA_(GCC diagnostic ignored "-Wpragmas") \ + _C10_PRAGMA_(GCC diagnostic ignored warning) + +#define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(GCC diagnostic pop) + +#else + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) +#define C10_DIAGNOSTIC_POP() + +#endif + +// This macro is used to find older C++ compilers +// that don't support move optimization for return values. + +#if (defined(__GNUC__) && __GNUC__ < 13) || \ + (defined(__clang_major__) && __clang_major__ < 13) +#define C10_RETURN_MOVE_IF_OLD_COMPILER 1 +#else +#define C10_RETURN_MOVE_IF_OLD_COMPILER 0 +#endif + +// The HIDDEN_NAMESPACE_BEGIN and HIDDEN_NAMESPACE_END below +// are needed for maintaining robustness in our header APIs in +// torch/headeronly and torch/csrc/stable under the namespaces +// torch::headeronly and torch::stable respectively. We enforce +// hidden visibility for these APIs because we want to enable +// loading custom extensions compiled against different libtorch +// versions where these APIs may have changed. + +// Helper macros to handle 1-3 hidden namespace levels when not windows +#define _HIDDEN_NS_GET_MACRO(_1, _2, _3, NAME, ...) NAME +#define _HIDDEN_NS_1(n1) namespace n1 __attribute__((visibility("hidden"))) { +#define _HIDDEN_NS_2(n1, n2) \ + namespace n1 { \ + namespace n2 __attribute__((visibility("hidden"))) { +#define _HIDDEN_NS_3(n1, n2, n3) \ + namespace n1::n2 { \ + namespace n3 __attribute__((visibility("hidden"))) { + +// Helper macros to close namespaces when not windows +#define _HIDDEN_NS_END_1(n1) } +#define _HIDDEN_NS_END_N(n1, ...) \ + } \ + } + +// Helper macros to join strs with :: (for win, where symbols are hidden by +// default) +#define _EXPAND(...) __VA_ARGS__ +#define _JOIN_GET_MACRO(_1, _2, _3, NAME, ...) NAME +#define _JOIN_NS1(a) a +#define _JOIN_NS2(a, b) a::b +#define _JOIN_NS3(a, b, c) a::b::c + +#if !defined(HIDDEN_NAMESPACE_BEGIN) +#if defined(__GNUG__) && !defined(_WIN32) +#define HIDDEN_NAMESPACE_BEGIN(...) \ + _HIDDEN_NS_GET_MACRO( \ + __VA_ARGS__, _HIDDEN_NS_3, _HIDDEN_NS_2, _HIDDEN_NS_1)(__VA_ARGS__) +#else +#define HIDDEN_NAMESPACE_BEGIN(...) \ + namespace _EXPAND(_JOIN_GET_MACRO( \ + __VA_ARGS__, _JOIN_NS3, _JOIN_NS2, _JOIN_NS1)(__VA_ARGS__)) { +#endif +#endif + +#if !defined(HIDDEN_NAMESPACE_END) +#if defined(__GNUG__) && !defined(_WIN32) +#define HIDDEN_NAMESPACE_END(...) \ + _HIDDEN_NS_GET_MACRO( \ + __VA_ARGS__, _HIDDEN_NS_END_N, _HIDDEN_NS_END_N, _HIDDEN_NS_END_1)( \ + __VA_ARGS__) +#else +#define HIDDEN_NAMESPACE_END(...) } +#endif +#endif + +#endif // C10_MACROS_MACROS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/cmake_macros.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/cmake_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..8b8894ca9473bffc5a7711b74df4ae48f01352bc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/macros/cmake_macros.h @@ -0,0 +1,14 @@ +#ifndef C10_MACROS_CMAKE_MACROS_H_ +#define C10_MACROS_CMAKE_MACROS_H_ + +// Automatically generated header file for the C10 library. +// Do not include this file directly. Instead, include torch/headeronly/macros/Macros.h. + +#define C10_BUILD_SHARED_LIBS +/* #undef C10_USE_GLOG */ +/* #undef C10_USE_GFLAGS */ +/* #undef C10_USE_NUMA */ +/* #undef C10_USE_MSVC_STATIC_RUNTIME */ +/* #undef C10_USE_ROCM_KERNEL_ASSERT */ + +#endif // C10_MACROS_CMAKE_MACROS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/BFloat16.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/BFloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..64479ba36f125c77e8941f29012ca2a8baecb6ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/BFloat16.h @@ -0,0 +1,480 @@ +#pragma once + +// Defines the bloat16 type (brain floating-point). This representation uses +// 1 bit for the sign, 8 bits for the exponent and 7 bits for the mantissa. + +#include +#include + +#include +#include +#include +#include +#include + +#if defined(__CUDACC__) && !defined(USE_ROCM) +#include +#endif + +#if defined(CL_SYCL_LANGUAGE_VERSION) +#include // for SYCL 1.2.1 +#elif defined(SYCL_LANGUAGE_VERSION) +#include // for SYCL 2020 +#endif + +namespace c10 { + +struct alignas(2) BFloat16 { + uint16_t x; + + // HIP wants __host__ __device__ tag, CUDA does not +#if defined(USE_ROCM) && defined(__HIPCC__) + C10_HOST_DEVICE BFloat16() = default; +#else + BFloat16() = default; +#endif + + struct from_bits_t {}; + static constexpr C10_HOST_DEVICE from_bits_t from_bits() { + return from_bits_t(); + } + + constexpr C10_HOST_DEVICE BFloat16( + unsigned short bits, + from_bits_t /*unused*/) + : x(bits) {} + /* implicit */ inline C10_HOST_DEVICE BFloat16(float value); + inline C10_HOST_DEVICE operator float() const; + +#if defined(__CUDACC__) && !defined(USE_ROCM) + inline C10_HOST_DEVICE BFloat16(const __nv_bfloat16& value); + explicit inline C10_HOST_DEVICE operator __nv_bfloat16() const; +#endif + +#if defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + inline C10_HOST_DEVICE BFloat16(const sycl::ext::oneapi::bfloat16& value); + explicit inline C10_HOST_DEVICE operator sycl::ext::oneapi::bfloat16() const; +#endif +}; + +inline std::ostream& operator<<(std::ostream& out, const BFloat16& value) { + out << (float)value; + return out; +} + +namespace detail { +inline C10_HOST_DEVICE float f32_from_bits(uint16_t src) { + float res = 0; + uint32_t tmp = src; + tmp <<= 16; + +#if defined(USE_ROCM) && defined(__HIPCC__) + float* tempRes; + + // We should be using memcpy in order to respect the strict aliasing rule + // but it fails in the HIP environment. + tempRes = reinterpret_cast(&tmp); + res = *tempRes; +#else + std::memcpy(&res, &tmp, sizeof(tmp)); +#endif + + return res; +} + +inline C10_HOST_DEVICE uint16_t bits_from_f32(float src) { + uint32_t res = 0; + +#if defined(USE_ROCM) && defined(__HIPCC__) + // We should be using memcpy in order to respect the strict aliasing rule + // but it fails in the HIP environment. + uint32_t* tempRes = reinterpret_cast(&src); + res = *tempRes; +#else + std::memcpy(&res, &src, sizeof(res)); +#endif + + return res >> 16; +} + +inline C10_HOST_DEVICE uint16_t round_to_nearest_even(float src) { +#if defined(USE_ROCM) && defined(__HIPCC__) + if (src != src) { +#elif defined(_MSC_VER) + if (isnan(src)) { +#else + if (std::isnan(src)) { +#endif + return UINT16_C(0x7FC0); + } else { + const uint32_t U32 = c10::bit_cast(src); + uint32_t rounding_bias = ((U32 >> 16) & 1) + UINT32_C(0x7FFF); + return static_cast((U32 + rounding_bias) >> 16); + } +} + +} // namespace detail + +//-------- the following is copied from c10/util/BFloat16-inl.h ---------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +/// Constructors +inline C10_HOST_DEVICE BFloat16::BFloat16(float value) + : +#if defined(__CUDACC__) && !defined(USE_ROCM) && defined(__CUDA_ARCH__) && \ + __CUDA_ARCH__ >= 800 + x(__bfloat16_as_ushort(__float2bfloat16(value))) +#elif defined(__SYCL_DEVICE_ONLY__) && \ + defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + x(c10::bit_cast(sycl::ext::oneapi::bfloat16(value))) +#else + // RNE by default + x(detail::round_to_nearest_even(value)) +#endif +{ +} + +/// Implicit conversions +inline C10_HOST_DEVICE BFloat16::operator float() const { +#if defined(__CUDACC__) && !defined(USE_ROCM) + return __bfloat162float(*reinterpret_cast(&x)); +#elif defined(__SYCL_DEVICE_ONLY__) && \ + defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + return float(*reinterpret_cast(&x)); +#else + return detail::f32_from_bits(x); +#endif +} + +#if defined(__CUDACC__) && !defined(USE_ROCM) +inline C10_HOST_DEVICE BFloat16::BFloat16(const __nv_bfloat16& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE BFloat16::operator __nv_bfloat16() const { + return *reinterpret_cast(&x); +} +#endif + +#if defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) +inline C10_HOST_DEVICE BFloat16::BFloat16( + const sycl::ext::oneapi::bfloat16& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE BFloat16::operator sycl::ext::oneapi::bfloat16() const { + return *reinterpret_cast(&x); +} +#endif + +// CUDA intrinsics + +#if defined(__CUDACC__) || defined(__HIPCC__) +inline C10_DEVICE BFloat16 __ldg(const BFloat16* ptr) { +#if !defined(USE_ROCM) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + return __ldg(reinterpret_cast(ptr)); +#else + return *ptr; +#endif +} +#endif + +/// Arithmetic + +inline C10_HOST_DEVICE BFloat16 +operator+(const BFloat16& a, const BFloat16& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 +operator-(const BFloat16& a, const BFloat16& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 +operator*(const BFloat16& a, const BFloat16& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator/(const BFloat16& a, const BFloat16& b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator-(const BFloat16& a) { + return -static_cast(a); +} + +inline C10_HOST_DEVICE BFloat16& operator+=(BFloat16& a, const BFloat16& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator-=(BFloat16& a, const BFloat16& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator*=(BFloat16& a, const BFloat16& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator/=(BFloat16& a, const BFloat16& b) { + a = a / b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator|(BFloat16& a, const BFloat16& b) { + a.x = a.x | b.x; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator^(BFloat16& a, const BFloat16& b) { + a.x = a.x ^ b.x; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator&(BFloat16& a, const BFloat16& b) { + a.x = a.x & b.x; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(BFloat16 a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(BFloat16 a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(BFloat16 a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(BFloat16 a, float b) { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, BFloat16 b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, BFloat16 b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, BFloat16 b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, BFloat16 b) { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const BFloat16& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const BFloat16& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const BFloat16& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const BFloat16& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(BFloat16 a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(BFloat16 a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(BFloat16 a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(BFloat16 a, double b) { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, BFloat16 b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, BFloat16 b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, BFloat16 b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, BFloat16 b) { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE BFloat16 operator+(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator-(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator*(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator/(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator+(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE BFloat16 operator-(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE BFloat16 operator*(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE BFloat16 operator/(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE BFloat16 operator+(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator-(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator*(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator/(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator+(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE BFloat16 operator-(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE BFloat16 operator*(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE BFloat16 operator/(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +// Overloading < and > operators, because std::max and std::min use them. + +inline C10_HOST_DEVICE bool operator>(BFloat16& lhs, BFloat16& rhs) { + return float(lhs) > float(rhs); +} + +inline C10_HOST_DEVICE bool operator<(BFloat16& lhs, BFloat16& rhs) { + return float(lhs) < float(rhs); +} + +C10_CLANG_DIAGNOSTIC_POP() +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +namespace detail { +using c10::detail::bits_from_f32; +using c10::detail::f32_from_bits; +using c10::detail::round_to_nearest_even; +} // namespace detail + +using c10::BFloat16; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator<; +using c10::operator>; +using c10::operator<<; +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_signed = true; + static constexpr bool is_specialized = true; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = true; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = true; + static constexpr auto has_denorm = numeric_limits::has_denorm; + static constexpr auto has_denorm_loss = + numeric_limits::has_denorm_loss; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = false; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 8; + static constexpr int digits10 = 2; + static constexpr int max_digits10 = 4; + static constexpr int radix = 2; + static constexpr int min_exponent = -125; + static constexpr int min_exponent10 = -37; + static constexpr int max_exponent = 128; + static constexpr int max_exponent10 = 38; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = + numeric_limits::tinyness_before; + + static constexpr c10::BFloat16 min() { + return c10::BFloat16(0x0080, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 lowest() { + return c10::BFloat16(0xFF7F, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 max() { + return c10::BFloat16(0x7F7F, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 epsilon() { + return c10::BFloat16(0x3C00, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 round_error() { + return c10::BFloat16(0x3F00, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 infinity() { + return c10::BFloat16(0x7F80, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 quiet_NaN() { + return c10::BFloat16(0x7FC0, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 signaling_NaN() { + return c10::BFloat16(0x7F80, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 denorm_min() { + return c10::BFloat16(0x0001, c10::BFloat16::from_bits()); + } +}; + +} // namespace std diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Deprecated.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Deprecated.h new file mode 100644 index 0000000000000000000000000000000000000000..88440a0242eb4e9e87433278006863fd38c5450d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Deprecated.h @@ -0,0 +1,102 @@ +#pragma once + +/** + * This file provides portable macros for marking declarations + * as deprecated. You should generally use C10_DEPRECATED, + * except when marking 'using' declarations as deprecated, + * in which case you should use C10_DEFINE_DEPRECATED_USING + * (due to portability concerns). + */ + +// Sample usage: +// +// C10_DEPRECATED void bad_func(); +// struct C10_DEPRECATED BadStruct { +// ... +// }; + +// NB: __cplusplus doesn't work for MSVC, so for now MSVC always uses +// the "__declspec(deprecated)" implementation and not the C++14 +// "[[deprecated]]" attribute. We tried enabling "[[deprecated]]" for C++14 on +// MSVC, but ran into issues with some older MSVC versions. +#if (defined(__cplusplus) && __cplusplus >= 201402L) +#define C10_DEPRECATED [[deprecated]] +#define C10_DEPRECATED_MESSAGE(message) [[deprecated(message)]] +#elif defined(__GNUC__) +#define C10_DEPRECATED __attribute__((deprecated)) +// TODO Is there some way to implement this? +#define C10_DEPRECATED_MESSAGE(message) __attribute__((deprecated)) + +#elif defined(_MSC_VER) +#define C10_DEPRECATED __declspec(deprecated) +#define C10_DEPRECATED_MESSAGE(message) __declspec(deprecated(message)) +#else +#warning "You need to implement C10_DEPRECATED for this compiler" +#define C10_DEPRECATED +#endif + +// Sample usage: +// +// C10_DEFINE_DEPRECATED_USING(BadType, int) +// +// which is the portable version of +// +// using BadType [[deprecated]] = int; + +// technically [[deprecated]] syntax is from c++14 standard, but it works in +// many compilers. +#if defined(__has_cpp_attribute) +#if __has_cpp_attribute(deprecated) && !defined(__CUDACC__) +#define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \ + using TypeName [[deprecated]] = TypeThingy; +#endif +#endif + +#if defined(_MSC_VER) +#if defined(__CUDACC__) +// neither [[deprecated]] nor __declspec(deprecated) work on nvcc on Windows; +// you get the error: +// +// error: attribute does not apply to any entity +// +// So we just turn the macro off in this case. +#if defined(C10_DEFINE_DEPRECATED_USING) +#undef C10_DEFINE_DEPRECATED_USING +#endif +#define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \ + using TypeName = TypeThingy; +#else +// [[deprecated]] does work in windows without nvcc, though msc doesn't support +// `__has_cpp_attribute` when c++14 is supported, otherwise +// __declspec(deprecated) is used as the alternative. +#ifndef C10_DEFINE_DEPRECATED_USING +#if defined(_MSVC_LANG) && _MSVC_LANG >= 201402L +#define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \ + using TypeName [[deprecated]] = TypeThingy; +#else +#define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \ + using TypeName = __declspec(deprecated) TypeThingy; +#endif +#endif +#endif +#endif + +#if !defined(C10_DEFINE_DEPRECATED_USING) && defined(__GNUC__) +// nvcc has a bug where it doesn't understand __attribute__((deprecated)) +// declarations even when the host compiler supports it. We'll only use this gcc +// attribute when not cuda, and when using a GCC compiler that doesn't support +// the c++14 syntax we checked for above (available in __GNUC__ >= 5) +#if !defined(__CUDACC__) +#define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \ + using TypeName __attribute__((deprecated)) = TypeThingy; +#else +// using cuda + gcc < 5, neither deprecated syntax is available so turning off. +#define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \ + using TypeName = TypeThingy; +#endif +#endif + +#if !defined(C10_DEFINE_DEPRECATED_USING) +#warning "You need to implement C10_DEFINE_DEPRECATED_USING for this compiler" +#define C10_DEFINE_DEPRECATED_USING +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Exception.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Exception.h new file mode 100644 index 0000000000000000000000000000000000000000..0e067244a50e15db01d65ecfeb5908c29aecaeba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Exception.h @@ -0,0 +1,83 @@ +#pragma once + +#include +#include + +#include +#include + +namespace c10 { +// On nvcc, C10_UNLIKELY thwarts missing return statement analysis. In cases +// where the unlikely expression may be a constant, use this macro to ensure +// return statement analysis keeps working (at the cost of not getting the +// likely/unlikely annotation on nvcc). +// https://github.com/pytorch/pytorch/issues/21418 +// +// Currently, this is only used in the error reporting macros below. If you +// want to use it more generally, move me to Macros.h +// +// TODO: Brian Vaughan observed that we might be able to get this to work on +// nvcc by writing some sort of C++ overload that distinguishes constexpr inputs +// from non-constexpr. Since there isn't any evidence that losing C10_UNLIKELY +// in nvcc is causing us perf problems, this is not yet implemented, but this +// might be an interesting piece of C++ code for an intrepid bootcamper to +// write. +#if defined(__CUDACC__) +#define C10_UNLIKELY_OR_CONST(e) e +#else +#define C10_UNLIKELY_OR_CONST(e) C10_UNLIKELY(e) +#endif + +} // namespace c10 + +// STD_TORCH_CHECK throws std::runtime_error instead of c10::Error which is +// useful when certain headers are used in a libtorch-independent way, +// e.g. when Vectorized is used in AOTInductor generated code, or +// for custom ops to have an ABI stable dependency on libtorch. +#ifdef STRIP_ERROR_MESSAGES +#define STD_TORCH_CHECK_MSG(cond, type, ...) \ + (#cond #type " CHECK FAILED at " C10_STRINGIZE(__FILE__)) +#else // so STRIP_ERROR_MESSAGES is not defined +HIDDEN_NAMESPACE_BEGIN(torch, headeronly, detail) +template +std::string stdTorchCheckMsgImpl(const char* /*msg*/, const Args&... args) { + // This is similar to the one in c10/util/Exception.h, but does + // not depend on the more complex c10::str() function. ostringstream + // supports fewer data types than c10::str(), but should be sufficient + // in the headeronly world. + std::ostringstream oss; + ((oss << args), ...); + return oss.str(); +} + +inline const char* stdTorchCheckMsgImpl(const char* msg) { + return msg; +} +// If there is just 1 user-provided C-string argument, use it. +inline const char* stdTorchCheckMsgImpl(const char* /*msg*/, const char* args) { + return args; +} +HIDDEN_NAMESPACE_END(torch, headeronly, detail) + +#define STD_TORCH_CHECK_MSG(cond, type, ...) \ + (torch::headeronly::detail::stdTorchCheckMsgImpl( \ + "Expected " #cond \ + " to be true, but got false. " \ + "(Could this error message be improved? If so, " \ + "please report an enhancement request to PyTorch.)", \ + ##__VA_ARGS__)) +#endif // STRIP_ERROR_MESSAGES + +#define STD_TORCH_CHECK(cond, ...) \ + if (C10_UNLIKELY_OR_CONST(!(cond))) { \ + throw std::runtime_error(STD_TORCH_CHECK_MSG( \ + cond, \ + "", \ + __func__, \ + ", ", \ + __FILE__, \ + ":", \ + __LINE__, \ + ", ", \ + ##__VA_ARGS__)); \ + } diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float4_e2m1fn_x2.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float4_e2m1fn_x2.h new file mode 100644 index 0000000000000000000000000000000000000000..00075914cdc346af4d212f089731c5fea6943873 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float4_e2m1fn_x2.h @@ -0,0 +1,47 @@ +#pragma once +#include + +#include + +/// Defines the Float4_e2m1fn_x2 type (4-bit floating-point, two elements packed +/// into one byte). This is the FP4 dtype from the OCP MX format spec +/// (https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf, +/// Section 5.3.3) +/// +/// Given two high precision values val0 and val1, here is the +/// binary configuration of their packed representation, from MSB to LSB: +/// +/// original value | val1 : val0 +/// ======================================== +/// bit index (MSB==7, LSB==0) | 7654 : 3210 +/// sign/exponent/mantissa | seem : seem +/// + +namespace c10 { + +struct alignas(1) Float4_e2m1fn_x2 { + uint8_t val_; + Float4_e2m1fn_x2() = default; + C10_HOST_DEVICE explicit Float4_e2m1fn_x2(uint8_t val) : val_(val) {} +}; + +/// Comparison operators +inline C10_HOST_DEVICE bool operator==( + const Float4_e2m1fn_x2& a, + const Float4_e2m1fn_x2& b) { + return a.val_ == b.val_; +} + +inline C10_HOST_DEVICE bool operator!=( + const Float4_e2m1fn_x2& a, + const Float4_e2m1fn_x2& b) { + return a.val_ != b.val_; +} + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::Float4_e2m1fn_x2; +using c10::operator==; +using c10::operator!=; +HIDDEN_NAMESPACE_END(torch, headeronly) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e4m3fn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e4m3fn.h new file mode 100644 index 0000000000000000000000000000000000000000..b35fb1a7aa85d18a2884bdea359a351dea57332b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e4m3fn.h @@ -0,0 +1,531 @@ +#pragma once + +/// Defines the Float8_e4m3fn type (8-bit floating-point) including conversions +/// to standard C types and basic arithmetic operations. Note that arithmetic +/// operations are implemented by converting to floating point and +/// performing the operation in float32. +/// Binary configuration: +/// s eeee mmm +/// 1 sign bit +/// 4 exponent bits +/// 3 mantissa bits +/// bias = 7 +/// +/// Implementation based on the paper https://arxiv.org/pdf/2209.05433.pdf +/// and inspired by Half implementation from pytorch/c10/util/Half.h + +#include +#include + +#if defined(__cplusplus) +#include +#include +#elif !defined(__OPENCL_VERSION__) +#include +#include +#endif + +#ifdef _MSC_VER +#include +#endif + +#include +#include + +namespace c10 { + +struct alignas(1) Float8_e4m3fn { + uint8_t x; + + struct from_bits_t {}; + C10_HOST_DEVICE static constexpr from_bits_t from_bits() { + return from_bits_t(); + } + + Float8_e4m3fn() = default; + + constexpr C10_HOST_DEVICE Float8_e4m3fn(uint8_t bits, from_bits_t /*unused*/) + : x(bits) {} + inline C10_HOST_DEVICE Float8_e4m3fn(float value); + inline C10_HOST_DEVICE operator float() const; + inline C10_HOST_DEVICE bool isnan() const; +}; + +inline std::ostream& operator<<(std::ostream& out, const Float8_e4m3fn& value) { + out << (float)value; + return out; +} + +namespace detail { + +/* + * Convert a 8-bit floating-point number in fp8 E4M3FN format, in bit + * representation, to a 32-bit floating-point number in IEEE single-precision + * format, in bit representation. + * + * @note The implementation doesn't use any floating-point operations. + */ +inline C10_HOST_DEVICE float fp8e4m3fn_to_fp32_value(uint8_t input) { + /* + * Extend the fp8 E4M3FN number to 32 bits and shift to the + * upper part of the 32-bit word: + * +---+----+---+-----------------------------+ + * | S |EEEE|MMM|0000 0000 0000 0000 0000 0000| + * +---+----+---+-----------------------------+ + * Bits 31 27-30 24-26 0-23 + * + * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0 + * - zero bits. + */ + const uint32_t w = (uint32_t)input << 24; + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = w & UINT32_C(0x80000000); + /* + * Extract mantissa and biased exponent of the input number into the bits 0-30 + * of the 32-bit word: + * + * +---+----+---+-----------------------------+ + * | S |EEEE|MMM|0000 0000 0000 0000 0000 0000| + * +---+----+---+-----------------------------+ + * Bits 31 27-30 24-26 0-23 + */ + const uint32_t nonsign = w & UINT32_C(0x7FFFFFFF); + /* + * Renorm shift is the number of bits to shift mantissa left to make the + * half-precision number normalized. If the initial number is normalized, some + * of its high 5 bits (sign == 0 and 4-bit exponent) equals one. In this case + * renorm_shift == 0. If the number is denormalize, renorm_shift > 0. Note + * that if we shift denormalized nonsign by renorm_shift, the unit bit of + * mantissa will shift into exponent, turning the biased exponent into 1, and + * making mantissa normalized (i.e. without leading 1). + */ +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + uint32_t renorm_shift = __clz(nonsign); +#elif defined(__SYCL_DEVICE_ONLY__) + // Note: zero is not a supported input into `__builtin_clz` + uint32_t renorm_shift = + nonsign != 0 ? __builtin_clz(nonsign) : sizeof(uint32_t) * CHAR_BIT; +#elif defined(_MSC_VER) && !defined(__clang__) + unsigned long nonsign_bsr; + _BitScanReverse(&nonsign_bsr, (unsigned long)nonsign); + uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31; +#else + // Note: zero is not a supported input into `__builtin_clz` + uint32_t renorm_shift = + nonsign != 0 ? __builtin_clz(nonsign) : sizeof(uint32_t) * CHAR_BIT; +#endif + renorm_shift = renorm_shift > 4 ? renorm_shift - 4 : 0; + /* + * Iff fp8e4m3fn number has all exponent and mantissa bits set to 1, + * the addition overflows it into bit 31, and the subsequent shift turns the + * high 9 bits into 1. Thus inf_nan_mask == 0x7F800000 if the fp8e4m3fn number + * is Nan, 0x00000000 otherwise + */ + const int32_t inf_nan_mask = + ((int32_t)(nonsign + 0x01000000) >> 8) & INT32_C(0x7F800000); + /* + * Iff nonsign is 0, it overflows into 0xFFFFFFFF, turning bit 31 + * into 1. Otherwise, bit 31 remains 0. The signed shift right by 31 + * broadcasts bit 31 into all bits of the zero_mask. Thus zero_mask == + * 0xFFFFFFFF if the half-precision number was zero (+0.0h or -0.0h) + * 0x00000000 otherwise + */ + const int32_t zero_mask = (int32_t)(nonsign - 1) >> 31; + /* + * 1. Shift nonsign left by renorm_shift to normalize it (if the input + * was denormal) + * 2. Shift nonsign right by 4 so the exponent (4 bits originally) + * becomes an 8-bit field and 3-bit mantissa shifts into the 3 high + * bits of the 23-bit mantissa of IEEE single-precision number. + * 3. Add 0x78 to the exponent (starting at bit 23) to compensate the + * different in exponent bias (0x7F for single-precision number less 0x07 + * for fp8e4m3fn number). + * 4. Subtract renorm_shift from the exponent (starting at bit 23) to + * account for renormalization. As renorm_shift is less than 0x78, this + * can be combined with step 3. + * 5. Binary OR with inf_nan_mask to turn the exponent into 0xFF if the + * input was NaN or infinity. + * 6. Binary ANDNOT with zero_mask to turn the mantissa and exponent + * into zero if the input was zero. + * 7. Combine with the sign of the input number. + */ + uint32_t result = sign | + ((((nonsign << renorm_shift >> 4) + ((0x78 - renorm_shift) << 23)) | + inf_nan_mask) & + ~zero_mask); + return fp32_from_bits(result); +} + +/* + * Convert a 32-bit floating-point number in IEEE single-precision format to a + * 8-bit floating-point number in fp8 E4M3FN format, in bit representation. + */ +inline C10_HOST_DEVICE uint8_t fp8e4m3fn_from_fp32_value(float f) { + /* + * Binary representation of 480.0f, which is the first value + * not representable in fp8e4m3fn range: + * 0 1111 111 - fp8e4m3fn + * 0 10000111 11100000000000000000000 - fp32 + */ + constexpr uint32_t fp8_max = UINT32_C(1087) << 20; + + /* + * A mask for converting fp32 numbers lower than fp8e4m3fn normal range + * into denorm representation + * magic number: ((127 - 7) + (23 - 3) + 1) + */ + constexpr uint32_t denorm_mask = UINT32_C(141) << 23; + + uint32_t f_bits = fp32_to_bits(f); + + uint8_t result = 0u; + + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = f_bits & UINT32_C(0x80000000); + + /* + * Set sign bit to 0 + */ + f_bits ^= sign; + + if (f_bits >= fp8_max) { + // NaN - all exponent and mantissa bits set to 1 + result = 0x7f; + } else { + if (f_bits < (UINT32_C(121) << 23)) { + // Input number is smaller than 2^(-6), which is the smallest + // fp8e4m3fn normal number + f_bits = + fp32_to_bits(fp32_from_bits(f_bits) + fp32_from_bits(denorm_mask)); + result = static_cast(f_bits - denorm_mask); + } else { + // resulting mantissa is odd + uint8_t mant_odd = (f_bits >> 20) & 1; + + // update exponent, rounding bias part 1 + f_bits += ((uint32_t)(7 - 127) << 23) + 0x7FFFF; + + // rounding bias part 2 + f_bits += mant_odd; + + // take the bits! + result = static_cast(f_bits >> 20); + } + } + + result |= static_cast(sign >> 24); + return result; +} + +} // namespace detail + +// -------- below is copied from c10/util/Float8_e4m3fn-inl.h --------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +/// Constructors + +inline C10_HOST_DEVICE Float8_e4m3fn::Float8_e4m3fn(float value) + : x(detail::fp8e4m3fn_from_fp32_value(value)) {} + +/// Implicit conversions + +inline C10_HOST_DEVICE Float8_e4m3fn::operator float() const { + return detail::fp8e4m3fn_to_fp32_value(x); +} + +/// Special values helper + +inline C10_HOST_DEVICE bool Float8_e4m3fn::isnan() const { + return (x & 0b01111111) == 0b01111111; +} + +/// Arithmetic + +inline C10_HOST_DEVICE Float8_e4m3fn +operator+(const Float8_e4m3fn& a, const Float8_e4m3fn& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fn +operator-(const Float8_e4m3fn& a, const Float8_e4m3fn& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fn +operator*(const Float8_e4m3fn& a, const Float8_e4m3fn& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fn operator/( + const Float8_e4m3fn& a, + const Float8_e4m3fn& b) __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fn operator-(const Float8_e4m3fn& a) { + return -static_cast(a); +} + +inline C10_HOST_DEVICE Float8_e4m3fn& operator+=( + Float8_e4m3fn& a, + const Float8_e4m3fn& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE Float8_e4m3fn& operator-=( + Float8_e4m3fn& a, + const Float8_e4m3fn& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE Float8_e4m3fn& operator*=( + Float8_e4m3fn& a, + const Float8_e4m3fn& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE Float8_e4m3fn& operator/=( + Float8_e4m3fn& a, + const Float8_e4m3fn& b) { + a = a / b; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(Float8_e4m3fn a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(Float8_e4m3fn a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(Float8_e4m3fn a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(Float8_e4m3fn a, float b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, Float8_e4m3fn b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, Float8_e4m3fn b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, Float8_e4m3fn b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, Float8_e4m3fn b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const Float8_e4m3fn& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const Float8_e4m3fn& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const Float8_e4m3fn& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const Float8_e4m3fn& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(Float8_e4m3fn a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(Float8_e4m3fn a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(Float8_e4m3fn a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(Float8_e4m3fn a, double b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, Float8_e4m3fn b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, Float8_e4m3fn b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, Float8_e4m3fn b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, Float8_e4m3fn b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE Float8_e4m3fn operator+(Float8_e4m3fn a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fn operator-(Float8_e4m3fn a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fn operator*(Float8_e4m3fn a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fn operator/(Float8_e4m3fn a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fn operator+(int a, Float8_e4m3fn b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Float8_e4m3fn operator-(int a, Float8_e4m3fn b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Float8_e4m3fn operator*(int a, Float8_e4m3fn b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Float8_e4m3fn operator/(int a, Float8_e4m3fn b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE Float8_e4m3fn operator+(Float8_e4m3fn a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fn operator-(Float8_e4m3fn a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fn operator*(Float8_e4m3fn a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fn operator/(Float8_e4m3fn a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fn operator+(int64_t a, Float8_e4m3fn b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Float8_e4m3fn operator-(int64_t a, Float8_e4m3fn b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Float8_e4m3fn operator*(int64_t a, Float8_e4m3fn b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Float8_e4m3fn operator/(int64_t a, Float8_e4m3fn b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +/// NOTE: we do not define comparisons directly and instead rely on the implicit +/// conversion from c10::Float8_e4m3fn to float. + +C10_CLANG_DIAGNOSTIC_POP() + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::Float8_e4m3fn; +using c10::operator<<; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_specialized = true; + static constexpr bool is_signed = true; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = false; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = false; + static constexpr auto has_denorm = true; + static constexpr auto has_denorm_loss = true; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = false; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 4; + static constexpr int digits10 = 0; + static constexpr int max_digits10 = 3; + static constexpr int radix = 2; + static constexpr int min_exponent = -5; + static constexpr int min_exponent10 = -1; + static constexpr int max_exponent = 8; + static constexpr int max_exponent10 = 2; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = false; + + static constexpr c10::Float8_e4m3fn min() { + return c10::Float8_e4m3fn(0x08, c10::Float8_e4m3fn::from_bits()); + } + static constexpr c10::Float8_e4m3fn lowest() { + return c10::Float8_e4m3fn(0xFE, c10::Float8_e4m3fn::from_bits()); + } + static constexpr c10::Float8_e4m3fn max() { + return c10::Float8_e4m3fn(0x7E, c10::Float8_e4m3fn::from_bits()); + } + static constexpr c10::Float8_e4m3fn epsilon() { + return c10::Float8_e4m3fn(0x20, c10::Float8_e4m3fn::from_bits()); + } + static constexpr c10::Float8_e4m3fn round_error() { + return c10::Float8_e4m3fn(0x30, c10::Float8_e4m3fn::from_bits()); + } + static constexpr c10::Float8_e4m3fn quiet_NaN() { + return c10::Float8_e4m3fn(0x7F, c10::Float8_e4m3fn::from_bits()); + } + static constexpr c10::Float8_e4m3fn denorm_min() { + return c10::Float8_e4m3fn(0x01, c10::Float8_e4m3fn::from_bits()); + } +}; + +} // namespace std diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e4m3fnuz.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e4m3fnuz.h new file mode 100644 index 0000000000000000000000000000000000000000..e361a2f92a2a586a15b5730029cb27b15581fa59 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e4m3fnuz.h @@ -0,0 +1,444 @@ +#pragma once + +/// Defines the Float8_e4m3fnuz type (8-bit floating-point) including +/// conversions to standard C types and basic arithmetic operations. Note that +/// arithmetic operations are implemented by converting to floating point and +/// performing the operation in float32. +/// Binary configuration remains the same as Float8_e4m3fn: +/// s eeee mmm +/// 1 sign bit +/// 4 exponent bits +/// 3 mantissa bits +/// The key differences versus Float8_e4m3fn are: +/// bias = 8 +/// no infinities or negative zero +/// NaN only when sign bit is 1, rest all 0s +/// +/// Implementation based on the paper https://arxiv.org/pdf/2206.02915.pdf and +/// the existing Float8_e4m3fn implementation. + +#include +#include +#include + +#include + +#if defined(__cplusplus) +#include +#elif !defined(__OPENCL_VERSION__) +#include +#include +#endif + +#include +#include + +namespace c10 { + +struct alignas(1) Float8_e4m3fnuz { + uint8_t x; + + struct from_bits_t {}; + C10_HOST_DEVICE static constexpr from_bits_t from_bits() { + return from_bits_t(); + } + + Float8_e4m3fnuz() = default; + + constexpr C10_HOST_DEVICE Float8_e4m3fnuz( + uint8_t bits, + from_bits_t /*unused*/) + : x(bits) {} + inline C10_HOST_DEVICE Float8_e4m3fnuz(float value); + inline C10_HOST_DEVICE operator float() const; + inline C10_HOST_DEVICE bool isnan() const; +}; + +inline std::ostream& operator<<( + std::ostream& out, + const Float8_e4m3fnuz& value) { + out << (float)value; + return out; +} + +namespace detail { + +/* + * Convert a 32-bit floating-point number in IEEE single-precision format to a + * 8-bit floating-point number in fp8 E4M3FNUZ format, in bit representation. + */ +inline C10_HOST_DEVICE uint8_t fp8e4m3fnuz_from_fp32_value(float f) { + /* + * Binary representation of 256.0f, which is the first value not representable + * (i.e. the first value which would overflow in to the sign bit, resulting in + * a NaN) in fp8e4m3fnuz range: + * 1 0000 000 - fp8e4m3fnuz + * 0 10000111 00000000000000000000000 - fp32 + */ + constexpr uint32_t fnuz_max = UINT32_C(0x87) << 23; + + /* + * A mask for converting fp32 numbers lower than fp8e4m3fnuz normal range + * into denorm representation + * magic number: ((127 - 8) + (23 - 3) + 1) + */ + constexpr uint32_t denorm_mask = UINT32_C(0x8C) << 23; + + uint32_t f_bits = fp32_to_bits(f); + + uint32_t result = 0u; + + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = f_bits & UINT32_C(0x80000000); + + /* + * Set sign bit to 0 + */ + f_bits ^= sign; + + if (f_bits >= fnuz_max) { + // NaN -- sign bit set to 1, rest 0s. + return 0x80; + } + + if (f_bits < (UINT32_C(0x78) << 23) /* 2^-7 in float32 */) { + // Input exponent is less than -7, the smallest e4m3fnuz exponent, so the + // number will become subnormal. + f_bits = fp32_to_bits(fp32_from_bits(f_bits) + fp32_from_bits(denorm_mask)); + result = static_cast(f_bits - denorm_mask); + if (result == 0) { + // fnuz types don't have negative zero. + return 0; + } + } else { + // resulting mantissa is odd + uint8_t mant_odd = (f_bits >> 20) & 1; + + // update exponent, rounding bias part 1 + f_bits += ((uint32_t)(8 - 127) << 23) + 0x7FFFF; + + // rounding bias part 2 + f_bits += mant_odd; + + // take the bits! + result = static_cast(f_bits >> 20); + } + + result |= sign >> 24; + return result; +} + +} // namespace detail + +//------ below is copied from c10/util/Float8_e4m3fnuz-inl.h ------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +/// Constructors + +inline C10_HOST_DEVICE Float8_e4m3fnuz::Float8_e4m3fnuz(float value) + : x(detail::fp8e4m3fnuz_from_fp32_value(value)) {} + +/// Implicit conversions + +inline C10_HOST_DEVICE Float8_e4m3fnuz::operator float() const { + return torch::headeronly::detail::fp8_fnuz_to_fp32_value<4, 3>(x); +} + +/// Special values helper + +inline C10_HOST_DEVICE bool Float8_e4m3fnuz::isnan() const { + return x == 0b10000000; +} + +/// Arithmetic + +inline C10_HOST_DEVICE Float8_e4m3fnuz +operator+(const Float8_e4m3fnuz& a, const Float8_e4m3fnuz& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz +operator-(const Float8_e4m3fnuz& a, const Float8_e4m3fnuz& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz +operator*(const Float8_e4m3fnuz& a, const Float8_e4m3fnuz& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz operator/( + const Float8_e4m3fnuz& a, + const Float8_e4m3fnuz& b) __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(const Float8_e4m3fnuz& a) { + return -static_cast(a); +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz& operator+=( + Float8_e4m3fnuz& a, + const Float8_e4m3fnuz& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz& operator-=( + Float8_e4m3fnuz& a, + const Float8_e4m3fnuz& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz& operator*=( + Float8_e4m3fnuz& a, + const Float8_e4m3fnuz& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz& operator/=( + Float8_e4m3fnuz& a, + const Float8_e4m3fnuz& b) { + a = a / b; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(Float8_e4m3fnuz a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(Float8_e4m3fnuz a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(Float8_e4m3fnuz a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(Float8_e4m3fnuz a, float b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, Float8_e4m3fnuz b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, Float8_e4m3fnuz b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, Float8_e4m3fnuz b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, Float8_e4m3fnuz b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const Float8_e4m3fnuz& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const Float8_e4m3fnuz& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const Float8_e4m3fnuz& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const Float8_e4m3fnuz& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(Float8_e4m3fnuz a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(Float8_e4m3fnuz a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(Float8_e4m3fnuz a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(Float8_e4m3fnuz a, double b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, Float8_e4m3fnuz b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, Float8_e4m3fnuz b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, Float8_e4m3fnuz b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, Float8_e4m3fnuz b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE Float8_e4m3fnuz operator+(Float8_e4m3fnuz a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(Float8_e4m3fnuz a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator*(Float8_e4m3fnuz a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(Float8_e4m3fnuz a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz operator+(int a, Float8_e4m3fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(int a, Float8_e4m3fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator*(int a, Float8_e4m3fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(int a, Float8_e4m3fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE Float8_e4m3fnuz operator+(Float8_e4m3fnuz a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(Float8_e4m3fnuz a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator*(Float8_e4m3fnuz a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(Float8_e4m3fnuz a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e4m3fnuz operator+(int64_t a, Float8_e4m3fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(int64_t a, Float8_e4m3fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator*(int64_t a, Float8_e4m3fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(int64_t a, Float8_e4m3fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +/// NOTE: we do not define comparisons directly and instead rely on the implicit +/// conversion from c10::Float8_e4m3fnuz to float. + +C10_CLANG_DIAGNOSTIC_POP() + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::Float8_e4m3fnuz; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator<<; + +namespace detail { +using c10::detail::fp8e4m3fnuz_from_fp32_value; +} // namespace detail + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_specialized = true; + static constexpr bool is_signed = true; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = false; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = false; + static constexpr auto has_denorm = true; + static constexpr auto has_denorm_loss = true; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = false; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 4; + static constexpr int digits10 = 0; + static constexpr int max_digits10 = 3; + static constexpr int radix = 2; + static constexpr int min_exponent = -6; + static constexpr int min_exponent10 = -1; + static constexpr int max_exponent = 8; + static constexpr int max_exponent10 = 2; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = false; + + static constexpr c10::Float8_e4m3fnuz min() { + return c10::Float8_e4m3fnuz(0x08, c10::Float8_e4m3fnuz::from_bits()); + } + static constexpr c10::Float8_e4m3fnuz lowest() { + return c10::Float8_e4m3fnuz(0xFF, c10::Float8_e4m3fnuz::from_bits()); + } + static constexpr c10::Float8_e4m3fnuz max() { + return c10::Float8_e4m3fnuz(0x7F, c10::Float8_e4m3fnuz::from_bits()); + } + static constexpr c10::Float8_e4m3fnuz epsilon() { + return c10::Float8_e4m3fnuz(0x28, c10::Float8_e4m3fnuz::from_bits()); + } + static constexpr c10::Float8_e4m3fnuz round_error() { + return c10::Float8_e4m3fnuz(0x38, c10::Float8_e4m3fnuz::from_bits()); + } + static constexpr c10::Float8_e4m3fnuz infinity() { + // NaN (no infinities) + return c10::Float8_e4m3fnuz(0x80, c10::Float8_e4m3fnuz::from_bits()); + } + static constexpr c10::Float8_e4m3fnuz quiet_NaN() { + return c10::Float8_e4m3fnuz(0x80, c10::Float8_e4m3fnuz::from_bits()); + } + static constexpr c10::Float8_e4m3fnuz denorm_min() { + return c10::Float8_e4m3fnuz(0x01, c10::Float8_e4m3fnuz::from_bits()); + } +}; + +} // namespace std diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e5m2.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e5m2.h new file mode 100644 index 0000000000000000000000000000000000000000..0aa856d0d5546fc53b7bf7148fefef72c563b262 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e5m2.h @@ -0,0 +1,458 @@ +#pragma once + +/// Defines the Float8_e5m2 type (8-bit floating-point) including conversions +/// to standard C types and basic arithmetic operations. Note that arithmetic +/// operations are implemented by converting to floating point and +/// performing the operation in float32. +/// Binary configuration: +/// s eeeee mm +/// 1 sign bit +/// 5 exponent bits +/// 2 mantissa bits +/// bias = 15 +/// +/// Implementation based on the paper https://arxiv.org/pdf/2209.05433.pdf +/// and inspired by Half implementation from pytorch/c10/util/Half.h + +#include +#include + +#include + +namespace c10 { + +struct alignas(1) Float8_e5m2 { + uint8_t x; + + struct from_bits_t {}; + C10_HOST_DEVICE static constexpr from_bits_t from_bits() { + return from_bits_t(); + } + + Float8_e5m2() = default; + + constexpr C10_HOST_DEVICE Float8_e5m2(uint8_t bits, from_bits_t /*unused*/) + : x(bits) {} + inline C10_HOST_DEVICE Float8_e5m2(float value); + inline C10_HOST_DEVICE operator float() const; + inline C10_HOST_DEVICE bool isnan() const; + inline C10_HOST_DEVICE bool isinf() const; +}; + +inline std::ostream& operator<<(std::ostream& out, const Float8_e5m2& value) { + out << (float)value; + return out; +} + +namespace detail { + +/* + * Convert a 8-bit floating-point number in fp8 E5M2 format, in bit + * representation, to a 32-bit floating-point number in IEEE single-precision + * format, in bit representation. + * + * @note The implementation doesn't use any floating-point operations. + */ +inline C10_HOST_DEVICE float fp8e5m2_to_fp32_value(uint8_t input) { + /* + * Extend the fp8 E5M2 number to 32 bits and shift to the + * upper part of the 32-bit word: + * +---+----+---+-----------------------------+ + * | S |EEEEE|MM|0000 0000 0000 0000 0000 0000| + * +---+----+---+-----------------------------+ + * Bits 31 26-30 24-25 0-23 + * + * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0 + * - zero bits. + */ + uint16_t half_representation = input; + half_representation <<= 8; + return fp16_ieee_to_fp32_value(half_representation); +} + +/* + * Convert a 32-bit floating-point number in IEEE single-precision format to a + * 8-bit floating-point number in fp8 E5M2 format, in bit representation. + */ +inline C10_HOST_DEVICE uint8_t fp8e5m2_from_fp32_value(float f) { + /* + * Binary representation of fp32 infinity + * 0 11111111 00000000000000000000000 + */ + constexpr uint32_t fp32_inf = UINT32_C(255) << 23; + + /* + * Binary representation of 65536.0f, which is the first value + * not representable in fp8e5m2 range: + * 0 11111 00 - fp8e5m2 + * 0 10001111 00000000000000000000000 - fp32 + */ + constexpr uint32_t fp8_max = UINT32_C(143) << 23; + + /* + * A mask for converting fp32 numbers lower than fp8e5m2 normal range + * into denorm representation + * magic number: ((127 - 15) + (23 - 2) + 1) + */ + constexpr uint32_t denorm_mask = UINT32_C(134) << 23; + + uint32_t f_bits = fp32_to_bits(f); + uint8_t result = 0u; + + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = f_bits & UINT32_C(0x80000000); + + /* + * Set sign bit to 0 + */ + f_bits ^= sign; + + if (f_bits >= fp8_max) { + // NaN - all exponent and mantissa bits set to 1 + result = f_bits > fp32_inf ? UINT8_C(0x7F) : UINT8_C(0x7C); + } else { + if (f_bits < (UINT32_C(113) << 23)) { + // Input number is smaller than 2^(-14), which is the smallest + // fp8e5m2 normal number + f_bits = + fp32_to_bits(fp32_from_bits(f_bits) + fp32_from_bits(denorm_mask)); + result = static_cast(f_bits - denorm_mask); + } else { + // resulting mantissa is odd + uint32_t mant_odd = (f_bits >> 21) & 1; + + // update exponent, rounding bias part 1 + f_bits += ((uint32_t)(15 - 127) << 23) + 0xFFFFF; + + // rounding bias part 2 + f_bits += mant_odd; + + // take the bits! + result = static_cast(f_bits >> 21); + } + } + + result |= static_cast(sign >> 24); + return result; +} + +} // namespace detail + +// -------- below is copied from c10/util/Float8_e5m2-inl.h --------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +#define EXP_WIDTH_FP8 5 +#define MAN_WIDTH_FP8 2 +#define EXP_BIAS_FP8 15 + +/// Constructors + +inline C10_HOST_DEVICE Float8_e5m2::Float8_e5m2(float value) + : x(detail::fp8e5m2_from_fp32_value(value)) {} + +/// Implicit conversions + +inline C10_HOST_DEVICE Float8_e5m2::operator float() const { + return detail::fp8e5m2_to_fp32_value(x); +} + +/// Special values helpers + +inline C10_HOST_DEVICE bool Float8_e5m2::isnan() const { + return (x & 0b01111111) > 0b01111100; +} + +inline C10_HOST_DEVICE bool Float8_e5m2::isinf() const { + return (x & 0b01111111) == 0b01111100; +} + +/// Arithmetic + +inline C10_HOST_DEVICE Float8_e5m2 +operator+(const Float8_e5m2& a, const Float8_e5m2& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2 +operator-(const Float8_e5m2& a, const Float8_e5m2& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2 +operator*(const Float8_e5m2& a, const Float8_e5m2& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2 operator/( + const Float8_e5m2& a, + const Float8_e5m2& b) __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2 operator-(const Float8_e5m2& a) { + return -static_cast(a); +} + +inline C10_HOST_DEVICE Float8_e5m2& operator+=( + Float8_e5m2& a, + const Float8_e5m2& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE Float8_e5m2& operator-=( + Float8_e5m2& a, + const Float8_e5m2& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE Float8_e5m2& operator*=( + Float8_e5m2& a, + const Float8_e5m2& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE Float8_e5m2& operator/=( + Float8_e5m2& a, + const Float8_e5m2& b) { + a = a / b; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(Float8_e5m2 a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(Float8_e5m2 a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(Float8_e5m2 a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(Float8_e5m2 a, float b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, Float8_e5m2 b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, Float8_e5m2 b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, Float8_e5m2 b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, Float8_e5m2 b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const Float8_e5m2& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const Float8_e5m2& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const Float8_e5m2& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const Float8_e5m2& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(Float8_e5m2 a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(Float8_e5m2 a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(Float8_e5m2 a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(Float8_e5m2 a, double b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, Float8_e5m2 b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, Float8_e5m2 b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, Float8_e5m2 b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, Float8_e5m2 b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE Float8_e5m2 operator+(Float8_e5m2 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2 operator-(Float8_e5m2 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2 operator*(Float8_e5m2 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2 operator/(Float8_e5m2 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2 operator+(int a, Float8_e5m2 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Float8_e5m2 operator-(int a, Float8_e5m2 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Float8_e5m2 operator*(int a, Float8_e5m2 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Float8_e5m2 operator/(int a, Float8_e5m2 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE Float8_e5m2 operator+(Float8_e5m2 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2 operator-(Float8_e5m2 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2 operator*(Float8_e5m2 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2 operator/(Float8_e5m2 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2 operator+(int64_t a, Float8_e5m2 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Float8_e5m2 operator-(int64_t a, Float8_e5m2 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Float8_e5m2 operator*(int64_t a, Float8_e5m2 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Float8_e5m2 operator/(int64_t a, Float8_e5m2 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +/// NOTE: we do not define comparisons directly and instead rely on the implicit +/// conversion from c10::Float8_e5m2 to float. +C10_CLANG_DIAGNOSTIC_POP() +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::Float8_e5m2; +using c10::operator<<; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; + +namespace detail { +using c10::detail::fp8e5m2_from_fp32_value; +using c10::detail::fp8e5m2_to_fp32_value; +} // namespace detail +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_signed = true; + static constexpr bool is_integer = false; + static constexpr bool is_specialized = true; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = true; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = false; + static constexpr auto has_denorm = true; + static constexpr auto has_denorm_loss = true; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = false; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 3; + static constexpr int digits10 = 0; + static constexpr int max_digits10 = 2; + static constexpr int radix = 2; + static constexpr int min_exponent = -13; + static constexpr int min_exponent10 = -4; + static constexpr int max_exponent = 16; + static constexpr int max_exponent10 = 4; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = + numeric_limits::tinyness_before; + + static constexpr c10::Float8_e5m2 min() { + return c10::Float8_e5m2(0x4, c10::Float8_e5m2::from_bits()); + } + static constexpr c10::Float8_e5m2 max() { + return c10::Float8_e5m2(0x7B, c10::Float8_e5m2::from_bits()); + } + static constexpr c10::Float8_e5m2 lowest() { + return c10::Float8_e5m2(0xFB, c10::Float8_e5m2::from_bits()); + } + static constexpr c10::Float8_e5m2 epsilon() { + return c10::Float8_e5m2(0x34, c10::Float8_e5m2::from_bits()); + } + static constexpr c10::Float8_e5m2 round_error() { + return c10::Float8_e5m2(0x38, c10::Float8_e5m2::from_bits()); + } + static constexpr c10::Float8_e5m2 infinity() { + return c10::Float8_e5m2(0x7C, c10::Float8_e5m2::from_bits()); + } + static constexpr c10::Float8_e5m2 quiet_NaN() { + return c10::Float8_e5m2(0x7F, c10::Float8_e5m2::from_bits()); + } + static constexpr c10::Float8_e5m2 denorm_min() { + return c10::Float8_e5m2(0x01, c10::Float8_e5m2::from_bits()); + } +}; + +} // namespace std diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e5m2fnuz.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e5m2fnuz.h new file mode 100644 index 0000000000000000000000000000000000000000..6b0f79b75adea4a994a3c44e666b73767b68c66d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e5m2fnuz.h @@ -0,0 +1,448 @@ +#pragma once + +/// Defines the Float8_e5m2fnuz type (8-bit floating-point) including +/// conversions to standard C types and basic arithmetic operations. Note that +/// arithmetic operations are implemented by converting to floating point and +/// performing the operation in float32. +/// Binary configuration remains the same as e5m2: +/// s eeeee mm +/// 1 sign bit +/// 5 exponent bits +/// 2 mantissa bits +/// The key differences that e5m2fnuz brings are: +/// bias = 16 +/// no infinities or negative zero +/// NaN only when sign bit is 1, rest all 0s +/// +/// Implementation based on the paper https://arxiv.org/pdf/2206.02915.pdf and +/// the existing Float8_e4m3fn implementation. + +#include +#include +#include +#include + +#if defined(__cplusplus) +#include +#elif !defined(__OPENCL_VERSION__) +#include +#include +#endif + +#include +#include + +namespace c10 { + +struct alignas(1) Float8_e5m2fnuz { + uint8_t x; + + struct from_bits_t {}; + C10_HOST_DEVICE static constexpr from_bits_t from_bits() { + return from_bits_t(); + } + + Float8_e5m2fnuz() = default; + + constexpr C10_HOST_DEVICE Float8_e5m2fnuz( + uint8_t bits, + from_bits_t /*unused*/) + : x(bits) {} + inline C10_HOST_DEVICE Float8_e5m2fnuz(float value); + inline C10_HOST_DEVICE operator float() const; + inline C10_HOST_DEVICE bool isnan() const; + inline C10_HOST_DEVICE bool isinf() const; +}; + +inline std::ostream& operator<<( + std::ostream& out, + const Float8_e5m2fnuz& value) { + out << (float)value; + return out; +} + +namespace detail { + +/* + * Convert a 32-bit floating-point number in IEEE single-precision format to a + * 8-bit floating-point number in fp8 E5M2 format, in bit representation. + */ +inline C10_HOST_DEVICE uint8_t fp8e5m2fnuz_from_fp32_value(float f) { + /* + * Binary representation of 65536.0f, which is the first value not + * representable (i.e. the first value which would overflow in to the sign + * bit, resulting in a NaN) in fp8e4m3fnuz range: + * 1 00000 00 - fp8e5m2fnuz + * 0 10001111 00000000000000000000000 - fp32 + */ + constexpr uint32_t fnuz_max = UINT32_C(0x8F) << 23; + + /* + * A mask for converting fp32 numbers lower than fp8e5m2fnuz normal range + * into denormalized representation. + * magic number: ((127 - 16) + (23 - 2) + 1) + */ + constexpr uint32_t denorm_mask = UINT32_C(0x85) << 23; + + uint32_t f_bits = fp32_to_bits(f); + uint32_t result = 0u; + + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = f_bits & UINT32_C(0x80000000); + + /* + * Set sign bit to 0 + */ + f_bits ^= sign; + + if (f_bits >= fnuz_max) { + // NaN -- sign bit set to 1, rest 0s + return 0x80; + } + + if (f_bits < (UINT32_C(0x70) << 23) /* 2^-15 in float32 */) { + // Input exponent is less than -15, the smallest e5m2fnuz exponent, so the + // number will become subnormal. + f_bits = fp32_to_bits(fp32_from_bits(f_bits) + fp32_from_bits(denorm_mask)); + result = static_cast(f_bits - denorm_mask); + if (result == 0) { + // fnuz types don't have negative zero. + return 0; + } + } else { + // resulting mantissa is odd + uint8_t mant_odd = (f_bits >> 21) & 1; + + // update exponent, rounding bias part 1 + f_bits += ((uint32_t)(16 - 127) << 23) + 0xFFFFF; + + // rounding bias part 2 + f_bits += mant_odd; + + // take the bits! + result = static_cast(f_bits >> 21); + } + + result |= sign >> 24; + return result; +} + +} // namespace detail + +//------ below is copied from c10/util/Float8_e5m2fnuz-inl.h ------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +/// Constructors + +inline C10_HOST_DEVICE Float8_e5m2fnuz::Float8_e5m2fnuz(float value) + : x(detail::fp8e5m2fnuz_from_fp32_value(value)) {} + +/// Implicit conversions + +inline C10_HOST_DEVICE Float8_e5m2fnuz::operator float() const { + return torch::headeronly::detail::fp8_fnuz_to_fp32_value<5, 2>(x); +} + +/// Special values helpers + +inline C10_HOST_DEVICE bool Float8_e5m2fnuz::isnan() const { + return x == 0b10000000; +} + +inline C10_HOST_DEVICE bool Float8_e5m2fnuz::isinf() const { + return false; +} + +/// Arithmetic + +inline C10_HOST_DEVICE Float8_e5m2fnuz +operator+(const Float8_e5m2fnuz& a, const Float8_e5m2fnuz& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz +operator-(const Float8_e5m2fnuz& a, const Float8_e5m2fnuz& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz +operator*(const Float8_e5m2fnuz& a, const Float8_e5m2fnuz& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz operator/( + const Float8_e5m2fnuz& a, + const Float8_e5m2fnuz& b) __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(const Float8_e5m2fnuz& a) { + return -static_cast(a); +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz& operator+=( + Float8_e5m2fnuz& a, + const Float8_e5m2fnuz& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz& operator-=( + Float8_e5m2fnuz& a, + const Float8_e5m2fnuz& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz& operator*=( + Float8_e5m2fnuz& a, + const Float8_e5m2fnuz& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz& operator/=( + Float8_e5m2fnuz& a, + const Float8_e5m2fnuz& b) { + a = a / b; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(Float8_e5m2fnuz a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(Float8_e5m2fnuz a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(Float8_e5m2fnuz a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(Float8_e5m2fnuz a, float b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, Float8_e5m2fnuz b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, Float8_e5m2fnuz b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, Float8_e5m2fnuz b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, Float8_e5m2fnuz b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const Float8_e5m2fnuz& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const Float8_e5m2fnuz& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const Float8_e5m2fnuz& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const Float8_e5m2fnuz& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(Float8_e5m2fnuz a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(Float8_e5m2fnuz a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(Float8_e5m2fnuz a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(Float8_e5m2fnuz a, double b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, Float8_e5m2fnuz b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, Float8_e5m2fnuz b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, Float8_e5m2fnuz b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, Float8_e5m2fnuz b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE Float8_e5m2fnuz operator+(Float8_e5m2fnuz a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(Float8_e5m2fnuz a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator*(Float8_e5m2fnuz a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(Float8_e5m2fnuz a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz operator+(int a, Float8_e5m2fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(int a, Float8_e5m2fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator*(int a, Float8_e5m2fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(int a, Float8_e5m2fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE Float8_e5m2fnuz operator+(Float8_e5m2fnuz a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(Float8_e5m2fnuz a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator*(Float8_e5m2fnuz a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(Float8_e5m2fnuz a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Float8_e5m2fnuz operator+(int64_t a, Float8_e5m2fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(int64_t a, Float8_e5m2fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator*(int64_t a, Float8_e5m2fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(int64_t a, Float8_e5m2fnuz b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +/// NOTE: we do not define comparisons directly and instead rely on the implicit +/// conversion from c10::Float8_e5m2fnuz to float. + +C10_CLANG_DIAGNOSTIC_POP() + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::Float8_e5m2fnuz; +using c10::operator<<; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; + +namespace detail { +using c10::detail::fp8e5m2fnuz_from_fp32_value; +} +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_signed = true; + static constexpr bool is_integer = false; + static constexpr bool is_specialized = true; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = false; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = false; + static constexpr auto has_denorm = true; + static constexpr auto has_denorm_loss = true; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = false; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 3; + static constexpr int digits10 = 0; + static constexpr int max_digits10 = 2; + static constexpr int radix = 2; + static constexpr int min_exponent = -14; + static constexpr int min_exponent10 = -4; + static constexpr int max_exponent = 16; + static constexpr int max_exponent10 = 4; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = + numeric_limits::tinyness_before; + + static constexpr c10::Float8_e5m2fnuz min() { + return c10::Float8_e5m2fnuz(0x04, c10::Float8_e5m2fnuz::from_bits()); + } + static constexpr c10::Float8_e5m2fnuz max() { + return c10::Float8_e5m2fnuz(0x7F, c10::Float8_e5m2fnuz::from_bits()); + } + static constexpr c10::Float8_e5m2fnuz lowest() { + return c10::Float8_e5m2fnuz(0xFF, c10::Float8_e5m2fnuz::from_bits()); + } + static constexpr c10::Float8_e5m2fnuz epsilon() { + return c10::Float8_e5m2fnuz(0x34, c10::Float8_e5m2fnuz::from_bits()); + } + static constexpr c10::Float8_e5m2fnuz round_error() { + return c10::Float8_e5m2fnuz(0x38, c10::Float8_e5m2fnuz::from_bits()); + } + static constexpr c10::Float8_e5m2fnuz infinity() { + return c10::Float8_e5m2fnuz(0x80, c10::Float8_e5m2fnuz::from_bits()); + } + // TODO(future): we are mapping neg_zero to both inf and NaN, this is + // surprising and we should figure out what to do about it. + static constexpr c10::Float8_e5m2fnuz quiet_NaN() { + return c10::Float8_e5m2fnuz(0x80, c10::Float8_e5m2fnuz::from_bits()); + } + static constexpr c10::Float8_e5m2fnuz denorm_min() { + return c10::Float8_e5m2fnuz(0x01, c10::Float8_e5m2fnuz::from_bits()); + } +}; + +} // namespace std diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e8m0fnu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e8m0fnu.h new file mode 100644 index 0000000000000000000000000000000000000000..80d89439c90b939259e1ec20b0b0c0256d3ced84 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_e8m0fnu.h @@ -0,0 +1,226 @@ +#pragma once + +/// Defines the Float8_e8m0fnu type (8-bit floating-point) including +/// conversions to standard C types +/// Binary configuration : +/// eeeeeeee +/// no sign bits +/// 8 exponent bits +/// no mantissa bits +/// +/// This is the E8M0 dtype from the OCP MX format spec +/// (https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf, +/// Section 5.4.1) + +#include +#include + +// TODO(#146647): do we need to special case OPENCL? +#if defined(__cplusplus) +#include +#elif !defined(__OPENCL_VERSION__) +#include +#include +#endif + +#include +#include +#include + +namespace c10 { + +struct alignas(1) Float8_e8m0fnu { + uint8_t x; + + struct from_bits_t {}; + C10_HOST_DEVICE static constexpr from_bits_t from_bits() { + return from_bits_t(); + } + + Float8_e8m0fnu() = default; + + constexpr C10_HOST_DEVICE Float8_e8m0fnu(uint8_t bits, from_bits_t /*unused*/) + : x(bits) {} + inline C10_HOST_DEVICE Float8_e8m0fnu(float value); + inline C10_HOST_DEVICE operator float() const; + inline C10_HOST_DEVICE bool isnan() const; +}; + +inline std::ostream& operator<<( + std::ostream& out, + const Float8_e8m0fnu& value) { + out << (float)value; + return out; +} + +namespace detail { +/* + * Convert a 32-bit floating-point number in IEEE single-precision format to a + * 8-bit floating-point number in fp8 e8m0fnu format, in bit representation. + */ +inline C10_HOST_DEVICE uint8_t fp8e8m0fnu_from_fp32_value(float f) { + // TODO(#146647): maybe rewrite without control flow + + uint32_t f_bits = c10::detail::fp32_to_bits(f); + + // extract the exponent + uint32_t exponent = (f_bits >> 23) & 0b11111111; + + // special case float32 NaN and +-inf to map to e8m0 nan + if (exponent == 0b11111111) { + return exponent; + } + + // next, we use guard, round, sticky bits and the LSB to implement round to + // nearest, with ties to even + + // guard bit - bit 23, or 22 zero-indexed + uint8_t g = (f_bits & 0x400000) > 0; + // round bit - bit 22, or 21 zero-indexed + uint8_t r = (f_bits & 0x200000) > 0; + // sticky bit - bits 21 to 1, or 20 to 0 zero-indexed + uint8_t s = (f_bits & 0x1FFFFF) > 0; + // in casting to e8m0, LSB is the implied mantissa bit. It equals to 0 if the + // original float32 is denormal, and to 1 if the original float32 is normal. + uint8_t lsb = exponent > 0; + + // implement the RNE logic + bool round_up = false; + + // if g == 0, round down (no-op) + if (g == 1) { + if ((r == 1) || (s == 1)) { + // round up + round_up = true; + } else { + if (lsb == 1) { + // round up + round_up = true; + } + // if lsb == 0, round down (no-op) + } + } + + if (round_up) { + // adjust exponent + // note that if exponent was 255 we would have already returned earlier, so + // we know we can add one safely without running out of bounds + exponent++; + } + + return exponent; +} + +} // namespace detail + +//------- the below is from c10/util/Float8_e8m0fnu-inl.h ------// +// TODO(#146647): Can we remove the below warning? +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +/// Constructors +inline C10_HOST_DEVICE Float8_e8m0fnu::Float8_e8m0fnu(float value) + : x(detail::fp8e8m0fnu_from_fp32_value(value)) {} + +/// Implicit conversions + +inline C10_HOST_DEVICE Float8_e8m0fnu::operator float() const { + // TODO(#146647): maybe rewrite without control flow + + // if exponent is zero, need to special case to return 2^-127 instead of zero + if (x == 0) { + return c10::detail::fp32_from_bits(0x00400000); + } + + // if exponent is NaN, need to special case to return properly encoded NaN + if (isnan()) { + return c10::detail::fp32_from_bits(0x7f800001); + } + + // leave sign at 0, set the exponent bits, leave stored mantissa at 0 + uint32_t res = x << 23; + + return c10::detail::fp32_from_bits(res); +} + +/// Special values helper + +inline C10_HOST_DEVICE bool Float8_e8m0fnu::isnan() const { + return x == 0b11111111; +} + +/// NOTE: we do not define comparisons directly and instead rely on the implicit +/// conversion from c10::Float8_e8m0fnu to float. +C10_CLANG_DIAGNOSTIC_POP() + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::Float8_e8m0fnu; +using c10::operator<<; + +namespace detail { +using c10::detail::fp8e8m0fnu_from_fp32_value; +} // namespace detail +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_specialized = true; + static constexpr bool is_signed = false; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = false; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = false; + static constexpr auto has_denorm = false; + static constexpr auto has_denorm_loss = false; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = false; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 1; + static constexpr int digits10 = 0; + static constexpr int max_digits10 = 1; // just a 2! + static constexpr int radix = 2; + static constexpr int min_exponent = -126; + static constexpr int min_exponent10 = -38; + static constexpr int max_exponent = 128; + static constexpr int max_exponent10 = 38; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = false; + + static constexpr c10::Float8_e8m0fnu min() { + // 2^-127 + return c10::Float8_e8m0fnu(0b00000000, c10::Float8_e8m0fnu::from_bits()); + } + static constexpr c10::Float8_e8m0fnu lowest() { + // 2^-127 + return c10::Float8_e8m0fnu(0b00000000, c10::Float8_e8m0fnu::from_bits()); + } + static constexpr c10::Float8_e8m0fnu max() { + // 254 biased, which is 127 unbiased, so 2^127 + return c10::Float8_e8m0fnu(0b11111110, c10::Float8_e8m0fnu::from_bits()); + } + static constexpr c10::Float8_e8m0fnu epsilon() { + // according to https://en.cppreference.com/w/cpp/types/numeric_limits, this + // is "the difference between 1.0 and the next representable value of the + // given floating-point type". The next representable value is 2.0, so the + // difference is 1.0 which is 2^0. 0 unbiased is 127 biased. + return c10::Float8_e8m0fnu(0b01111111, c10::Float8_e8m0fnu::from_bits()); + } + static constexpr c10::Float8_e8m0fnu round_error() { + // 0.5 in float, which is 2^-1, and -1 + 127 = 126 + return c10::Float8_e8m0fnu(0b01111110, c10::Float8_e8m0fnu::from_bits()); + } + static constexpr c10::Float8_e8m0fnu quiet_NaN() { + return c10::Float8_e8m0fnu(0b11111111, c10::Float8_e8m0fnu::from_bits()); + } +}; + +} // namespace std diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_fnuz_cvt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_fnuz_cvt.h new file mode 100644 index 0000000000000000000000000000000000000000..59fab8cc28dbfb2c9c8cb4951deaf2bb06dd06ec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Float8_fnuz_cvt.h @@ -0,0 +1,69 @@ +#pragma once + +#include +#include + +#include + +#if defined(SYCL_LANGUAGE_VERSION) +#include +#endif + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly, detail) + +/* + * Convert a 8-bit floating-point number in either f8 E4M3FNUZ or bf8 E5M2FNUZ + * format, in bit representation, to a 32-bit floating-point number. + */ +template +inline C10_HOST_DEVICE float fp8_fnuz_to_fp32_value(uint8_t x) { + static_assert((we == 4 && wm == 3) || (we == 5 && wm == 2)); + constexpr uint32_t weo = 8; + constexpr uint32_t wmo = 23; + + if (x == 0) { + return 0; + } + + if (x == 0x80) { + constexpr uint32_t ifNaN = 0x7F800001; + return fp32_from_bits(ifNaN); + } + + uint32_t mantissa = x & ((1 << wm) - 1); + uint32_t exponent = (x & 0x7F) >> wm; + + // subnormal input + if (exponent == 0) { + // guaranteed mantissa!=0 since cases 0x0 and 0x80 are handled above +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + uint32_t renorm_shift = __clz(mantissa); +#elif defined(__SYCL_DEVICE_ONLY__) + uint32_t renorm_shift = sycl::clz(mantissa); +#elif defined(_MSC_VER) + unsigned long nonsign_bsr; + _BitScanReverse(&nonsign_bsr, (unsigned long)mantissa); + uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31; +#else + uint32_t renorm_shift = __builtin_clz(mantissa); +#endif + uint32_t sh = 1 + renorm_shift - (32 - wm); + mantissa <<= sh; + exponent += 1 - sh; + mantissa &= ((1 << wm) - 1); + } + + const uint32_t exp_low_cutoff = (1 << (weo - 1)) - (1 << (we - 1)); + exponent += exp_low_cutoff - 1; + mantissa <<= wmo - wm; + + uint32_t sign = x >> 7; + uint32_t retval = (sign << 31) | (exponent << 23) | mantissa; + return fp32_from_bits(retval); +} + +HIDDEN_NAMESPACE_END(torch, headeronly, detail) + +namespace c10::detail { +using torch::headeronly::detail::fp8_fnuz_to_fp32_value; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Half.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Half.h new file mode 100644 index 0000000000000000000000000000000000000000..a9c0b166ba2ea825ee8c2933e519de40112dae6f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Half.h @@ -0,0 +1,788 @@ +#pragma once + +/// Defines the Half type (half-precision floating-point) including conversions +/// to standard C types and basic arithmetic operations. Note that arithmetic +/// operations are implemented by converting to floating point and +/// performing the operation in float32, instead of using CUDA half intrinsics. +/// Most uses of this type within ATen are memory bound, including the +/// element-wise kernels, and the half intrinsics aren't efficient on all GPUs. +/// If you are writing a compute bound kernel, you can use the CUDA half +/// intrinsics directly on the Half type from device code. + +#include +#include +#include + +#if defined(__cplusplus) +#include +#elif !defined(__OPENCL_VERSION__) +#include +#endif + +#ifdef _MSC_VER +#include +#endif + +#include +#include +#include + +#ifdef __CUDACC__ +#include +#endif + +#ifdef __HIPCC__ +#include +#endif + +#if defined(CL_SYCL_LANGUAGE_VERSION) +#include // for SYCL 1.2.1 +#elif defined(SYCL_LANGUAGE_VERSION) +#include // for SYCL 2020 +#endif + +#if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) +#include +#endif + +#if defined(__aarch64__) && !defined(__CUDACC__) +#include +#endif + +#if defined(__GNUC__) || defined(__clang__) +#if defined(__x86_64__) || defined(_M_X64) || defined(__i386) || \ + defined(_M_IX86) +#if defined(__F16C__) && \ + !(defined(__CUDA_ARCH__) || defined(__CUDACC__) || \ + defined(__HIP_DEVICE_COMPILE__)) +#define C10_X86_F16 1 +#include // import conversion ops from f16cintrin.h +#endif // defined(__F16C__) && !(defined(__CUDA_ARCH__) || defined(__CUDACC__) + // || defined(__HIP_DEVICE_COMPILE__)) +#endif // __x86_64__ || _M_X64 || __i386 || _M_IX86 +#endif // __GNUC__ || __clang__ + +namespace c10 { + +struct alignas(2) Half { + unsigned short x; + + struct from_bits_t {}; + C10_HOST_DEVICE static constexpr from_bits_t from_bits() { + return from_bits_t(); + } + + // HIP wants __host__ __device__ tag, CUDA does not +#if defined(USE_ROCM) + C10_HOST_DEVICE Half() = default; +#else + Half() = default; +#endif + + constexpr C10_HOST_DEVICE Half(unsigned short bits, from_bits_t /*unused*/) + : x(bits) {} +#if defined(__aarch64__) && !defined(__CUDACC__) + inline Half(float16_t value); + inline operator float16_t() const; +#else + inline C10_HOST_DEVICE Half(float value); + inline C10_HOST_DEVICE operator float() const; +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) + inline C10_HOST_DEVICE Half(const __half& value); + inline C10_HOST_DEVICE operator __half() const; +#endif +#ifdef SYCL_LANGUAGE_VERSION + inline C10_HOST_DEVICE Half(const sycl::half& value); + inline C10_HOST_DEVICE operator sycl::half() const; +#endif +}; + +inline std::ostream& operator<<(std::ostream& out, const Half& value) { + out << (float)value; + return out; +} + +namespace detail { +/* + * Convert a 16-bit floating-point number in IEEE half-precision format, in bit + * representation, to a 32-bit floating-point number in IEEE single-precision + * format. + * + * @note The implementation relies on IEEE-like (no assumption about rounding + * mode and no operations on denormals) floating-point operations and bitcasts + * between integer and floating-point variables. + */ +C10_HOST_DEVICE inline float fp16_ieee_to_fp32_value(uint16_t h) { +#ifdef C10_X86_F16 + return _cvtsh_ss(h); +#else + /* + * Extend the half-precision floating-point number to 32 bits and shift to the + * upper part of the 32-bit word: + * +---+-----+------------+-------------------+ + * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 31 26-30 16-25 0-15 + * + * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0 + * - zero bits. + */ + const uint32_t w = (uint32_t)h << 16; + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = w & UINT32_C(0x80000000); + /* + * Extract mantissa and biased exponent of the input number into the high bits + * of the 32-bit word: + * + * +-----+------------+---------------------+ + * |EEEEE|MM MMMM MMMM|0 0000 0000 0000 0000| + * +-----+------------+---------------------+ + * Bits 27-31 17-26 0-16 + */ + const uint32_t two_w = w + w; + + /* + * Shift mantissa and exponent into bits 23-28 and bits 13-22 so they become + * mantissa and exponent of a single-precision floating-point number: + * + * S|Exponent | Mantissa + * +-+---+-----+------------+----------------+ + * |0|000|EEEEE|MM MMMM MMMM|0 0000 0000 0000| + * +-+---+-----+------------+----------------+ + * Bits | 23-31 | 0-22 + * + * Next, there are some adjustments to the exponent: + * - The exponent needs to be corrected by the difference in exponent bias + * between single-precision and half-precision formats (0x7F - 0xF = 0x70) + * - Inf and NaN values in the inputs should become Inf and NaN values after + * conversion to the single-precision number. Therefore, if the biased + * exponent of the half-precision input was 0x1F (max possible value), the + * biased exponent of the single-precision output must be 0xFF (max possible + * value). We do this correction in two steps: + * - First, we adjust the exponent by (0xFF - 0x1F) = 0xE0 (see exp_offset + * below) rather than by 0x70 suggested by the difference in the exponent bias + * (see above). + * - Then we multiply the single-precision result of exponent adjustment by + * 2**(-112) to reverse the effect of exponent adjustment by 0xE0 less the + * necessary exponent adjustment by 0x70 due to difference in exponent bias. + * The floating-point multiplication hardware would ensure than Inf and + * NaN would retain their value on at least partially IEEE754-compliant + * implementations. + * + * Note that the above operations do not handle denormal inputs (where biased + * exponent == 0). However, they also do not operate on denormal inputs, and + * do not produce denormal results. + */ + constexpr uint32_t exp_offset = UINT32_C(0xE0) << 23; + // const float exp_scale = 0x1.0p-112f; + constexpr uint32_t scale_bits = (uint32_t)15 << 23; + float exp_scale_val = 0; +#if defined(_MSC_VER) && defined(__clang__) + __builtin_memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val)); +#else + std::memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val)); +#endif + + const float exp_scale = exp_scale_val; + const float normalized_value = + fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale; + + /* + * Convert denormalized half-precision inputs into single-precision results + * (always normalized). Zero inputs are also handled here. + * + * In a denormalized number the biased exponent is zero, and mantissa has + * on-zero bits. First, we shift mantissa into bits 0-9 of the 32-bit word. + * + * zeros | mantissa + * +---------------------------+------------+ + * |0000 0000 0000 0000 0000 00|MM MMMM MMMM| + * +---------------------------+------------+ + * Bits 10-31 0-9 + * + * Now, remember that denormalized half-precision numbers are represented as: + * FP16 = mantissa * 2**(-24). + * The trick is to construct a normalized single-precision number with the + * same mantissa and thehalf-precision input and with an exponent which would + * scale the corresponding mantissa bits to 2**(-24). A normalized + * single-precision floating-point number is represented as: FP32 = (1 + + * mantissa * 2**(-23)) * 2**(exponent - 127) Therefore, when the biased + * exponent is 126, a unit change in the mantissa of the input denormalized + * half-precision number causes a change of the constructed single-precision + * number by 2**(-24), i.e. the same amount. + * + * The last step is to adjust the bias of the constructed single-precision + * number. When the input half-precision number is zero, the constructed + * single-precision number has the value of FP32 = 1 * 2**(126 - 127) = + * 2**(-1) = 0.5 Therefore, we need to subtract 0.5 from the constructed + * single-precision number to get the numerical equivalent of the input + * half-precision number. + */ + constexpr uint32_t magic_mask = UINT32_C(126) << 23; + constexpr float magic_bias = 0.5f; + const float denormalized_value = + fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias; + + /* + * - Choose either results of conversion of input as a normalized number, or + * as a denormalized number, depending on the input exponent. The variable + * two_w contains input exponent in bits 27-31, therefore if its smaller than + * 2**27, the input is either a denormal number, or zero. + * - Combine the result of conversion of exponent and mantissa with the sign + * of the input number. + */ + constexpr uint32_t denormalized_cutoff = UINT32_C(1) << 27; + const uint32_t result = sign | + (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) + : fp32_to_bits(normalized_value)); + return fp32_from_bits(result); +#endif // C10_X86_F16 +} + +/* + * Convert a 32-bit floating-point number in IEEE single-precision format to a + * 16-bit floating-point number in IEEE half-precision format, in bit + * representation. + * + * @note The implementation relies on IEEE-like (no assumption about rounding + * mode and no operations on denormals) floating-point operations and bitcasts + * between integer and floating-point variables. + */ +inline uint16_t fp16_ieee_from_fp32_value(float f) { +#ifdef C10_X86_F16 + return _cvtss_sh(f, _MM_FROUND_TO_NEAREST_INT); +#else + // const float scale_to_inf = 0x1.0p+112f; + // const float scale_to_zero = 0x1.0p-110f; + constexpr uint32_t scale_to_inf_bits = (uint32_t)239 << 23; + constexpr uint32_t scale_to_zero_bits = (uint32_t)17 << 23; + float scale_to_inf_val = 0, scale_to_zero_val = 0; + std::memcpy(&scale_to_inf_val, &scale_to_inf_bits, sizeof(scale_to_inf_val)); + std::memcpy( + &scale_to_zero_val, &scale_to_zero_bits, sizeof(scale_to_zero_val)); + const float scale_to_inf = scale_to_inf_val; + const float scale_to_zero = scale_to_zero_val; + +#if defined(_MSC_VER) && _MSC_VER == 1916 + float base = ((signbit(f) != 0 ? -f : f) * scale_to_inf) * scale_to_zero; +#else + float base = (fabsf(f) * scale_to_inf) * scale_to_zero; +#endif + + const uint32_t w = fp32_to_bits(f); + const uint32_t shl1_w = w + w; + const uint32_t sign = w & UINT32_C(0x80000000); + uint32_t bias = shl1_w & UINT32_C(0xFF000000); + if (bias < UINT32_C(0x71000000)) { + bias = UINT32_C(0x71000000); + } + + base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base; + const uint32_t bits = fp32_to_bits(base); + const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00); + const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF); + const uint32_t nonsign = exp_bits + mantissa_bits; + return static_cast( + (sign >> 16) | + (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign)); +#endif // C10_X86_F16 +} + +/* + * Convert a 16-bit floating-point number in IEEE half-precision format, in bit + * representation, to a 32-bit floating-point number in IEEE single-precision + * format, in bit representation. + * + * @note The implementation doesn't use any floating-point operations. + */ +inline uint32_t fp16_ieee_to_fp32_bits(uint16_t h) { + /* + * Extend the half-precision floating-point number to 32 bits and shift to the + * upper part of the 32-bit word: + * +---+-----+------------+-------------------+ + * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 31 26-30 16-25 0-15 + * + * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0 + * - zero bits. + */ + const uint32_t w = (uint32_t)h << 16; + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = w & UINT32_C(0x80000000); + /* + * Extract mantissa and biased exponent of the input number into the bits 0-30 + * of the 32-bit word: + * + * +---+-----+------------+-------------------+ + * | 0 |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 30 27-31 17-26 0-16 + */ + const uint32_t nonsign = w & UINT32_C(0x7FFFFFFF); + /* + * Renorm shift is the number of bits to shift mantissa left to make the + * half-precision number normalized. If the initial number is normalized, some + * of its high 6 bits (sign == 0 and 5-bit exponent) equals one. In this case + * renorm_shift == 0. If the number is denormalize, renorm_shift > 0. Note + * that if we shift denormalized nonsign by renorm_shift, the unit bit of + * mantissa will shift into exponent, turning the biased exponent into 1, and + * making mantissa normalized (i.e. without leading 1). + */ +#ifdef _MSC_VER + unsigned long nonsign_bsr; + _BitScanReverse(&nonsign_bsr, (unsigned long)nonsign); + uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31; +#else + uint32_t renorm_shift = __builtin_clz(nonsign); +#endif + renorm_shift = renorm_shift > 5 ? renorm_shift - 5 : 0; + /* + * Iff half-precision number has exponent of 15, the addition overflows + * it into bit 31, and the subsequent shift turns the high 9 bits + * into 1. Thus inf_nan_mask == 0x7F800000 if the half-precision number + * had exponent of 15 (i.e. was NaN or infinity) 0x00000000 otherwise + */ + const int32_t inf_nan_mask = + ((int32_t)(nonsign + 0x04000000) >> 8) & INT32_C(0x7F800000); + /* + * Iff nonsign is 0, it overflows into 0xFFFFFFFF, turning bit 31 + * into 1. Otherwise, bit 31 remains 0. The signed shift right by 31 + * broadcasts bit 31 into all bits of the zero_mask. Thus zero_mask == + * 0xFFFFFFFF if the half-precision number was zero (+0.0h or -0.0h) + * 0x00000000 otherwise + */ + const int32_t zero_mask = (int32_t)(nonsign - 1) >> 31; + /* + * 1. Shift nonsign left by renorm_shift to normalize it (if the input + * was denormal) + * 2. Shift nonsign right by 3 so the exponent (5 bits originally) + * becomes an 8-bit field and 10-bit mantissa shifts into the 10 high + * bits of the 23-bit mantissa of IEEE single-precision number. + * 3. Add 0x70 to the exponent (starting at bit 23) to compensate the + * different in exponent bias (0x7F for single-precision number less 0xF + * for half-precision number). + * 4. Subtract renorm_shift from the exponent (starting at bit 23) to + * account for renormalization. As renorm_shift is less than 0x70, this + * can be combined with step 3. + * 5. Binary OR with inf_nan_mask to turn the exponent into 0xFF if the + * input was NaN or infinity. + * 6. Binary ANDNOT with zero_mask to turn the mantissa and exponent + * into zero if the input was zero. + * 7. Combine with the sign of the input number. + */ + return sign | + ((((nonsign << renorm_shift >> 3) + ((0x70 - renorm_shift) << 23)) | + inf_nan_mask) & + ~zero_mask); +} + +#ifdef C10_X86_F16 +#undef C10_X86_F16 +#endif // C10_X86_F16 + +#if defined(__aarch64__) && !defined(__CUDACC__) +inline float16_t fp16_from_bits(uint16_t h) { + return c10::bit_cast(h); +} + +inline uint16_t fp16_to_bits(float16_t f) { + return c10::bit_cast(f); +} + +// According to https://godbolt.org/z/frExdbsWG it would translate to single +// fcvt s0, h0 +inline float native_fp16_to_fp32_value(uint16_t h) { + return static_cast(fp16_from_bits(h)); +} + +inline uint16_t native_fp16_from_fp32_value(float f) { + return fp16_to_bits(static_cast(f)); +} +#endif + +} // namespace detail + +//---------- below is copied from c10/util/Half-inl.h ----------------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +#if defined(__aarch64__) && !defined(__CUDACC__) +/// Constructors +inline Half::Half(float16_t value) : x(detail::fp16_to_bits(value)) {} +inline Half::operator float16_t() const { + return detail::fp16_from_bits(x); +} +#else + +inline C10_HOST_DEVICE Half::Half(float value) + : +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + x(__half_as_short(__float2half(value))) +#elif defined(__SYCL_DEVICE_ONLY__) + x(c10::bit_cast(sycl::half(value))) +#elif (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) + x(at::vec::float2half_scalar(value)) +#else + x(detail::fp16_ieee_from_fp32_value(value)) +#endif +{ +} + +/// Implicit conversions + +inline C10_HOST_DEVICE Half::operator float() const { +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + return __half2float(*reinterpret_cast(&x)); +#elif defined(__SYCL_DEVICE_ONLY__) + return float(c10::bit_cast(x)); +#elif (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) + return at::vec::half2float_scalar(x); +#elif defined(__aarch64__) && !defined(__CUDACC__) + return detail::native_fp16_to_fp32_value(x); +#else + return detail::fp16_ieee_to_fp32_value(x); +#endif +} + +#endif /* !defined(__aarch64__) || defined(__CUDACC__) \ + */ + +#if defined(__CUDACC__) || defined(__HIPCC__) +inline C10_HOST_DEVICE Half::Half(const __half& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE Half::operator __half() const { + return *reinterpret_cast(&x); +} +#endif + +#ifdef SYCL_LANGUAGE_VERSION +inline C10_HOST_DEVICE Half::Half(const sycl::half& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE Half::operator sycl::half() const { + return *reinterpret_cast(&x); +} +#endif + +// CUDA intrinsics + +#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 350)) || \ + (defined(__clang__) && defined(__CUDA__)) +inline __device__ Half __ldg(const Half* ptr) { + return __ldg(reinterpret_cast(ptr)); +} +#endif + +/// Arithmetic + +inline C10_HOST_DEVICE Half operator+(const Half& a, const Half& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE Half operator-(const Half& a, const Half& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE Half operator*(const Half& a, const Half& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE Half operator/(const Half& a, const Half& b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator-(const Half& a) { +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530) || \ + defined(__HIP_DEVICE_COMPILE__) + return __hneg(a); +#elif defined(__SYCL_DEVICE_ONLY__) + return -c10::bit_cast(a); +#else + return -static_cast(a); +#endif +} + +inline C10_HOST_DEVICE Half& operator+=(Half& a, const Half& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE Half& operator-=(Half& a, const Half& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE Half& operator*=(Half& a, const Half& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE Half& operator/=(Half& a, const Half& b) { + a = a / b; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(Half a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(Half a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(Half a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(Half a, float b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, Half b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, Half b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, Half b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, Half b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const Half& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const Half& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const Half& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const Half& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(Half a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(Half a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(Half a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(Half a, double b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, Half b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, Half b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, Half b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, Half b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE Half operator+(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Half operator-(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Half operator*(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Half operator/(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator+(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Half operator-(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Half operator*(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Half operator/(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE Half operator+(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Half operator-(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Half operator*(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Half operator/(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator+(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Half operator-(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Half operator*(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Half operator/(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) / b; +} + +/// NOTE: we do not define comparisons directly and instead rely on the implicit +/// conversion from c10::Half to float. + +C10_CLANG_DIAGNOSTIC_POP() + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +using c10::Half; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator<<; + +namespace detail { +#if defined(__aarch64__) && !defined(__CUDACC__) +using c10::detail::fp16_from_bits; +using c10::detail::fp16_to_bits; +using c10::detail::native_fp16_from_fp32_value; +using c10::detail::native_fp16_to_fp32_value; +#endif + +using c10::detail::fp16_ieee_from_fp32_value; +using c10::detail::fp16_ieee_to_fp32_bits; +using c10::detail::fp16_ieee_to_fp32_value; +} // namespace detail + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_specialized = true; + static constexpr bool is_signed = true; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = true; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = true; + static constexpr auto has_denorm = numeric_limits::has_denorm; + static constexpr auto has_denorm_loss = + numeric_limits::has_denorm_loss; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = true; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 11; + static constexpr int digits10 = 3; + static constexpr int max_digits10 = 5; + static constexpr int radix = 2; + static constexpr int min_exponent = -13; + static constexpr int min_exponent10 = -4; + static constexpr int max_exponent = 16; + static constexpr int max_exponent10 = 4; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = + numeric_limits::tinyness_before; + static constexpr c10::Half min() { + return c10::Half(0x0400, c10::Half::from_bits()); + } + static constexpr c10::Half lowest() { + return c10::Half(0xFBFF, c10::Half::from_bits()); + } + static constexpr c10::Half max() { + return c10::Half(0x7BFF, c10::Half::from_bits()); + } + static constexpr c10::Half epsilon() { + return c10::Half(0x1400, c10::Half::from_bits()); + } + static constexpr c10::Half round_error() { + return c10::Half(0x3800, c10::Half::from_bits()); + } + static constexpr c10::Half infinity() { + return c10::Half(0x7C00, c10::Half::from_bits()); + } + static constexpr c10::Half quiet_NaN() { + return c10::Half(0x7E00, c10::Half::from_bits()); + } + static constexpr c10::Half signaling_NaN() { + return c10::Half(0x7D00, c10::Half::from_bits()); + } + static constexpr c10::Half denorm_min() { + return c10::Half(0x0001, c10::Half::from_bits()); + } +}; + +} // namespace std diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/HeaderOnlyArrayRef.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/HeaderOnlyArrayRef.h new file mode 100644 index 0000000000000000000000000000000000000000..751ffef32bb1da3a00f3735f9f7200d805f3f9d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/HeaderOnlyArrayRef.h @@ -0,0 +1,248 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace c10 { + +/// HeaderOnlyArrayRef - A subset of ArrayRef that is implemented only +/// in headers. This will be a base class from which ArrayRef inherits, so that +/// we can keep much of the implementation shared. +/// +/// [HeaderOnlyArrayRef vs ArrayRef note] +/// As HeaderOnlyArrayRef is a subset of ArrayRef, it has slightly less +/// functionality than ArrayRef. We document the minor differences below: +/// 1. ArrayRef has an extra convenience constructor for SmallVector. +/// 2. ArrayRef uses TORCH_CHECK. HeaderOnlyArrayRef uses header-only +/// STD_TORCH_CHECK, which will output a std::runtime_error vs a +/// c10::Error. Consequently, you should use ArrayRef when possible +/// and HeaderOnlyArrayRef only when necessary to support headeronly code. +/// In all other aspects, HeaderOnlyArrayRef is identical to ArrayRef, with the +/// positive benefit of being header-only and thus independent of libtorch.so. +template +class HeaderOnlyArrayRef { + public: + using iterator = const T*; + using const_iterator = const T*; + using size_type = size_t; + using value_type = T; + + using reverse_iterator = std::reverse_iterator; + + protected: + /// The start of the array, in an external buffer. + const T* Data; + + /// The number of elements. + size_type Length; + + public: + /// @name Constructors + /// @{ + + /// Construct an empty HeaderOnlyArrayRef. + /* implicit */ constexpr HeaderOnlyArrayRef() : Data(nullptr), Length(0) {} + + /// Construct a HeaderOnlyArrayRef from a single element. + // TODO Make this explicit + constexpr HeaderOnlyArrayRef(const T& OneElt) : Data(&OneElt), Length(1) {} + + /// Construct a HeaderOnlyArrayRef from a pointer and length. + constexpr HeaderOnlyArrayRef(const T* data, size_t length) + : Data(data), Length(length) {} + + /// Construct a HeaderOnlyArrayRef from a range. + constexpr HeaderOnlyArrayRef(const T* begin, const T* end) + : Data(begin), Length(end - begin) {} + + template < + typename Container, + typename U = decltype(std::declval().data()), + typename = std::enable_if_t< + (std::is_same_v || std::is_same_v)>> + /* implicit */ HeaderOnlyArrayRef(const Container& container) + : Data(container.data()), Length(container.size()) {} + + /// Construct a HeaderOnlyArrayRef from a std::vector. + // The enable_if stuff here makes sure that this isn't used for + // std::vector, because ArrayRef can't work on a std::vector + // bitfield. + template + /* implicit */ HeaderOnlyArrayRef(const std::vector& Vec) + : Data(Vec.data()), Length(Vec.size()) { + static_assert( + !std::is_same_v, + "HeaderOnlyArrayRef cannot be constructed from a std::vector bitfield."); + } + + /// Construct a HeaderOnlyArrayRef from a std::array + template + /* implicit */ constexpr HeaderOnlyArrayRef(const std::array& Arr) + : Data(Arr.data()), Length(N) {} + + /// Construct a HeaderOnlyArrayRef from a C array. + template + // NOLINTNEXTLINE(*c-arrays*) + /* implicit */ constexpr HeaderOnlyArrayRef(const T (&Arr)[N]) + : Data(Arr), Length(N) {} + + /// Construct a HeaderOnlyArrayRef from a std::initializer_list. + /* implicit */ constexpr HeaderOnlyArrayRef( + const std::initializer_list& Vec) + : Data( + std::begin(Vec) == std::end(Vec) ? static_cast(nullptr) + : std::begin(Vec)), + Length(Vec.size()) {} + + /// @} + /// @name Simple Operations + /// @{ + + constexpr iterator begin() const { + return this->Data; + } + constexpr iterator end() const { + return this->Data + this->Length; + } + + // These are actually the same as iterator, since ArrayRef only + // gives you const iterators. + constexpr const_iterator cbegin() const { + return this->Data; + } + constexpr const_iterator cend() const { + return this->Data + this->Length; + } + + constexpr reverse_iterator rbegin() const { + return reverse_iterator(end()); + } + constexpr reverse_iterator rend() const { + return reverse_iterator(begin()); + } + + /// Check if all elements in the array satisfy the given expression + constexpr bool allMatch(const std::function& pred) const { + return std::all_of(cbegin(), cend(), pred); + } + + /// empty - Check if the array is empty. + constexpr bool empty() const { + return this->Length == 0; + } + + constexpr const T* data() const { + return this->Data; + } + + /// size - Get the array size. + constexpr size_t size() const { + return this->Length; + } + + /// front - Get the first element. + constexpr const T& front() const { + STD_TORCH_CHECK( + !this->empty(), + "HeaderOnlyArrayRef: attempted to access front() of empty list"); + return this->Data[0]; + } + + /// back - Get the last element. + constexpr const T& back() const { + STD_TORCH_CHECK( + !this->empty(), + "HeaderOnlyArrayRef: attempted to access back() of empty list"); + return this->Data[this->Length - 1]; + } + + /// equals - Check for element-wise equality. + constexpr bool equals(HeaderOnlyArrayRef RHS) const { + return this->Length == RHS.Length && + std::equal(begin(), end(), RHS.begin()); + } + + /// slice(n, m) - Take M elements of the array starting at element N + constexpr HeaderOnlyArrayRef slice(size_t N, size_t M) const { + STD_TORCH_CHECK( + N + M <= this->size(), + "HeaderOnlyArrayRef: invalid slice, N = ", + N, + "; M = ", + M, + "; size = ", + this->size()); + return HeaderOnlyArrayRef(this->data() + N, M); + } + + /// slice(n) - Chop off the first N elements of the array. + constexpr HeaderOnlyArrayRef slice(size_t N) const { + STD_TORCH_CHECK( + N <= this->size(), + "HeaderOnlyArrayRef: invalid slice, N = ", + N, + "; size = ", + this->size()); + return slice(N, this->size() - N); + } + + /// @} + /// @name Operator Overloads + /// @{ + constexpr const T& operator[](size_t Index) const { + return this->Data[Index]; + } + + /// Vector compatibility + constexpr const T& at(size_t Index) const { + STD_TORCH_CHECK( + Index < this->Length, + "HeaderOnlyArrayRef: invalid index Index = ", + Index, + "; Length = ", + this->Length); + return this->Data[Index]; + } + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t, HeaderOnlyArrayRef>& operator=( + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + U&& Temporary) = delete; + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t, HeaderOnlyArrayRef>& operator=( + std::initializer_list) = delete; + + /// @} + /// @name Expensive Operations + /// @{ + std::vector vec() const { + return std::vector(this->Data, this->Data + this->Length); + } + + /// @} +}; + +} // namespace c10 + +namespace torch::headeronly { +using c10::HeaderOnlyArrayRef; +using IntHeaderOnlyArrayRef = HeaderOnlyArrayRef; +} // namespace torch::headeronly diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Metaprogramming.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Metaprogramming.h new file mode 100644 index 0000000000000000000000000000000000000000..2589f338d35dbcf569e15966a788dd16130c0681 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/Metaprogramming.h @@ -0,0 +1,237 @@ +#pragma once + +#include +#include +#include + +namespace c10::guts { + +/** + * Access information about result type or arguments from a function type. + * Example: + * using A = function_traits::return_type // A == int + * using A = function_traits::parameter_types::tuple_type + * // A == tuple + */ +template +struct function_traits { + static_assert( + !std::is_same_v, + "In function_traits, Func must be a plain function type."); +}; +template +struct function_traits { + using func_type = Result(Args...); + using return_type = Result; + using parameter_types = typelist::typelist; + static constexpr auto number_of_parameters = sizeof...(Args); +}; + +/** + * infer_function_traits: creates a `function_traits` type for a simple + * function (pointer) or functor (lambda/struct). Currently does not support + * class methods. + */ + +template +struct infer_function_traits { + using type = function_traits< + c10::guts::detail::strip_class_t>; +}; + +template +struct infer_function_traits { + using type = function_traits; +}; + +template +struct infer_function_traits { + using type = function_traits; +}; + +template +using infer_function_traits_t = typename infer_function_traits::type; + +/** + * make_function_traits: creates a `function_traits` type given a Return type + * and a typelist of Argument types + * + * Example: + * bool f(int, int); + * + * infer_function_traits_t == make_function_traits_t> + */ +template +struct make_function_traits { + static_assert( + false_t::value, + "In guts::make_function_traits, the ArgList argument must be typelist<...>."); +}; + +template +struct make_function_traits> { + using type = function_traits; +}; + +template +using make_function_traits_t = + typename make_function_traits::type; + +/** + * make_offset_index_sequence + * Like make_index_sequence, but starting from Start instead of 0. + * + * Example: + * make_offset_index_sequence<10, 3> == std::index_sequence<10, 11, 12> + */ +template +struct make_offset_index_sequence_impl + : make_offset_index_sequence_impl { + static_assert( + static_cast(Start) >= 0, + "make_offset_index_sequence: Start < 0"); + static_assert(static_cast(N) >= 0, "make_offset_index_sequence: N < 0"); +}; + +template +struct make_offset_index_sequence_impl { + typedef std::index_sequence type; +}; + +template +using make_offset_index_sequence = + typename make_offset_index_sequence_impl::type; + +/** + * Use tuple_elements to extract a position-indexed subset of elements + * from the argument tuple into a result tuple. + * + * Example: + * std::tuple t = std::make_tuple(0, "HEY", 2.0); + * std::tuple result = tuple_elements(t, std::index_sequence<0, + * 2>()); + */ +template +constexpr auto tuple_elements(Tuple t, std::index_sequence /*unused*/) { + return std::tuple...>(std::get(t)...); +} + +/** + * Use tuple_take to extract the first or last n elements from the argument + * tuple into a result tuple. + * + * Example: + * std::tuple t = std::make_tuple(0, "HEY", 2.0); + * std::tuple first_two = tuple_take(t); + * std::tuple last_two = tuple_take(t); + */ +template +struct TupleTake {}; + +template +struct TupleTake= 0, void>> { + static auto call(Tuple t) { + constexpr size_t size = std::tuple_size(); + static_assert(N <= size, "tuple_take: N > size"); + return tuple_elements(t, std::make_index_sequence{}); + } +}; + +template + struct TupleTake < Tuple, + N, std::enable_if_t> { + static auto call(Tuple t) { + constexpr size_t size = std::tuple_size(); + static_assert(-N <= size, "tuple_take: -N > size"); + return tuple_elements(t, make_offset_index_sequence{}); + } +}; + +template +auto tuple_take(Tuple t) { + return TupleTake::call(t); +} + +/** + * Use tuple_slice to extract a contiguous subtuple from the argument. + * + * Example: + * std::tuple t = std::make_tuple(0, + * "HEY", 2.0, false); std::tuple middle_two = + * tuple_slice(t); + */ +template +constexpr auto tuple_slice(Tuple t) { + constexpr size_t size = std::tuple_size(); + static_assert(Start + N <= size, "tuple_slice: Start + N > size"); + return tuple_elements(t, make_offset_index_sequence{}); +} + +/** + * Use tuple_map to run a mapping function over a tuple to get a new tuple. + * + * Example 1: + * auto result = tuple_map(std::tuple(3, 4, 5), [] + * (int32_t a) -> int16_t {return a+1;}); + * // result == std::tuple(4, 5, 6) + * + * Example 2: + * struct Mapper { + * std::string operator()(int32_t a) const { + * return std::to_string(a); + * } + * int64_t operator()(const std::string& a) const { + * return atoi(a.c_str()); + * } + * }; + * auto result = tuple_map(std::tuple(3, "4"), + * Mapper()); + * // result == std::tuple("3", 4) + * + * Example 3: + * struct A final { + * int32_t func() { + * return 5; + * } + * }; + * struct B final { + * std::string func() { + * return "5"; + * } + * }; + * auto result = tuple_map(std::make_tuple(A(), B()), [] (auto a) { return + * a.func(); }); + * // result == std::tuple(5, "5"); + */ +namespace detail { +template +auto tuple_map( + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) + std::tuple&& tuple, + const Mapper& mapper, + std::index_sequence /*unused*/) { + return std::tuple(std::get( + tuple))))...>(mapper(std::forward(std::get(tuple)))...); +} +} // namespace detail + +template +auto tuple_map(std::tuple&& tuple, const Mapper& mapper) { + return detail::tuple_map( + std::move(tuple), mapper, std::index_sequence_for()); +} + +} // namespace c10::guts + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly, guts) + +using c10::guts::function_traits; +using c10::guts::infer_function_traits_t; +using c10::guts::make_function_traits_t; +using c10::guts::tuple_elements; +using c10::guts::tuple_map; +using c10::guts::tuple_slice; +using c10::guts::tuple_take; + +HIDDEN_NAMESPACE_END(torch, headeronly, guts) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/TypeList.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/TypeList.h new file mode 100644 index 0000000000000000000000000000000000000000..cd81f0cc1dcf97e0444ace259be265693c2935ec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/headeronly/util/TypeList.h @@ -0,0 +1,548 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace c10::guts { + +template +struct false_t : std::false_type {}; +template