diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/clear_undefinedness.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/clear_undefinedness.h new file mode 100644 index 0000000000000000000000000000000000000000..134a50a2c6b521735b7dab5e1225394dda1dfee0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/clear_undefinedness.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +// Undefinedness makes argument matching fail for regular tensor operations +// if 1+ arguments are undefined or possibly undefined tensors. +// Technically, undefined tensors are **not** tensors as the regular tensor +// operations do not know how to handle them. +// However, in practice, there are guards and conversion operators that +// **always** gate regular operations if undefined tensors may be present +// Eventually, we would love to move to the world where we use optionals +// in lieu of undefined tensors. +// When this happens, this pass will be removed +TORCH_API void ClearUndefinedness(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/common_subexpression_elimination.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/common_subexpression_elimination.h new file mode 100644 index 0000000000000000000000000000000000000000..6ba9168870d9bb1db49aaee14ba5b94e90f5e7a8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/common_subexpression_elimination.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API bool EliminateCommonSubexpression( + const std::shared_ptr& graph); +} + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h new file mode 100644 index 0000000000000000000000000000000000000000..2bb17068b66a9ea42362a7779808341319eca31e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Eliminates common inputs among `aten::cat` ops. +TORCH_API bool EliminateConcatCommonInputs(const std::shared_ptr& graph); + +// Expands `aten::cat` ops into `aten::copy` ops and eliminates redudancies +// in the buffers used for concatenation if possible. +TORCH_API void ExpandConcatAndEliminateRedundancy( + const std::shared_ptr& graph); + +TORCH_API bool CombineConcats(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_pooling.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_pooling.h new file mode 100644 index 0000000000000000000000000000000000000000..7fcaf321f353f1a89d8e2ec7170c55463a58871c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_pooling.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void ConstantPooling(const std::shared_ptr& graph); + +} + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h new file mode 100644 index 0000000000000000000000000000000000000000..bd25c7c3851924b85195d5c4fca6555acd38ad2f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h @@ -0,0 +1,35 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Runs constant propagation on all objects unless ignore_custom_classes is +// specified as true, in which case user defined classes are skipped. This is +// useful to prevent early fusion of packing operations, which end up lowering +// away information about their constructors (e.g. packed::linear_clamp_prepack +// and prepacked::conv2d_clamp_prepack) +// Returns True if the pass made a change to the graph +TORCH_API bool ConstantPropagation( + std::shared_ptr& graph, + bool ignore_custom_classes = false); + +// runs constant propagation only on ops that have non-aliasing inputs & outputs +// Returns True if the pass made a change to the graph +TORCH_API bool ConstantPropagationImmutableTypes(std::shared_ptr& graph); + +// Runs the node if its inputs are constants. Callers of this function must +// make their own determination if constant prop is appropriate - for example +// non-deterministic ops or ops with side effects. If ignore_custom_classes is +// specified, nodes that output user defined classes are not run. +TORCH_API std::optional runNodeIfInputsAreConstant( + const Node* node, + bool ignore_custom_classes = false, + AliasDb* db = nullptr); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_autodiff_subgraphs.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_autodiff_subgraphs.h new file mode 100644 index 0000000000000000000000000000000000000000..fb4824c8fb8c190e781fb035ef32c023926aefc4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_autodiff_subgraphs.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::jit { + +// insert GraphExecutor nodes that group together +// subgraphs that are differentiable by the jit's autodiff passes +// threshold - minimum number of nodes that will appear in a block +// returns all differentiable blocks that have been found +TORCH_API std::vector CreateAutodiffSubgraphs( + const std::shared_ptr& graph, + size_t threshold = 2); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h new file mode 100644 index 0000000000000000000000000000000000000000..ad3c2e3c9778ea4930c131a0739532a6720bea78 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API void CreateFunctionalGraphs(const std::shared_ptr& graph); + +TORCH_API void InlineFunctionalGraphs(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dbr_quantization/remove_redundant_aliases.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dbr_quantization/remove_redundant_aliases.h new file mode 100644 index 0000000000000000000000000000000000000000..5d5ec2c402a79d8b201241becdb491efe5b61596 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dbr_quantization/remove_redundant_aliases.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// This function replaces instances of +// +// %b = aten::alias(%a) +// %c = foo(%b) +// +// with +// +// %c = foo(%a) +// +// on the module forward, if it's safe to do so. +TORCH_API Module DBRQuantRemoveRedundantAliases(Module& 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dead_code_elimination.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dead_code_elimination.h new file mode 100644 index 0000000000000000000000000000000000000000..0768c102d94460bd159d4ff0304c06671a4068f7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dead_code_elimination.h @@ -0,0 +1,45 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// If given a top-level graph, DCE will construct do alias analysis that allows +// for "smarter" dead code elimination (we will eliminate mutable ops if we can +// prove the mutated values are not used). Otherwise, we will not allow DCE to +// eliminate mutable ops. +// +// So, prefer to use the graph version if you can. +enum class DCESideEffectPolicy : uint8_t { + // default behavior: dead code elimination will check if a node has side + // effects + // and not delete it if it does. + DONT_DELETE_NODES_WITH_SIDE_EFFECTS, + // with this flag, dead code elimination will not check if a node has side + // effects and treat nodes with side effects like any other node, + // i.e. delete them if their outputs aren't used anywhere. + ALLOW_DELETING_NODES_WITH_SIDE_EFFECTS +}; + +TORCH_API void EliminateDeadCode( + const std::shared_ptr& graph, + DCESideEffectPolicy sideEffectPolicy = + DCESideEffectPolicy::DONT_DELETE_NODES_WITH_SIDE_EFFECTS); +TORCH_API void EliminateDeadCode( + Block* block, + bool recurse = true, + DCESideEffectPolicy sideEffectPolicy = + DCESideEffectPolicy::DONT_DELETE_NODES_WITH_SIDE_EFFECTS); + +// Invoke the user-provided callback on all live values before deleting anything +TORCH_API void EliminateDeadCode( + Block* block, + std::function&)> cb, + DCESideEffectPolicy sideEffectPolicy = + DCESideEffectPolicy::DONT_DELETE_NODES_WITH_SIDE_EFFECTS); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..eca49af30188b48f5a3f5ca3d3b9a787c112b5a6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void DecomposeOps(std::shared_ptr& graph); + +} + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/device_type_analysis.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/device_type_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..da2918b45f0c8ae32bab087241ef188af1615043 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/device_type_analysis.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { +struct Graph; + +// Propagates Device type info throughout the given graph. +TORCH_API bool DeviceTypePropagation(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dtype_analysis.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dtype_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..2a35b85ac435cfaaed3a45b4603f73949532ba32 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dtype_analysis.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { +struct Graph; + +// Propagate tensor properties (e.g., dtype, device, is_contiguous, layout) +// propagation on all tensor objects. Currently, we only support dtype +// propagation +TORCH_API bool DtypePropagation(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/eliminate_no_ops.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/eliminate_no_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b54a0f597ae04bd74b089d4d63e06d1820480a9a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/eliminate_no_ops.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Remove ops that do nothing on the forward pass (like aten::detach). +// This pass is invoked as a part of freeze_module. +// This function also takes a set of custom ops to eliminate. All ops in this +// set must take their output as their first input, i.e. x = f(x, ...) +TORCH_API bool EliminateNoOps( + std::shared_ptr& graph, + std::unordered_set custom_ops = {}); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h new file mode 100644 index 0000000000000000000000000000000000000000..a07403371551c7fc51de7e6158a7e4f52406fd98 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h @@ -0,0 +1,26 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Erase NumberType information. This is necessary for and only used in +// exporting to ONNX. This pass ensures that no remaining Values have +// NumberType types, replacing them with tensors. +// The following things are done to erase NumberType info: +// - NumberType outputs are changed to DynamicType. +// - prim::Constant nodes which are numbers get changed into 0-dim tensors of +// the corresponding type +// - prim::TensorToNum, aten::Float, aten::Int and prim::NumToTensor nodes +// are erased. +// +// The pass assumes that DCE will be called sometime after. +TORCH_API void EraseNumberTypes(const std::shared_ptr& graph); +TORCH_API void EraseNumberTypesOnBlock(Block* block); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h new file mode 100644 index 0000000000000000000000000000000000000000..e6a5a15dc1d6428ff0776412c2eb860ad924c586 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +// Directly after tracing, we have an ill-formed graph with blocks inserted. +// Example: +// +// graph(%self : ClassType, +// %input.1 : Float(3, 4)): +// %1 : ClassType = prim::GetAttr[name="relu1"](%self) +// %2 : ClassType = prim::GetAttr[name="relu2"](%self) +// %3 : ClassType = prim::GetAttr[name="rrr"](%2) +// = prim::TracedModuleForward[scope="__module.relu1"]() +// block0(): +// %input : Float(3, 4) = aten::relu(%input.1), +// -> () +// = prim::TracedModuleForward[scope="__module.relu2"](), +// block0(): +// = prim::TracedModuleForward[scope="__module.relu2.rrr"](), +// block0(): +// %6 : Float(3, 4) = aten::relu(%input), +// -> () +// -> () +// return (%6) +// +// In this pass, we: +// 1) Lift Value defs to as high of a scope as needed to ensure that +// they dominate all their uses. For example, `input` in the above +// graph needs to be lifted to the top-level block so that its use +// in the second `relu` operator is dominated. +// 2) Lambda lift the blocks. This ensures that all values used within +// each scope have their defs captured. +// 3) Convert the scope blocks into methods on their respective Modules, +// and convert TracedModuleForward nodes to CallMethod nodes into those +// methods. +// +// Then, we'll have a well-formed graph with proper method calls. +TORCH_API void FixupTraceScopeBlocks( + std::shared_ptr& graph, + Module* self); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_conv_bn.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_conv_bn.h new file mode 100644 index 0000000000000000000000000000000000000000..ecdd7d39540262c49af085a7d4f4a0b5a4ccb125 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_conv_bn.h @@ -0,0 +1,40 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +/** \brief Fold Conv2d-BatchNorm2d into Conv2d in all methods of this + * module and all its submodules, forward is included by default. + * + * The weight and bias of the Conv2d are correspondingly updated. Should only be + * used on modules in eval mode. + */ +TORCH_API Module FoldConvBatchNorm(const Module& module); + +struct TORCH_API ConvBNParameters { + at::Tensor conv_w; + at::Tensor conv_b; + at::Tensor bn_rm; + at::Tensor bn_rv; + double bn_eps = 0.0; + at::Tensor bn_w; + at::Tensor bn_b; +}; + +/** + * Given the current weight and bias tensors of a Conv module and parameters + * of the BatchNorm module we're folding with, compute the updated values + * for the weight and bias. + * + * The function is basically copied from torch/nn/utils/fusion.py + */ +TORCH_API std::tuple computeUpdatedConvWeightAndBias( + const ConvBNParameters& p); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_linear_bn.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_linear_bn.h new file mode 100644 index 0000000000000000000000000000000000000000..9725255f4efa62ef1a2a66b80b5c88da307f57b7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_linear_bn.h @@ -0,0 +1,32 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +struct TORCH_API LinearBNParameters { + at::Tensor linear_w; + at::Tensor linear_b; + at::Tensor bn_rm; + at::Tensor bn_rv; + double bn_eps = 0.0; + at::Tensor bn_w; + at::Tensor bn_b; +}; + +/** + * Given the current weight and bias tensors of a Linear module and parameters + * of the BatchNorm module we're folding with, compute the updated values + * for the weight and bias. + * + * The function is basically copied from torch/nn/utils/fusion.py + */ +TORCH_API std::tuple computeUpdatedLinearWeightAndBias( + const LinearBNParameters& p); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/freeze_module.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/freeze_module.h new file mode 100644 index 0000000000000000000000000000000000000000..9281743a4801dd11ee383ac4e893fe561c190a1b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/freeze_module.h @@ -0,0 +1,39 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** \brief This file defines freezing Torchscript module API. + * + * This API has python-binding and can be invoked directly or as a part of + * general optimization pipeline. + */ +#pragma once + +#include +#include + +/** \brief Freeze Module, i.e., Assume all attributes are constants. + * + * Freezing module is a functionality that allows the JIT to internalize + * immutable attributes. Combined with inlining, the module is aggressively + * optimized and significant overhead is optimized away. The freezeModule API + * produces a cloned frozen module. + */ + +namespace torch::jit { + +TORCH_API Module freeze_module( + const Module& module, + std::vector preservedAttrs = std::vector(), + bool freezeInterfaces = true, + bool preserveParameters = false); + +// Clone-free version of freeze_module. This modifies the module inplace. +// Use this version to avoid extra memory usage incurred by cloning the module. +TORCH_API void freeze_module_inplace( + Module* module, + std::vector preservedAttrs = std::vector(), + bool freezeInterfaces = true, + bool preserveParameters = false); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_concat_linear.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_concat_linear.h new file mode 100644 index 0000000000000000000000000000000000000000..c8dc43e1f264dd6379de56370041caa2f122adf8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_concat_linear.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Concats multiple linear ops with the same Tensor input +// into a single linear op. +TORCH_API bool FrozenConcatLinear(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_add_relu_fusion.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_add_relu_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..c0ec86b5e84b5346e2ba002234b745d123d15edc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_add_relu_fusion.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API extern std::function&)>& +getFuseFrozenConvAddReluImpl(); + +TORCH_API void FuseFrozenConvAddRelu(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_folding.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_folding.h new file mode 100644 index 0000000000000000000000000000000000000000..7be1df9bb211fe4d2d895c81bf26000e12bee60f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_folding.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Fuses Convolution -> Batchnorm into a single Convolution by +// folding batchnorm weights into conv weights. +// This pass only works on Frozen Graphs; otherwise it is a No-Op. +TORCH_API bool FoldFrozenConvBatchnorm(std::shared_ptr& graph); + +// Fuses Convolution -> Add/Sub into a single Convolution by +// folding add constant tensor into conv weights. +// This pass only works on Frozen Graphs; otherwise it is a No-Op. +TORCH_API bool FoldFrozenConvAddOrSub(std::shared_ptr& graph); + +// Fuses Convolution -> Mul/Div into a single Convolution by +// folding add constant tensor into conv weights. +// This pass only works on Frozen Graphs; otherwise it is a No-Op. +TORCH_API bool FoldFrozenConvMulOrDiv(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_graph_optimizations.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_graph_optimizations.h new file mode 100644 index 0000000000000000000000000000000000000000..8c435cbebf000189967373afe992f1c633e7af4d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_graph_optimizations.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +/** \brief Runs a set of Optimizations that Optimize Frozen Graphs + * + * Currently this set of optimizations is: + * - FoldFrozenConvBatchnorm + * - FoldFrozenConvAddOrSub + * - FoldFrozenConvMulOrDiv + * - FoldFrozenLinearBatchnorm + */ + +namespace torch::jit { + +TORCH_API void OptimizeFrozenGraph( + std::shared_ptr& graph, + bool optimize_numerics = true); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_folding.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_folding.h new file mode 100644 index 0000000000000000000000000000000000000000..9615bff1c4f477064c89e9991d4e14cc68f19f63 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_folding.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Fuses Linear -> BatchNormNd into a single Linear by +// folding batchnorm weights into linear weights. +// This pass only works on Frozen Graphs; otherwise it is a No-Op. +TORCH_API bool FoldFrozenLinearBatchnorm(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_transpose.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_transpose.h new file mode 100644 index 0000000000000000000000000000000000000000..c1e7d52f78130c983f1ba63b8f46911a29c29cdf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_transpose.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Transposes the weight matrix for frozen linear modules. +// and converts it into a matmul +TORCH_API bool FrozenLinearTranspose(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h new file mode 100644 index 0000000000000000000000000000000000000000..3a6dc2b906a9bcd1236c6a516a2b3c4bba439a90 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Converts operators & their parameters to mkldnn if it is profitable +// Currently encompassing Conv2d and Conv3d, and Linear +// Op must be in float32 and mkldnn must be built +// This pass only works on frozen graph +TORCH_API void ConvertFrozenOpsToMKLDNN(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_linear.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_linear.h new file mode 100644 index 0000000000000000000000000000000000000000..ad13f50ea137822d1e38617e7ba17ddea80f76c5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_linear.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** \brief Fusing linear patterns as single at::linear for easier pattern + * matching in later passes + */ +#pragma once + +#include + +namespace torch::jit { + +/** \brief Match the at::linear pattern and fuse it into a single at::linear + * This pass fuse the addmm or matmul + add generated by JIT back to linear + * This pass can be deleted once the JIT can emit the aten::linear in the future + */ +TORCH_API void FuseLinear(std::shared_ptr& graph); + +/** Swap functional linear CallFunctions to aten::linear + */ +TORCH_API void SwapFunctionalLinear(std::shared_ptr& graph); +/** Swap all functional linear CallFunctions in module + */ +TORCH_API void SwapFunctionalLinear(Module& 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_relu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_relu.h new file mode 100644 index 0000000000000000000000000000000000000000..749a6487b8fa93f818437d3089ce95aa05d8f4c2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_relu.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { +TORCH_API void FuseAddRelu(script::Module& module); +TORCH_API void FuseAddRelu(std::shared_ptr& graph); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_fuser.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_fuser.h new file mode 100644 index 0000000000000000000000000000000000000000..eb1c5de6f88efff396eb2e756febb0cda5291212 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_fuser.h @@ -0,0 +1,40 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API bool canFuseOnCPULegacy(); +TORCH_API void overrideCanFuseOnCPULegacy(bool value); + +// NB: Be sure to run DCE before fusion, because dead instructions +// can prevent fusion opportunities from being exploited. +// On Windows will noop, NYI +TORCH_API void FuseGraph( + std::shared_ptr& graph, + bool strict_fuser_check = false); + +// \brief Custom fusion pass using a node-level callback to +// determine the inclusion of nodes in a subgraph. +// +// This helper omits aliased inputs and fusion across control flow +// boundaries. +// +// \arg graph The graph to be modified in-place +// \arg is_fusable A callback run on each fusable node in the graph. +// \arg kind The label given to the resultant fused subgraph +// \arg arg_limit The maximum number of args the resultant fused subgraph +// should have. Note: This will likely develop into a general +// post condition on the fused subgraph. +TORCH_API void CustomFuseGraph( + std::shared_ptr& graph, + const std::function& is_fusable, + Symbol kind, + size_t arg_limit = std::numeric_limits::max()); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_rewrite_helper.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_rewrite_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..011d55177772914c920e3070dce107ede8d50e47 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_rewrite_helper.h @@ -0,0 +1,55 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::graph_rewrite_helper { + +std::string getFuncName(Value* func_value); +Value* getValue( + const std::string& name, + const std::unordered_map& match_vmap, + const std::unordered_map& vmap); +std::optional getIValue( + const std::string& name, + const std::unordered_map& match_vmap, + const std::unordered_map& vmap); +TORCH_API void replaceConvolutionWithAtenConv(std::shared_ptr& graph); + +bool isClampFusable( + const Match& match, + const std::unordered_map& vmap); + +// This struct contains a compiled IR patterns slated for use in the +// findPatternMatches function. The struct encapsulates the common +// information from parseIR that is used in conjunction with the +// pattern matching facility. A const instance of this struct can +// also be stored away to cache the compiled IR pattern and reduce +// runtime cost +struct PatternInfo { + std::string pattern_string; + std::unique_ptr pattern_graph; + std::unordered_map vmap; + std::vector filters; + + static PatternInfo parse_from_str( + std::string pattern_string, + const std::vector& filters = {}) { + PatternInfo rv{ + std::move(pattern_string), + std::make_unique(), + decltype(vmap){}, + filters}; + parseIR(rv.pattern_string, rv.pattern_graph.get(), rv.vmap); + return rv; + } +}; + +} // namespace torch::jit::graph_rewrite_helper + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/guard_elimination.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/guard_elimination.h new file mode 100644 index 0000000000000000000000000000000000000000..79661a9d5d5333e2c2af2669745b8ef6976d53b6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/guard_elimination.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::jit { + +TORCH_API void EliminateRedundantGuards(std::shared_ptr graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/hoist_conv_packed_params.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/hoist_conv_packed_params.h new file mode 100644 index 0000000000000000000000000000000000000000..bab51295e51dfe2a069fa18c8c351e7ccf82e0a2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/hoist_conv_packed_params.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +void HoistConvPackedParams(script::Module& m); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_autodiff_subgraphs.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_autodiff_subgraphs.h new file mode 100644 index 0000000000000000000000000000000000000000..38c7253d947a70304412967356fc137a9dea2f1c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_autodiff_subgraphs.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API bool canRunWithAutograd(Node* node); + +TORCH_API void InlineAutodiffSubgraphs( + std::shared_ptr& graph, + size_t threshold = 5); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_fork_wait.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_fork_wait.h new file mode 100644 index 0000000000000000000000000000000000000000..a4fbf517439474178cc726152b08de73052eabcf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_fork_wait.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Inline Fork and Wait calls. This is used, for example, in ONNX export, where +// we do not support the explicit parallelism structures and would rather +// just have a flat graph. This inlines the forked section in the fork() +// callsite and replaces uses of the result of wait() calls with the values +// produced from the (now-inlined) forked section. +TORCH_API void InlineForkWait(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_forked_closures.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_forked_closures.h new file mode 100644 index 0000000000000000000000000000000000000000..125a5681c5cd6f4d9181e6e49982cce61970134d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_forked_closures.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API void inlineForkedClosures(std::shared_ptr& to_clean); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inliner.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inliner.h new file mode 100644 index 0000000000000000000000000000000000000000..9de6df90451d490af3d52244d0e782bf1a655f03 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inliner.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Inline function and method calls. +TORCH_API void Inline(Graph& graph); + +TORCH_API GraphFunction* tryToGraphFunction(Node* n); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inplace_check.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inplace_check.h new file mode 100644 index 0000000000000000000000000000000000000000..c45c0a27ed634e4540164cfaf0aeac99a35a0e08 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inplace_check.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void CheckInplace(std::shared_ptr& graph); + +} + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/insert_guards.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/insert_guards.h new file mode 100644 index 0000000000000000000000000000000000000000..fe477baa97fb17cb074ea1a35f53bf7671ab4b10 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/insert_guards.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::jit { + +TORCH_API void InsertGuards(std::shared_ptr graph); + +TORCH_API void RemoveProfilingNodes(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/integer_value_refinement.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/integer_value_refinement.h new file mode 100644 index 0000000000000000000000000000000000000000..8a692daee3b8f2074855ab6b25fceb73ba270c38 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/integer_value_refinement.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// return true if graph is modified +TORCH_API bool RefineIntegerValues(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lift_closures.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lift_closures.h new file mode 100644 index 0000000000000000000000000000000000000000..978c14cde21f4995073a6c795ada4c040e6e6661 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lift_closures.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API void liftClosures(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/liveness.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/liveness.h new file mode 100644 index 0000000000000000000000000000000000000000..574a0be83f81d2bbd32c5fcbde3d1e5972e54536 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/liveness.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +using SparseBitVector = ::c10::SparseBitVector<256>; + +// BuildLivenessSets computes "bailout" liveness which is equivalent to +// "{LIVE_IN} or {GEN}" or "{LIVE_OUT} - {KILL}" +TORCH_API std::unordered_map> BuildLivenessSets( + std::shared_ptr graph); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/loop_unrolling.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/loop_unrolling.h new file mode 100644 index 0000000000000000000000000000000000000000..e6c064f7b1870062022e497223535d9853fd2698 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/loop_unrolling.h @@ -0,0 +1,39 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// return true if graph is modified +TORCH_API bool UnrollLoops(std::shared_ptr& graph); + +// Only unrolls constant loops. Will unroll them regardless of loop block size +TORCH_API bool UnrollConstantLoops(std::shared_ptr& graph); + +TORCH_API Node* PeelLoop(Node* n, size_t times); + +// return true if graph is modified +TORCH_API bool PeelProfilingLoops(const std::shared_ptr& graph); + +struct TORCH_API LoopsPeeler { + LoopsPeeler(std::function callback, size_t num_iterations = 1) + : callback_(std::move(callback)), num_iterations_(num_iterations) {} + + bool run(const std::shared_ptr& graph); + + private: + void collectLoop(Node* n); + void collectLoops(Block* block); + void peelLoops(); + + std::function callback_ = nullptr; + Node* in_loop_ = nullptr; + std::list loops_to_peel_; + size_t num_iterations_ = 1; +}; +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h new file mode 100644 index 0000000000000000000000000000000000000000..cf4d238e1355513649139a43deba9173723726cc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// This pass removes 'grad_of' nodes, replacing them with conditionals of +// the form: +// if any_defined(inputs): +// outputs = +// else: +// outputs = undefineds +TORCH_API void LowerGradOf(Graph& g); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..d1e6338cd1bcc70c475a825e58f56b8bd1a12367 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +using ModulePtr = c10::intrusive_ptr; + +// Given a graph with of a method which first argument is %self, lower it to a +// graph where all attributes accesses are replaced with explicit inputs of the +// graph (rather than results of prim::GetAttr executed on %self). +// +// Returns a tuple (graph, parameters) where the last module.parameters.size() +// inputs to the graph are the trainable parameters used in this method. The +// remaining inputs are the true inputs to the function. +TORCH_API std::pair, std::vector> LowerGraph( + Graph& graph, + const ModulePtr& self); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_tuples.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_tuples.h new file mode 100644 index 0000000000000000000000000000000000000000..5358b4f68e1a774da4b05370656e367fa7ea130b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_tuples.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// removes tuples where TupleConstruct and TupleUnpack are matched +// but leaves tuples in place across if statements, loops, and as inputs/outputs +TORCH_API void LowerSimpleTuples(const std::shared_ptr& graph); + +// removes _all_ tuples and raises an error if some cannot be removed +// this is used by ONNX to ensure there are not tuples before conversion, +// but will not work on graphs whose inputs contain tuples. +TORCH_API void LowerAllTuples(const std::shared_ptr& graph); + +TORCH_API void LowerSimpleTuples(Block* block); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/metal_rewrite.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/metal_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..e26b4ff635d69d87ae8694b09acc61b3abc6f4f8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/metal_rewrite.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::jit { +TORCH_API void metalInsertPrePackedOps(std::shared_ptr& graph); +TORCH_API void metalInsertPrePackedOps(script::Module& module); +TORCH_API void metalFusePrePackedConvWithClamp(script::Module& module); +TORCH_API void metalFoldPrePackingOps(script::Module& module); +TORCH_API script::Module metalOptimizeForMobile( + const script::Module& module, + const std::vector& preserved_methods); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mkldnn_rewrite.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mkldnn_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..709eeb2c92b5f441a75de4c114fd953429e0537c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mkldnn_rewrite.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#if AT_MKLDNN_ENABLED() + +#include + +#endif // AT_MKLDNN_ENABLED() + +namespace torch::jit { + +#if AT_MKLDNN_ENABLED() + +namespace mkldnn { + +const static std::map> + fusion_rewrite_map = { + {"none", {}}, + {"relu", {}}, +}; + +} // namespace mkldnn + +#endif // AT_MKLDNN_ENABLED() + +void FuseConvWithEltwise(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mobile_optimizer_type.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mobile_optimizer_type.h new file mode 100644 index 0000000000000000000000000000000000000000..dd88910ecfc21fa505fce9466ede956ef2045b22 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mobile_optimizer_type.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +enum class MobileOptimizerType : int8_t { + CONV_BN_FUSION, + INSERT_FOLD_PREPACK_OPS, + REMOVE_DROPOUT, + FUSE_ADD_RELU, + HOIST_CONV_PACKED_PARAMS, + CONV_1D_TO_2D, + VULKAN_AUTOMATIC_GPU_TRANSFER, +}; + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/normalize_ops.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/normalize_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..1de085401a1c839de96c1a46a12b9eef5af0ed7d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/normalize_ops.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// This pass converts aten ops to a normalized form. It is +// run immediately after IR generation in both the tracer and compiler, +// so downstream consumers of the IR do not need handle ops in their +// pre-normalized form. +// Currently only handles normalization of op aliases. +TORCH_API void NormalizeOps(const std::shared_ptr& graph); + +const std::unordered_map& getOperatorAliasMap(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onednn_graph_fuser.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onednn_graph_fuser.h new file mode 100644 index 0000000000000000000000000000000000000000..79783afd330e4d5df24380d3c1f85e67381c1bb9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onednn_graph_fuser.h @@ -0,0 +1,66 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::jit { + +namespace fuser::onednn { + +static std::atomic onednn_enabled{true}; + +static std::atomic& getLlgaEnabled() { + return onednn_enabled; +} + +TORCH_API void fuseGraph(std::shared_ptr& g); + +} // namespace fuser::onednn + +struct C10_EXPORT RegisterLlgaFuseGraph + : public PassManager { + static bool setEnabled(bool enabled) { + TORCH_CHECK( + AT_MKLDNN_ENABLED(), + "Running oneDNN Graph fuser is only supported with MKLDNN builds."); + bool oldState = fuser::onednn::getLlgaEnabled(); + fuser::onednn::getLlgaEnabled() = enabled; + if (enabled) { + registerPass(fuser::onednn::fuseGraph); + } else { + clearPass(); + } + return oldState; + } + + static bool isEnabled() { + return fuser::onednn::getLlgaEnabled(); + } + + // override PassManager::registerPass to register pre-pass + static bool registerPass(GraphPass p) { + if (!isRegistered()) { + passID(registerPrePass(std::move(p)), true); + isRegistered(true); + return false; + } + return true; + } + + // override PassManager::clearPass to clear pre-pass + static void clearPass() { + if (isRegistered()) { + clearPrePass(passID()); + isRegistered(true); + } + } +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..a0bc542b554654a77bda379869958fd2ff9498d6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx.h @@ -0,0 +1,33 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +TORCH_API std::shared_ptr ToONNX( + std::shared_ptr& state, + ::torch::onnx::OperatorExportTypes operator_export_type); +TORCH_API py::dict BlockToONNX( + Block* old_block, + Block* new_block, + ::torch::onnx::OperatorExportTypes operator_export_type, + py::dict& env, + py::set& values_in_env, + bool is_sub_block = false); +TORCH_API void NodeToONNX( + Node* old_node, + Block* new_block, + ::torch::onnx::OperatorExportTypes operator_export_type, + py::dict& env, + py::set& values_in_env); +TORCH_API void RemovePrintOps(std::shared_ptr& graph); +TORCH_API void PreprocessCaffe2Ops(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/cast_all_constant_to_floating.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/cast_all_constant_to_floating.h new file mode 100644 index 0000000000000000000000000000000000000000..39fbd77a87591372577bf2ce4c6261b4d25e5da0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/cast_all_constant_to_floating.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit { +// see .cpp for docs +TORCH_API void CastAllConstantToFloating(const std::shared_ptr& graph); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/constant_fold.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/constant_fold.h new file mode 100644 index 0000000000000000000000000000000000000000..347ed105b0974537e141aceca9457411b545e038 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/constant_fold.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +namespace torch::jit { + +const int ONNX_OPSET_9 = 9; +const int ONNX_OPSET_10 = 10; +const int ONNX_OPSET_11 = 11; +const int ONNX_OPSET_12 = 12; +const int ONNX_OPSET_13 = 13; +const int ONNX_OPSET_14 = 14; + +namespace onnx_constant_fold { + +at::Tensor IntToTensor(int64_t value); + +std::optional runTorchBackendForOnnx( + const Node* node, + std::vector& inputTensorValues, + int opset_version); +} // namespace onnx_constant_fold + +void ConstantFoldONNX( + std::shared_ptr& g, + std::map& paramDict, + int opset_version); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/constant_map.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/constant_map.h new file mode 100644 index 0000000000000000000000000000000000000000..a73ccef68eeea8e56a24b22f034759e3fb2726b3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/constant_map.h @@ -0,0 +1,117 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +#include +#include +#include + +namespace torch::jit { + +using ShapeDataMap = + std::unordered_map; + +class ConstantValueMap { + public: + static ConstantValueMap& getInstance(); + static void SetRank(const std::string& tensorName, size_t rankValue); + static bool HasRank(const std::string& tensorName); + static std::optional GetRank(const std::string& tensorName); + + static void SetAllGraphInputsStatic(bool all_static); + static std::optional GetAllGraphInputsStatic(); + + static void SetAllGraphInputsReliableComputed(bool computed); + static bool GetAllGraphInputsReliableComputed(); + + static void SetShape( + const std::string& tensorName, + const c10::SymbolicShape& shapeValue); + static bool HasShape(const std::string& tensorName); + static std::optional GetShape( + const std::string& tensorName); + + static void SetValue(const std::string& tensorName, const at::Tensor& value); + static bool HasValue(const std::string& tensorName); + static std::optional GetValue(const std::string& tensorName); + static void EraseValue(const std::string& tensorName); + + static std::vector GetCompleteShapeInto1DInt64Vector( + const c10::SymbolicShape& shape); + static std::optional> GetShapeInto1DInt64Vector( + const std::string& value_name); + static std::optional> + GetShapeInto1DInt64VectorWithOneUnknown(const std::string& value_name); + static std::vector GetValueInto1DInt64Vector( + const std::string& value_name); + + static void SetTypeReliable(const std::string& tensorName, bool reliable); + static bool HasTypeReliable(const std::string& tensorName); + static std::optional GetTypeReliable(const std::string& tensorName); + + static void SetUseInferredType( + const std::string& tensorName, + bool useInferredType); + static bool HasUseInferredType(const std::string& tensorName); + static std::optional GetUseInferredType(const std::string& tensorName); + + static void SetShapeValue( + const std::string& tensorName, + const c10::SymbolicShape& shapeValue); + static bool HasShapeValue(const std::string& tensorName); + static std::optional GetShapeValue( + const std::string& tensorName); + + static ShapeDataMap& GetInferredShapeData(); + + static SymbolDimMap& GetSymbolDimMap(); + static DimSymbolMap& GetDimSymbolMap(); + + static void UpdateValueName( + const std::string& old_name, + const std::string& new_name); + + static void PrintMaps(); + static void ClearMaps(); + ~ConstantValueMap() = default; + + ConstantValueMap& operator=(const ConstantValueMap&) = delete; + + private: + ConstantValueMap() = default; + + std::unordered_map rankMap; + std::unordered_map shapeMap; + std::unordered_map tensorValueMap; + // This map indicates whether the current type is reliably estimated or not. + std::unordered_map typeReliableMap; + // This map indicates whether the current type is estimated through inference + // or tracer. + std::unordered_map useInferredTypeMap; + // This map indicates a tensor value which represents a shape. + // We assume that the rank of the tensor value <= 1, and we ensure this when + // we write the processing logic for the operators. When the rank > 1, we + // should be able to rewrite the model so that the rank <= 1. The difference + // between shapeMap and shapeValueMap: shapeMap stores the shape of the tensor + // from a node. shapeValueMap stores the value of the tensor from a node when + // this tensor represents a shape. + std::unordered_map shapeValueMap; + // Stores earlier data propagation results so that they are accessible + // during future node-level shape inference. + ShapeDataMap inferredShapeData; + SymbolDimMap symbolDimMap; + DimSymbolMap dimSymbolMap; + // Stores if all graph-level inputs have static shape + std::optional allGraphInputsStatic; + // True if reliable has been computed for all graph inputs + bool allGraphInputsReliableComputed{}; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/deduplicate_initializers.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/deduplicate_initializers.h new file mode 100644 index 0000000000000000000000000000000000000000..9820f3f7a2345045d849925a5e005e3e2d1de2fd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/deduplicate_initializers.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit { + +void DeduplicateInitializers( + std::shared_ptr& g, + std::map& paramsDict, + bool is_train); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/eliminate_unused_items.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/eliminate_unused_items.h new file mode 100644 index 0000000000000000000000000000000000000000..0b4cd693bd74d270dc6cb440549b1a90362e108b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/eliminate_unused_items.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// EliminateUnusedItemsONNX pass is removing unused +// initializers and inputs, this is needed because +// dce pass is only removing unused fork inputs +void EliminateUnusedItemsONNX( + Block* b, + std::map& paramDict); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/eval_peephole.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/eval_peephole.h new file mode 100644 index 0000000000000000000000000000000000000000..4af16a22c7bf84f49d6c727ca6125907e7e81962 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/eval_peephole.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit { + +void EvalPeepholeONNX( + std::shared_ptr& g, + std::map& paramDict); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/fixup_onnx_controlflow.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/fixup_onnx_controlflow.h new file mode 100644 index 0000000000000000000000000000000000000000..9ae93de28bab2d9d41108c76adf0001788e4b246 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/fixup_onnx_controlflow.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +std::vector FixupONNXControlflowNode(Node* n, int opset_version); +void FixupONNXControlflowNodeOutputs(Node* n); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/function_extraction.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/function_extraction.h new file mode 100644 index 0000000000000000000000000000000000000000..71d441436eff786f0a97b89d40ed54113d6d1ab6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/function_extraction.h @@ -0,0 +1,69 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// This api will be used by serialization/export.cpp to extract function +// information. It should do conversion on graph to +// 1. Extract subgraph pattern of functions and define as local function +// node. +// 2. Replace subgraph pattern of functions with a single node reflecting +// that local function node type. +// Function attribute map information is also returned, as Torch IR cannot +// represent these info inside Graph object. +// export.cpp will serialize the ONNX model with function_proto with +// above information. +namespace torch::jit::onnx { + +// The following return types are used to track information regarding function +// attributes, that are unable to be traced through Torch IR. +// NodeAttrNameMap tracks mapping from attribute name of IR Node inside function +// subgraph, to function attribute name. Here's an example of exporting CELU and +// LayerNorm. +// +// clang-format off +// class M(torch.nn.Module): +// def __init__(self) -> None: +// super().__init__() +// self.lns = torch.nn.ModuleList([torch.nn.LayerNorm(3, eps = i) for i in range(2)]) +// self.celu1 = torch.nn.CELU(1.0) +// self.celu2 = torch.nn.CELU(2.0) + +// def forward(self, x: torch.Tensor, y: torch.Tensor, z: torch.Tensor) -> torch.Tensor: +// res1 = self.celu1(x) +// res2 = self.celu2(y) +// for ln in self.lns: +// z = ln(z) +// return res1 + res2 + z +// clang-format on +// +// Returning +// +// NodeAttrNameMap: +// { +// %1 : Float(2, 3) = onnx::Celu[alpha=2.](%y) : { +// 'alpha' : 'Celu_alpha' +// } +// } +// +// The info here helps graph._export_onnx to construct function attributes for +// onnx local FunctionProto. +using NodeAttrNameMap = std:: + unordered_map>; + +TORCH_API NodeAttrNameMap ONNXFunctionExtraction( + std::shared_ptr& graph, + const std::unordered_set& module_names, + const std::vector& param_names); + +TORCH_API void ONNXClearScopeRecords(); + +TORCH_API void ONNXTrackScopeAttributes( + std::shared_ptr& graph, + std::map& attributes); + +} // namespace torch::jit::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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/function_substitution.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/function_substitution.h new file mode 100644 index 0000000000000000000000000000000000000000..bfa5fff13e630eeae239c21909b4378ee5258194 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/function_substitution.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void ONNXFunctionCallSubstitution(Graph& graph); + +} + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/helper.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/helper.h new file mode 100644 index 0000000000000000000000000000000000000000..9cf0ae45c273fd295124056b89187a1c5b3dd867 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/helper.h @@ -0,0 +1,77 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +// Utility functions for PyTorch to ONNX conversion. + +static const int OPSET_VERSION_1 = 1; +static const int OPSET_VERSION_9 = 9; +static const int OPSET_VERSION_10 = 10; +static const int OPSET_VERSION_11 = 11; +static const int OPSET_VERSION_12 = 12; +static const int OPSET_VERSION_13 = 13; +static const int OPSET_VERSION_14 = 14; +static const int OPSET_VERSION_15 = 15; +static const int OPSET_VERSION_16 = 16; + +using ValueToParamPairMap = std::map>; + +using ParamMap = std::map; + +TORCH_API void buildParamsMapFromValueToParamsMap( + const ValueToParamPairMap& valsToParamsMap, + ParamMap& paramsDict); +TORCH_API ValueToParamPairMap +buildValueToParamsMap(Block* b, const ParamMap& paramsDict); +TORCH_API void eraseUnusedValuesFromMap(ValueToParamPairMap& valsToParamsMap); +TORCH_API void eraseUnusedBlockInputs(Block* b); + +TORCH_API Node* addNodeToBlock( + Block* block, + Symbol kind, + ArrayRef inputs); + +TORCH_API Value* addInputToBlock(Block* block); + +TORCH_API std::optional ONNXTypeToATenType(int32_t onnx_type); + +// Use int return type as no sable way exists to forward declare protobuf enum +TORCH_API int ATenTypeToOnnxType(at::ScalarType at_type); + +TORCH_API void ONNXLintGraph(const std::shared_ptr& graph); + +Node* createONNXUnsqueeze( + Graph* graph, + Node* n_to_insert_before, + Value* input, + int axis, + int opset_version); +Node* createONNXConstant( + Graph* graph, + Node* n_to_insert_before, + at::Tensor value); + +bool isValidToTransformToONNXConcatNode(Node* lc_node); + +Node* transformToONNXConcatNode( + Graph* graph, + Node* lc_node, + bool need_new_input, + int opset_version); + +class ScalarTypeHashFunction { + public: + size_t operator()(const c10::ScalarType& type) const { + return static_cast(type); + } +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/list_model_parameters.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/list_model_parameters.h new file mode 100644 index 0000000000000000000000000000000000000000..9dfad50d210487654dc553a00de925edbdaf1434 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/list_model_parameters.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API std::pair> list_module_parameters( + const Module& 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/naming.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/naming.h new file mode 100644 index 0000000000000000000000000000000000000000..174dadcf9e3021082fc265f28f76d70e6cf0ce87 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/naming.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::onnx { + +namespace ONNXScopeName { + +std::string createFullScopeName( + const std::string& class_name, + const std::string& variable_name); +std::string variableName(const torch::jit::ScopePtr& scope); +std::string variableNameFromRoot( + const torch::jit::ScopePtr& scope, + const std::string& layer_separator); +std::string className(const torch::jit::ScopePtr& scope); +std::string classNameFromRoot( + const torch::jit::ScopePtr& scope, + const std::string& layer_separator); +bool isCompatibleScope(const torch::jit::ScopePtr& scope); + +} // namespace ONNXScopeName + +TORCH_API void AssignScopedNamesForNodeAndValue(std::shared_ptr& graph); + +} // namespace torch::jit::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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/onnx_log.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/onnx_log.h new file mode 100644 index 0000000000000000000000000000000000000000..22162bacb8cd05e62a6ef144e6289807cf67180d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/onnx_log.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::jit::onnx { + +TORCH_API bool is_log_enabled(); + +TORCH_API void set_log_enabled(bool enabled); + +TORCH_API void set_log_output_stream(std::shared_ptr out_stream); + +TORCH_API std::ostream& _get_log_output_stream(); + +#define ONNX_LOG(...) \ + if (::torch::jit::onnx::is_log_enabled()) { \ + ::torch::jit::onnx::_get_log_output_stream() \ + << ::c10::str(__VA_ARGS__) << std::endl; \ + } + +} // namespace torch::jit::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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/autograd_function_process.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/autograd_function_process.h new file mode 100644 index 0000000000000000000000000000000000000000..53551bab18164c077c87c3e73802085fa6e8a822 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/autograd_function_process.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void ONNXAutogradFunctionProcess(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/common.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/common.h new file mode 100644 index 0000000000000000000000000000000000000000..50c1b40cdf180dcdf1684ed1f249db281773014e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/common.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// Functions used by both encapsulation and conversion. + +namespace torch::jit { + +struct IndexingPatternFinder { + public: + static std::vector FetchSliceAndSelect(const Node* node); + + private: + static bool IsSameSource(const Node* n, const Node* m); +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/pattern_conversion.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/pattern_conversion.h new file mode 100644 index 0000000000000000000000000000000000000000..0497bab7457257a94050bab0c73e00a402538d70 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/pattern_conversion.h @@ -0,0 +1,49 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +// Introduction +// +// The conversion part is called inside the onnx pass. +// In onnx pass, _run_symbolic_function will be called for each node in +// topological order. When it reaches the placeholder node, this function will +// be invoked. It will convert the nodes inside the sub-block based on pattern. +// By that time, it will have shape/type of upstream operators available. After +// the conversion is complete, the placeholder node will be removed, and nodes +// inside its sub-block converted. NodeToONNX will be called for these +// nodes, and they will be converted from ATen operator to ONNX operator. +// +// Note: Edit Pattern Conversion +// +// Each pattern is differentiated by the name attribute of placeholder node. +// The placeholder node is part of torch IR graph, After this function, the aten +// nodes under placeholder node subblock will be converted to ONNX and appended +// to the new_block, which is under the new ONNX graph. For the pattern +// conversion code, it can be divided into three parts. +// 1. Nodes in this pattern should be captured inside the subblock of +// Placeholder node after pattern encapsulation[see +// pattern_encapsulation.h]. These nodes will be converted based on +// pattern. This part of conversion is from aten to aten. It happens on +// the torch IR graph inside placeholder node subblock. +// 2. The second part of conversion is to convert the aten nodes produced +// into ONNX. This is done by calling NodeToONNX for each node. The new +// ONNX nodes are appended to the new_block, which is under the new ONNX +// graph. +// 3. The last part of conversion is to find and return, in the same order, +// the ONNX outputs corresponding to the original output for the +// placeholder node. +TORCH_API std::vector ConvertPatternFromSubblock( + Block* new_block, + Node* old_node, + py::dict& env, + py::set& values_in_env); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/pattern_encapsulation.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/pattern_encapsulation.h new file mode 100644 index 0000000000000000000000000000000000000000..8d5cce99154810fc5537be4e8615d3196d992023 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/pattern_encapsulation.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Introduction +// +// The encapsulation part will find the nodes of patterns, like how other +// pre-onnx passes are written. But instead of converting the nodes, it will +// encapsulate them into a sub-block of a new placeholder node. This part is +// called before onnx pass, so it runs before calling symbolic functions. +// +// Note: Why separate the function into two parts +// +// The purpose is to support conversions that depend on shape and type +// information. Shape and type information is only available after +// _jit_pass_onnx, which converts aten nodes to onnx nodes. So there is a +// interdependent issue. _jit_pass_onnx depends on preprocess passes to convert +// aten nodes into convertible condition, and preprocess passes depend on +// _jit_pass_onnx to convert upstream nodes and apply onnx shape inference. +// Separating the pass into two parts breaks the interdependency. +// +// Note: Edit Pattern Encapsulation +// +// Encapsulation step identifies the pattern, and copies the nodes into +// the subblock of a new placeholder node. The outputs of the new placeholder +// node are used in place of the original nodes instead. The category of the +// pattern is stored as attr::name. +TORCH_API std::optional EncapsulatePatternIntoSubblock(Node* n); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/peephole.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/peephole.h new file mode 100644 index 0000000000000000000000000000000000000000..e0adf3dda39b0931bde457bc45bf5c65812d6841 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/peephole.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +void PeepholeOptimizeONNX( + std::shared_ptr& graph, + int opset_version, + bool fixed_batch_size); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/prepare_division_for_onnx.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/prepare_division_for_onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..29d86fe75dd7ec7afaa4a6660abfae2a72c74ad9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/prepare_division_for_onnx.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Prepare division ops for ONNX export. This is necessary for and only used +// by ONNX export. +// +// The pass corrects the following: +// +// - aten::div(int, int) -> float is the python truediv operator. This doesn't +// exist in ONNX so we cast the ints to FloatTensors +// +TORCH_API void PrepareDivisionForONNX(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/preprocess_for_onnx.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/preprocess_for_onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..b714e438240c5005ad5f3c667ebf1c37bcbedb49 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/preprocess_for_onnx.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +void PreprocessForONNX(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/remove_inplace_ops_for_onnx.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/remove_inplace_ops_for_onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..37a04f8d6e0c6cb7a5a49326b47493e1499b5b32 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/remove_inplace_ops_for_onnx.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void RemoveInplaceOpsForONNX( + const std::shared_ptr& graph, + Module* model); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/scalar_type_analysis.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/scalar_type_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..8dde9341f60cfec4e72fc1d3ab408603473ac995 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/scalar_type_analysis.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void ScalarTypeAnalysisForONNX( + const std::shared_ptr& graph, + bool lowprecision_cast, + int opset_version); +void ScalarTypeAnalysisNodeForONNX(Node* n); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/shape_type_inference.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/shape_type_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..2f684c9cb83f73d78ce85871ad2ca16759470013 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/shape_type_inference.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace torch::jit { + +// Merges existing_type and inferred_type. +// Returns {merged type, whether or not inferred_type was used}. +// +// The inferred type will take higher precedence, since it is produced by ONNX +// shape inference, and is more compatible with ONNX. In cases where ONNX shape +// inference fails to produce an inferred type, or produces an inferred type +// that is incomplete, refer to existing type and fill in the gap that is +// missing. Currently the following cases are supported. +// 1. existing type: Tensor[], inferred type: Tensor[] +// For list of tensors, existing type does not store datatype nor shape for +// inner tensor. Thus inferred type always contain more information, and is +// returned. +// 2. existing type: Tensor, inferred type: Tensor +// Fill in missing info (shape, data type) for inferred type from existing +// type. +// 3. existing type: Scalar[], inferred type: Tensor +// ONNX represents list of scalars by 1-d Tensor. Return inferred type since +// it is more compatible with ONNX. +std::pair MergeInferredType( + const TypePtr& existing_type, + const TypePtr& inferred_type); + +void MergeInferredTypeAndSetMap( + Value* dest_v, + const TypePtr& existing_type, + const TypePtr& inferred_type); + +// Update graph input types with dynamic axes info. +// Axes that are marked as dynamic will be assigned as dynamic ShapeSymbol. +// Note it is possible for multiple axes to share the same ShapeSymbol, +// if they are defined as such in dynamic_axes. +TORCH_API void ONNXSetDynamicInputShape( + std::shared_ptr& graph, + const std::unordered_map< + std::string, + std::unordered_map>& dynamic_axes, + const std::vector& input_names); + +// Update graph output with types of output Tensors. +// If onnx_shape_inference is true, types of output Tensors will be compared and +// merged with inferred types. It is possible that inferred types contain +// dynamic axes, hence it takes precedence over types of output Tensors. +TORCH_API void ONNXAssignOutputShape( + std::shared_ptr& graph, + at::ArrayRef outputs, + const python::IODescriptor& desc, + bool onnx_shape_inference, + bool is_script, + int opset_version); + +// Replace None in output with Optional node (opset > 15) if it's +// script model. This helps align the output format in ONNX internal tests +// when comparing pytorch results with ONNX results, as they have different +// process for None in output. +void ReplaceGraphOutputNoneWithOptional( + std::shared_ptr& graph, + size_t outputs_index); +Node* ONNXOptionalNodeForNone(std::shared_ptr& graph); + +// Utilize ONNX Shape Inference for node. +// The node must have ONNX namespace, and is valid ONNX node according to spec. +// On successful ONNX shape inference runs, the function updates output types of +// n with inferred shape and type. Otherwise n is unchanged. +TORCH_API void ONNXShapeTypeInference( + Node* n, + const ParamMap& params_dict, + int opset_version); + +// Utilize ONNX Shape Inference for graph. +// Internally calls ONNXShapeTypeInference for each node, to achieve more +// coverage that skips only individual nodes if illegal, instead of skipping for +// the entire graph. +TORCH_API void ONNXShapeTypeInference( + std::shared_ptr& g, + const ParamMap& params_dict, + int opset_version); + +bool AllGraphInputsStatic(const Graph* g); +std::pair AreInputsReliableOrStatic(Node* n); +void UpdateReliable( + torch::jit::Value* output, + const std::pair& input_reliable, + bool no_type_warning = false); + +void UpdateReliable(torch::jit::Node* n); +void UpdateShapeConstantIfReliable(torch::jit::Value* output); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/unpack_quantized_weights.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/unpack_quantized_weights.h new file mode 100644 index 0000000000000000000000000000000000000000..4461870c64172a68fa33eaf57ba06e8c8776b3d7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx/unpack_quantized_weights.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace torch::jit { + +TORCH_API void UnpackQuantizedWeights( + std::shared_ptr& graph, + std::map& paramsDict); +TORCH_API void insertPermutes( + std::shared_ptr& graph, + std::map& paramsDict); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/pass_manager.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/pass_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..d3cc4bc3b3417402b0f97fdf15ce658c321ba885 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/pass_manager.h @@ -0,0 +1,139 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +/* `getCustomPrePasses()` returns a vector of passes that will be executed + * after differentiation but before any fusion. This is the de-facto location + * for compiler backends to insert passes. + * + * `getCustomPostPasses()` returns a vector of passes that will be + * executed after differentiation and after fusion (if any). This is the + * location for fusion cleanup passes if they are needed. + * + * Static registration of a pass can be done by creating a global + * `Register{Pre,Post}Pass r(Pass)` variable in a compilation unit. + * + * pass_manager.h uses a Meyer's singleton to store a vector of `Pass`es, which + * modify the IR graph in place. + */ + +namespace torch::jit { + +// A pass modifies a Graph in place. +using GraphPass = std::function&)>; + +// Since Passes are std::functions, we associate a UUID to each pass, this way +// if we want to deregister a pass, we have something to reference it by. +using GraphPassNameType = unsigned int; + +// Graph pass entries have a name associated with them +using GraphPassEntry = std::pair; + +// Return currently registered passes. Passes are stored in a static vector +TORCH_API std::vector>& +getCustomPostPasses(); +TORCH_API std::vector>& +getCustomPrePasses(); + +TORCH_API GraphPassNameType registerPostPass(GraphPass p); +TORCH_API GraphPassNameType registerPrePass(GraphPass p); + +// Look up pass by name passed in, remove it from registered passes +TORCH_API void clearPostPass(GraphPassNameType p); +TORCH_API void clearPrePass(GraphPassNameType p); + +// Remove all passes +TORCH_API void clearAllPostPasses(); +TORCH_API void clearAllPrePasses(); + +// LEGACY CALL +struct TORCH_API RegisterPostPass { + RegisterPostPass(GraphPass p); +}; + +using RegisterPass = RegisterPostPass; + +/* + * PassManager is a wrapper on the register/clear PostPass functions above. It + * will register the pass provided in "registerPass" and will hold on to its + * associated name that way clearPass can be later called and will delete the + * pass used to register when called. + * + * PassManager is templated because we want static variables based on a + * particular GraphPass. When deriving from PassManager, you should send as the + * template parameter your derived class as you would for the curiously + * recurring template pattern. This template parameter isn't actually used and + * is simply done to prevent static members from being shared across derived + * types. + */ +template +struct C10_EXPORT PassManager { + private: + // We want this class to be abstract because it's + virtual void abstract() = 0; + + protected: + /* + * isRegistered() will return if a pass has been registered + * isRegistered(true) will change the value of the internal static bool + * + * There's an internal static bool to this function to keep track of the + * state, this is so when functions are derived from this class, they don't + * have to worry about initializing the static members. + */ + static bool isRegistered(bool flip_bit = false) { + static bool val = false; + if (flip_bit) + val = !val; + return val; + } + + /* + * name() will return the name of the registered pass + * name(pass_name, true) will set the name of the pass + * Similarly to isRegistered we use an internal static variable to hold the + * name. + */ + static GraphPassNameType passID( + GraphPassNameType PassID = 0, + bool set = false) { + static GraphPassNameType pass_id = 0; + if (set) + pass_id = PassID; + return pass_id; + } + + public: + // registerPass(pass) will register the pass provided and set the + // name/isRegistered functions appropriately, it returns a bool value + // indicating whether the given pass is already registered previously. + static bool registerPass(GraphPass p) { + if (!isRegistered()) { + // If we don't already have a registered pass, register pass + // hold on to its name, change isRegistered to true + passID(registerPostPass(std::move(p)), true); + isRegistered(true); + return false; + } + return true; + } + + // Calls ClearPostPass(passID()) + static void clearPass() { + // If the pass is registered, clear it and change isRegistered to false. + if (isRegistered()) { + clearPostPass(passID()); + isRegistered(true); + } + } + + // clang-tidy requires virtual destructor; + virtual ~PassManager() = default; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole.h new file mode 100644 index 0000000000000000000000000000000000000000..ca9437fd7d99358ecfd0cae8287a20d797c5145d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// return true if graph is modified +TORCH_API bool PeepholeOptimize( + const std::shared_ptr& graph, + bool disable_shape_peepholes = false); +// return true if graph is modified +TORCH_API bool PeepholeOptimize( + Block* block, + bool disable_shape_peepholes = false); +// return true if graph is modified +TORCH_API bool FuseAddMM(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h new file mode 100644 index 0000000000000000000000000000000000000000..c5ed890ddcd1dda39d85048f1fbd2d9d2c4fe944 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Peephole Optimizes alias sensitive peepholes +// Currently this is invoked as part of PeepholeOptimize +// return true if graph is modified +// Optimizes on TensorType if shape_peepholes is true +TORCH_API bool PeepholeOptimizeAliasSensitive( + const std::shared_ptr& graph, + bool shape_peepholes); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_dict_idioms.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_dict_idioms.h new file mode 100644 index 0000000000000000000000000000000000000000..21bd2f97c159dc7f583b2365f8b3475a4bd0b545 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_dict_idioms.h @@ -0,0 +1,41 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Peephole Optimizes Dict Ops such as len() and __getitem__ +// 1. getitem optimizations +// Given a function like this: +// def foo(): +// d = {0 : 1} +// x = d[0] +// return x +// This pass produces (after dead code elimination): +// def foo(a, b): +// return 1 +// +// This optimization can only happen if the dict is not modified +// and the dict has constant, non overlapping keys. +// +// 2. len optimizations +// Given a function like this: +// def foo(): +// d = {0 : 1} +// return len(d) +// This pass produces (after dead code elimination): +// def foo(): +// return 1 +// +// This has the same requirements as the getitem optimizations. +// +// Currently this is invoked as part of PeepholeOptimize +// return true if graph is modified. +TORCH_API bool PeepholeOptimizeDictIdioms(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_list_idioms.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_list_idioms.h new file mode 100644 index 0000000000000000000000000000000000000000..e52aaed75d54cb8ad982dc84860372607b9c0fc9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_list_idioms.h @@ -0,0 +1,75 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Peephole Optimizes List ops such as len(li) and li[1]. +// 1. Construct/Unpack optimizations +// Given a function like this: +// def foo(a, b): +// li = [a, b] +// x, y = li +// return x, y +// This pass produces (after dead code elimination): +// def foo(a, b): +// return a, b +// +// This is only applied to lists that are not modified. +// +// 2. getitem optimizations +// Given a function like this: +// def foo(a, b): +// li = [a, b] +// x = li[0] +// return x +// This pass produces (after dead code elimination): +// def foo(a, b): +// return a +// +// This optimization can only happen if the list is not modified. +// +// 3. len optimizations +// Given a function like this: +// def foo(): +// li = [1, 2] +// return len(li) +// This pass produces (after dead code elimination): +// def foo(): +// return 2 +// +// This has the same requirements as the getitem optimizations. +// +// 4. ListConstruct + ListConstruct +// Given a function like this: +// def foo(): +// return [1, 2] + [3, 4] +// This pass produces (after dead code elimination): +// def foo(): +// return [1, 2, 3, 4] +// +// This is only applied to lists that are not modified. +// +// 5. Slice +// Given a function like this: +// def foo(): +// return [1, 2, 3, 4, 5][0:2] +// This pass produces (after deadcode elimination): +// def foo(): +// return [1, 2] +// +// Currently this is invoked as part of PeepholeOptimize +// return true if graph is modified. +// If `refine_list_len` is true will attempt to refine the len of lists through +// len comparisons and assertions. This does not generally optimize pytorch +// programs so it is not called by default in PeepholeOptimize. +TORCH_API bool PeepholeOptimizeListIdioms( + const std::shared_ptr& graph, + bool refine_list_len = false); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_non_tensor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_non_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..ce4416223c63307ed9e5bac3136f528ea6712d95 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_non_tensor.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// return true if graph is modified +// Optimizing General Graph Patterns that +// are not covered in peephole.cpp and peephole_list_idioms +TORCH_API bool PeepholeOptimizeNonTensor(const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/prepack_folding.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/prepack_folding.h new file mode 100644 index 0000000000000000000000000000000000000000..d609f83cd5074f084a0af47dbad5bdf171fa7ba8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/prepack_folding.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +using PrePackingOpsFilterFn = std::function; + +void PrePackingOpsFolder( + script::Module& m, + const PrePackingOpsFilterFn& is_foldable_op, + const std::string& attr_prefix); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/dedup_module_uses.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/dedup_module_uses.h new file mode 100644 index 0000000000000000000000000000000000000000..fdaac9df01811de7d826d4f1c816d1f33d5c16cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/dedup_module_uses.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +/** Recursively deduplicate multiple uses of the same module by + * creating an instance clone for each use of the module, which means + * the type will be the same as before and all the attributes will be + * copied, then we'll change the use of the original module to the use + * of cloned module in the Graph. + * + * This is done to ensure that modules can survive destructive passes + * without changing model behavior. For example, here: + * + * x = self.conv1(x) + * x = self.relu(x) + * x = self.conv2(x) + * x = self.relu(x) + * + * self.relu needs to be deduplicated for potential future destructive passes + * to work properly. + */ +TORCH_API void DedupModuleUses(Module& 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/finalize.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/finalize.h new file mode 100644 index 0000000000000000000000000000000000000000..8fb9403cf4beac11604c4d2a76fc9d17cd8abac6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/finalize.h @@ -0,0 +1,66 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +/** \brief Backend specific pass to fuse dequantize - op - quantize calls + * as quantized_op calls. + * + * Right now this is a fusion for fbgemm backend and only works for quantized + * conv op, we'll extend to more ops and more backends in the future. + * + * Currently supported fusion: + * q(conv2d(dq(a), dq(w), dq(b))) --> to_nchw(fbgemm_conv2d(prepack(to_nhwc(a)), + * prepack(to_nhwc(w)), + * prepack(to_nhwc(b)))) + * + * q(linear(dq(a), dq(w), dq(b))) --> to_nchw(fbgemm_linear(prepack(to_nhwc(a)), + * prepack(to_nhwc(w)), + * prepack(to_nhwc(b)))) + * + * \param graph the graph we want to apply fusion + */ +TORCH_API void QuantFusion( + std::shared_ptr& graph, + QuantType quant_type = QuantType::STATIC); + +/** \brief Insert prepack and unpack function in graph + * We want add pack/unpack functions for quantized weight because later we want + * to fold the packed weight as an attribute of the module, in order to reduce + * the cost of packing the weight on the fly in quantized models. + * + * Each quantized op has it's corresponding prepack/unpack function, + * right now, we only need to do prepack/unpack for quantized::linear + * and quantized::conv2d. + */ +TORCH_API void InsertPrepackUnpack(std::shared_ptr& graph); + +/** \brief Insert pack and unpack function in all graphs + * of module + * + * Go through graphs of all the methods of all child modules + * and call InsertPrepackUnpack on the graph. + */ +TORCH_API void InsertPrepackUnpack(Module& module); + +TORCH_API script::Module Finalize( + script::Module& module, + QuantType quant_type = QuantType::STATIC, + const std::vector& preserved_attrs = + std::vector()); + +TORCH_API void FoldQuantizedPrepackingOps(Module& module); + +TORCH_API Module FinalizeOnDevicePTQ( + Module& module, + QuantType quant_type, + const std::string& method_name); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/fusion_passes.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/fusion_passes.h new file mode 100644 index 0000000000000000000000000000000000000000..063c09a3cdc2aea3215225a315d2ff3c7b48b1f2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/fusion_passes.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { +TORCH_API void FuseQuantizedAddRelu(std::shared_ptr& graph); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/helper.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/helper.h new file mode 100644 index 0000000000000000000000000000000000000000..5e85cfcae7e732be65edecd8ab886350b53fb2c9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/helper.h @@ -0,0 +1,219 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::jit { + +using graph_rewrite_helper::getFuncName; + +// Vector of a module and the name of its method +using ModuleMethodVector = std::vector>; +// Map of quantization parameter name and value +// for example _scale, _zero_point, +// _scalar_type and _axis(for per channel quantization) +using QParamVector = std::vector>; + +// =========== helper functions for Value ========= +// Check if a value is weight, since we need to use weight observer +// for weight +TORCH_API bool isWeight(Value* v); + +// Check if a value is bias for conv and linear, which we do not +// quantize +TORCH_API bool isBiasOfConvOrLinear(Value* v); + +TORCH_API bool isEmbeddingBagNonInput(Value* v); + +// Get the use as scalar input of clamp ops for the input value +std::optional getClampScalarInputUse(Value* v); + +// For a given value `v`, get the list of values that we need to check +// if they are observed/quantized or not, if so, we can say the +// `v` is also observed/quantized, since we can derive +// the quantization parameters for `v` given the list of values +TORCH_API std::vector getPassThroughInputs(Value* v); + +// Clones the method by the name of orig_method_name into new_method_name method +TORCH_API void cloneMethod( + Module& module, + const std::string& orig_method_name, + const std::string& new_method_name); + +// Check if a value in the graph is a Scalar value +TORCH_API bool isScalar(Value* v); + +// Check if value is the input of the graph +TORCH_API bool hitGraphInput(Value* value); + +// Converts a mangled name, such as +// __torch__.torch.ao.nn.quantized.modules.conv.___torch_mangle_7.Conv2d +// into an unmangled name, such as +// __torch__.torch.ao.nn.quantized.modules.conv.Conv2d +TORCH_API std::string removeTorchMangle(const std::string& orig_name); + +// Return the module name that corresponds to the value. +TORCH_API std::optional getModuleName(Value* value); + +// =========== helper functions for Node ========= +TORCH_API bool isSingleInputGeneralShapeAtenFunction(Node* n); + +TORCH_API bool isSingleInputGeneralValueAtenFunction(Node* n); + +TORCH_API bool isSingleInputGeneralCallFunction(Node* n); + +TORCH_API bool isSingleInputGeneralAtenFunction(Node* n); + +TORCH_API bool isClamp(Node* n); + +// Check if the node will produce the same result regardless of whether +// the input tensor is quantized or not, example: aten::size +TORCH_API bool isTensorInfoNode(Node* n); + +// Check if this the propagate op that has single input, e.g. aten::cat +TORCH_API bool isPropagateQuantSingleInputOp(Node* n); + +// Check if this is the propagate op that has two inputs, e.g. aten::add +TORCH_API bool isPropagateQuantBinaryOp(Node* n); + +// Check if this is the node that we'll quantize or not quantize depending on +// whether the input of the node is quantized, example: aten::cat +TORCH_API bool isPropagateQuantOp(Node* n); + +// Check if the node is a binary op like aten::add and aten::mul and +// if the input 1 is a scalar, these ops will be quantized to +// quantized::{op}_scalar +TORCH_API bool isBinaryOpWithScalarInput(Node* n); + +TORCH_API std::optional> getFixedQParams( + Node* n); + +// We don't want to analyze the graph for some `builtin` CallFunctions +// like `linear` because we want to preserve the op boundary +TORCH_API bool userDefinedCallFunction(Node* n); + +// Check if the node has scalar input +TORCH_API bool hasScalarInput(Node* n); + +// Check if a node is quantizable +TORCH_API bool nodeQuantizable( + Node* n, + QuantType quant_type = QuantType::STATIC); + +// Nodes which only require quantization of weight value, eg. embedding_bag +bool isWeightOnlyStaticQuantOp(Node* n); + +// Check if a use of the value is quantizable, this depends on +// both the use node and the offset +TORCH_API bool useQuantizable(const Use& use, QuantType quant_type); + +// Given a CallFunction node, extract the graph of the called function +TORCH_API std::shared_ptr getCallFunctionGraph(Node* n); + +// Check if `use` is a CallFunction of name `func_name` and if value +// `v` is the nth argument (if provided) of the function +bool matchCallFuncToUse( + const Use& use, + const std::string& func_name, + std::optional nth_arg); + +// Check if `use` is a AtenFunction of name `func_name` and if value +// `v` is the nth argument (if provided) of the function +bool matchAtenFuncToUse( + const Use& use, + const std::string& func_name, + std::optional nth_arg); + +// =========== helper functions for Block ========= +// checks if a block will always raise an Exception +TORCH_API bool alwaysRaisesException(Block* block); + +// =========== helper functions for Module ========== +// TODO: remove +TORCH_API std::vector getModuleAccessPath( + Value* instance, + Value* self); +// TODO: remove +TORCH_API Module +findChildModule(const Module& module, const std::vector& path); + +// Given an CallMethod node, get the module instance corresponding +// to the instance Value +// TODO: refactor all current uses of this function to the Opt one +TORCH_API Module getInvokedModule(Module& module, Node* n, Value* self); + +// Given an CallMethod node, get the module instance corresponding +// to the instance Value if the instance is a module, otherwise return +// std::nullopt +std::optional getInvokedModuleOpt( + const Module& module, + Node* n, + Value* self); + +// ==================== filter functions for matches ============== +// filter to check Value `vname` is a constant of int value `value` +bool is_int_constant( + const Match& match, + const std::unordered_map& vmap, + const std::string& vname, + int value); + +// filter to check if the %alpha argument of aten::add is constant 1 +bool aten_add_alpha_is_one( + const Match& match, + const std::unordered_map& vmap); + +// filter to check if the functional in CallFunction is relu +bool is_functional_relu( + const Match& match, + const std::unordered_map& vmap); + +// filter to check if the module is torch.nn.ReLU +bool is_relu_module( + const Match& match, + const std::unordered_map& vmap); + +bool is_linear_module( + const Match& match, + const std::unordered_map& vmap); + +// TODO: add a macro to declare the filters +bool is_conv1d_module( + const Match& match, + const std::unordered_map& vmap); + +bool is_conv2d_module( + const Match& match, + const std::unordered_map& vmap); + +bool is_conv3d_module( + const Match& match, + const std::unordered_map& vmap); + +bool is_conv_transpose1d_module( + const Match& match, + const std::unordered_map& vmap); + +bool is_conv_transpose2d_module( + const Match& match, + const std::unordered_map& vmap); + +bool is_batchnorm2d_module( + const Match& match, + const std::unordered_map& vmap); + +bool is_batchnorm3d_module( + const Match& match, + const std::unordered_map& vmap); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/insert_observers.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/insert_observers.h new file mode 100644 index 0000000000000000000000000000000000000000..bbc0b3cd92209f86d377d6a05f6baffb1c0b9135 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/insert_observers.h @@ -0,0 +1,71 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace std { + +template <> +struct hash { + inline size_t operator()(const torch::jit::Module& arg) const { + return std::hash>()(arg._ivalue()); + } +}; + +} // namespace std + +namespace torch::jit { + +using QConfig = std::tuple; +using QConfigDict = std::unordered_map>; + +/** \brief Insert observer module and observer function call for + * the Tensors that needs to be observed. + * + * For each Tensor that needs to be observed in the method, insert observer + * module to the input module and add forward calls of observer to the specified + * method. + * + * \param module the input module + * \param method_name the method we want to insert observers for + * \param qconfig_dict the qconfig dictionary that specifies how + * each module is going to be quantized + * \param inplace whether we want to do inplace modification to the input module + * or clone the module + * \param is_dynamic whether the dynamic quantization script is being used. + */ +TORCH_API Module InsertObservers( + Module& module, + const std::string& method_name, + const QConfigDict& qconfig_dict, + bool inplace, + QuantType quant_type = QuantType::STATIC); + +/** \brief Insert observer module and observer method for + * the Tensors that needs to be observed. + * + * For each Tensor that needs to be observed in the method, insert observer + * module to the input module and observe_ methods to the module. + * This method is clone of mehtod_name with forward calls of observer added. + * + * \param module the input module + * \param method_name the method we want to insert observers for + * \param qconfig_dict the qconfig dictionary that specifies how + * each module is going to be quantized + * \param inplace whether we want to do inplace modification to the input module + * or clone the module + * \param is_dynamic whether the dynamic quantization script is being used. + */ +TORCH_API Module InsertObserversForOnDevicePTQ( + Module& module, + const std::string& method_name, + const QConfigDict& qconfig_dict, + bool inplace, + QuantType quant_type = QuantType::STATIC); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/insert_quant_dequant.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/insert_quant_dequant.h new file mode 100644 index 0000000000000000000000000000000000000000..2410ddf652b6641ce11520a49764b1b356bc220a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/insert_quant_dequant.h @@ -0,0 +1,49 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +/** Replicate quantize node for prim::If blocks, so that we can match + * quantization patterns in prim::If blocks + */ +TORCH_API void ReplicateQuant(std::shared_ptr& graph); + +/** Replicate dequantize node for each use, so that we can match + * quantization patterns + */ +TORCH_API void ReplicateDeQuant(std::shared_ptr& graph); + +/** \brief Insert quantize - dequantize calls to the Tensors + * that are observed in insert_observers pass + * + * For each Tensor that is observed, get the observer module and call + * calculate_qparam on the observer module to get quantization parameters + * and add quantize - int_repr - dequantize function calls using these + * parameters we also have special handling for quantizing "bias" right now. + * + * \param module the input module + * \param method_name the method we want to insert quantization calls for + */ +TORCH_API Module InsertQuantDeQuant( + Module& module, + const std::string& method_name, + bool inplace, + bool debug, + QuantType quant_type = QuantType::STATIC); + +TORCH_API Module InsertQuantDeQuantOnDevicePTQ( + Module& module, + const std::string& method_name, + bool inplace, + bool debug, + QuantType quant_type = QuantType::STATIC); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/quantization_patterns.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/quantization_patterns.h new file mode 100644 index 0000000000000000000000000000000000000000..8ce511b1e375368baabd643634940c39742eb9ca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/quantization_patterns.h @@ -0,0 +1,1269 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +struct QuantFusionInfo { + std::string quantized_op_name; + std::string pattern; + std::string replacement; + std::vector filters; +}; + +namespace { +std::string getExtraArgList(std::vector extra_args) { + return std::accumulate( + extra_args.begin(), + extra_args.end(), + std::string(), + [](const std::string& acc, const std::string& arg) { + return acc + ", " + arg; + }); +} + +// Get the pattern we want to replace the match with +std::string getAtenOpPattern( + const std::string& graph_header, + const std::string& op_name, + const std::vector& extra_op_args, + bool scalar_args = false) { + std::vector _extra_op_args = extra_op_args; + std::string aten_op_pattern = graph_header; + if (scalar_args) { + for (const auto& extra_arg : _extra_op_args) { + aten_op_pattern + .append(R"( + )") + .append(extra_arg) + .append("_scalar = aten::item(") + .append(extra_arg) + .append(")"); + } + + for (auto& _extra_op_arg : _extra_op_args) { + _extra_op_arg.append("_scalar"); + } + } + const auto& extra_op_arg_list = getExtraArgList(std::move(_extra_op_args)); + aten_op_pattern += R"( + %r = )"; + aten_op_pattern += op_name + "(" + "%a_quant" + extra_op_arg_list + ")"; + aten_op_pattern += R"( + return (%r) )"; + return aten_op_pattern; +} + +// generate ops for quantize pattern for a scalar value +std::string getQuantizeForScalar(const std::string& value) { + // 6 is `torch.float` ScalarType, we are creating a float scalar + // tensor from a scalar value + std::string quantize_pattern = R"( + )" + + value + "_float_scalar_type : int = prim::Constant[value=6]()"; + quantize_pattern += R"( + )" + + value + "_none : None = prim::Constant()"; + quantize_pattern += R"( + )" + + value + "_tensor : Tensor = aten::scalar_tensor(" + value + ", " + value + + "_float_scalar_type"; + for ([[maybe_unused]] const auto i : c10::irange(3)) { + quantize_pattern += ", " + value + "_none"; + } + quantize_pattern += ")"; + quantize_pattern += + R"( + )" + + value + "_quant = aten::quantize_per_tensor(" + value + "_tensor" + + getExtraArgList( + {value + "_scale", value + "_zero_point", value + "_dtype"}) + + ")"; + return quantize_pattern; +} + +std::string getDequantize(const std::string& value) { + return R"( + )" + + value + "_dequant = aten::dequantize(" + value + "_quant)"; +} + +std::string getItem(const std::string& value) { + return R"( + )" + + value + "_scalar : float = aten::item(" + value + "_dequant)"; +} + +// Patterns for the ops that inherit parameters from input +std::string getInputTensorQParamOpPattern( + const std::string& op_name, + const std::vector& extra_op_args) { + const auto& extra_op_arg_list = getExtraArgList(extra_op_args); + std::string op_pattern = "graph(%a_quant" + extra_op_arg_list + "):" + R"( + %a_dequant = aten::dequantize(%a_quant) + %r = )" + + op_name + "(" + "%a_dequant" + extra_op_arg_list + ")" + R"( + %r_scale : float = aten::q_scale(%a_quant) + %r_zero_point : int = aten::q_zero_point(%a_quant) + %r_dtype : int = prim::dtype(%a_quant) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + return op_pattern; +} + +// QuantFusionInfo for the ops that inherit parameters from input +QuantFusionInfo getInputTensorQParamOpFusionInfo( + const std::string& op_name, + const std::vector& extra_op_args) { + std::string op_pattern = + getInputTensorQParamOpPattern(op_name, extra_op_args); + const auto& extra_op_arg_list = getExtraArgList(extra_op_args); + std::string graph_header = "graph(%a_quant" + extra_op_arg_list + "):"; + std::string op_replacement = + getAtenOpPattern(graph_header, op_name, extra_op_args); + + return {op_name, std::move(op_pattern), std::move(op_replacement)}; +} + +// quant fusion for ops like `quantized::add_scalar`, `quantized::mul_scalar` +QuantFusionInfo getBinaryOpScalarFusionInfo( + const std::string& op_name, + const std::vector& extra_op_args, + const std::string& quantized_op_name, + const std::vector& extra_quantized_op_args, + const std::vector& filters = {}) { + std::string op_pattern = + getInputTensorQParamOpPattern(op_name, extra_op_args); + + const auto& extra_op_arg_list = getExtraArgList(extra_op_args); + std::string graph_header = "graph(%a_quant" + extra_op_arg_list + "):"; + std::string op_replacement = getAtenOpPattern( + graph_header, quantized_op_name, extra_quantized_op_args); + + return {op_name, std::move(op_pattern), std::move(op_replacement), filters}; +} + +QuantFusionInfo getClampOpFusionInfo( + const std::string& op_name, + const std::vector& extra_op_args) { + std::vector header_args = extra_op_args; + std::vector input_qparams = {"_scale", "_zero_point", "_dtype"}; + for (const auto& arg : extra_op_args) { + for (const auto& qparam : input_qparams) { + header_args.push_back(arg + qparam); + } + } + for (const auto& qparam : input_qparams) { + header_args.push_back("%r" + qparam); + } + const auto& extra_header_arg_list = getExtraArgList(std::move(header_args)); + std::string graph_header = "graph(%a_quant" + extra_header_arg_list + "):"; + std::string op_pattern = graph_header; + for (const auto& arg : extra_op_args) { + op_pattern += getQuantizeForScalar(arg); + op_pattern += getDequantize(arg); + op_pattern += getItem(arg); + } + op_pattern += getDequantize("%a"); + op_pattern += R"( + %r = )"; + std::vector scalar_extra_args; + scalar_extra_args.reserve(extra_op_args.size()); + for (const auto& arg : extra_op_args) { + scalar_extra_args.push_back(arg + "_scalar"); + } + op_pattern += op_name + "(" + "%a_dequant" + + getExtraArgList(std::move(scalar_extra_args)) + ")"; + // IR pattern common to all ops that inherit qparam from input + op_pattern += R"( + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + std::string aten_op_pattern = + getAtenOpPattern(graph_header, op_name, extra_op_args); + + return {op_name, std::move(op_pattern), std::move(aten_op_pattern)}; +} + +// Patterns for the ops that has fixed quantization parameters +QuantFusionInfo getFixedQParamOpFusionInfo( + const std::string& op_name, + const std::vector& extra_op_args, + bool is_symmetric) { + const auto& extra_op_arg_list = getExtraArgList(extra_op_args); + std::string graph_header = "graph(%a_quant" + extra_op_arg_list + "):"; + std::string op_pattern = graph_header; + op_pattern += R"( + %a_dequant = aten::dequantize(%a_quant) + %r = )"; + op_pattern += op_name + "(" + "%a_dequant" + extra_op_arg_list + ")"; + // IR pattern common to all ops with fixed quantization parameters for + // asymmetric quantization + std::string asym_fixed_qparam_op_suffix = R"( + %r_scale : float = prim::Constant[value=0.00390625]() + %r_zero_point : int = prim::Constant[value=0]() + %r_dtype : int = prim::Constant[value=13]() + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + std::string sym_fixed_qparam_op_suffix = R"( + %r_scale : float = prim::Constant[value=0.0078125]() + %r_zero_point : int = prim::Constant[value=128]() + %r_dtype : int = prim::Constant[value=13]() + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + op_pattern += + is_symmetric ? sym_fixed_qparam_op_suffix : asym_fixed_qparam_op_suffix; + + std::string aten_op_pattern = + getAtenOpPattern(graph_header, op_name, extra_op_args); + + return {op_name, std::move(op_pattern), std::move(aten_op_pattern)}; +} + +// filter that checks %b_scalar is a scalar +bool input_b_is_scalar( + const Match& match, + const std::unordered_map& vmap) { + const auto& match_vmap = match.values_map; + auto b_scalar = match_vmap.at(vmap.at("b_scalar")); + return isScalar(b_scalar); +} + +// Patterns for ops that require observation for output quantization parameters +// Example: +// +// before fusion: +// +// graph(%a_quant, %r_scale, %r_zero_point, %r_dtype): +// %a_dequant = aten::dequantize(%a_quant) +// %r = {op_name}(%a_dequant, {extra_args}) +// %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, +// %r_dtype) return (%r_quant) +// +// after fusion: +// +// graph(%a_quant, %r_scale, %r_zero_point, %r_dtype): +// %r_quant = {quantized_op_name}(%a_quant, {extra_args}, %r_scale, +// %r_zero_point) return (%r_quant) +QuantFusionInfo getObservedQParamOpFusionInfo( + const std::string& fp_op_name, + const std::string& q_op_name, + const std::vector& fp_extra_args, + const std::vector& q_extra_args) { + const auto& fp_extra_arg_list = getExtraArgList(fp_extra_args); + const auto& q_extra_arg_list = getExtraArgList(q_extra_args); + + std::string op_pattern = "graph(%a_quant" + fp_extra_arg_list + + ", %r_scale, %r_zero_point, %r_dtype):" + R"( + %a_dequant = aten::dequantize(%a_quant) + %r = )" + + fp_op_name + "(" + "%a_dequant" + fp_extra_arg_list + ")" + R"( + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + std::string aten_op_pattern = "graph(%a_quant" + fp_extra_arg_list + + ", %r_scale, %r_zero_point, %r_dtype):" + R"( + %r_quant = )" + + q_op_name + "(%a_quant" + q_extra_arg_list + + ", %r_scale, %r_zero_point)" + R"( + return (%r_quant) )"; + + return {q_op_name, std::move(op_pattern), std::move(aten_op_pattern)}; +} + +} // namespace + +static std::vector quant_fusion_pattern_and_replacements() { + // aten::conv1d + std::string conv1d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv1d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv1d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // aten::conv1d - aten::relu + std::string conv1d_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv1d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %conv_out = aten::conv1d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r = aten::relu(%conv_out) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // aten::conv1d - aten::relu_ + std::string conv1d_inplace_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv1d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %conv_out = aten::conv1d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r = aten::relu_(%conv_out) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // quantized::conv1d + std::string quantized_conv1d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %r_quant = quantized::conv1d(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r_quant) )"; + + // quantized::conv1d_relu + std::string quantized_conv1d_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %r_quant = quantized::conv1d_relu(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r_quant) )"; + + // aten::conv2d + std::string conv2d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv2d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv2d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // aten::conv2d - aten::relu + std::string conv2d_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv2d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %conv_out = aten::conv2d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r = aten::relu(%conv_out) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // aten::conv2d - aten::relu_ + std::string conv2d_inplace_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv2d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %conv_out = aten::conv2d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r = aten::relu_(%conv_out) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // quantized::conv2d + std::string quantized_conv2d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %r_quant = quantized::conv2d(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r_quant) )"; + + // quantized::conv2d_relu + std::string quantized_conv2d_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %r_quant = quantized::conv2d_relu(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r_quant) )"; + + // aten::conv3d + std::string conv3d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv3d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv3d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // aten::conv3d - aten::relu + std::string conv3d_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv3d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %conv_out = aten::conv3d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r = aten::relu(%conv_out) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // aten::conv3d - aten::relu_ + std::string conv3d_inplace_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv3d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %conv_out = aten::conv3d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + %r = aten::relu_(%conv_out) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // quantized::conv3d + std::string quantized_conv3d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %r_quant = quantized::conv3d(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r_quant) )"; + + // quantized::conv3d_relu + std::string quantized_conv3d_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %dilation, %groups): + %r_quant = quantized::conv3d_relu(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r_quant) )"; + + // aten::conv_transpose1d + std::string conv_transpose1d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %output_padding, %groups, %dilation): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv_transpose1d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv_transpose1d(%a_dequant, %w_dequant, %b, %stride, %padding, %output_padding, %groups, %dilation) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // quantized::conv_transpose1d + std::string quantized_conv_transpose1d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %output_padding, %groups, %dilation): + %r_quant = quantized::conv_transpose1d(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r_quant) )"; + + // aten::conv_transpose2d + std::string conv_transpose2d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %output_padding, %groups, %dilation): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::conv_transpose2d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv_transpose2d(%a_dequant, %w_dequant, %b, %stride, %padding, %output_padding, %groups, %dilation) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // quantized::conv_transpose1d + std::string quantized_conv_transpose2d = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype, %stride, %padding, %output_padding, %groups, %dilation): + %r_quant = quantized::conv_transpose2d(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r_quant) )"; + + std::string add_relu = R"( +graph(%a_quant, %b_quant, %alpha, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_add = aten::add(%a_dequant, %b_dequant, %alpha) + %r_relu = aten::relu(%r_add) + %r = aten::quantize_per_tensor(%r_relu, %scale, %zero_point, %dtype) + return (%r) )"; + + std::string add_inplace_relu = R"( +graph(%a_quant, %b_quant, %alpha, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_add = aten::add(%a_dequant, %b_dequant, %alpha) + %r_relu = aten::relu_(%r_add) + %r = aten::quantize_per_tensor(%r_relu, %scale, %zero_point, %dtype) + return (%r) )"; + + std::string inplace_add_relu = R"( +graph(%a_quant, %b_quant, %alpha, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_add = aten::add_(%a_dequant, %b_dequant, %alpha) + %r_relu = aten::relu(%r_add) + %r = aten::quantize_per_tensor(%r_relu, %scale, %zero_point, %dtype) + return (%r) )"; + + std::string inplace_add_inplace_relu = R"( +graph(%a_quant, %b_quant, %alpha, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_add = aten::add_(%a_dequant, %b_dequant, %alpha) + %r_relu = aten::relu_(%r_add) + %r = aten::quantize_per_tensor(%r_relu, %scale, %zero_point, %dtype) + return (%r) )"; + + std::string quantized_add_relu = R"( +graph(%a_quant, %b_quant, %alpha, %scale, %zero_point, %dtype): + %r = quantized::add_relu(%a_quant, %b_quant, %scale, %zero_point) + return (%r) )"; + + // aten::linear + std::string linear = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::linear_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %r = aten::linear(%a_dequant, %w_dequant, %b) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + std::string linear_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::linear_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %linear_out = aten::linear(%a_dequant, %w_dequant, %b) + %r = aten::relu(%linear_out) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + std::string linear_inplace_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype): + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::linear_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %linear_out = aten::linear(%a_dequant, %w_dequant, %b) + %r = aten::relu_(%linear_out) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // quantized::linear + std::string quantized_linear = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype): + %r = quantized::linear(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r) )"; + + std::string quantized_linear_relu = R"( +graph(%a_quant, %packed_params, %r_scale, %r_zero_point, %r_dtype): + %r = quantized::linear_relu(%a_quant, %packed_params, %r_scale, %r_zero_point) + return (%r) )"; + + std::string cat = R"( +graph(%input_quant, %dim, %r_scale, %r_zero_point, %r_dtype): + %input_dequant = aten::dequantize(%input_quant) + %r = aten::cat(%input_dequant, %dim) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + std::string quantized_cat = R"( +graph(%input_quant, %dim, %r_scale, %r_zero_point, %r_dtype): + %r_quant = quantized::cat(%input_quant, %dim, %r_scale, %r_zero_point) + return (%r_quant) )"; + + // aten::add + std::string add = R"( +graph(%a_quant, %b_quant, %alpha, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_add = aten::add(%a_dequant, %b_dequant, %alpha) + %r = aten::quantize_per_tensor(%r_add, %scale, %zero_point, %dtype) + return (%r) )"; + + // TODO: add %dtype after when https://github.com/pytorch/pytorch/issues/34351 + // is fixed + // quantized::add + std::string quantized_add = R"( +graph(%a_quant, %b_quant, %alpha, %scale, %zero_point, %dtype): + %r = quantized::add(%a_quant, %b_quant, %scale, %zero_point) + return (%r) )"; + + // aten::add_ + std::string inplace_add = R"( +graph(%a_quant, %b_quant, %alpha, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_add = aten::add_(%a_dequant, %b_dequant, %alpha) + %r = aten::quantize_per_tensor(%r_add, %scale, %zero_point, %dtype) + return (%r) )"; + + auto add_scalar = getBinaryOpScalarFusionInfo( + "aten::add", + {"%b_scalar", "%alpha"}, + "quantized::add_scalar", + {"%b_scalar"}, + {aten_add_alpha_is_one, input_b_is_scalar}); + + auto add_scalar_out = getBinaryOpScalarFusionInfo( + "aten::add_", + {"%b_scalar", "%alpha"}, + "quantized::add_scalar_out", + {"%b_scalar", "%a_quant"}, + {aten_add_alpha_is_one, input_b_is_scalar}); + + // quantized::add_scalar_relu -- fusing quantized::add_scalar + // and aten::relu + auto quantized_add_scalar_relu_pattern = R"( +graph(%a_quant, %b_scalar): + %r_add = quantized::add_scalar(%a_quant, %b_scalar) + %r = aten::relu(%r_add) + return (%r) )"; + + auto quantized_add_scalar_inplace_relu_pattern = R"( +graph(%a_quant, %b_scalar): + %r_add = quantized::add_scalar(%a_quant, %b_scalar) + %r = aten::relu_(%r_add) + return (%r) )"; + + auto quantized_add_scalar_relu_replacement = R"( +graph(%a_quant, %b_scalar): + %r = quantized::add_scalar_relu(%a_quant, %b_scalar) + return (%r) )"; + + // quantized::add_scalar_relu_out -- fusing quantized::add_scalarOut + // and aten::relu + auto quantized_add_scalar_relu_out_pattern = R"( +graph(%a_quant, %b_scalar): + %r_add = quantized::add_scalar_out(%a_quant, %b_scalar, %a_quant) + %r = aten::relu(%r_add) + return (%r) )"; + + auto quantized_add_scalar_inplace_relu_out_pattern = R"( +graph(%a_quant, %b_scalar): + %r_add = quantized::add_scalar_out(%a_quant, %b_scalar, %a_quant) + %r = aten::relu_(%r_add) + return (%r) )"; + + auto quantized_add_scalar_relu_out_replacement = R"( +graph(%a_quant, %b_scalar): + %r = quantized::add_scalar_relu_out(%a_quant, %b_scalar, %a_quant) + return (%r) )"; + + // quantized::batch_norm + std::string batch_norm = R"( +graph(%a_quant, %weight, %bias, %mean, %var, %training, %eaf, %eps, %7, %scale, %zero_point, %scalar_type): + %a_dequant = aten::dequantize(%a_quant) + %r_bn = aten::batch_norm(%a_dequant, %weight, %bias, %mean, %var, %training, %eaf, %eps, %7) + %r = aten::quantize_per_tensor(%r_bn, %scale, %zero_point, %scalar_type) + return (%r) )"; + std::string quantized_batch_norm = R"( +graph(%a_quant, %weight, %bias, %mean, %var, %training, %eaf, %eps, %7, %scale, %zero_point, %scalar_type): + %r = quantized::batch_norm(%a_quant, %weight, %bias, %mean, %var, %eps, %scale, %zero_point) + return (%r) )"; + + std::string batch_norm_relu = R"( +graph(%a_quant, %weight, %bias, %mean, %var, %training, %eaf, %eps, %7, %scale, %zero_point, %scalar_type): + %a_dequant = aten::dequantize(%a_quant) + %bn_out = aten::batch_norm(%a_dequant, %weight, %bias, %mean, %var, %training, %eaf, %eps, %7) + %relu = aten::relu(%bn_out) + %r = aten::quantize_per_tensor(%relu, %scale, %zero_point, %scalar_type) + return (%r) )"; + std::string batch_norm_inplace_relu = R"( +graph(%a_quant, %weight, %bias, %mean, %var, %training, %eaf, %eps, %7, %scale, %zero_point, %scalar_type): + %a_dequant = aten::dequantize(%a_quant) + %bn_out = aten::batch_norm(%a_dequant, %weight, %bias, %mean, %var, %training, %eaf, %eps, %7) + %relu = aten::relu_(%bn_out) + %r = aten::quantize_per_tensor(%relu, %scale, %zero_point, %scalar_type) + return (%r) )"; + + std::string quantized_batch_norm_relu = R"( +graph(%a_quant, %weight, %bias, %mean, %var, %training, %eaf, %eps, %7, %scale, %zero_point, %scalar_type): + %r = quantized::batch_norm_relu(%a_quant, %weight, %bias, %mean, %var, %eps, %scale, %zero_point) + return (%r) )"; + + // aten::mul + std::string mul = R"( +graph(%a_quant, %b_quant, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_mul = aten::mul(%a_dequant, %b_dequant) + %r = aten::quantize_per_tensor(%r_mul, %scale, %zero_point, %dtype) + return (%r) )"; + + // aten::mul_ + std::string inplace_mul = R"( +graph(%a_quant, %b_quant, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_mul = aten::mul_(%a_dequant, %b_dequant) + %r = aten::quantize_per_tensor(%r_mul, %scale, %zero_point, %dtype) + return (%r) )"; + + // quantized::mul + std::string quantized_mul = R"( +graph(%a_quant, %b_quant, %scale, %zero_point, %dtype): + %r = quantized::mul(%a_quant, %b_quant, %scale, %zero_point) + return (%r) )"; + + auto mul_scalar = getBinaryOpScalarFusionInfo( + "aten::mul", + {"%b_scalar"}, + "quantized::mul_scalar", + {"%b_scalar"}, + {input_b_is_scalar}); + + auto mul_scalar_out = getBinaryOpScalarFusionInfo( + "aten::mul_", + {"%b_scalar"}, + "quantized::mul_scalar_out", + {"%b_scalar", "%a_quant"}, + {input_b_is_scalar}); + + // quantized::mul_relu + std::string mul_relu = R"( +graph(%a_quant, %b_quant, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_mul = aten::mul(%a_dequant, %b_dequant) + %r_relu = aten::relu(%r_mul) + %r = aten::quantize_per_tensor(%r_relu, %scale, %zero_point, %dtype) + return (%r) )"; + + std::string mul_inplace_relu = R"( +graph(%a_quant, %b_quant, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_mul = aten::mul(%a_dequant, %b_dequant) + %r_relu = aten::relu_(%r_mul) + %r = aten::quantize_per_tensor(%r_relu, %scale, %zero_point, %dtype) + return (%r) )"; + + std::string inplace_mul_relu = R"( +graph(%a_quant, %b_quant, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_mul = aten::mul_(%a_dequant, %b_dequant) + %r_relu = aten::relu(%r_mul) + %r = aten::quantize_per_tensor(%r_relu, %scale, %zero_point, %dtype) + return (%r) )"; + + std::string inplace_mul_inplace_relu = R"( +graph(%a_quant, %b_quant, %scale, %zero_point, %dtype): + %a_dequant = aten::dequantize(%a_quant) + %b_dequant = aten::dequantize(%b_quant) + %r_mul = aten::mul_(%a_dequant, %b_dequant) + %r_relu = aten::relu_(%r_mul) + %r = aten::quantize_per_tensor(%r_relu, %scale, %zero_point, %dtype) + return (%r) )"; + + std::string quantized_mul_relu = R"( +graph(%a_quant, %b_quant, %scale, %zero_point, %dtype): + %r = quantized::mul_relu(%a_quant, %b_quant, %scale, %zero_point) + return (%r) )"; + + // quantized::mul_scalar_relu -- fusing quantized::mul_scalar + // and aten::relu + auto quantized_mul_scalar_relu_pattern = R"( +graph(%a_quant, %b_scalar): + %r_mul = quantized::mul_scalar(%a_quant, %b_scalar) + %r = aten::relu(%r_mul) + return (%r) )"; + + auto quantized_mul_scalar_inplace_relu_pattern = R"( +graph(%a_quant, %b_scalar): + %r_mul = quantized::mul_scalar(%a_quant, %b_scalar) + %r = aten::relu_(%r_mul) + return (%r) )"; + + auto quantized_mul_scalar_relu_replacement = R"( +graph(%a_quant, %b_scalar): + %r = quantized::mul_scalar_relu(%a_quant, %b_scalar) + return (%r) )"; + + // quantized::mul_scalar_relu_out -- fusing quantized::mul_scalarOut + // and aten::relu + auto quantized_mul_scalar_relu_out_pattern = R"( +graph(%a_quant, %b_scalar): + %r_mul = quantized::mul_scalar_out(%a_quant, %b_scalar, %a_quant) + %r = aten::relu(%r_mul) + return (%r) )"; + + auto quantized_mul_scalar_inplace_relu_out_pattern = R"( +graph(%a_quant, %b_scalar): + %r_mul = quantized::mul_scalar_out(%a_quant, %b_scalar, %a_quant) + %r = aten::relu_(%r_mul) + return (%r) )"; + + auto quantized_mul_scalar_relu_out_replacement = R"( +graph(%a_quant, %b_scalar): + %r = quantized::mul_scalar_relu_out(%a_quant, %b_scalar, %a_quant) + return (%r) )"; + + // quantized::elu + std::string elu = R"( +graph(%a_quant, %alpha, %scale, %input_scale, %r_scale, %r_zero_point, %r_dtype): + %a_dequant = aten::dequantize(%a_quant) + %r = aten::elu(%a_dequant, %alpha, %scale, %input_scale) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + std::string quantized_elu = R"( +graph(%a_quant, %alpha, %scale, %input_scale, %r_scale, %r_zero_point, %r_dtype): + %r_quant = quantized::elu(%a_quant, %r_scale, %r_zero_point, %alpha, %scale, %input_scale) + return (%r_quant) )"; + + std::string elu_ = R"( +graph(%a_quant, %alpha, %scale, %input_scale, %r_scale, %r_zero_point, %r_dtype): + %a_dequant = aten::dequantize(%a_quant) + %r = aten::elu_(%a_dequant, %alpha, %scale, %input_scale) + %r_quant = aten::quantize_per_tensor(%r, %r_scale, %r_zero_point, %r_dtype) + return (%r_quant) )"; + + // ============= General Ops that inherit quantization parameters from input + // tensor ============= + auto avg_pool1d = getInputTensorQParamOpFusionInfo( + "aten::avg_pool1d", + {"%kernel_size", + "%stride", + "%padding", + "%ceil_mode", + "%count_include_pad"}); + + auto avg_pool2d = getInputTensorQParamOpFusionInfo( + "aten::avg_pool2d", + {"%kernel_size", + "%stride", + "%padding", + "%ceil_mode", + "%count_include_pad", + "%divisor_override"}); + + auto avg_pool3d = getInputTensorQParamOpFusionInfo( + "aten::avg_pool3d", + {"%kernel_size", + "%stride", + "%padding", + "%ceil_mode", + "%count_include_pad", + "%divisor_override"}); + + auto adaptive_avg_pool1d = getInputTensorQParamOpFusionInfo( + "aten::adaptive_avg_pool1d", {"%output_size"}); + + auto adaptive_avg_pool2d = getInputTensorQParamOpFusionInfo( + "aten::adaptive_avg_pool2d", {"%output_size"}); + + auto adaptive_avg_pool3d = getInputTensorQParamOpFusionInfo( + "aten::adaptive_avg_pool3d", {"%output_size"}); + + auto mean1 = getInputTensorQParamOpFusionInfo("aten::mean", {"%dim"}); + + auto mean2 = getInputTensorQParamOpFusionInfo( + "aten::mean", {"%dim", "%keepdim", "%out"}); + + auto upsample_nearest1d_vec = getInputTensorQParamOpFusionInfo( + "aten::upsample_nearest1d", {"%output_size", "%scale_factors"}); + + auto upsample_nearest2d_vec = getInputTensorQParamOpFusionInfo( + "aten::upsample_nearest2d", {"%output_size", "%scale_factors"}); + + auto upsample_nearest3d_vec = getInputTensorQParamOpFusionInfo( + "aten::upsample_nearest3d", {"%output_size", "%scale_factors"}); + + auto upsample_linear1d_vec = getInputTensorQParamOpFusionInfo( + "aten::upsample_linear1d", + {"%output_size", "%align_corners", "%scale_factors"}); + + auto upsample_bilinear2d_vec = getInputTensorQParamOpFusionInfo( + "aten::upsample_bilinear2d", + {"%output_size", "%align_corners", "%scale_factors"}); + + auto upsample_trilinear3d_vec = getInputTensorQParamOpFusionInfo( + "aten::upsample_trilinear3d", + {"%output_size", "%align_corners", "%scale_factors"}); + + auto upsample_nearest1d = getInputTensorQParamOpFusionInfo( + "aten::upsample_nearest1d", {"%output_size", "%scales"}); + + auto upsample_nearest2d = getInputTensorQParamOpFusionInfo( + "aten::upsample_nearest2d", {"%output_size", "%scale_h", "%scale_w"}); + + auto upsample_nearest3d = getInputTensorQParamOpFusionInfo( + "aten::upsample_nearest3d", + {"%output_size", "%scale_d", "%scale_h", "%scale_w"}); + + auto upsample_linear1d = getInputTensorQParamOpFusionInfo( + "aten::upsample_linear1d", {"%output_size", "%align_corners", "%scales"}); + + auto upsample_bilinear2d = getInputTensorQParamOpFusionInfo( + "aten::upsample_bilinear2d", + {"%output_size", "%align_corners", "%scale_h", "%scale_w"}); + + auto upsample_trilinear3d = getInputTensorQParamOpFusionInfo( + "aten::upsample_trilinear3d", + {"%output_size", "%align_corners", "%scale_d", "%scale_h", "%scale_w"}); + + auto clamp = getClampOpFusionInfo("aten::clamp", {"%min", "%max"}); + + auto hardtanh = getClampOpFusionInfo("aten::hardtanh", {"%min", "%max"}); + + auto hardtanh_ = getClampOpFusionInfo("aten::hardtanh_", {"%min", "%max"}); + + auto leaky_relu = + getInputTensorQParamOpFusionInfo("aten::leaky_relu", {"%negative_slope"}); + + auto leaky_relu_ = getInputTensorQParamOpFusionInfo( + "aten::leaky_relu_", {"%negative_slope"}); + + // Ops with fixed quantization parameters + auto hardsigmoid = getFixedQParamOpFusionInfo("aten::hardsigmoid", {}, false); + + auto hardsigmoid_ = + getFixedQParamOpFusionInfo("aten::hardsigmoid_", {}, false); + + auto sigmoid = getFixedQParamOpFusionInfo("aten::sigmoid", {}, false); + + auto sigmoid_ = getFixedQParamOpFusionInfo("aten::sigmoid_", {}, false); + + auto tanh = getFixedQParamOpFusionInfo("aten::tanh", {}, true); + + auto tanh_ = getFixedQParamOpFusionInfo("aten::tanh_", {}, true); + + auto hardswish = getObservedQParamOpFusionInfo( + "aten::hardswish", "quantized::hardswish", {}, {}); + + auto hardswish_ = getObservedQParamOpFusionInfo( + "aten::hardswish_", "quantized::hardswish", {}, {}); + + auto layer_norm = getObservedQParamOpFusionInfo( + "aten::layer_norm", + "quantized::layer_norm", + {"%normalized_shape", "%weight", "%bias", "%eps", "%cudnn_enabled"}, + {"%normalized_shape", "%weight", "%bias", "%eps"}); + + auto group_norm = getObservedQParamOpFusionInfo( + "aten::group_norm", + "quantized::group_norm", + {"%num_groups", "%weight", "%bias", "%eps", "%cudnn_enabled"}, + {"%num_groups", "%weight", "%bias", "%eps"}); + + auto instance_norm = getObservedQParamOpFusionInfo( + "aten::instance_norm", + "quantized::instance_norm", + {"%weight", + "%bias", + "%running_mean", + "%running_var", + "%use_input_stats", + "%momentum", + "%eps", + "%cudnn_enabled"}, + {"%weight", "%bias", "%eps"}); + + return { + {"quantized::conv1d", std::move(conv1d), std::move(quantized_conv1d)}, + {"quantized::conv1d_relu", std::move(conv1d_relu), quantized_conv1d_relu}, + {"quantized::conv1d_relu", + std::move(conv1d_inplace_relu), + std::move(quantized_conv1d_relu)}, + {"quantized::conv2d", std::move(conv2d), std::move(quantized_conv2d)}, + {"quantized::conv2d_relu", std::move(conv2d_relu), quantized_conv2d_relu}, + {"quantized::conv2d_relu", + std::move(conv2d_inplace_relu), + std::move(quantized_conv2d_relu)}, + {"quantized::conv3d", std::move(conv3d), std::move(quantized_conv3d)}, + {"quantized::conv3d_relu", std::move(conv3d_relu), quantized_conv3d_relu}, + {"quantized::conv3d_relu", + std::move(conv3d_inplace_relu), + std::move(quantized_conv3d_relu)}, + {"quantized::conv_transpose1d", + std::move(conv_transpose1d), + std::move(quantized_conv_transpose1d)}, + {"quantized::conv_transpose2d", + std::move(conv_transpose2d), + std::move(quantized_conv_transpose2d)}, + {"quantized::linear", std::move(linear), std::move(quantized_linear)}, + {"quantized::linear_relu", std::move(linear_relu), quantized_linear_relu}, + {"quantized::linear_relu", + std::move(linear_inplace_relu), + std::move(quantized_linear_relu)}, + {"quantized::add_relu", + std::move(add_relu), + quantized_add_relu, + {aten_add_alpha_is_one}}, + {"quantized::add_relu", + std::move(add_inplace_relu), + quantized_add_relu, + {aten_add_alpha_is_one}}, + {"quantized::add_relu", + std::move(inplace_add_relu), + quantized_add_relu, + {aten_add_alpha_is_one}}, + {"quantized::add_relu", + std::move(inplace_add_inplace_relu), + std::move(quantized_add_relu), + {aten_add_alpha_is_one}}, + std::move(add_scalar), + std::move(add_scalar_out), + // note that these must come after quantized::add_scalar and + // quantized::add_scalar_out patterns + {"quantized::add_scalar_relu", + quantized_add_scalar_relu_pattern, + quantized_add_scalar_relu_replacement}, + {"quantized::add_scalar_relu", + quantized_add_scalar_inplace_relu_pattern, + quantized_add_scalar_relu_replacement}, + {"quantized::add_scalar_relu_out", + quantized_add_scalar_relu_out_pattern, + quantized_add_scalar_relu_out_replacement}, + {"quantized::add_scalar_relu_out", + quantized_add_scalar_inplace_relu_out_pattern, + quantized_add_scalar_relu_out_replacement}, + {"quantized::add", + std::move(add), + quantized_add, + {aten_add_alpha_is_one}}, + {"quantized::add", + std::move(inplace_add), + std::move(quantized_add), + {aten_add_alpha_is_one}}, + {"quantized::cat", std::move(cat), std::move(quantized_cat)}, + {"quantized::batch_norm", + std::move(batch_norm), + std::move(quantized_batch_norm)}, + {"quantized::batch_norm_relu", + std::move(batch_norm_relu), + quantized_batch_norm_relu}, + {"quantized::batch_norm_relu", + std::move(batch_norm_inplace_relu), + std::move(quantized_batch_norm_relu)}, + std::move(mul_scalar), + std::move(mul_scalar_out), + // note that these must come after quantized::mul_scalar and + // quantized::mul_scalar_out patterns + {"quantized::mul_scalar_relu", + quantized_mul_scalar_relu_pattern, + quantized_mul_scalar_relu_replacement}, + {"quantized::mul_scalar_relu", + quantized_mul_scalar_inplace_relu_pattern, + quantized_mul_scalar_relu_replacement}, + {"quantized::mul_scalar_relu_out", + quantized_mul_scalar_relu_out_pattern, + quantized_mul_scalar_relu_out_replacement}, + {"quantized::mul_scalar_relu_out", + quantized_mul_scalar_inplace_relu_out_pattern, + quantized_mul_scalar_relu_out_replacement}, + {"quantized::mul_relu", std::move(mul_relu), quantized_mul_relu}, + {"quantized::mul_relu", std::move(mul_inplace_relu), quantized_mul_relu}, + {"quantized::mul_relu", std::move(inplace_mul_relu), quantized_mul_relu}, + {"quantized::mul_relu", + std::move(inplace_mul_inplace_relu), + std::move(quantized_mul_relu)}, + {"quantized::mul", std::move(mul), quantized_mul}, + {"quantized::mul", std::move(inplace_mul), std::move(quantized_mul)}, + std::move(hardswish), + std::move(hardswish_), + std::move(layer_norm), + std::move(group_norm), + std::move(instance_norm), + {"quantized::elu", std::move(elu), quantized_elu}, + {"quantized::elu_", std::move(elu_), std::move(quantized_elu)}, + std::move(avg_pool1d), + std::move(avg_pool2d), + std::move(avg_pool3d), + std::move(adaptive_avg_pool1d), + std::move(adaptive_avg_pool2d), + std::move(adaptive_avg_pool3d), + std::move(mean1), + std::move(mean2), + std::move(upsample_nearest1d), + std::move(upsample_nearest2d), + std::move(upsample_nearest3d), + std::move(upsample_linear1d), + std::move(upsample_bilinear2d), + std::move(upsample_trilinear3d), + std::move(upsample_nearest1d_vec), + std::move(upsample_nearest2d_vec), + std::move(upsample_nearest3d_vec), + std::move(upsample_linear1d_vec), + std::move(upsample_bilinear2d_vec), + std::move(upsample_trilinear3d_vec), + std::move(clamp), + std::move(hardtanh), + std::move(hardtanh_), + std::move(leaky_relu), + std::move(leaky_relu_), + // fixed qparam ops + std::move(hardsigmoid), + std::move(hardsigmoid_), + std::move(sigmoid), + std::move(sigmoid_), + std::move(tanh), + std::move(tanh_), + }; +} + +inline std::vector +dynamic_quantized_linear_pattern_and_replacements() { + std::string linear_dynamic = R"( +graph(%packed_params, %a): + %w_quant : Tensor, %b : Tensor? = quantized::linear_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %r = aten::linear(%a, %w_dequant, %b) + return (%r) )"; + + // This pattern ignores reduce range + // Set the reduce range to default to true, since qnnpack backend ignores this + // argument. + std::string quantized_linear_dynamic = R"( +graph(%packed_params, %a): + %reduce_range : bool = prim::Constant[value=1]() + %r = quantized::linear_dynamic(%a, %packed_params, %reduce_range) + return (%r) )"; + + return { + {"quantized::linear_dynamic", + std::move(linear_dynamic), + std::move(quantized_linear_dynamic)}, + }; +} + +static std::vector +dynamic_quant_fusion_pattern_and_replacements() { + std::string linear_dynamic = R"( +graph(%packed_params, %a, %reduce_range, %a_dtype): + %a_scale : float, %a_zero_point : int = aten::_choose_qparams_per_tensor(%a, %reduce_range) + %a_quant = aten::quantize_per_tensor(%a, %a_scale, %a_zero_point, %a_dtype) + %a_dequant = aten::dequantize(%a_quant) + %w_quant : Tensor, %b : Tensor? = quantized::linear_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant) + %r = aten::linear(%a_dequant, %w_dequant, %b) + return (%r) )"; + + std::string quantized_linear_dynamic = R"( +graph(%packed_params, %a, %reduce_range, %a_dtype): + %r = quantized::linear_dynamic(%a, %packed_params, %reduce_range) + return (%r) )"; + + std::string linear_dynamic_fp16 = R"( +graph(%packed_params, %a): + %w_unpacked : Tensor, %b : Tensor? = quantized::linear_unpack_fp16(%packed_params) + %r = aten::linear(%a, %w_unpacked, %b) + return (%r) )"; + + std::string quantized_linear_dynamic_fp16 = R"( +graph(%packed_params, %a): + %r = quantized::linear_dynamic_fp16(%a, %packed_params) + return (%r) )"; + + return { + {"quantized::linear_dynamic", + std::move(linear_dynamic), + std::move(quantized_linear_dynamic)}, + {"quantized::linear_dynamic_fp16", + std::move(linear_dynamic_fp16), + std::move(quantized_linear_dynamic_fp16)}, + }; +} + +static std::vector linear_prepack_unpack_patterns() { + std::string linear_with_quant = R"( +graph(%a_dequant, %w_quant, %b): + %w_dequant = aten::dequantize(%w_quant) + %r = aten::linear(%a_dequant, %w_dequant, %b) + return (%r) )"; + + std::string linear_with_quant_prepack = R"( +graph(%a_dequant, %w_quant, %b): + %packed_params = quantized::linear_prepack(%w_quant, %b) + %w_quant_unpacked : Tensor, %b_unpacked : Tensor? = quantized::linear_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant_unpacked) + %r = aten::linear(%a_dequant, %w_dequant, %b_unpacked) + return (%r) )"; + std::string linear_fp16_with_cast = R"( +graph(%w, %a_dq, %b): + %fp16_tensor = aten::_saturate_weight_to_fp16(%w) + %r = aten::linear(%a_dq, %fp16_tensor, %b) + return (%r) )"; + std::string linear_fp16_with_prepack = R"( +graph(%w, %a_dq, %b): + %packed_params = quantized::linear_prepack_fp16(%w, %b) + %w_unpacked : Tensor, %b_unpacked : Tensor? = quantized::linear_unpack_fp16(%packed_params) + %r = aten::linear(%a_dq, %w_unpacked, %b_unpacked) + return (%r) )"; + + return { + {"linear_prepack_unpack", + std::move(linear_with_quant), + std::move(linear_with_quant_prepack)}, + {"linear_fp16_prepack_unpack", + std::move(linear_fp16_with_cast), + std::move(linear_fp16_with_prepack)}, + }; +} + +static std::vector conv_prepack_unpack_patterns() { + std::string conv1d_with_quant = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %dilation, %groups): + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv1d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + return (%r) )"; + + std::string conv1d_with_quant_prepack = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %dilation, %groups): + %packed_params : __torch__.torch.classes.quantized.Conv2dPackedParamsBase = quantized::conv1d_prepack(%w_quant, %b, %stride, %padding, %dilation, %groups) + %w_quant_unpacked : Tensor, %b_unpacked : Tensor? = quantized::conv1d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant_unpacked) + %r = aten::conv1d(%a_dequant, %w_dequant, %b_unpacked, %stride, %padding, %dilation, %groups) + return (%r) )"; + + std::string conv2d_with_quant = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %dilation, %groups): + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv2d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + return (%r) )"; + + std::string conv2d_with_quant_prepack = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %dilation, %groups): + %packed_params : __torch__.torch.classes.quantized.Conv2dPackedParamsBase = quantized::conv2d_prepack(%w_quant, %b, %stride, %padding, %dilation, %groups) + %w_quant_unpacked : Tensor, %b_unpacked : Tensor? = quantized::conv2d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant_unpacked) + %r = aten::conv2d(%a_dequant, %w_dequant, %b_unpacked, %stride, %padding, %dilation, %groups) + return (%r) )"; + + std::string conv3d_with_quant = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %dilation, %groups): + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv3d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups) + return (%r) )"; + + std::string conv3d_with_quant_prepack = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %dilation, %groups): + %packed_params : __torch__.torch.classes.quantized.Conv3dPackedParamsBase = quantized::conv3d_prepack(%w_quant, %b, %stride, %padding, %dilation, %groups) + %w_quant_unpacked : Tensor, %b_unpacked : Tensor? = quantized::conv3d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant_unpacked) + %r = aten::conv3d(%a_dequant, %w_dequant, %b_unpacked, %stride, %padding, %dilation, %groups) + return (%r) )"; + + std::string conv_transpose1d_with_quant = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %output_padding, %groups, %dilation): + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv_transpose1d(%a_dequant, %w_dequant, %b, %stride, %padding, %output_padding, %groups, %dilation) + return (%r) )"; + + std::string conv_transpose1d_with_quant_prepack = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %output_padding, %groups, %dilation): + %packed_params : __torch__.torch.classes.quantized.Conv2dPackedParamsBase = quantized::conv_transpose1d_prepack(%w_quant, %b, %stride, %padding, %output_padding, %dilation, %groups) + %w_quant_unpacked : Tensor, %b_unpacked : Tensor? = quantized::conv_transpose1d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant_unpacked) + %r = aten::conv_transpose1d(%a_dequant, %w_dequant, %b_unpacked, %stride, %padding, %output_padding, %groups, %dilation) + return (%r) )"; + + std::string conv_transpose2d_with_quant = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %output_padding, %groups, %dilation): + %w_dequant = aten::dequantize(%w_quant) + %r = aten::conv_transpose2d(%a_dequant, %w_dequant, %b, %stride, %padding, %output_padding, %groups, %dilation) + return (%r) )"; + + std::string conv_transpose2d_with_quant_prepack = R"( +graph(%a_dequant, %w_quant, %b, %stride, %padding, %output_padding, %groups, %dilation): + %packed_params : __torch__.torch.classes.quantized.Conv2dPackedParamsBase = quantized::conv_transpose2d_prepack(%w_quant, %b, %stride, %padding, %output_padding, %dilation, %groups) + %w_quant_unpacked : Tensor, %b_unpacked : Tensor? = quantized::conv_transpose2d_unpack(%packed_params) + %w_dequant = aten::dequantize(%w_quant_unpacked) + %r = aten::conv_transpose2d(%a_dequant, %w_dequant, %b_unpacked, %stride, %padding, %output_padding, %groups, %dilation) + return (%r) )"; + + return { + {"conv1d_prepack_unpack", + std::move(conv1d_with_quant), + std::move(conv1d_with_quant_prepack)}, + {"conv2d_prepack_unpack", + std::move(conv2d_with_quant), + std::move(conv2d_with_quant_prepack)}, + {"conv3d_prepack_unpack", + std::move(conv3d_with_quant), + std::move(conv3d_with_quant_prepack)}, + {"conv_transpose1d_prepack_unpack", + std::move(conv_transpose1d_with_quant), + std::move(conv_transpose1d_with_quant_prepack)}, + {"conv_transpose2d_prepack_unpack", + std::move(conv_transpose2d_with_quant), + std::move(conv_transpose2d_with_quant_prepack)}}; +} + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/quantization_type.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/quantization_type.h new file mode 100644 index 0000000000000000000000000000000000000000..7f9f123ba89e777e6144097dcd10f5b81cb25402 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/quantization_type.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +namespace torch::jit { + +// Quantization type (dynamic quantization, static quantization). +// Should match the Python enum in quantize_jit.py +enum QuantType : std::uint8_t { DYNAMIC = 0, STATIC }; + +std::ostream& operator<<(std::ostream& os, QuantType t); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/register_packed_params.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/register_packed_params.h new file mode 100644 index 0000000000000000000000000000000000000000..fbc1a48c9d791fdf3e7b714a118a373a9660d708 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/quantization/register_packed_params.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +using PrePackParamFilterFn = std::function; + +TORCH_API std::unordered_set RegisterPrePackParams( + Module& m, + const std::string& method_name, + const PrePackParamFilterFn& is_packed_param, + const std::string& attr_prefix); + +TORCH_API std::string joinPaths(const std::vector& paths); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/refine_tuple_types.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/refine_tuple_types.h new file mode 100644 index 0000000000000000000000000000000000000000..bff1d48ba87e957602c00304d24856291f952610 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/refine_tuple_types.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// updates the types of tuples according to the type of their current inputs. +TORCH_API void RefineTupleTypes(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_dropout.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_dropout.h new file mode 100644 index 0000000000000000000000000000000000000000..e97600c3288e4fa14f7d812048e17cf891471906 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_dropout.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API void removeDropout(std::shared_ptr& graph); + +TORCH_API void removeDropout(script::Module& 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_exceptions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_exceptions.h new file mode 100644 index 0000000000000000000000000000000000000000..00a824427644dca888f307bcd48de11d6f05db95 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_exceptions.h @@ -0,0 +1,26 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Considering prim::RaiseException nodes unreachable, simplify prim::If nodes +// when one of the branches contains prim::RaiseException. +// +// This pass is illegal in general case as the modified graph might not throw +// an exception that the original graph would throw. The purpose of the pass is +// to cleanup the graph in a "risky" way by removing pathways leading to +// RaiseExceptions nodes. In some sense, this pass could be considered as a +// "Release" mode, while the original graph was in a "Debug" mode. +// The pass should only be used when such transformation is guaranteed to be +// safe by some other mechanisms. For instance, when we know exact shapes of +// tensors flowing through the graph and tensors with such shapes never cause +// exceptions. +TORCH_API void EliminateExceptions(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_expands.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_expands.h new file mode 100644 index 0000000000000000000000000000000000000000..472ed1e84f458042c024273287235719cd23fac2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_expands.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void RemoveExpands(const std::shared_ptr& graph); + +} + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_inplace_ops.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_inplace_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e39a5ffe5a9b59de5107529b382dd27e02d0ad58 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_inplace_ops.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit { +// see .cpp for docs +TORCH_API void RemoveInplaceOps(const std::shared_ptr& graph); + +TORCH_API void ImplicitCastForBinaryInplaceOps(Block* block); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h new file mode 100644 index 0000000000000000000000000000000000000000..ed541091465c766e000e9b449050f495dac34d25 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h @@ -0,0 +1,86 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit { + +struct TORCH_API MutationRemover { + MutationRemover( + std::shared_ptr graph, + std::optional> mutation_filter = std::nullopt) + : mutation_filter_(std::move(mutation_filter)), + aliasDb_(nullptr), + graph_(std::move(graph)) {} + + // return true if graph is modified + bool removeListMutation(); + + // return true if graph is modified + bool removeTensorMutation(); + + bool isSpecialMappedOp(Node* n) { + return n->matches("aten::zero_(Tensor(a!) self) -> Tensor(a!)") || + n->matches( + "aten::fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!)") || + n->matches( + "aten::normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!)"); + } + + bool inplaceOpVariant(Node* n); + + static bool hasSideEffectOrAlias(Value* v, AliasDb* aliasDb); + + private: + Node* createSpecialMappedOp(Node* n); + bool listMutationFollowingListConstruct(Node* n); + bool tryMakeCreationAndMutationAtomic( + Value* mutated_value, + Node* mutating_op); + bool tryMakeUnaliasedIfOutputAndMutationAtomic( + Value* mutated_value, + Node* mutating_op); + // return true if graph is modified + bool RemoveListMutation(Block* block); + // return true if graph is modified + bool RemoveTensorMutation(Block* block); + + AliasDb* getOrCreateAliasDb() { + if (!aliasDb_) { + aliasDb_ = std::make_unique(graph_); + } + return aliasDb_.get(); + } + + std::optional> mutation_filter_; + std::unique_ptr aliasDb_ = nullptr; + std::shared_ptr graph_; +}; + +// Removes list mutation with functional equivalents +// return true if graph is modified +TORCH_API bool RemoveListMutation(const std::shared_ptr& graph); + +// Replaces in-place aten ops with their functional equivalents +// when it can be proven that this does not change graph semantics +// if `mutation_filter` is present, the pass will only attempt to +// remove mutation on nodes which return true for the filter +// return true if graph is modified +TORCH_API bool RemoveTensorMutation( + const std::shared_ptr& graph, + std::optional> mutation_filter = std::nullopt); + +// Replaces in-place aten activation ops with their functional equivalence +TORCH_API bool InplaceToFunctionalActivation( + const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h new file mode 100644 index 0000000000000000000000000000000000000000..913a9a4fe5019bd78ac600d3fae9e45b8dc4b3ae --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void RemoveRedundantProfiles(std::shared_ptr& graph); +TORCH_API void RemoveRedundantProfiles(Block* block, AliasDb& db); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/replacement_of_old_operators.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/replacement_of_old_operators.h new file mode 100644 index 0000000000000000000000000000000000000000..d3cb6abcabb0b94d186894caefd2ace2b68e791b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/replacement_of_old_operators.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Find the valid upgrader graph for the upgrader and cache the result +// for later lookups. Will error out if there is no valid upgrader graph +// provided for the upgrader name. +std::shared_ptr getUpgraderGraph(const std::string& upgrader_name); + +TORCH_API void ReplaceOldOperatorsWithUpgraders(std::shared_ptr graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..d143d219bb19b862261ee96ea44e75881ff319ce --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit { + +struct Graph; +struct ArgumentSpec; + +TORCH_API void PropagateRequiresGrad(std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/restore_mutation.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/restore_mutation.h new file mode 100644 index 0000000000000000000000000000000000000000..eb92d07c161326426bb07066ecb8478303cb8e44 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/restore_mutation.h @@ -0,0 +1,66 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +// A map which stores if an activation operator can perform type promotion +const std::unordered_map activation_type_promotion_mapping = { + {aten::sigmoid, true}, + {aten::tanh, true}, + {aten::celu, false}, + {aten::elu, false}, + {aten::gelu, false}, + {aten::glu, false}, + {aten::hardshrink, false}, + {aten::hardsigmoid, false}, + {aten::hardswish, false}, + {aten::hardtanh, false}, + {aten::leaky_relu, false}, + {aten::prelu, false}, + {aten::relu6, false}, + {aten::relu, false}, + {aten::rrelu, false}, + {aten::selu, false}, + {aten::silu, false}}; + +class FunctionalToInplaceRewriter { + public: + FunctionalToInplaceRewriter(std::shared_ptr graph); + + bool FunctionalToInplace(Block* block); + + private: + AliasDb* getOrCreateAliasDb() { + if (!aliasDb_) { + aliasDb_ = std::make_unique(graph_); + } + return aliasDb_.get(); + } + + bool CanBeInplace(Node* node); + + std::unique_ptr aliasDb_ = nullptr; + std::shared_ptr graph_; +}; + +// A common application scenario is to apply InplaceToFunctionalActivation +// before some JIT optimization passes, so that those passes are less +// constrained by in-place ops. After those passes are done, we can call +// FunctionalToInplaceActivation to recover in-place activation ops, +// so that we won't lose the performance benefit coming from memory reduction. + +// Replaces functional aten activation ops with their in-place equivalents +TORCH_API bool FunctionalToInplaceActivation( + const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/shape_analysis.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/shape_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..224ec887d0b63b4d4e47660bed4b94825e823309 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/shape_analysis.h @@ -0,0 +1,46 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +struct Graph; + +struct propagation_error : std::exception {}; + +class PropertyPropBase { + // Used for both Shape Propagation and Dtype/Device Propagation + public: + explicit PropertyPropBase(std::shared_ptr graph) + : graph_(std::move(graph)) {} + virtual ~PropertyPropBase() = default; + + void propagateBlock(Block* block, bool insert_expands = true); + // insert_expands is used for shape inference + + void processIf(Node* node); + void processLoop(Node* node); + + protected: + virtual void propagateNode(Node* node, bool insert_expands = true) = 0; + void setUnshapedType(Value* o); + void setUnshapedType(Node* node); + std::shared_ptr graph_; +}; + +TORCH_API void EraseShapeInformation(const std::shared_ptr& graph); +TORCH_API void PropagateInputShapes(const std::shared_ptr& graph); + +TORCH_API bool mergeTypes( + ArrayRef lhs, + ArrayRef rhs, + ArrayRef outputs); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/specialize_autogradzero.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/specialize_autogradzero.h new file mode 100644 index 0000000000000000000000000000000000000000..37e8ce67eb967be9800bbf9eb16d8265de80adc2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/specialize_autogradzero.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// propagate autograd zero information through a gradient graph and +// remove grad_of blocks if present. +// Note: this is a very limited pass. It only propagates autograd zeros for +// operations generated by the symbolic autodiff code and cleans up +// AutogradAdds when possible. Outputs of other nodes are conservatively +// marked Unknown and not optimized. +TORCH_API void specializeAutogradZero(std::shared_ptr g); + +struct ProfilingRecord; + +TORCH_API void InsertProfileNodesForSpecializeAutogradZero(ProfilingRecord* pr); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/subgraph_rewrite.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/subgraph_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..f5eea4078efdff8462841bf6c2b0ca92cbc2f17d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/subgraph_rewrite.h @@ -0,0 +1,120 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +/** This file defines API for pattern-based subgraph rewrites. + * + * The API can be used for finding concrete patterns in the model and replacing + * the corresponding subgraphs with another subgraph. A special case of such + * rewrites is fusion, where the new subgraph consists of just a single node. + * + * There is a default set of the most common patterns that everyone could use. + * Alternatively, an arbitrary pattern can be registered. + */ +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch::jit { + +// Forward declarations. +struct RewritePatternDescr; +struct Match; + +using MatchFilter = std::function< + bool(const Match&, const std::unordered_map&)>; + +/** Run pattern-based subgraph rewrites on all methods in the module. + * + * This pass will go through all methods in the module and try to replace all + * recognized patterns (see SubgraphRewriter::RegisterDefaultPatterns for the + * list of these patterns). + */ +TORCH_API Module PatternBasedRewrite(const Module& module); + +/** A class implementing API for pattern-based subgraph rewrites. + * + * To perform pattern-based subgraph rewrites on a module using this API, one + * needs to create an object of such class, register rewrite patterns and run + * the transformation pass (`runOnModule`). + * + * To use standard patterns, one could use `RegisterDefaultPatterns`. + * + * To enable rewrites of custom patterns, the custom patterns must be registered + * with `RegisterRewritePattern`. + */ +class TORCH_API SubgraphRewriter { + public: + // Run pattern-based subgraph rewrite pass on the module. + Module runOnModule(const Module& module); + + // Run pattern-based subgraph rewrite pass on the graph (used in testing). + // `filter` is a function that does extra filtering on the match. If it + // returns false for a given Match, we'll skip the Match. The filter + // function's arguments consist of a Match and a value map from parsing the + // pattern graph. Both the Match and the value map are necessary because we + // need to 1) do extra filtering on the matched result as well as 2) refer to + // the values in the matched result through the values in the pattern graph. + void runOnGraph( + std::shared_ptr& graph, + const std::vector& filters); + + void runOnGraph( + std::shared_ptr& graph, + const MatchFilter& filter = + [](const Match&, const std::unordered_map&) { + return true; + }) { + runOnGraph(graph, std::vector({filter})); + } + + // Register standard rewrite patterns. + void RegisterDefaultPatterns(); + + /** Register a custom rewrite pattern. + * + * The method takes two parameters specifying the pattern: + * \p PATTERN - IR string representing the pattern subgraph. + * \p REPLACEMENT - IR string representing the replacement subgraph. + * \p value name map - vector of pairs mapping values in the replacement graph + * to the values in the pattern graph. Used for preserving source range info + * across graph rewrite. + * + * See examples of pattern registering in `RegisterDefaultPatterns`. + */ + void RegisterRewritePattern( + const std::string& pattern, + const std::string& replacement, + const std::vector>& value_name_pair = + {}); + + private: + std::vector patterns_; + std::unordered_set nodes_to_delete_; + + void rewriteSinglePatternOnGraph( + std::shared_ptr& graph, + const RewritePatternDescr& pattern, + const std::vector& filters); + + bool overlapsWithPreviousMatches(const Match* match); +}; + +/** Rewrite pattern descriptor. + * + * This structure is used in the implementation of `SubgraphRewriter` and + * is not supposed to be used externally. + */ +struct RewritePatternDescr { + std::string pattern; + std::string replacement; + std::unordered_map value_name_map; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..9afac592de18fb5350a34f97c8bda30a16293671 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +// CAUTION NOT TO BE USED, STILL A WIP, NOT STABLE + +TORCH_API void PropagateShapesOnGraph(std::shared_ptr& graph); + +// CAUTION NOT TO BE USED, STILL A WIP, NOT STABLE +// From [beg, end) attempt to propagate shapes and +// build up a graph that will compute all remaining symbolic +// shapes in [beg, end) that can be executed before beg + +struct ShapeComputeGraphMapping { + ShapeComputeGraphMapping( + std::shared_ptr partial_eval_shape_graph, + std::unordered_map + enclosing_graph_value_to_shape_graph_input, + std::unordered_map graph_output_to_symbolic_shape_dim) + : partial_eval_shape_graph(std::move(partial_eval_shape_graph)), + enclosing_graph_value_to_shape_graph_input_( + std::move(enclosing_graph_value_to_shape_graph_input)), + graph_output_to_symbolic_shape_dim_( + std::move(graph_output_to_symbolic_shape_dim)) {} + + std::shared_ptr partial_eval_shape_graph; + std::unordered_map + enclosing_graph_value_to_shape_graph_input_; + std::unordered_map graph_output_to_symbolic_shape_dim_; +}; + +TORCH_API std::optional +PropagateShapesAndBuildLargeShapeComputeGraph( + std::shared_ptr& graph, + Node* beg, + Node* end); + +// don't insert complete tensor shapes in shape compute graphs and instead +// rely on our partial evaluation pipeline to propagate information. +// this is a good proxy for our ability to propagate non-complete shape +// information. +TORCH_API bool setSymbolicShapeAnalysisTestMode(bool value); +TORCH_API bool symbolicShapeAnalysisTestModeEnabled(); + +using SSAInput = std::variant; +TORCH_API std::optional> +calculateSymbolicShapesOnOp( + const FunctionSchema* schema, + const std::vector& inputs); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_cache.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..df37fe446397e6e8419b5b3d9eb21fa1e5b58bf8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_cache.h @@ -0,0 +1,60 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +struct TORCH_API CanonicalizedSymbolicShape { + // TODO: Consider in the future if it is reasonable to + // merge code with SymbolicShape or VaryingShape while keeping + // the two not implicitly convertible (and cause bugs). + CanonicalizedSymbolicShape( + const c10::SymbolicShape& orig_shape, + std::unordered_map& ss_map) { + init(orig_shape, ss_map); + } + + CanonicalizedSymbolicShape(c10::SymbolicShape& orig_shape) { + std::unordered_map new_ssmap; + init(orig_shape, new_ssmap); + } + + size_t hash() const; + + c10::SymbolicShape toSymbolicShape( + std::unordered_map& inverse_ss_map) const; + + TORCH_API friend bool operator==( + const CanonicalizedSymbolicShape& a, + const CanonicalizedSymbolicShape& b); + + private: + std::optional> values_; + + void init( + const c10::SymbolicShape& orig_shape, + std::unordered_map& ss_map); +}; + +// SHAPE CACHE API +TORCH_API std::optional> +get_cached_shape_function( + const FunctionSchema* schema, + const std::vector& arg_vec); + +TORCH_API void cache_shape_function( + const FunctionSchema* schema, + const std::vector& arg_vec, + const std::vector& ret_vec); + +// For use in test code +TORCH_API void clear_shape_cache(); +TORCH_API size_t get_shape_cache_size(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..3c356073c2d8013000cdc4858c4b54fd1b46d4a5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h @@ -0,0 +1,56 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +// Takes in a TensorExprGraph of static shapes and generalizes the input shapes +// to symbolic dimensions. Dimensions of value 1 will be preserved, otherwise +// dimensions with the same value will be bucketed to the same symbolic shape. +// E.g. Tensor(5, 3), Tensor(3, 1) -> Tensor(SS(-1), SS(-2)), Tensor(SS(-2), 1) +// From there, runs symbolic shape inference on the graph, and creates a +// versioning if in the graph with prim::TensorExprDynamicGuard checking if +// the inputs at runtime match the Generalized Symbolic Shapes that are inputs +// to the TE Kernel. The computate to calculate all symbolic dimensions is +// inlined in to the if block with the TE Kernel. All Sym Dim Value* are +// appended to the end of the TE Kernel Graph/Node inputs, and the Node is +// augmented with a integer list attr `symbolic_shape_inputs` that gives the +// mapping from Value * -> Symbolic Shape int64_t value. For more lengthy IR +// examples and walkthrough look at ShapeAnalysisTest.DynamicShapesFusion in +// `test_shape_analysis` Returns True on Success, False on Failure, can fail if +// shape propagation fails to propagate # of dims or if complete shapes on +// inputs not set + +TORCH_API bool GenerateGuard( + Node* tensorexpr_graph_node, + bool add_composed_op = false); + +TORCH_API void runTensorExprDynamicGroup(const Code& code, Stack& stack); + +enum class StrideInput { + // Tensors natively store whether they are contiguous or not as a property + // this makes it faster to query `is_contiguous` or + // `is_contiguous(memory_format=channels_last)` + // than looping through the sizes/strides yourself + // For tensors with these properties, we only store one value: + TENSOR_CONT, + TENSOR_CONT_CHANNELS_LAST, + // now, we describe other cases, where there is one stride enum + // per dimension + S_ONE, // STRIDE_ONE: packed + S_CONT, // STRIDE_CONTIGUOUS: stride[i + 1] * sizes[i + 1] + S_TRAN_CONT, // STRIDE_TRANSPOSED_CONTIGUOUS: stride[i-1] * sizes[i-1] + S_AS_ARG, // STRIDE_AS_ARG: stride passed in as runtime value +}; + +TORCH_API std::string toString(StrideInput si); +TORCH_API StrideInput strideInputFromString(const std::string& si); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/tensorexpr_fuser.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/tensorexpr_fuser.h new file mode 100644 index 0000000000000000000000000000000000000000..a54e6c6e88c5610516892c39a9bd793666590cd8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/tensorexpr_fuser.h @@ -0,0 +1,82 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +// Run TensorExpressions-based fuser. +// If add_composed_op is true, creates a single operation that +// performs both the runtime check that types align +// and then the dispatch to the kernel/unoptimized graph +TORCH_API void FuseTensorExprs( + std::shared_ptr& graph, + size_t min_group_size = 2, + bool add_composed_op = false, + bool fuse_to_dynamic_shapes = false); + +TORCH_API void setTensorExprFuserEnabled(bool val); +TORCH_API bool tensorExprFuserEnabled(); +TORCH_API void setTensorExprDynamicShapeFusionEnabled(bool val); +TORCH_API bool tensorExprDynamicShapeFusionEnabled(); +TORCH_API bool setTexprReductionsEnabled(bool value); +TORCH_API bool texprReductionsEnabled(); + +TORCH_API void RemoveProfileNodesAndSpecializeTypes( + std::shared_ptr& graph); +TORCH_API bool hasTensorTypeSpecialization(Value* v); +TORCH_API void RemoveTensorTypeSpecializations(std::shared_ptr& graph); +TORCH_API void removeTensorTypeSpecializations(Block* block); + +using tensor_type_converter_t = + c10::function_ref; + +// inserts a TypeCheck pattern +// +// around the guarded node that has a Subgraph attribute, this inserts a pattern +// +// if TypeCheck(...): +// guarded_node +// else: +// FallbackGraph(...) +// +// The TypeCheck includes the types of all Tensor inputs to the guarded_node, +// as processed by the type_converter, a lambda +// TensorTypePtr(const TensorTypePtr& t). This allows to erase irrelevant +// aspects of the type. +// +// The Fallback graph will have the same subgraph as the guarded node (with the +// expectation that the guarded_node's subgraph will then be optimized. +TORCH_API void insertTypeGuard( + Node* guarded_node, + tensor_type_converter_t type_converter, + c10::Symbol kind); + +TORCH_API bool usedOnlyInSize(Value* v); +TORCH_API Value* broadcastSizes(at::ArrayRef sizes, AliasDb* db); + +namespace tensorexpr { +TORCH_API bool isSupported(Node* node); + +/// Get the modifiable custom operator set object. +/// +/// For static shapes, if a custom operator has been added to the custom +/// operator set, it will be pulled into the NNC fusion group. But it doesn't +/// work with dynamic shapes unless explicitly register the shape function via +/// `torch::jit::RegisterShapeComputeGraphForSchema` for the custom operator. +/// +/// @return Reference of the custom operator set +/// +TORCH_API OperatorSet& getCustomOperatorSet(); + +} // namespace tensorexpr +} // namespace torch::jit + +C10_DECLARE_bool(torch_jit_disable_cat); +C10_DECLARE_bool(torch_jit_enable_dynamic_shape_fusion); + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/update_differentiable_graph_requires_grad.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/update_differentiable_graph_requires_grad.h new file mode 100644 index 0000000000000000000000000000000000000000..b1721a4714ba2243e104dca50346f1ba79493930 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/update_differentiable_graph_requires_grad.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Because differentiable graphs detach the gradients of input Tensors, +// creating and inlining differentiable graphs changes the requires_grad +// property of tensors in the graph. This pass updates prim::profiles +// requires_grad to keep profiled properties up to date, it does not update +// grad properties of other nodes like graph inputs bc the only downstream +// user of the grad property is the profiling executor, which just uses +// the types of prim::profiles +TORCH_API void UpdateDifferentiableGraphRequiresGrad( + std::shared_ptr& diff_forward_graph, + std::optional new_requires_grad); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/check_alias_annotation.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/check_alias_annotation.h new file mode 100644 index 0000000000000000000000000000000000000000..9f038180f3b85dbba36ac10b811edc76733f8ea8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/check_alias_annotation.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +// Verify that alias annotations are correct. See impl for definition of +// "correct". +// +// This function expects a graph with a single op with `unqualifiedOpName`, plus +// the inputs that you would otherwise have passed to the graph executor. +TORCH_API void checkAliasAnnotation( + const std::shared_ptr& graph, + std::vector pythonInputs, + const std::string& unqualifiedOpName); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/memory_dag.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/memory_dag.h new file mode 100644 index 0000000000000000000000000000000000000000..755aead9375fbc1a563bb555871973755dfa8c5c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/memory_dag.h @@ -0,0 +1,179 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// Uses a compressed index representation for faster comparisons +typedef c10::SparseBitVector<256> MemoryLocations; +namespace torch::jit { + +struct Value; + +using AliasTypeSet = std::vector; + +// `Element` represents a vertex in the points-to graph. It represents +// anything that could have an aliasing relationship--mostly IR +// `Value`s, but also wildcards or the type inside a container (e.g. `T` +// in `List[T]`) +struct Element { + Element(const Value* value_, unsigned index_); + // wildcard constructor + explicit Element(unsigned index_); + + // Index into the owning DAG's bit vector that represents this element. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + unsigned index; + + // All elements that this element *may* point to. It's possible to have + // multiple elements that you might point to due to control flow/complex ops + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + MemoryLocations pointsTo; + // Backreference for points-to. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + MemoryLocations pointedFrom; + + // Elements can contain other elements (e.g. List[Tensor]) + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + MemoryLocations containedElements; + + // The values that this element corresponds to. May be empty if this element + // doesn't represent a first-class value. + // This is for debug information only. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::unordered_set values; + + private: + // Make `from` point at `to`. + void makePointerTo(Element* from, Element* to); + + friend class MemoryDAG; + // We memoize the results of `getMemoryLocations` to speed up queries. + // A nullopt means that this cache is not yet populated. Since `MemoryDAG` is + // immutable, this cache should never need to be invalidated. + mutable std::optional cachedMemoryLocations_; + + mutable std::optional cachedAllContainedMemoryLocations_; +}; + +// class MemoryDAG +// +// This class tracks the "A points to B" graph for all values. It is used by +// AliasDb to provide a higher-level API. +// +// We maintain a DAG where: +// - Vertices (called "Elements") represent Values and +// other aliasing entities (e.g. the stuff inside a list) +// - Edges represent a "points-to" relationship. +// +// Leaves in this DAG are entities that don't point to anything, and thus +// correspond to unique "memory locations". +// +// So, by traversing the "points-to" graph to the leaves, you can determine +// which memory locations an element may point to. +class TORCH_API MemoryDAG { + public: + explicit MemoryDAG(std::vector> indexToElementMap) + : indexToElementMap_(std::move(indexToElementMap)) {} + // explicitly delete copy constructor because otherwise windows build is + // confused for an exported class see + // https://stackoverflow.com/a/51033485/105137 + MemoryDAG(const MemoryDAG&) = delete; + MemoryDAG& operator=(const MemoryDAG&) = delete; + + // Return the unique memory locations that `Element` might represent. + const MemoryLocations& getMemoryLocations(const Element* e) const; + + // Do `a` and `b` potentially share a memory location? + bool mayAlias(const Element* a, const Element* b) const; + + // Does `a` hold reference to any memory that is stored in `b`, or vice versa? + bool mayContainAlias(const Element* a, const Element* b) const; + + bool mayContainAlias(const Element* a, const at::ArrayRef b) const; + + bool mayContainAlias( + const at::ArrayRef a, + const at::ArrayRef b) const; + + // Converts from the compressed index representation + const Element* fromIndex(unsigned x) const; + Element* fromIndex(unsigned x); + void collectAllContainedMemoryLocations( + const Element* elem, + MemoryLocations& cont) const; + + /** + * The following methods are special cases where we need to mutate the + * internals of MemoryDAG for efficiency reasons. Don't call them unless you + * know what you're doing! In particular, don't add new mutating methods + * without ensuring that you are maintaining cache consistency for memory + * locations. + */ + + // Adding wildcards can trigger extremely expensive cache invalidations. This + // method adds them in a more efficient cache-aware way. + void setWildcards( + const std::unordered_set& wildcards, + const ska::flat_hash_map& elementMap, + const std::function& getWildcardElement); + Element* unsafeMakeFreshValue(const Value* v); + + private: + const MemoryLocations& getAllContainedMemoryLocations( + const Element* elem) const; + void collectAllContainedMemoryLocationsImpl( + const Element* elem, + MemoryLocations& cont) const; + std::vector> indexToElementMap_; +}; + +/** + * Helper to build up the points-to graph. + * + * We separate the "building" into a different class because it allows us to + * cache internally to MemoryDAG without worrying about how the DAG structure + * is mutated. + */ +class TORCH_API MemoryDAGBuilder { + public: + MemoryDAGBuilder() = default; + MemoryDAGBuilder(const MemoryDAGBuilder&) = delete; + MemoryDAGBuilder& operator=(const MemoryDAGBuilder&) = delete; + + // Make `from` point at `to`. + void makePointerTo(Element* from, Element* to); + + void addToContainedElements(Element* contained, Element* container); + + std::unique_ptr createMemoryDAG() && { + return std::make_unique(std::move(indexToElementMap_)); + } + + // Make a fresh Element (i.e. an Element that doesn't point to anything) and + // return it. + Element* makeFreshValue(const Value* v); + + friend MemoryDAG; + + private: + // `MemoryDAGBuilder` builds up `indexToElementMap_`, then uses + // the map to construct the `MemoryDAG` + std::vector> indexToElementMap_; +}; +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/op_registry.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/op_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..d6a566d1ef06843ff0d27b6b07b42970f8c89825 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/op_registry.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { +// Moved from shape_analysis.cpp + +// Requirements: +// dims : preserved from the first argument +// scalar type : preserved from the first argument (doesn't have to +// match other arguments) +// device : always matching and preserved +// tensor inputs : * +// tensor outputs : 1 +// NB: those ops (with slight adjustments) are good candidates for restarts. +// Knowing the type and device of weights or biases is usually enough to +// infer the output type. +std::shared_ptr nn_ops_first_input_preserving(); + +// Requirements: +// dims : Changed from first argument +// scalar type : preserved from the first argument +// device : always matching and preserved +// tensor inputs : 1 +// tensor outputs : 1 +std::shared_ptr ops_one_tensor_in_shape_transform(); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/optimization_utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/optimization_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..189d8128354445927ca03f457ca51951e81453e3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/optimization_utils.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) + +#pragma once + +#include + +namespace torch::jit { + +// Checks if the parameters, not including the +// first param are all constants. +bool nonConstantParameters(Node* n); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/subgraph_utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/subgraph_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..eb84520636361f0353ddafbb0d27d12c6de0df58 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/utils/subgraph_utils.h @@ -0,0 +1,75 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +// Utilities for dealing with nodes that contain subgraphs. +// +// They handle the complexity of editing inputs/outputs as you merge nodes in +// and out of subgraphs. +namespace torch::jit::SubgraphUtils { + +// Create a new subgraph node that contains only `n`. The new subgraph will have +// `subgraphKind` as its type. +// +// `n` is destroyed. +// +// Returns the new subgraph node. +TORCH_API Node* createSingletonSubgraph(Node* n, Symbol subgraphKind); + +// Creates a new subgraph that only contains `n`, amd updates the new outputs +// of the subgraph to have the aliasing properties of the original `n` outputs +TORCH_API Node* createSingletonSubgraphAndUpdateAliasing( + Node* to_merge, + Symbol subgraphKind, + AliasDb& db); + +// Merge a node into a subgraph node. If `toMerge` is also a subgraph, the +// subgraphs are merged. +// If `destroyNode` is true `toMerge` is destroyed. +// An optional argument 'vmap' could be used to retrieve value mappings. +// Values will be mapped to their new subgraph values +TORCH_API void mergeNodeIntoSubgraph( + Node* toMerge, + Node* subgraphNode, + bool destroyNode = true); + +// Merges a node into a subgraph node, and updates the new outputs of the +// subgraph to have the aliasing properties of the corresponding `to_merge` +// outputs +TORCH_API void mergeNodeIntoSubgraphAndUpdateAliasing( + Node* to_merge, + Node* subgraphNode, + AliasDb& db); + +TORCH_API std::vector unmergeAliasedOutputs( + Node* subgraphNode, + AliasDb& db); + +// Move nodes from a subgraph node to the outer graph. +// `subgraphNode` is destroyed. +TORCH_API void unmergeSubgraph(Node* subgraphNode); + +// Move `node_to_unmerge` and its descendants after `subgraphNode` +// promotes any dependencies of `node_to_unmerge` to subgraphNode outputs +TORCH_API void unmergeNode(Node* node_to_unmerge, Node* subgraphNode); + +TORCH_API bool unmergeOutputsAlisingInputs(Node* subgraphNode); + +TORCH_API bool unmergeAliasedOutputs(Node* subgraphNode); + +// Convenience function +std::shared_ptr getSubgraph(Node* n); + +TORCH_API std::string generateNameForGraph( + const std::shared_ptr& graph, + size_t maxlen = 40, + const std::string& prefix = "fused"); + +} // namespace torch::jit::SubgraphUtils + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/value_refinement_utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/value_refinement_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..87922b88f957eed96baaad5b6443435d96af0157 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/value_refinement_utils.h @@ -0,0 +1,84 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +// Refine from Value of type List -> len of list +// If a refinement mapping of List Value * -> len is present in a block +// the list is guaranteed to be that length +// TODO: vector may be faster +using ListRefinement = std::unordered_map; + +TORCH_API ListRefinement +intersectRefinements(const ListRefinement& ref1, const ListRefinement& ref2); + +TORCH_API ListRefinement +unionRefinements(const ListRefinement& ref1, const ListRefinement& ref2); + +// Represents the refinement information that can be carried on a boolean +struct BooleanRefinementMapping { + BooleanRefinementMapping( + ListRefinement true_refine, + ListRefinement false_refine) + : true_refine_(std::move(true_refine)), + false_refine_(std::move(false_refine)) {} + BooleanRefinementMapping() = default; // empty + + static BooleanRefinementMapping FalseRefinements( + ListRefinement false_refine) { + return BooleanRefinementMapping({}, std::move(false_refine)); + } + + static BooleanRefinementMapping TrueRefinements(ListRefinement true_refine) { + return BooleanRefinementMapping(std::move(true_refine), {}); + } + + BooleanRefinementMapping intersectBooleanRefinementMapping( + BooleanRefinementMapping& other) { + return BooleanRefinementMapping( + intersectRefinements(true_refine_, other.true_refine()), + intersectRefinements(false_refine_, other.false_refine())); + } + + ListRefinement& true_refine() { + return true_refine_; + } + + ListRefinement& false_refine() { + return false_refine_; + } + + private: + ListRefinement true_refine_; + ListRefinement false_refine_; +}; + +TORCH_API void joinIfRefinements( + Node* if_node, + std::unordered_set& throwing_blocks, + ListRefinement& curr_block_refinements, + ListRefinement& true_block_refinements, + ListRefinement& false_block_refinements, + std::unordered_map& info); + +// handles adding blocks to throwing blocks and propagating refinements via +// boolean comparisons +TORCH_API bool handleCommonRefinentOperators( + Node* n, + std::unordered_set& throwing_blocks, + std::unordered_map& info); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/variadic_ops.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/variadic_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a017a91293e330a0b9afc7029acdd0463b55193f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/variadic_ops.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Try to replace an op that takes a list input with another op that takes a +// variadic number of arguments. +TORCH_API bool UseVariadicOp( + const std::shared_ptr& graph, + NodeKind op, + NodeKind variadic_op); + +TORCH_API bool RemoveListMutationAndUseVariadicOp( + const std::shared_ptr& graph, + NodeKind op, + NodeKind variadic_op); + +// Convenient functions for replacing aten::stack/aten::cat with their +// variadic versions. +TORCH_API bool UseVariadicCat(const std::shared_ptr& graph); +TORCH_API bool RemoveListMutationAndUseVariadicCat( + const std::shared_ptr& graph); + +TORCH_API bool UseVariadicStack(const std::shared_ptr& graph); +TORCH_API bool RemoveListMutationAndUseVariadicStack( + const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/vulkan_rewrite.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/vulkan_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..c1dbb8d23e58a416dea4c95d5e45df787b51025e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/vulkan_rewrite.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { +TORCH_API void vulkanInsertPrePackedOps(std::shared_ptr& graph); +TORCH_API void vulkanInsertPrePackedOps(script::Module& module); +TORCH_API void vulkanFusePrePackedConvWithClamp(script::Module& module); +TORCH_API void vulkanFoldPrePackingOps(script::Module& module); +TORCH_API script::Module vulkanOptimizeForMobile( + const script::Module& module, + const std::set& optimization_blocklist, + const std::vector& preserved_methods); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/xnnpack_rewrite.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/xnnpack_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..39e08ec04f9ae75eba189a644f028d4e05fe56a4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/xnnpack_rewrite.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +TORCH_API void transformConv1dToConv2d(std::shared_ptr& graph); +TORCH_API void transformConv1dToConv2d(script::Module& module); +TORCH_API void insertPrePackedOps(std::shared_ptr& graph); +TORCH_API void insertPrePackedOps(script::Module& module); +TORCH_API void fusePrePackedLinearConvWithClamp(script::Module& module); +TORCH_API void FoldPrePackingOps(script::Module& module); +TORCH_API script::Module optimizeForMobile( + const script::Module& module, + const std::set& optimization_blocklist = {}, + const std::vector& preserved_methods = {}); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/init.h new file mode 100644 index 0000000000000000000000000000000000000000..29180349f5aade9591e36fe892eabf91cb92d064 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/init.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +void initJITBindings(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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/module_python.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/module_python.h new file mode 100644 index 0000000000000000000000000000000000000000..c127ff8b5a6ac87672a7a1e77158351b9d5dc591 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/module_python.h @@ -0,0 +1,69 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +namespace py = pybind11; + +namespace torch::jit { + +inline std::optional as_module(py::handle obj) { +#if IS_PYBIND_2_13_PLUS + PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store + storage; + auto& ScriptModule = + storage + .call_once_and_store_result([]() -> py::object { + return py::module_::import("torch.jit").attr("ScriptModule"); + }) + .get_stored(); +#else + static py::handle ScriptModule = + py::module::import("torch.jit").attr("ScriptModule"); +#endif + if (py::isinstance(obj, ScriptModule)) { + return py::cast(obj.attr("_c")); + } + return std::nullopt; +} + +inline std::optional as_object(py::handle obj) { +#if IS_PYBIND_2_13_PLUS + PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store< + std::tuple> + storage; + auto& [ScriptObject, RecursiveScriptClass] = + storage + .call_once_and_store_result( + []() -> std::tuple { + return { + py::module_::import("torch").attr("ScriptObject"), + py::module_::import("torch.jit") + .attr("RecursiveScriptClass")}; + }) + .get_stored(); +#else + static py::handle ScriptObject = + py::module::import("torch").attr("ScriptObject"); + + static py::handle RecursiveScriptClass = + py::module::import("torch.jit").attr("RecursiveScriptClass"); +#endif + + if (py::isinstance(obj, ScriptObject)) { + return py::cast(obj); + } + if (py::isinstance(obj, RecursiveScriptClass)) { + return py::cast(obj.attr("_c")); + } + return std::nullopt; +} + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/opaque_obj.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/opaque_obj.h new file mode 100644 index 0000000000000000000000000000000000000000..8f6b6c324b0ac2642fc38ef05a323a544cc2c1b3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/opaque_obj.h @@ -0,0 +1,84 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { +struct OpaqueObject : public CustomClassHolder { + OpaqueObject(py::object payload) : payload_(std::move(payload)) {} + + void setPayload(py::object payload) { + payload_ = std::move(payload); + } + + py::object getPayload() { + return payload_; + } + + py::object payload_; +}; + +static auto register_opaque_obj_class = + torch::class_("aten", "OpaqueObject") + .def( + "__eq__", + [](const c10::intrusive_ptr& self, + const c10::intrusive_ptr& other) { + auto self_payload = self->getPayload(); + auto other_payload = other->getPayload(); + + if (!self_payload.ptr() || !other_payload.ptr()) { + return false; + } + + py::gil_scoped_acquire gil; + auto res = PyObject_RichCompareBool( + self_payload.ptr(), other_payload.ptr(), Py_EQ); + if (res == -1) { + throw py::error_already_set(); + } + return res > 0; + }) + .def_pickle( + [](const c10::intrusive_ptr& self) { // __getstate__ + // Since we cannot directly return the py::object due to + // CustomClassHolder's signature limitations, we will have to + // serialize it directly here. We also can't return py::bytes so + // need to encode it into a string. + py::module_ pickle = py::module_::import("pickle"); + py::module_ base64 = py::module_::import("base64"); + py::bytes pickled_payload = + pickle.attr("dumps")(self->getPayload()); + py::bytes encoded_payload = + base64.attr("b64encode")(pickled_payload); + return std::string(encoded_payload); + }, + [](const std::string& state) { // __setstate__ + py::module_ pickle = py::module_::import("pickle"); + py::module_ base64 = py::module_::import("base64"); + py::bytes state_bytes(state); + py::bytes decoded_payload = base64.attr("b64decode")(state_bytes); + py::object restored_payload = + pickle.attr("loads")(decoded_payload); + return c10::make_intrusive(restored_payload); + }) + .def( + "__obj_flatten__", + [](const c10::intrusive_ptr& self) { + throw std::runtime_error( + "Unable to implement __obj_flatten__ for opaque objects."); + }); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..6ded51cf15914dea299a1e76b7abb534153a08b5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind.h @@ -0,0 +1,218 @@ +#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 py = pybind11; + +namespace torch::jit { + +// This is a variant of shared_ptr that "sees through" a wrapper. +// We use it to convert Value, Node, Block and node to "wrapped" Python +// values. When we destruct the C++ object, the wrapper's pointer will +// be set to 0 and any future dereferencing will throw. We need this +// because the Python objects may hang around after the C++ object +// has already been destroyed. +// This also needs the magic type_caster below, which is from the +// workaround offered in https://github.com/pybind/pybind11/issues/2751 +template +class unwrapping_shared_ptr { + static_assert( + std::is_same_v || + std::is_same_v || + std::is_same_v, + "unwrapping type only defined for Graph object types"); + + private: + std::shared_ptr> impl; + + public: + unwrapping_shared_ptr() : impl({}) {} + explicit unwrapping_shared_ptr(T* p) : impl(p->wrap()) { + impl->clear_cb = &clear_registered_instances; + } + T* get() const { + if (!impl->elem) { + throw std::logic_error("has been invalidated"); + } + return impl->elem; + } + // we need to disable the overloaded & for PyBind11 < 2.3 due. + // see https://github.com/pybind/pybind11/pull/1435 +#if (PYBIND11_VERSION_MAJOR > 2) || \ + ((PYBIND11_VERSION_MAJOR == 2) && (PYBIND11_VERSION_MINOR >= 3)) + T** operator&() { + if (!impl->elem) { + throw std::logic_error("has been invalidated"); + } + return &(impl->elem); + } +#endif +}; + +} // namespace torch::jit + +PYBIND11_DECLARE_HOLDER_TYPE(T, torch::jit::unwrapping_shared_ptr, true) + +namespace pybind11::detail { + +#define CREATE_UNWRAPPING_CASTER(Class) \ + template <> \ + struct type_caster : public type_caster_base { \ + public: \ + using type = Class; \ + using holder_type = torch::jit::unwrapping_shared_ptr; \ + \ + bool load(handle src, bool convert) { \ + return load_impl>(src, convert); \ + } \ + \ + explicit operator type*() { \ + return static_cast(value); \ + } \ + explicit operator type&() { \ + return *static_cast(value); \ + } \ + \ + protected: \ + friend class type_caster_generic; \ + \ + bool load_value(const value_and_holder& v_h) { \ + if (v_h.holder_constructed()) { \ + value = v_h.template holder().get(); \ + return true; \ + } else { \ + throw cast_error( \ + "Unable to cast from non-held to held instance (#Class& to Holder<#Class>)"); \ + } \ + } \ + } + +CREATE_UNWRAPPING_CASTER(torch::jit::Node); +CREATE_UNWRAPPING_CASTER(torch::jit::Value); +CREATE_UNWRAPPING_CASTER(torch::jit::Block); + +#undef CREATE_UNWRAPPING_CASTER + +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(torch::jit::IValue, _("IValue")); + + bool load(handle src, bool /*unused*/) { + try { + value = torch::jit::toTypeInferredIValue(src); + return true; + } catch (std::exception&) { + return false; + } + } + + static handle cast( + torch::jit::IValue src, + return_value_policy /* policy */, + handle /* parent */) { + return torch::jit::toPyObject(std::move(src)).release(); + } +}; + +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(torch::jit::Symbol, _("Symbol")); + + bool load(handle src, bool /*unused*/) { + // TODO: Is there a way to py::cast that doesn't raise an exception on + // failure? Can we catch pybind11::cast_error here instead? + std::string src_str; + try { + src_str = py::cast(src); + } catch (std::exception&) { + return false; + } + value = torch::jit::Symbol::fromQualString(src_str); + return true; + } + + static handle cast( + torch::jit::Symbol src, + return_value_policy /* policy */, + handle /* parent */) { + return py::cast(std::string(src.toQualString()), return_value_policy::copy) + .release(); + } +}; + +template <> +struct type_caster { + public: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + PYBIND11_TYPE_CASTER(torch::jit::AttributeKind, _("AttributeKind")); + + bool load(handle src, bool /*unused*/) { + return false; + } + + static handle cast( + torch::jit::AttributeKind src, + return_value_policy /* policy */, + handle /* parent */) { + return py::cast( + std::string(torch::jit::toString(src)), + return_value_policy::copy) + .release(); + } +}; + +// See https://github.com/pybind/pybind11/issues/637 +using ListCasterBase = pybind11::detail:: + list_caster, torch::jit::Node*>; +template <> +struct type_caster> : ListCasterBase { + static handle cast( + const std::vector& src, + return_value_policy /*unused*/, + handle parent) { + return ListCasterBase::cast(src, return_value_policy::reference, parent); + } + static handle cast( + const std::vector* src, + return_value_policy pol, + handle parent) { + return cast(*src, pol, parent); + } +}; + +} // namespace pybind11::detail + +namespace torch::jit { + +static inline py::tuple tuple_tail(const py::tuple& tup) { + py::tuple r(tup.size() - 1); + for (const auto i : c10::irange(1, tup.size())) { + r[i - 1] = tup[i]; + } + return r; +} + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind_utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..888926575eb40b7d0fb7a35f2fd8bea1edbc5f92 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind_utils.h @@ -0,0 +1,1337 @@ +#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 +#include +#include +#ifdef USE_DISTRIBUTED +#include +#include +#endif + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +// The visibility attribute is to avoid a warning about storing a field in the +// struct that has a different visibility (from pybind) than the struct. +#ifdef _WIN32 +#define VISIBILITY_HIDDEN +#else +#define VISIBILITY_HIDDEN __attribute__((visibility("hidden"))) +#endif + +namespace torch::jit { + +using ResolutionCallback = std::function; + +void clear_registered_instances(void* ptr); + +TORCH_PYTHON_API IValue toIValue( + py::handle obj, + const TypePtr& type, + std::optional N = std::nullopt); + +TORCH_PYTHON_API py::object toPyObject(IValue ivalue); + +// Hack to overload the behavior of toIValue to accept Python +// numbers in places where a Tensor is expected +// See also torch::should_allow_numbers_as_tensors +class TORCH_PYTHON_API ToIValueAllowNumbersAsTensors { + bool old_; + + public: + ToIValueAllowNumbersAsTensors(bool enable); + ~ToIValueAllowNumbersAsTensors(); +}; + +// Wrap Python function to guard deref +// NB: Need VISIBILITY_HIDDEN for silencing compiler error, +// 'torch::jit::PythonFunctionGuard' declared with greater visibility than the +// type of its field 'torch::jit::PythonFunctionGuard::func_' +struct VISIBILITY_HIDDEN PythonFunctionGuard { + explicit PythonFunctionGuard(py::function func) : func_(std::move(func)) {} + PythonFunctionGuard(const PythonFunctionGuard&) = delete; + PythonFunctionGuard(PythonFunctionGuard&&) = delete; + PythonFunctionGuard& operator=(const PythonFunctionGuard&) = delete; + PythonFunctionGuard& operator=(PythonFunctionGuard&&) = delete; + + ~PythonFunctionGuard() { + pybind11::gil_scoped_acquire ag; + func_.dec_ref(); + // explicitly setting PyObject* to nullptr to prevent py::object's dtor to + // decref on the PyObject again. + // See Note [Destructing py::object] in python_ivalue.h + func_.ptr() = nullptr; + } + + py::function func_; +}; + +// The PythonFutureWrapper for ivalue::Future +// +// NB: VISIBILITY_HIDDEN is for silencing compiling error, +// "error: 'torch::jit::PythonFutureWrapper' declared with greater visibility +// than the type of its field 'torch::jit::PythonFutureWrapper::unwrap_func' +// [-Werror=attributes]" +// +// NB: inherit from enable_shared_from_this because then(py::function) needs to +// get a shared_ptr from this pointer. +struct VISIBILITY_HIDDEN PythonFutureWrapper + : std::enable_shared_from_this { + using UnwrapFunc = std::function; + + explicit PythonFutureWrapper( + c10::intrusive_ptr fut, + std::optional unwrap_func = std::nullopt) + : fut(std::move(fut)), unwrap_func(std::move(unwrap_func)) {} + + explicit PythonFutureWrapper(const PythonFutureWrapper&) = delete; + PythonFutureWrapper& operator=(const PythonFutureWrapper&) = delete; + PythonFutureWrapper(PythonFutureWrapper&&) = default; + PythonFutureWrapper& operator=(PythonFutureWrapper&&) = default; + ~PythonFutureWrapper() = default; + + bool done() { + return fut->completed(); + } + + py::object value() { + // acquiring GIL as toPyObject creates new py::object + // without grabbing the GIL. + py::gil_scoped_acquire acquire; + py::object py_obj = toPyObject(fut->value()); + // unwrap_func is a general compositional function that takes in a + // py::object and executes some python function. It is currently mostly used + // to throw python exceptions. + if (unwrap_func) { + (*unwrap_func)(py_obj); + } + return py_obj; + } + + py::object wait() { + fut->wait(); + if (jit::tracer::isTracing()) { + auto graph = jit::tracer::getTracingState()->graph; + + Value* fut_val = jit::tracer::getValueTrace(fut); + auto output = graph->insert(aten::wait, {fut_val}); + jit::tracer::setValueTrace(fut->value(), output); + } + return value(); + } + + // The py::function cb arg must take a std::shared_ptr + // (i.e., torch._C.Future) as the only argument. If the type mismatches, an + // error will be thrown when waiting for the value of this returned Future. + std::shared_ptr then(py::function cb) { + // We need this an additional layer of wrapper here to guard the + // destruction of the py::function object. Because, the + // Future owns a reference to the py::function in its callback + // vector, but Future does not acquire GIL on destruction. + auto pf = std::make_shared(std::move(cb)); + + return std::make_shared(fut->then( + // Capture a copy of the ivalue::Future instead of the `this` pointer + // because the PythonFutureWrapper object could have been deleted + // when the callbacks are fired. For example, RPC only captures the + // ivalue::Future instead of PythonFutureWrapper in JitFuture's + // callback functions. Hence, if user code does not hold a reference to + // this PythonFutureWrapper object, there is no guarantee that the + // PythonFutureWrapper is still valid when running the callback. + [pyFut(this->getPtr()), + pf(std::move(pf))](c10::ivalue::Future& /* unused */) -> IValue { + try { + pybind11::gil_scoped_acquire ag; + return toIValue(pf->func_(pyFut), PyObjectType::get()); + } catch (py::error_already_set& e) { + auto err = std::runtime_error(c10::str( + "Got the following error when running the callback: ", + e.what())); + { + pybind11::gil_scoped_acquire ag; + // Release ownership on py::objects and also restore Python + // Error Indicator. + e.restore(); + // Clear the Python Error Indicator as we has recorded the + // exception in the response message. + PyErr_Clear(); + } + + throw std::runtime_error(err); + } + }, + PyObjectType::get())); + } + + void add_done_callback(py::function cb) { + auto pf = std::make_shared(std::move(cb)); + // NOLINTNEXTLINE(modernize-avoid-bind) + fut->addCallback(std::bind( + [pyFut(this->getPtr())]( + const std::shared_ptr& pf) { + try { + pybind11::gil_scoped_acquire ag; + pf->func_(pyFut); + } catch (py::error_already_set& e) { + { + pybind11::gil_scoped_acquire ag; + // Release ownership on py::objects and also restore Python + // Error Indicator. + e.restore(); + // Clear the Python Error Indicator as we has recorded the + // exception in the response message. + PyErr_Clear(); + } + // Log and ignore exceptions raised through the callback + LOG(ERROR) << "Got the following error when running the callback: " + << e.what(); + + } catch (const std::exception& e) { + // Log and ignore exceptions raised through the callback + LOG(ERROR) << "Got the following error when running the callback: " + << e.what(); + } + }, + std::move(pf))); + } + + void markCompleted(const py::object& pyValue) { + DCHECK(PyGILState_Check()); + IValue value = toIValue(pyValue, PyObjectType::get()); + + py::gil_scoped_release release; + fut->markCompleted(std::move(value)); + } + + c10::intrusive_ptr fut; + // unwrap_func works like a callback for the value returned by + // PythonFutureWrapper::wait(). + std::optional unwrap_func; + + private: + std::shared_ptr getPtr() { + return shared_from_this(); + } +}; + +// The PythonAwaitWrapper for ivalue::Await +// +// Expresses delayed function execution with Lazy semantic. +// i.e. Await[W] in eager mode can be used as W. +// When the attribute of W type is requested, Await[W] will return the +// attribute of W, transparently calling wait() beforehand. +// No Lazy semantic for script, explicit wait(Await[W]) -> W must be called to +// convert to type W. +// +// The Await object takes shared ownership of specified function and the +// arguments. After first call for wait() it owns the result. Deliberately no +// type inference for eager mode. +struct VISIBILITY_HIDDEN PythonAwaitWrapper + : std::enable_shared_from_this { + explicit PythonAwaitWrapper(c10::intrusive_ptr aw) + : aw_(std::move(aw)) {} + explicit PythonAwaitWrapper(py::handle input) { + args_ = py::tuple(1u); + args_[0] = input; + auto type = PyObjectType::get(); + aw_ = c10::make_intrusive(type); + aw_->markCompleted(toIValue(input, type)); + } + + explicit PythonAwaitWrapper(py::function pf, py::tuple args) + : args_(std::move(args)) { + pyfg_ = std::make_shared(std::move(pf)); + + std::function f = [fg(pyfg_), &args(args_)]() { + pybind11::gil_scoped_acquire ag; + return toIValue(fg->func_(*args), PyObjectType::get()); + }; + aw_ = c10::make_intrusive( + PyObjectType::get(), std::move(f)); + } + + explicit PythonAwaitWrapper(const PythonAwaitWrapper&) = delete; + PythonAwaitWrapper& operator=(const PythonAwaitWrapper&) = delete; + PythonAwaitWrapper(PythonAwaitWrapper&&) = default; + PythonAwaitWrapper& operator=(PythonAwaitWrapper&&) = default; + ~PythonAwaitWrapper() = default; + + py::object wait() { + py::gil_scoped_acquire acquire; + return toPyObject(aw_->wait()); + } + + // Nowait semantic means trivial case when Await is constructed from the + // result + bool is_nowait() { + return pyfg_ == nullptr; + } + + const py::function fn() { + TORCH_CHECK( + pyfg_, "Await constructed as awaitable_nowait does not have fn"); + return pyfg_->func_; + } + + const py::tuple args() { + return args_; + } + + TypePtr type() { + return aw_->type(); + } + + c10::intrusive_ptr aw_; + std::shared_ptr pyfg_; + py::tuple args_; + + private: + std::shared_ptr getPtr() { + return shared_from_this(); + } +}; + +// error reporting: when reporting user-caused errors, these functions should +// not use AT_ERROR macros, since these macros add stack trace information +// that is confusing to display to the end user since it always reports +// locations in libtorch code rather than user code. + +inline std::shared_ptr get_python_cu() { + return py::module::import("torch.jit._state") + .attr("_python_cu") + .cast>(); +} + +struct TypedIValue : public std::pair { + using pair::pair; + + IValue& ivalue() { + return this->first; + } + TypePtr& type() { + return this->second; + } +}; + +inline TypedIValue toDictKeyIValue(py::handle key) { + if (py::isinstance(key)) { + return TypedIValue( + ConstantString::create(py::cast(key)), StringType::get()); + } else if (py::isinstance(key)) { + return TypedIValue(py::cast(key), IntType::get()); + } else if (py::isinstance(key)) { + return TypedIValue(py::cast(key), FloatType::get()); + } else { + TORCH_CHECK( + false, "Dictionary inputs may only have string, int, or float keys"); + } +} + +inline std::optional unifyOrInitializeType( + const TypePtr& accum, + const TypePtr& unify) { + if (!accum) { + return unify; + } + return unifyTypes(accum, unify); +} + +using InferredType = c10::InferredType; + +InferredType tryToInferContainerType(py::handle input, bool primitiveTypeOnly); + +// Try to infer the type of a Python object +// The type cannot be inferred if: +// input is an empty container (list, dict) +// input is an list with element types that cannot be unified +// input is an dict with key or value types that cannot be unified +inline InferredType tryToInferType(py::handle input) { + // Try tensor types + if (THPVariable_Check(input.ptr())) { + return InferredType(TensorType::get()); + } + + if (input.is_none()) { + return InferredType(NoneType::get()); + } + + if (py::isinstance(input)) { + auto fn = py::cast(input).function_; + return InferredType(FunctionType::create(fn)); + } + + // Try basic types first + if (py::isinstance(input)) { + return InferredType(BoolType::get()); + // NOLINTNEXTLINE(bugprone-branch-clone) + } else if (py::isinstance(input)) { + return InferredType(IntType::get()); + } else if (py::isinstance(input)) { + return InferredType(FloatType::get()); + } else if (PyComplex_CheckExact(input.ptr())) { + return InferredType(ComplexType::get()); + // NOLINTNEXTLINE(bugprone-branch-clone) + } else if (py::isinstance(input)) { + // NOTE: We may need a ByteType in the future + return InferredType(StringType::get()); + } else if (py::isinstance(input)) { + return InferredType(StringType::get()); + } else if (THPLayout_Check(input.ptr())) { + return InferredType(IntType::get()); + } else if (THPDevice_Check(input.ptr())) { + return InferredType(DeviceObjType::get()); + } else if (THPGenerator_Check(input.ptr())) { + return InferredType(GeneratorType::get()); + } else if (THPStream_Check(input.ptr())) { + return InferredType(StreamObjType::get()); + } else if (THPDtype_Check(input.ptr())) { + return InferredType(IntType::get()); + } else if (THPQScheme_Check(input.ptr())) { + return InferredType(IntType::get()); + } else if (THPLayout_Check(input.ptr())) { + return InferredType(IntType::get()); + } + + auto enum_type = py::module::import("enum").attr("Enum"); + py::bool_ isEnumValue = py::isinstance(input, enum_type); + if (py::cast(isEnumValue)) { + auto enum_class = input.attr("__class__"); + auto enum_type = py::cast( + py::module::import("torch.jit.annotations") + .attr("try_ann_to_type")(enum_class, SourceRange())); + return InferredType(std::move(enum_type)); + } + + py::bool_ isClass = + py::module::import("inspect").attr("isclass")(py::type::handle_of(input)); + if (py::cast(isClass)) { + // Assume that the class is compiled already or will compile. Invalidate + // this later if needed. + bool class_compiled = true; + + // Check if the type is already compiled. + py::object existing_ty = + py::module::import("torch.jit._state") + .attr("_get_script_class")(py::type::handle_of(input)); + + if (existing_ty.is_none()) { + // If not, try to compile it. + py::bool_ can_compile = + py::module::import("torch._jit_internal") + .attr("can_compile_class")(py::type::handle_of(input)); + + if (py::cast(can_compile)) { + // Try to compile the class. This is wrapped in a try-catch because + // compilation of class types can raise an Exception and in that case, + // we want to defer to other attempts at type inference below rather + // than fail compilation altogether. + try { + py::module::import("torch.jit._script") + .attr("_recursive_compile_class")( + py::type::handle_of(input), SourceRange()); + } catch (...) { + // Invalidate the assumption that the class compiled so that we don't + // look up and return its JIT type as the type for the input. + class_compiled = false; + } + } + } + + // If the class compiled successfully, look up the existing JIT type by + // qualified name and return it. + if (class_compiled) { + auto script_class = + py::module::import("torch.jit._state") + .attr("_get_script_class")(py::type::handle_of(input)); + + if (!script_class.is_none()) { + auto class_type = py::cast(script_class); + + if (class_type && !class_type->is_module()) { + return InferredType(std::move(class_type)); + } + } + } + } + + if (py::isinstance(input)) { + auto object = py::cast(input); + return InferredType(object.type()); +#ifdef USE_RPC + } else if (py::isinstance(input)) { + auto rref_ivalue = input.cast().toIValue(); + return InferredType(rref_ivalue.type()); +#endif + } + + auto await_type = py::module::import("torch._awaits").attr("_Await"); + py::bool_ is_await = py::isinstance(input, await_type); + if (py::cast(is_await)) { + auto awptr = input.cast>(); + return InferredType(AwaitType::create(awptr->aw_->elementType())); + } + + if (as_module(py::cast(input))) { + return InferredType("Cannot infer type of ScriptModule"); + } + + auto module_type = py::module::import("torch.nn").attr("Module"); + py::bool_ is_module = py::isinstance(input, module_type); + if (py::cast(is_module)) { + return InferredType("Cannot infer concrete type of torch.nn.Module"); + } + + // Try container types + return tryToInferContainerType(input, false); +} + +// This function is similar to tryToInferType, but it only tries to infer +// primitive types (int, float, bool, complex) or nested container of primitive +// types. +inline InferredType tryToInferPrimitiveType(py::handle input) { + if (input.is_none()) { + return InferredType(NoneType::get()); + } + + // Only primitive data type + if (py::isinstance(input)) { + return InferredType(BoolType::get()); + // NOLINTNEXTLINE(bugprone-branch-clone) + } else if (py::isinstance(input)) { + return InferredType(IntType::get()); + } else if (py::isinstance(input)) { + return InferredType(FloatType::get()); + } else if (PyComplex_CheckExact(input.ptr())) { + return InferredType(ComplexType::get()); + } + + // Try container types + return tryToInferContainerType(input, true); +} + +inline InferredType tryToInferContainerType( + py::handle input, + bool primitiveTypeOnly = false) { + if (six::isTuple(input)) { + py::tuple tuple = py::cast(input); + std::vector element_types; + element_types.reserve(tuple.size()); + + for (py::handle elem : tuple) { + auto type_match = primitiveTypeOnly ? tryToInferPrimitiveType(elem) + : tryToInferType(elem); + if (type_match.success()) { + element_types.push_back(type_match.type()); + } else { + // Forward error message along + return type_match.reason(); + } + } + return InferredType(TupleType::create(std::move(element_types))); + } else if (PyDict_Check(input.ptr())) { + // Check to make sure we can generate useful input/output types + auto dict = py::cast(input); + size_t len = py::len(dict); + if (!len) { + return InferredType("Dictionary inputs must have entries"); + } + + TypePtr key_type = nullptr; + TypePtr value_type = nullptr; + + for (auto entry : dict) { + // Try to infer the key type and unify it with the existing one + auto entry_key_type_match = primitiveTypeOnly + ? tryToInferPrimitiveType(entry.first) + : tryToInferType(entry.first); + if (!entry_key_type_match.success()) { + return entry_key_type_match.reason(); + } + auto unified_key = + unifyOrInitializeType(key_type, entry_key_type_match.type()); + if (!unified_key) { + return InferredType(c10::str( + "Dictionary inputs to traced functions must have consistent type. Found ", + key_type->repr_str(), + " and ", + (entry_key_type_match.type())->repr_str())); + } + + // Try to infer the value type and unify it with the existing one + auto entry_value_type_match = primitiveTypeOnly + ? tryToInferPrimitiveType(entry.second) + : tryToInferType(entry.second); + if (!entry_value_type_match.success()) { + return entry_value_type_match.reason(); + } + auto unified_value = + unifyOrInitializeType(value_type, entry_value_type_match.type()); + if (!unified_value) { + return InferredType(c10::str( + "Dictionary inputs to traced functions must have consistent type. Found ", + value_type->repr_str(), + " and ", + (entry_value_type_match.type())->repr_str())); + } + + key_type = *unified_key; + value_type = *unified_value; + } + return InferredType( + DictType::create(std::move(key_type), std::move(value_type))); + } else if (PyList_Check(input.ptr())) { + auto list = py::cast(input); + size_t len = py::len(list); + if (!len) { + return InferredType("List trace inputs must have elements"); + } + + TypePtr element_type = nullptr; + for (auto elem : list) { + auto element_type_match = primitiveTypeOnly + ? tryToInferPrimitiveType(elem) + : tryToInferType(elem); + if (!element_type_match.success()) { + return InferredType(c10::str( + "Could not infer type of list element: ", + element_type_match.reason())); + } + auto unified_type = + unifyOrInitializeType(element_type, element_type_match.type()); + if (!unified_type) { + return InferredType(c10::str( + "List inputs to traced functions must have consistent element type. Found ", + element_type->repr_str(), + " and ", + (element_type_match.type())->repr_str())); + } + element_type = *unified_type; + } + return InferredType(ListType::create(element_type)); + } else { + if (primitiveTypeOnly) { + return InferredType(c10::str( + "Only tuple, list, or dict (possibly nested) of primitive types (bool, float, int, complex)", + "are supported ", + "as inputs or outputs of traced functions", + ", but instead got value of type ", + py::str(py::type::handle_of(input).attr("__name__")), + ".")); + } else { + // TODO: this message is not correct anymore, since this InferredType is + // used from a bunch of circumstances unrelated to tracing. We can reuse + // this instead of the attribute_failure stuff in concreteType + return InferredType(c10::str( + "Only tensors and (possibly nested) tuples of tensors, lists, or dicts ", + "are supported ", + "as inputs or outputs of traced functions", + ", but instead got value of type ", + py::str(py::type::handle_of(input).attr("__name__")), + ".")); + } + } +} + +inline bool isTraceableType(const TypePtr& type) { + if (type->isSubtypeOf(*TensorType::get())) { + return true; + } + + if (auto list_type = type->cast()) { + return isTraceableType(list_type->getElementType()); + } + + if (auto tuple_type = type->cast()) { + return std::all_of( + tuple_type->elements().begin(), + tuple_type->elements().end(), + [](const TypePtr& element_type) { + return isTraceableType(element_type); + }); + } + + if (auto dict_type = type->cast()) { + return isTraceableType(dict_type->getValueType()); + } + + return false; +} + +inline IValue toTypeInferredIValue(py::handle input) { + auto match = tryToInferType(input); + if (!match.success()) { + auto object = py::cast(input); + if (auto mod = as_module(object)) { + // if obj is already a ScriptModule, just return its ivalue + auto ptr = mod.value()._ivalue(); + // explicit copy semantics for strong ownership of the resource. + return c10::intrusive_ptr::reclaim_copy( + ptr.release()); + } + + // Check if the obj is a ScriptObject. + if (auto script_obj = as_object(object)) { + auto ptr = script_obj.value()._ivalue(); + return c10::intrusive_ptr::reclaim_copy( + ptr.release()); + } + TORCH_CHECK( + false, + "Tracer cannot infer type of ", + py::str(input), + "\n:", + match.reason()); + } + return toIValue(input, match.type()); +} + +inline Stack toTraceableStack(const py::tuple& inputs) { + auto info = toTypeInferredIValue(inputs); + TORCH_CHECK( + isTraceableType(info.type()), + "Type '", + info.type()->repr_str(), + "' cannot be traced. Only Tensors and (possibly nested) Lists, Dicts, and" + " Tuples of Tensors can be traced"); + return info.toTupleRef().elements().vec(); +} + +// Serialize the python dictionary into a traceable stack. +inline Stack toTraceableStack(const py::dict& inputs) { + Stack res; + for (auto it = inputs.begin(); it != inputs.end(); it++) { + if (THPVariable_Check(it->second.ptr())) { + res.push_back(toIValue(it->second, tryToInferType(it->second).type())); + } + } + return res; +} + +inline IValue createGenericList(py::handle obj, const TypePtr& elem_type) { + auto elems = c10::impl::GenericList(elem_type); + for (auto elem : obj) { + elems.push_back(toIValue(elem, elem_type)); + } + return IValue(elems); +} + +inline IValue createGenericDict( + const py::dict& obj, + const TypePtr& key_type, + const TypePtr& value_type) { + c10::impl::GenericDict elems(key_type, value_type); + elems.reserve(py::len(obj)); + for (auto& entry : obj) { + elems.insert( + toIValue(entry.first, key_type), toIValue(entry.second, value_type)); + } + return IValue(elems); +} + +template +inline void guardAgainstNamedTensor(const T& var) { + TORCH_CHECK( + !var.has_names(), + "NYI: Named tensors are currently unsupported in TorchScript. As a " + "workaround please drop names via `tensor = tensor.rename(None)`."); +} + +// Extract custom class registered with torchbind +template +c10::intrusive_ptr toCustomClass(py::handle obj) { + static_assert( + std::is_base_of_v, "T is not a CustomClass"); + const auto& type = c10::getCustomClassType>(); + c10::IValue ivalue = toIValue(obj, type); + return std::move(ivalue).toCustomClass(); +} + +// Small wrapper around getting the type name string from Python to make +// types easier to interpret, e.g. give the structural type for a NamedTuple +inline std::string friendlyTypeName(py::handle obj) { + if (py::isinstance(obj) && py::hasattr(obj, "_fields")) { + auto field_names = + py::cast>(py::getattr(obj, "_fields")); + std::stringstream ss; + ss << py::str(py::type::handle_of(obj).attr("__name__")); + ss << " (aka NamedTuple("; + bool first = true; + for (auto& field_name : field_names) { + if (!first) { + ss << ", "; + } + ss << field_name; + first = false; + } + ss << "))"; + return ss.str(); + } else { + return py::str(py::type::handle_of(obj).attr("__name__")); + } +} + +// Thrown when trying to create a schema for a list of python +// arguments that cannot be converted. +// Can be caught by the caller to attempt to use other schema +// when there is an overloaded operator. +struct schema_match_error : public std::runtime_error { + using std::runtime_error::runtime_error; +}; + +inline IValue argumentToIValue( + const FunctionSchema& schema, + size_t argumentPosition, + py::handle object) { + const auto& argument = schema.arguments().at(argumentPosition); + try { + return toIValue(object, argument.real_type(), argument.N()); + } catch (const py::cast_error& error) { + throw schema_match_error(c10::str( + schema.formatTypeMismatchMsg( + argument, + friendlyTypeName(object), + argumentPosition, + py::repr(object)), + "\nCast error details: ", + error.what())); + } catch (const py::error_already_set& error) { + throw schema_match_error(c10::str( + schema.formatTypeMismatchMsg( + argument, + friendlyTypeName(object), + argumentPosition, + py::repr(object)), + "\n Python error details: ", + error.what())); + } +} + +inline IValue returnToIValue(const TypePtr& type, py::handle object) { + try { + return toIValue(object, type); + } catch (const py::cast_error& error) { + throw std::runtime_error(c10::str( + " expected value of type ", + type->str(), + " for return value but instead got value of type ", + py::str(py::type::handle_of(object).attr("__name__")), + ".", + "\nValue: ", + py::repr(object), + "\nCast error details: ", + error.what())); + } +} + +inline py::object getScriptedClassOrError(const c10::NamedTypePtr& classType) { + auto py_class = + py::module::import("torch.jit._state") + .attr("_get_python_class")(classType->name()->qualifiedName()); + if (py_class.is_none()) { + std::stringstream err; + err << "Unknown reference to ScriptClass "; + err << classType->name()->qualifiedName(); + err << ". (Did you forget to import it?)"; + throw std::runtime_error(err.str()); + } + return py_class; +} + +struct VISIBILITY_HIDDEN tuple_slice { + /*implicit*/ tuple_slice(py::tuple tup_) + : tup(std::move(tup_)), b(0), e(static_cast(tup.size())) {} + tuple_slice(py::tuple tup_, int64_t b_) + : tup(std::move(tup_)), b(b_), e(static_cast(tup.size())) {} + tuple_slice(py::tuple tup_, int64_t b_, int64_t e_) + : tup(std::move(tup_)), b(b_), e(e_) {} + py::detail::tuple_iterator begin() const { + return {tup, static_cast(b)}; + } + py::detail::tuple_iterator end() const { + return {tup, static_cast(e)}; + } + size_t size() const { + return e - b; + } + py::detail::tuple_accessor operator[](size_t index) const { + return {tup, static_cast(b + index)}; + } + + private: + py::tuple tup; + int64_t b; + int64_t e; +}; + +inline bool validateFakeScriptObjectSchema( + const c10::FunctionSchema& schema, + size_t argumentPosition, + py::handle object) { + auto argument = schema.arguments().at(argumentPosition); + auto class_type = argument.real_type()->expect(); + auto fake_class_registry = + py::module::import("torch._library.fake_class_registry"); + auto fake_class = fake_class_registry.attr("find_fake_class")( + class_type->name().value().qualifiedName()); + if (!py::isinstance(object.attr("wrapped_obj"), fake_class)) { + throw schema_match_error(c10::str( + schema.formatTypeMismatchMsg( + argument, + friendlyTypeName(object), + argumentPosition, + py::repr(object.attr("wrapped_obj"))), + "\nCast error details: ", + argument.name(), + " is expected to be a FakeScriptObject of ", + class_type->name().value().qualifiedName())); + } + return true; +} + +inline bool matchSchemaAllowFakeScriptObject( + const FunctionSchema& schema, + const tuple_slice& args, + const py::kwargs& kwargs) { + size_t all_arguments = args.size() + kwargs.size(); + if (all_arguments > schema.arguments().size()) { + throw schema_match_error(c10::str( + schema.name(), + "() expected at most ", + schema.arguments().size(), + " argument(s) but received ", + all_arguments, + " argument(s). Declaration: ", + schema)); + } + + int64_t arg_idx = 0; + auto fake_class_registry = + py::module::import("torch._library.fake_class_registry"); + + // First push all positional args. + for (const auto& arg : args) { + // ...but refuse to do it if the schema says that this was supposed + // to be keyword only + if (schema.arguments()[arg_idx].kwarg_only()) { + throw schema_match_error(c10::str( + schema.name(), + "() takes ", + arg_idx, + " positional argument(s) but ", + args.size(), + " was/were given. Declaration: ", + schema)); + } + // Use the type information from the schema to convert the PyObject. + const auto& argument = schema.arguments().at(arg_idx); + if (argument.real_type()->kind() == TypeKind::ClassType && + py::isinstance(arg, fake_class_registry.attr("FakeScriptObject"))) { + validateFakeScriptObjectSchema(schema, arg_idx, arg); + } else { + argumentToIValue(schema, arg_idx, arg); + } + + arg_idx++; + } + + // Now for every remaining non-positional argument in the schema, look for it + // in the kwargs dict and push it if found, or use its default value if it + // has one. + size_t consumed_kwargs = 0; + for (size_t i = arg_idx; i < schema.arguments().size(); ++i) { + const auto& arg = schema.arguments()[i]; + if (kwargs.contains(arg.name().c_str())) { + auto cur_kwarg = kwargs[arg.name().c_str()]; + if (arg.real_type()->kind() == TypeKind::ClassType && + py::isinstance( + cur_kwarg, fake_class_registry.attr("FakeScriptObject"))) { + validateFakeScriptObjectSchema(schema, i, cur_kwarg); + } else { + argumentToIValue(schema, i, cur_kwarg); + } + consumed_kwargs += 1; + } else if (arg.default_value()) { + continue; + } else { + throw schema_match_error(c10::str( + schema.name(), + "() is missing value for argument '", + arg.name(), + "'. Declaration: ", + schema)); + } + } + + if (consumed_kwargs != kwargs.size()) { + std::vector names; + for (const auto& kwarg : kwargs) { + names.emplace_back(py::cast(kwarg.first)); + } + throw schema_match_error(schema.findErrorInKwargs(names)); + } + + return true; +} + +inline Stack createStackForSchema( + const FunctionSchema& schema, + const tuple_slice& args, + const py::kwargs& kwargs, + std::optional self) { + size_t all_arguments = (self ? 1 : 0) + args.size() + kwargs.size(); + if (all_arguments > schema.arguments().size()) { + throw schema_match_error(c10::str( + schema.name(), + "() expected at most ", + schema.arguments().size(), + " argument(s) but received ", + all_arguments, + " argument(s). Declaration: ", + schema)); + } + Stack stack; + stack.reserve(schema.arguments().size()); + + int64_t arg_idx = 0; + if (self) { + push(stack, std::move(*self)); + arg_idx++; + } + // First push all positional args. + for (const auto& arg : args) { + // ...but refuse to do it if the schema says that this was supposed + // to be keyword only + if (schema.arguments()[arg_idx].kwarg_only()) { + throw schema_match_error(c10::str( + schema.name(), + "() takes ", + arg_idx, + " positional argument(s) but ", + self ? 1 + args.size() : args.size(), + " was/were given. Declaration: ", + schema)); + } + // Use the type information from the schema to convert the PyObject. + push(stack, argumentToIValue(schema, stack.size(), arg)); + arg_idx++; + } + + // Now for every remaining non-positional argument in the schema, look for it + // in the kwargs dict and push it if found, or use its default value if it + // has one. + size_t consumed_kwargs = 0; + for (size_t i = stack.size(); i < schema.arguments().size(); ++i) { + const auto& arg = schema.arguments()[i]; + if (kwargs.contains(arg.name().c_str())) { + push(stack, argumentToIValue(schema, i, kwargs[arg.name().c_str()])); + consumed_kwargs += 1; + } else if (arg.default_value()) { + push(stack, *arg.default_value()); + } else { + throw schema_match_error(c10::str( + schema.name(), + "() is missing value for argument '", + arg.name(), + "'. Declaration: ", + schema)); + } + } + + if (consumed_kwargs != kwargs.size()) { + std::vector names; + for (const auto& kwarg : kwargs) { + names.emplace_back(py::cast(kwarg.first)); + } + throw schema_match_error(schema.findErrorInKwargs(names)); + } + + return stack; +} + +// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) +inline py::object createPyObjectForStack(Stack&& stack) { + if (stack.empty()) { + return py::none(); + } + + // Return a simple value and not a single-element tuple if there is only one + // return value. + if (stack.size() == 1) { + return toPyObject(std::move(stack[0])); + } + + // If there is more than one return value, pop them into a py::tuple. + py::tuple return_values(stack.size()); + for (const auto ret : c10::irange(return_values.size())) { + return_values[ret] = toPyObject(std::move(stack[ret])); + } + +#if defined(__clang__) + return std::move(return_values); +#else + return return_values; +#endif +} + +// TODO: Remove once we clean up the GraphExecutor usage. +inline Stack evilDeprecatedBadCreateStackDoNotUse( + const py::tuple& tuple, + at::ArrayRef inputs, + size_t reserve_extra_space = 0) { + if (tuple.size() != inputs.size()) { + TORCH_CHECK( + false, + "expected " + std::to_string(inputs.size()) + " inputs, but got " + + std::to_string(tuple.size())); + } + Stack result; + result.reserve(tuple.size() + reserve_extra_space); + for (const auto i : c10::irange(inputs.size())) { + result.push_back(toIValue(std::move(tuple[i]), inputs[i]->type())); + } + return result; +} + +// Run `callee`, potentially inserting a CallFunction/CallMethod node into the +// tracing graph. +inline py::object runAndInsertCall( + Function& callee, + const tuple_slice& args, + const py::kwargs& kwargs, + std::optional self, + // Lambda that tells this function how to insert `callee` into the graph if + // we're tracing. + const std::function& + callInserter) { + auto stack = + createStackForSchema(callee.getSchema(), args, kwargs, std::move(self)); + const auto& tracing_state = tracer::getTracingState(); + if (!tracing_state) { + pybind11::gil_scoped_release no_gil_guard; + // If we're not tracing, just run the callee as normal. + callee.run(stack); + } else { + // If we are tracing, insert the appropriate CallFunction or CallMethod node + // and then run the callee with tracing disabled. + + // Get the graph `Value`s that represent the input IValues + auto inputs = last(stack, callee.num_inputs()); + auto input_values = + fmap(inputs, [](const IValue& v) { return tracer::getValueTrace(v); }); + TORCH_INTERNAL_ASSERT(callee.getSchema().returns().size() == 1) + auto return_type = callee.getSchema().returns().at(0).type(); + auto graph = tracing_state->graph; + std::vector named_values; + named_values.reserve(input_values.size()); + for (Value* v : input_values) { + named_values.emplace_back(v); + } + + // Add a call node. + MatchedSchema match = matchSchema( + callee.getSchema(), + tracer::getPythonInterpreterSourceRange(), + *graph, + named_values, + {}); + auto output_value = callInserter(*graph, match); + + // Actually run the callee. Pause the tracer so that we don't double-add the + // callee nodes. + { + pybind11::gil_scoped_release no_gil_guard; + ResourceGuard guard(tracer::pauseTracing()); + callee.run(stack); + } + + // Associate the output IValues with the output `Value`s in the graph + tracer::setValueTrace(stack.back(), output_value); + } + + TORCH_CHECK( + !stack.empty(), + "Expected values in the stack after execution but found none"); + return toPyObject(std::move(stack.back())); +} + +inline std::optional maybeTorchFunctionDispatch( + const py::object& callee, + const tuple_slice& args_no_self, + const py::kwargs& kwargs, + const c10::QualifiedName& qualname) { + std::vector args_vec; + for (const auto& arg : args_no_self) { + args_vec.push_back(arg); + } + py::tuple args = py::cast(args_vec); + + // Handle __torch_function__ dispatch + std::vector overloaded_args; + size_t total_arg_num = args.size() + kwargs.size(); + for (const auto& arg : args) { + is_tensor_and_append_overloaded(arg.ptr(), &overloaded_args); + is_tensor_list_and_append_overloaded( + arg.ptr(), + &overloaded_args, + static_cast(total_arg_num), + false /* throw_error */); + } + // NB: for kwargs, we cannot guarantee the order of appending + // is the same as the argument order in operator's schema. + // This is suboptimal, but should be fine. Later when we have + // better schema matching and argument parsing, we could + // match the operator in `operations` first, then the order will + // be guaranteed. + for (auto item : kwargs) { + is_tensor_and_append_overloaded(item.second.ptr(), &overloaded_args); + is_tensor_list_and_append_overloaded( + item.second.ptr(), + &overloaded_args, + total_arg_num, + false /* throw_error */); + } + if (!overloaded_args.empty()) { + return pybind11::reinterpret_steal( + handle_torch_function_no_python_arg_parser( + /*overloaded_args=*/overloaded_args, + /*args=*/args.ptr(), + /*kwargs=*/kwargs.ptr(), + /*func_name=*/qualname.name().c_str(), + /*torch_api_function=*/callee.ptr(), + /*module_name=*/qualname.prefix().c_str())); + } + + return std::nullopt; +} + +inline py::object invokeScriptFunctionFromPython( + Function& callee, + const tuple_slice& args, + const py::kwargs& kwargs) { + // TODO: we could add __torch_function__ dispatch here but I don't know + // the implications of doing so + + return runAndInsertCall( + callee, + args, + kwargs, + /*self=*/std::nullopt, + [&](Graph& graph, const MatchedSchema& match) { + return graph.insertFunctionCall(&callee, match); + }); +} + +inline py::object invokeScriptMethodFromPython( + Method& callee, + const tuple_slice& args, + const py::kwargs& kwargs) { + auto self = callee.owner()._ivalue(); + + if (auto torch_fn_result = maybeTorchFunctionDispatch( + py::cast(callee), args, kwargs, callee.name())) { + return *torch_fn_result; + } + + return runAndInsertCall( + callee.function(), + args, + kwargs, + self, + [&](Graph& graph, const MatchedSchema& match) { + return graph.insertMethodCall(callee.name(), match); + }); +} + +TORCH_PYTHON_API std::pair, Stack> getOpWithStack( + const std::vector>& operations, + const py::args& args, + const py::kwargs& kwargs); + +// Efficient overload (does not require vector allocation) of the +// above for use from C++ code. +std::pair, Stack> getOpWithStack( + c10::ArrayRef> operations, + const py::args& args, + const py::kwargs& kwargs); + +TORCH_PYTHON_API py::object invokeOperatorFromPython( + const std::vector>& operations, + const py::args& args, + const py::kwargs& kwargs, + std::optional dk = std::nullopt); + +// Efficient overload (does not require vector allocation) of the +// above for use from C++ code. +py::object invokeOperatorFromPython( + c10::ArrayRef> operations, + const py::args& args, + const py::kwargs& kwargs, + std::optional dk = std::nullopt); + +TORCH_PYTHON_API std::optional _maybe_handle_torch_function( + const std::string& ns, + const std::string& method_name, + const std::string& overload_name, + bool is_overload, + const py::args& args, + const py::kwargs& kwargs); + +TORCH_PYTHON_API bool checkSchemaAllowFakeScriptObject( + const FunctionSchema& schema, + const py::args& args, + const py::kwargs& kwargs); + +TORCH_PYTHON_API py::object _get_operation_for_overload_or_packet( + const std::vector>& operations, + Symbol symbol, + const py::args& args, + const py::kwargs& kwargs, + bool is_overload, + std::optional dk = std::nullopt); + +// Efficient overload (does not require vector allocation) of the +// above for use from C++ code. +py::object _get_operation_for_overload_or_packet( + c10::ArrayRef> operations, + Symbol symbol, + const py::args& args, + const py::kwargs& kwargs, + bool is_overload, + std::optional dk = std::nullopt); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_arg_flatten.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_arg_flatten.h new file mode 100644 index 0000000000000000000000000000000000000000..873901a15199313fc3358fa0013b7333ce570d46 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_arg_flatten.h @@ -0,0 +1,124 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace torch::jit::python { + +struct IODescriptor { + struct VariableMetadata { + VariableMetadata(const autograd::Variable& var) + : sizes(var.sizes().vec()), + type(var.scalar_type()), + device(var.device()), + requires_grad(var.requires_grad()) {} + + bool operator==(const VariableMetadata& o) const { + return std::tie(device, requires_grad, type, sizes) == + std::tie(o.device, o.requires_grad, o.type, o.sizes); + } + + static size_t hash(const VariableMetadata& m) { + return c10::get_hash(m.sizes, m.device, m.requires_grad, m.type); + } + + std::vector sizes; + at::ScalarType type; + at::Device device; + bool requires_grad; + }; + + bool operator==(const IODescriptor& o) const { + return std::tie(structure, metadata, grad_enabled) == + std::tie(o.structure, o.metadata, o.grad_enabled); + } + + static size_t hash(const IODescriptor& o) { + return c10::get_hash(o.structure, o.metadata, o.grad_enabled); + } + + void extend(const autograd::variable_list& list) { + metadata.reserve(metadata.size() + list.size()); + for (auto& var : list) + metadata.emplace_back(var); + } + + // Description of argument structure. Variables are replaced with + // different characters, depending on their flags, beginnings and + // ends of tuples and lists are denoted by a pair of parenthesis + // of their corresponding kind. They should always be paired. + // Example desc: (vv[v(v)v]) + // NOTE: if extend() was ever called then metadata.size() can be + // different than the number of 'v's in structure. + std::string structure; + std::vector strings; + std::vector metadata; + bool grad_enabled = false; +}; + +static inline std::ostream& operator<<( + std::ostream& out, + const IODescriptor::VariableMetadata& meta) { + at::Device meta_device = meta.device; + auto& t = at::getDeprecatedTypeProperties( + meta_device.is_cpu() ? at::Backend::CPU : at::Backend::CUDA, meta.type); + out << t << "(requires_grad=" << meta.requires_grad; + if (meta_device.is_cuda()) { + out << ", device=" << meta_device.index(); + } + out << ") {"; + for (const auto i : c10::irange(meta.sizes.size())) { + if (i > 0) + out << ", "; + out << meta.sizes[i]; + } + out << '}'; + return out; +} + +static inline std::ostream& operator<<( + std::ostream& out, + const IODescriptor& desc) { + out << desc.structure << '\n'; + out << " with grad_enabled=" << desc.grad_enabled << '\n'; + for (const auto i : c10::irange(desc.metadata.size())) { + out << " with v" << i << " having type " << desc.metadata[i] << '\n'; + } + return out; +} + +struct ParsedArgs { + // Flat vector of Variables found in arguments + autograd::variable_list vars; + // Metadata describing nesting of objects received from Python and + // metadata of vars and whether grad is enabled. + IODescriptor desc; + + void extend(const autograd::variable_list& list) { + if (list.empty()) + return; + vars.reserve(vars.size() + list.size()); + for (auto& var : list) + vars.emplace_back(var); + desc.extend(list); + } +}; + +ParsedArgs flatten(py::handle obj); +PyObject* unflatten( + at::ArrayRef vars, + const IODescriptor& structure); + +} // namespace torch::jit::python + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_custom_class.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_custom_class.h new file mode 100644 index 0000000000000000000000000000000000000000..50af856c35ee8bf3e0c92676e2b71724631d5a82 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_custom_class.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +void initPythonCustomClassBindings(PyObject* module); + +struct ScriptClass { + ScriptClass(c10::StrongTypePtr class_type) + : class_type_(std::move(class_type)) {} + + py::object __call__(const py::args& args, const py::kwargs& kwargs); + + c10::StrongTypePtr class_type_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_dict.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_dict.h new file mode 100644 index 0000000000000000000000000000000000000000..e698d5ad0ebfa6b500e22be43c8a787e9689883a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_dict.h @@ -0,0 +1,132 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit { + +void initScriptDictBindings(PyObject* module); + +/// An iterator over the keys of ScriptDict. This is used to support +/// .keys() and iteration. +class ScriptDictKeyIterator final { + public: + ScriptDictKeyIterator( + c10::impl::GenericDict::iterator iter, + c10::impl::GenericDict::iterator end) + : iter_(std::move(iter)), end_(std::move(end)) {} + at::IValue next(); + + private: + c10::impl::GenericDict::iterator iter_; + c10::impl::GenericDict::iterator end_; +}; + +/// An iterator over the key-value pairs of ScriptDict. This is used to support +/// .items(). +class ScriptDictIterator final { + public: + ScriptDictIterator( + c10::impl::GenericDict::iterator iter, + c10::impl::GenericDict::iterator end) + : iter_(std::move(iter)), end_(std::move(end)) {} + at::IValue next(); + + private: + c10::impl::GenericDict::iterator iter_; + c10::impl::GenericDict::iterator end_; +}; + +/// A wrapper around c10::Dict that can be exposed in Python via pybind +/// with an API identical to the Python dictionary class. This allows +/// dictionaries to have reference semantics across the Python/TorchScript +/// boundary. +class ScriptDict final { + public: + // Constructor. + ScriptDict(const at::IValue& data) + : dict_(at::AnyType::get(), at::AnyType::get()) { + TORCH_INTERNAL_ASSERT(data.isGenericDict()); + dict_ = data.toGenericDict(); + } + + // Get the type of the dictionary. + at::DictTypePtr type() const { + return at::DictType::create(dict_.keyType(), dict_.valueType()); + } + + // Return a string representation that can be used + // to reconstruct the instance. + std::string repr() const { + std::ostringstream s; + s << '{'; + bool f = false; + for (auto const& kv : dict_) { + if (f) { + s << ", "; + } + s << kv.key() << ": " << kv.value(); + f = true; + } + s << '}'; + return s.str(); + } + + // Return an iterator over the keys of the dictionary. + ScriptDictKeyIterator iter() const { + auto begin = dict_.begin(); + auto end = dict_.end(); + return ScriptDictKeyIterator(begin, end); + } + + // Return an iterator over the key-value pairs of the dictionary. + ScriptDictIterator items() const { + auto begin = dict_.begin(); + auto end = dict_.end(); + return ScriptDictIterator(begin, end); + } + + // Interpret the dictionary as a boolean; empty means false, non-empty means + // true. + bool toBool() const { + return !(dict_.empty()); + } + + // Get the value for the given key. Throws std::out_of_range if the key does + // not exist. + at::IValue getItem(const at::IValue& key) { + return dict_.at(key); + } + + // Set the value for the given key. + void setItem(const at::IValue& key, const at::IValue& value) { + dict_.insert_or_assign(key, value); + } + + // Check whether the dictionary contains the given key. + bool contains(const at::IValue& key) { + return dict_.contains(key); + } + + // Delete the given key from the dictionary. + bool delItem(const at::IValue& key) { + return dict_.erase(key); + } + + // Get the size of the dictionary. + int64_t len() const { + return dict_.size(); + } + + // A c10::Dict instance that holds the actual data. + c10::impl::GenericDict dict_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_ir.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_ir.h new file mode 100644 index 0000000000000000000000000000000000000000..28c757a3d95dc33283441ea815486b67f1ef8eb9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_ir.h @@ -0,0 +1,55 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +void initPythonIRBindings(PyObject* module); + +// execute a Python function, used for Ops we can't optimize but that we want to +// optimize around +struct ConcretePythonOp : public PythonOp { + static Symbol Kind; + + ConcretePythonOp(Graph* graph) : PythonOp(graph, ::c10::prim::PythonOp) {} + ConcretePythonOp* init( + THPObjectPtr&& pyobj, + const std::string& cconv, + pyobj_list&& scalar_args) { + this->pyobj = std::move(pyobj); + this->scalar_args = std::move(scalar_args); + this->cconv = cconv; + return this; + } + // The Python object which contains the implementation of this function. + // This is either a class (non-legacy) or an object (legacy). See + // TraceInterpreterState for execution semantics. + THPObjectPtr pyobj; + // The calling convention for the Python function. + // 'c' -- constant argument + // 'd' -- dynamic argument + std::string cconv; + // Scalar arguments to the Python function. Not necessarily passed to + // the function in this order; see cconv for the correct order. + std::vector scalar_args; + + std::string name() const override; + void cloneFrom(Node* other_) override; + Node* allocNewInstance(Graph* g) override { + return new ConcretePythonOp(g); + } + // recover the autograd.Function instance, if this PythonOp's function + // was originally SomeFunction.apply + // used in ONNX for discovering symbolics + std::optional autogradFunction() const override; + void writeScalars(std::ostream& out) const override; + void lint_python() const override; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_ivalue.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_ivalue.h new file mode 100644 index 0000000000000000000000000000000000000000..fdb65d222f85a8551ae73f3532226a2d82e87804 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_ivalue.h @@ -0,0 +1,116 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +namespace py = pybind11; + +namespace c10::ivalue { + +// concrete ivalue Holder that hold a py::object +struct C10_EXPORT ConcretePyObjectHolder final : PyObjectHolder { + public: + static c10::intrusive_ptr create(py::object py_obj) { + return c10::make_intrusive(std::move(py_obj)); + } + + static c10::intrusive_ptr create(const py::handle& handle) { + py::gil_scoped_acquire ag; + return c10::make_intrusive( + handle.cast()); + } + + PyObject* getPyObject() override { + return py_obj_.ptr(); + } + + InferredType tryToInferType() override { + pybind11::gil_scoped_acquire ag; + return torch::jit::tryToInferType(py_obj_); + } + + IValue toIValue(const TypePtr& type, std::optional N = std::nullopt) + override { + pybind11::gil_scoped_acquire ag; + return torch::jit::toIValue(py_obj_, type, N); + } + + std::string toStr() override { + pybind11::gil_scoped_acquire ag; + return py::str(py_obj_); + } + + std::vector extractTensors() override { + // We could implement this entirely in C++ via pybind11 but it turns out to + // be substantially slower. Namely, the total time taken by markCompleted on + // a CUDAFuture is 21.5us with this implementation, but goes up to 58.7us + // when using C++. The reason is unclear. + try { + pybind11::gil_scoped_acquire ag; + +#if IS_PYBIND_2_13_PLUS + PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store + storage; + auto& extractorFn = + storage + .call_once_and_store_result([]() -> py::object { + return py::module_::import("torch._jit_internal") + .attr("_extract_tensors"); + }) + .get_stored(); +#else + static py::object& extractorFn = *new py::object( + py::module::import("torch._jit_internal").attr("_extract_tensors")); +#endif + + return extractorFn(py_obj_).cast>(); + } catch (py::error_already_set& e) { + auto err = std::runtime_error( + c10::str("Cannot extract tensors from value: ", e.what())); + { + pybind11::gil_scoped_acquire ag; + e.restore(); + PyErr_Clear(); + } + throw std::runtime_error(err); + } + } + + // Note [Destructing py::object] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~ + // + // (1) Why py_obj_ = py::none(); does not work. Because we also need to + // acquire GIL when destructing py::object of None that de-references None. + // https://docs.python.org/3/c-api/none.html#c.Py_RETURN_NONE + // + // https://stackoverflow.com/questions/15287590/why-should-py-increfpy-none-be-required-before-returning-py-none-in-c + // + // (2) Why we need to call dec_ref() explicitly. Because py::object of + // nullptr, on destruction, effectively does nothing because of it calls + // Py_XDECREF(NULL) underlying. + // https://docs.python.org/3/c-api/refcounting.html#c.Py_XDECREF + ~ConcretePyObjectHolder() override { + pybind11::gil_scoped_acquire ag; + py_obj_.dec_ref(); + // explicitly setting PyObject* to nullptr to prevent py::object's dtor to + // decref on the PyObject again. + py_obj_.ptr() = nullptr; + } + + // explicit construction to avoid erroneous implicit conversion and + // copy-initialization + explicit ConcretePyObjectHolder(py::object py_obj) + : py_obj_(std::move(py_obj)) {} + + private: + py::object py_obj_; +}; + +} // namespace c10::ivalue + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_list.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_list.h new file mode 100644 index 0000000000000000000000000000000000000000..a7e53f537833efdf013b13f67ba1b49a6762a10b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_list.h @@ -0,0 +1,233 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +void initScriptListBindings(PyObject* module); + +/// An iterator over the elements of ScriptList. This is used to support +/// __iter__(), . +class ScriptListIterator final { + public: + ScriptListIterator( + c10::impl::GenericList::iterator iter, + c10::impl::GenericList::iterator end) + : iter_(iter), end_(end) {} + at::IValue next(); + bool done() const; + + private: + c10::impl::GenericList::iterator iter_; + c10::impl::GenericList::iterator end_; +}; + +/// A wrapper around c10::List that can be exposed in Python via pybind +/// with an API identical to the Python list class. This allows +/// lists to have reference semantics across the Python/TorchScript +/// boundary. +class ScriptList final { + public: + // TODO: Do these make sense? + using size_type = size_t; + using diff_type = ptrdiff_t; + using ssize_t = Py_ssize_t; + + // Constructor for empty lists created during slicing, extending, etc. + ScriptList(const at::TypePtr& type) : list_(at::AnyType::get()) { + auto list_type = type->expect(); + list_ = c10::impl::GenericList(list_type); + } + + // Constructor for instances based on existing lists (e.g. a + // Python instance or a list nested inside another). + ScriptList(const at::IValue& data) : list_(at::AnyType::get()) { + TORCH_INTERNAL_ASSERT(data.isList()); + list_ = data.toList(); + } + + at::ListTypePtr type() const { + return at::ListType::create(list_.elementType()); + } + + // Return a string representation that can be used + // to reconstruct the instance. + std::string repr() const { + std::ostringstream s; + s << '['; + bool f = false; + for (auto const& elem : list_) { + if (f) { + s << ", "; + } + s << at::IValue(elem); + f = true; + } + s << ']'; + return s.str(); + } + + // Return an iterator over the elements of the list. + ScriptListIterator iter() const { + auto begin = list_.begin(); + auto end = list_.end(); + return ScriptListIterator(begin, end); + } + + // Interpret the list as a boolean; empty means false, non-empty means + // true. + bool toBool() const { + return !(list_.empty()); + } + + // Get the value for the given index. + at::IValue getItem(diff_type idx) { + idx = wrap_index(idx); + return list_.get(idx); + } + + // Set the value corresponding to the given index. + void setItem(diff_type idx, const at::IValue& value) { + idx = wrap_index(idx); + return list_.set(idx, value); + } + + // Check whether the list contains the given value. + bool contains(const at::IValue& value) { + for (const auto& elem : list_) { + if (elem == value) { + return true; + } + } + + return false; + } + + // Delete the item at the given index from the list. + void delItem(diff_type idx) { + idx = wrap_index(idx); + auto iter = list_.begin() + idx; + list_.erase(iter); + } + + // Get the size of the list. + ssize_t len() const { + return list_.size(); + } + + // Count the number of times a value appears in the list. + ssize_t count(const at::IValue& value) const { + ssize_t total = 0; + + for (const auto& elem : list_) { + if (elem == value) { + ++total; + } + } + + return total; + } + + // Remove the first occurrence of a value from the list. + void remove(const at::IValue& value) { + auto list = list_; + + int64_t idx = -1, i = 0; + + for (const auto& elem : list) { + if (elem == value) { + idx = i; + break; + } + + ++i; + } + + if (idx == -1) { + throw py::value_error(); + } + + list.erase(list.begin() + idx); + } + + // Append a value to the end of the list. + void append(const at::IValue& value) { + list_.emplace_back(value); + } + + // Clear the contents of the list. + void clear() { + list_.clear(); + } + + // Append the contents of an iterable to the list. + void extend(const at::IValue& iterable) { + list_.append(iterable.toList()); + } + + // Remove and return the element at the specified index from the list. If no + // index is passed, the last element is removed and returned. + at::IValue pop(std::optional idx = std::nullopt) { + at::IValue ret; + + if (idx) { + idx = wrap_index(*idx); + ret = list_.get(*idx); + list_.erase(list_.begin() + *idx); + } else { + ret = list_.get(list_.size() - 1); + list_.pop_back(); + } + + return ret; + } + + // Insert a value before the given index. + void insert(const at::IValue& value, diff_type idx) { + // wrap_index cannot be used; idx == len() is allowed + if (idx < 0) { + idx += len(); + } + + if (idx < 0 || idx > len()) { + throw std::out_of_range("list index out of range"); + } + + list_.insert(list_.begin() + idx, value); + } + + // A c10::List instance that holds the actual data. + c10::impl::GenericList list_; + + private: + // Wrap an index so that it can safely be used to access + // the list. For list of size sz, this function can successfully + // wrap indices in the range [-sz, sz-1] + diff_type wrap_index(diff_type idx) { + auto sz = len(); + if (idx < 0) { + idx += sz; + } + + if (idx < 0 || idx >= sz) { + throw std::out_of_range("list index out of range"); + } + + return idx; + } +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_sugared_value.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_sugared_value.h new file mode 100644 index 0000000000000000000000000000000000000000..8d907dfd8166b6c8270bee466b87627732652654 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_sugared_value.h @@ -0,0 +1,383 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +std::string typeString(py::handle h); + +inline std::shared_ptr toSimple(Value* v) { + return std::make_shared(v); +} + +// NB: This should be the single entry-point for instantiating a SugaredValue +// from a Python object. If you are adding support for converting a new Python +// type, *add it in this function's implementation*. +std::shared_ptr toSugaredValue( + py::object obj, + GraphFunction& m, + const SourceRange& loc, + bool is_constant = false); + +std::optional as_function(const py::object& obj); + +struct VISIBILITY_HIDDEN PythonValue : public SugaredValue { + PythonValue( + py::object the_self, + std::optional rcb = std::nullopt, + Value* module_self = nullptr) + : self(std::move(the_self)), + rcb(std::move(rcb)), + moduleSelf_(module_self) {} + + FunctionSchema getSchema( + const size_t n_args, + const size_t n_binders, + const SourceRange& loc); + + // call it like a function, e.g. `outputs = this(inputs)` + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + std::string kind() const override; + + std::vector> asTuple( + const SourceRange& loc, + GraphFunction& m, + const std::optional& size_hint = {}) override; + + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + Value* asValue(const SourceRange& loc, GraphFunction& m) override { + throw( + ErrorReport(loc) + << kind() << " cannot be used as a value. " + << "Perhaps it is a closed over global variable? If so, please " + << "consider passing it in as an argument or use a local variable " + << "instead."); + } + + protected: + py::object getattr(const SourceRange& loc, const std::string& name); + + void checkForAddToConstantsError(std::stringstream& ss); + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + py::object self; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::optional rcb; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + Value* moduleSelf_ = nullptr; +}; + +struct VISIBILITY_HIDDEN PythonModuleValue : public PythonValue { + explicit PythonModuleValue(py::object mod) : PythonValue(std::move(mod)) {} + + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; +}; + +// Used for desugaring uses of the torch.cuda module. All the CUDA APIs with +// torch.cuda.* are resolved using CUDAPythonModuleValue. +struct VISIBILITY_HIDDEN CUDAPythonModuleValue : public PythonValue { + explicit CUDAPythonModuleValue(py::object mod) + : PythonValue(std::move(mod)) {} + + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; +}; + +// Represents all the parameters of a module as a List[Tensor] +struct VISIBILITY_HIDDEN ConstantParameterList : public SugaredValue { + ConstantParameterList(Value* the_list) : the_list_(the_list) {} + std::string kind() const override { + return "constant parameter list"; + } + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& caller, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + return toSimple(the_list_); + } + + private: + Value* the_list_; +}; + +struct VISIBILITY_HIDDEN ModuleDictMethod : public SugaredValue { + explicit ModuleDictMethod(SugaredValuePtr iterable, std::string name) + : iterable_(std::move(iterable)), name_(std::move(name)) {} + + std::string kind() const override { + return name_; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& f, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + if (!args.empty() || !kwargs.empty()) { + throw( + ErrorReport(loc) << name_ << " method does not accept any arguments"); + } + return iterable_; + } + + SugaredValuePtr iterable_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::string name_; +}; + +struct SugaredDict; + +// defines how modules/methods behave inside the script subset. +// for now this does not have any interaction with python. +// in the future, we will add the ability to resolve `self.foo` to python +// {functions, modules, constants} so this SugaredValue is defined here +// anticipating we will eventually need to replace Module with a py::object +// holding the actual nn.Module class. + +struct VISIBILITY_HIDDEN ModuleValue : public SugaredValue { + ModuleValue(Value* self, std::shared_ptr concreteType) + : self_(self), concreteType_(std::move(concreteType)) {} + + std::string kind() const override { + return "module"; + } + + Value* asValue(const SourceRange& loc, GraphFunction& m) override; + + SugaredValuePtr asTupleValue(const SourceRange& loc, GraphFunction& m) + override; + + // select an attribute on it, e.g. `this.field` + std::shared_ptr tryGetAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field); + + // select an attribute on it, e.g. `this.field` + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + // select an attribute on it, e.g. `this.field` + bool hasAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + // call module.forward with pre_hooks and hooks + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& caller, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + std::shared_ptr getSugaredDict( + const SourceRange& loc, + GraphFunction& m); + + std::shared_ptr getSugaredNamedBufferDict( + const SourceRange& loc, + GraphFunction& m); + + std::shared_ptr getSugaredNamedParameterList( + const SourceRange& loc, + GraphFunction& m); + + std::shared_ptr getSugaredNamedParameterDict( + const SourceRange& loc, + GraphFunction& m); + + void setAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field, + Value* newValue) override; + + SugaredValuePtr iter(const SourceRange& loc, GraphFunction& m) override; + + std::shared_ptr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint) override; + + private: + // Check that the type of all submodules is a subtype of ty. If the function + // returns false, more information about why it returns false (e.g. which + // submodule's type is not a subtype of ty) is printed it why_not if it is not + // null. + bool areAllSubmodulesSubtypeOf( + const TypePtr& ty, + std::ostream* why_not = nullptr) const; + + Value* self_; + std::shared_ptr concreteType_; +}; + +bool isNamedTupleClass(const py::object& obj); +TypePtr registerNamedTuple( + const py::object& obj, + const SourceRange& loc, + const ResolutionCallback& rcb); + +void recurseThroughNestedModules( + const SourceRange& loc, + GraphFunction& m, + std::vector& keys, + std::vector& values, + std::shared_ptr& self, + const std::string& prefix, + const std::string& field); + +// Used to support named_modules() +struct VISIBILITY_HIDDEN SugaredDict : public SugaredValue { + explicit SugaredDict( + std::shared_ptr self, + std::shared_ptr keys, + std::shared_ptr modules) + : self_(std::move(self)), + keys_(std::move(keys)), + modules_(std::move(modules)) {} + + std::string kind() const override { + return "ModuleDict"; + } + + std::shared_ptr getKeys() { + return keys_; + } + + std::shared_ptr getModules() { + return modules_; + } + + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + SugaredValuePtr iter(const SourceRange& loc, GraphFunction& m) override { + return keys_; + } + + std::shared_ptr self_; + std::shared_ptr keys_; + std::shared_ptr modules_; +}; + +struct VISIBILITY_HIDDEN BooleanDispatchValue : public SugaredValue { + BooleanDispatchValue(py::dict dispatched_fn) + : dispatched_fn_(std::move(dispatched_fn)) {} + + std::string kind() const override { + return "boolean dispatch"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& caller, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + private: + py::dict dispatched_fn_; +}; + +struct VISIBILITY_HIDDEN PythonClassValue : public ClassValue { + PythonClassValue(ClassTypePtr type, py::object py_type) + : ClassValue(std::move(type)), py_type_(std::move(py_type)) {} + + std::string kind() const override { + return "Python type"; + } + + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + bool hasAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + private: + py::object py_type_; +}; + +struct VISIBILITY_HIDDEN PythonExceptionValue : public ExceptionValue { + explicit PythonExceptionValue(const py::object& exception_class) + : ExceptionValue( + py::str(py::getattr(exception_class, "__name__", py::str("")))), + exception_class_qualified_name_( + py::str(py::module::import("torch._jit_internal") + .attr("_qualified_name")( + exception_class, + /*mangle_name=*/false))) {} + + std::string kind() const override { + return "Python exception"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& caller, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + private: + std::string exception_class_qualified_name_; +}; + +// Python Slice class. +struct VISIBILITY_HIDDEN PythonSliceClass : public SugaredValue { + explicit PythonSliceClass() = default; + + std::string kind() const override { + return "Python slice class"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& caller, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tracer.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..d6fc5f502fb4820b8d45343d1fa104e4eaabb32e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tracer.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit { + +struct Module; + +namespace tracer { +void initPythonTracerBindings(PyObject* module); + +SourceRange getPythonInterpreterSourceRange(); + +Node* preRecordPythonTrace( + THPObjectPtr pyobj, + const std::string& arg_types, + at::ArrayRef inputs, + std::vector scalar_args); + +std::pair, Stack> createGraphByTracingWithDict( + const py::function& func, + const py::dict& inputs_dict, + const Stack& inputs, + const py::function& var_name_lookup_fn, + bool strict, + bool force_outplace, + Module* self = nullptr, + const std::vector& argument_names = {}); + +std::pair, Stack> createGraphByTracing( + const py::function& func, + Stack inputs, + const py::function& var_name_lookup_fn, + bool strict, + bool force_outplace, + Module* self = nullptr, + const std::vector& argument_names = {}); +} // namespace tracer +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tree_views.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tree_views.h new file mode 100644 index 0000000000000000000000000000000000000000..922babfff9ddd475c6f6bbf1da32080f71c39a32 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tree_views.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +void initTreeViewBindings(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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/script_init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/script_init.h new file mode 100644 index 0000000000000000000000000000000000000000..29aea54b291cb43ce5c921dd30ebaf98e209d27c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/script_init.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { +void initJitScriptBindings(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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/update_graph_executor_opt.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/update_graph_executor_opt.h new file mode 100644 index 0000000000000000000000000000000000000000..0ee12ba1cfabddba9b497b189fe756d7cdf3d221 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/update_graph_executor_opt.h @@ -0,0 +1,11 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +namespace torch::jit { +TORCH_API void setGraphExecutorOptimize(bool o); +TORCH_API bool getGraphExecutorOptimize(); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/utf8_decoding_ignore.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/utf8_decoding_ignore.h new file mode 100644 index 0000000000000000000000000000000000000000..8e0f57b2114203af5e68b519cf3b2d4ef2baaaf2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/utf8_decoding_ignore.h @@ -0,0 +1,11 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +namespace torch::jit { +TORCH_API void setUTF8DecodingIgnore(bool o); +TORCH_API bool getUTF8DecodingIgnore(); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/argument_spec.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/argument_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..1e8083dc7ab5e5f25fcfc0f6f0a5d9e9431d5f17 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/argument_spec.h @@ -0,0 +1,508 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wshorten-64-to-32") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wshorten-64-to-32") +#endif + +namespace torch::jit { + +// GraphExecutor creates specializations of Graphs for different +// dimensionalitities and types of inputs. + +struct ArgumentInfo { + friend struct ArgumentSpec; + using plain_data_type = uint64_t; + + bool defined() const { + return defined_; + } + at::Device device() const { + return at::Device(DeviceType(dev_type_), device_); + } + // XXX: It is guaranteed that this will return false when called on non-tensor + // arguments + bool requires_grad() const { + return requires_grad_; + } + int dim() const { + return dim_; + } + at::ScalarType type() const { + return at::ScalarType(type_); + } + TypePtr toType() const { + if (!defined()) + return TensorType::get(); + + return TensorType::create( + type(), device(), std::optional(dim()), requires_grad()); + } + operator TypePtr() const { + return toType(); + } + + private: + unsigned defined_ : 1; + unsigned requires_grad_ : 1; + unsigned : 5; + unsigned dim_ : 8; + unsigned device_ : 8; + unsigned type_ : 8; + unsigned dev_type_ : 16; + unsigned : 16; +}; + +static_assert( + std::is_standard_layout_v, + "ArgumentInfo is to be a POD struct"); +static_assert( + sizeof(ArgumentInfo) == sizeof(ArgumentInfo::plain_data_type), + "ArgumentInfo is expected to be a 32-bit struct"); + +struct ArgumentSpec { + ArgumentSpec(size_t num_flat_tensor_inputs, size_t num_flat_optional_inputs) + : hash_code(c10::hash_combine( + num_flat_tensor_inputs, + num_flat_optional_inputs)) { + tensor_args.reserve(num_flat_tensor_inputs); + optional_presence.reserve(num_flat_optional_inputs); + } + + void addOptional(const IValue& input) { + bool is_present = !input.isNone(); + optional_presence.push_back(is_present); + hash_code = c10::hash_combine(hash_code, is_present); + } + + void addTensor(const IValue& input, bool with_grad) { + AT_ASSERT(input.isTensor(), "Expected Tensor but found ", input.tagKind()); + tensor_args.emplace_back(); + auto& arg = tensor_args.back(); + // Initialize all fields to 0. This is convenient, because e.g. + // requires_grad() can be checked even on tensors AND will make + // padding bits all 0s. + std::memset(&arg, 0, sizeof(ArgumentInfo)); + + // [argspec refcounting] reinterpret the IValue to avoid having to refcount + // the Tensor microbenchmarks + // https://github.com/zdevito/pytorch/commit/21e7200a0a0fc456bea2f10e95b1781f83933d10 + // show overhead in extra refcounting along this path + const at::Tensor* t = reinterpret_cast(&input); + arg.defined_ = t->defined(); + if (arg.defined_) { + arg.requires_grad_ = with_grad && t->requires_grad(); + arg.dim_ = t->dim(); + at::Device device = t->device(); + arg.dev_type_ = + // NOLINTNEXTLINE(bugprone-signed-char-misuse) + static_cast>(device.type()); + // NOLINTNEXTLINE(bugprone-signed-char-misuse) + arg.device_ = device.index(); + arg.type_ = static_cast(t->scalar_type()); + } + combineHash(arg); + } + + void combineHash(const ArgumentInfo& arg) { + ArgumentInfo::plain_data_type arg_data = 0; + std::memcpy(&arg_data, &arg, sizeof(ArgumentInfo)); + hash_code = c10::hash_combine(hash_code, arg_data); + } + + // equality is fast: check ninputs, and then check the raw array data, + // there are no size/stride indirections + // hopefully std::vector has fast equality + bool operator==(const ArgumentSpec& spec) const { + if (optional_presence != spec.optional_presence) { + return false; + } + if (tensor_args.size() != spec.tensor_args.size()) + return false; + // NB: we need to break out early when there are no elements, because + // passing a nullptr to memcmp is UB. + if (tensor_args.empty()) + return true; + return std::memcmp( + tensor_args.data(), + spec.tensor_args.data(), + tensor_args.size() * sizeof(ArgumentInfo)) == 0; + } + bool operator!=(const ArgumentSpec& spec) const { + return !(*this == spec); + } + size_t numTensors() const { + return tensor_args.size(); + } + const ArgumentInfo& tensorAt(size_t i) const { + return tensor_args[i]; + } + size_t numOptionals() const { + return optional_presence.size(); + } + bool isPresent(size_t i) const { + return optional_presence[i]; + } + size_t hashCode() const { + return hash_code; + } + + private: + size_t hash_code; // precomputed on construction + std::vector tensor_args; + std::vector optional_presence; +}; + +namespace { +static constexpr size_t ARG_SPEC_DEPTH_LIMIT = 128; +} + +// ArgumentSpecCreator takes an initial graph and comes up with a set +// of simple instructions to compute the ArgumentSpec given a set of +// input tensors. +struct TORCH_API ArgumentSpecCreator { + // instructs acts on a stack of a list of input IValues + // at the beginning the stack contains a single list of the inputs to the + // function the ENTER_ instructs descend into subobjects and push new lists + // onto the stack + enum Inst : char { + ENTER_TUPLE, // consume a tuple ivalue from the top-most list, and push the + // list of its elements onto the stack as a new list + ENTER_OBJECT, // same as ENTER_TUPLE, but the input is a class + LEAVE, // pop the top-most list from the stack + SKIP, // consume an element from the top-most list, and discard + SPECIALIZE_OPTIONAL_TENSOR, // consume a optional tensor for the top-most + // list, and add it to the ArgSpec key being + // created + SPECIALIZE_TENSOR, // consume a tensor for the top-most + // list, and add it to the ArgSpec key being created + SPECIALIZE_OPTIONAL, + // consume a nontensor optional from the top-most list, + // and add it to the ArgSpec key being created + }; + ArgumentSpecCreator(Graph& graph); + ArgumentSpec create(bool with_grad, const Stack& stack) const; + void specializeTypes(Graph& g, const ArgumentSpec& spec) const; + void dump() const; + using WrittenSlots = std::unordered_set; + + private: + void scan( + const TypePtr& typ, + size_t depth, + const WrittenSlots& written_slots); + size_t num_inputs_; + size_t num_tensors_ = 0; + size_t num_optionals_ = 0; + std::vector instructions_; +}; + +// CompleteArgumentSpec represents one particular specialization. +// It is designed so that it can be created, hashed, and compared quickly +// since it is used along the hot-path of the JIT to check if the code +// we have created is valid for the given inputs. + +// COmpleteArgumentInfoPOD is only used internally in CompleteArgumentSpec +// API users should use ArgumentInfo +struct CompleteArgumentInfoPOD { + // total size is 64-bit + unsigned is_tensor : 8; // all other fields are invalid if this is false + unsigned type : 8; // scalar type + unsigned defined : 1; + unsigned requires_grad : 1; + signed device : 14; + unsigned dev_type : 16; + unsigned + total_dims : 16; // all TensorInfoPODs are in CompleteArgumentSpec's + // tensor_info() array. total_dims is the total number of + // dimensions seen so far in all previous members of + // tensor_info(), including this tensor 2*total_dims + // becomes the offset into the sizes_strides list for the + // _next_ tensor in the tensor_info array for tensor 0, + // the offset is always 0 +}; + +static_assert( + sizeof(CompleteArgumentInfoPOD) == sizeof(int64_t), + "CompleteArgumentInfoPOD must be 64-bit struct for CompleteArgumentSpec encoding to work"); + +struct CompleteArgumentInfo; + +struct CompleteArgumentSpec { + CompleteArgumentSpec(bool with_grad, at::ArrayRef inputs) + : ninputs(inputs.size()) { + int64_t all_dims = 0; + const auto num_inputs = inputs.size(); + for (const auto i : c10::irange(num_inputs)) { + if (!inputs[i].isTensor()) + continue; + auto& tensor = inputs[i].toTensor(); + all_dims += tensor.defined() ? tensor.ndimension() : 0; + } + // allocate enough room for all TensorPODs and dimensions + data.resize(ninputs + all_dims * 2); + + // and reinterpret our data array as these structs + auto* pods = reinterpret_cast(data.data()); + int64_t* next_dim = sizes_strides(); + int32_t total_dims = 0; + for (const auto i : c10::irange(num_inputs)) { + auto& pod = pods[i]; + pod.is_tensor = static_cast(inputs[i].isTensor()); + if (pod.is_tensor) { + at::Tensor t = inputs[i].toTensor(); + pod.defined = t.defined(); + if (pod.defined) { + pod.type = static_cast(t.scalar_type()); + at::Device device = t.device(); + // NOLINTNEXTLINE(bugprone-signed-char-misuse) + pod.dev_type = + static_cast>(device.type()); + // NOLINTNEXTLINE(bugprone-signed-char-misuse) + pod.device = device.index(); + pod.requires_grad = with_grad && t.requires_grad(); + total_dims += t.ndimension(); + auto sizes = t.sizes(); + std::copy(sizes.begin(), sizes.end(), next_dim); + next_dim += sizes.size(); + auto strides = t.strides(); + std::copy(strides.begin(), strides.end(), next_dim); + next_dim += strides.size(); + } + } + // each POD has a running tally of all dimensions including its own + TORCH_CHECK( + total_dims < std::numeric_limits::max(), + "The number of dims cannot be packed into CompleteArgumentSpec:", + total_dims); + pod.total_dims = total_dims; + } + // we precompute the hash_code to minimize the time inside of hash + // table operations where we may need to hold a compiler cache lock. + hash_code = c10::hash_combine(0, ninputs); + for (auto d : data) { + hash_code = c10::hash_combine(hash_code, d); + } + } + + // equality is fast: check ninputs, and then check the raw array data, + // there are no size/stride indirections + bool operator==(const CompleteArgumentSpec& spec) const { + return ninputs == spec.ninputs && data == spec.data; + } + bool operator!=(const CompleteArgumentSpec& spec) const { + return !(*this == spec); + } + friend struct CompleteArgumentInfo; + CompleteArgumentInfo at(size_t i) const; + size_t size() const { + return ninputs; + } + size_t hashCode() const { + return hash_code; + } + + private: + ArrayRef tensor_info() const { + return ArrayRef( + reinterpret_cast(data.data()), ninputs); + } + // the start of the sizes_strides information, which comes after the + // CompleteArgumentInfoPOD list. + const int64_t* sizes_strides() const { + return data.data() + ninputs; + } + int64_t* sizes_strides() { + return data.data() + ninputs; + } + size_t hash_code{0}; // precomputed on construction + size_t ninputs; + // layout is ninputs of TensorPOD (each 64-bit) followed by their size and + // stride info for 3 tensors: + // [t0POD][t1POD][t2POD]... + // [t0 sizes][t0 strides][t1 sizes][t1 strides][t2 sizes][t2 strides] + std::vector data; +}; + +// public view of compressed CompleteArgumentInfo +struct CompleteArgumentInfo { + CompleteArgumentInfo(const CompleteArgumentSpec& spec, const int i) + : spec(spec), i(i) {} + bool isTensor() const { + return pod(i).is_tensor; + } + at::ScalarType type() const { + return at::ScalarType(pod(i).type); + } + bool defined() const { + return pod(i).defined; + } + bool requires_grad() const { + return pod(i).requires_grad; + } + at::Device device() const { + return at::Device( + DeviceType(pod(i).dev_type), + static_cast(pod(i).device)); + } + int ndimension() const { + // See [valid range], it is always valid to ask for offset for (i + 1) + return (sizes_strides_offset(i + 1) - sizes_strides_offset(i)) / 2; + } + at::IntArrayRef sizes() const { + return at::IntArrayRef( + spec.sizes_strides() + sizes_strides_offset(i), ndimension()); + } + at::IntArrayRef strides() const { + int ndim = ndimension(); + return at::IntArrayRef( + spec.sizes_strides() + sizes_strides_offset(i) + ndim, ndim); + } + operator TypePtr() const { + if (!defined()) + return TensorType::get(); + return TensorType::create( + type(), + device(), + c10::VaryingShape{sizes()}, + c10::VaryingShape{strides()}, + requires_grad()); + } + + private: + // offsetinto sizes_strides() array where the sizes start for tensor j + // [valid range] valid range is [0, ninputs] + // (i.e. you can ask for the offset at ninputs, which would be the offset of + // the next tensor if it existed) + int sizes_strides_offset(int j) const { + if (j == 0) + return 0; + return 2 * pod(j - 1).total_dims; + } + const CompleteArgumentInfoPOD& pod(int j) const { + return spec.tensor_info().at(j); + } + const CompleteArgumentSpec& spec; + const int i; +}; + +inline std::ostream& operator<<(std::ostream& out, const ArgumentInfo& info) { + if (!info.defined()) { + return out << ""; + } + out << "Tensor(device=" << info.device() << ", type=" << toString(info.type()) + << ", requires_grad=" << info.requires_grad() << ", dims=" << info.dim() + << ')'; + return out; +} + +inline std::ostream& operator<<(std::ostream& out, const ArgumentSpec& spec) { + out << '{'; + for (const auto i : c10::irange(spec.numTensors())) { + if (i > 0) + out << ", "; + out << spec.tensorAt(i); + } + out << "; "; + for (const auto i : c10::irange(spec.numOptionals())) { + if (i > 0) + out << ", "; + out << spec.isPresent(i); + } + out << '}'; + return out; +} + +inline std::ostream& operator<<( + std::ostream& out, + const CompleteArgumentInfo& info) { + if (!info.defined()) { + return out << ""; + } + out << "Tensor(device=" << info.device() << ", type=" << toString(info.type()) + << ", requires_grad=" << info.requires_grad() + << ", sizes=" << info.sizes() << ", strides=" << info.strides() << ')'; + return out; +} + +inline std::ostream& operator<<( + std::ostream& out, + const CompleteArgumentSpec& spec) { + out << '{'; + for (const auto i : c10::irange(spec.size())) { + if (i > 0) + out << ", "; + out << spec.at(i); + } + out << '}'; + return out; +} + +inline CompleteArgumentInfo CompleteArgumentSpec::at(size_t i) const { + return CompleteArgumentInfo(*this, i); +} + +inline std::optional convertOptional( + std::optional const& from) { + return from ? std::optional(static_cast(*from)) + : std::optional{}; +} + +} // namespace torch::jit + +namespace std { + +template +struct hash> { + size_t operator()(const c10::VaryingShape& vs) const { + return c10::get_hash( + vs.size(), + vs.size() ? vs.sizes().value() : std::vector>()); + } +}; + +template <> +struct hash { + size_t operator()(const c10::TensorType& ptt) const { + return c10::get_hash< + std::optional, + c10::VaryingShape, + c10::VaryingShape, + std::optional>( + torch::jit::convertOptional(ptt.scalarType()), + ptt.sizes(), + ptt.strides(), + ptt.requiresGrad()); + } +}; + +template <> +struct hash { + size_t operator()(const torch::jit::ArgumentSpec& spec) const { + return spec.hashCode(); + } +}; +template <> +struct hash { + size_t operator()(const torch::jit::CompleteArgumentSpec& spec) const { + return spec.hashCode(); + } +}; +} // namespace std + +C10_CLANG_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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/autodiff.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/autodiff.h new file mode 100644 index 0000000000000000000000000000000000000000..9c47f7a9f08042a997b52e1d579042ad133c02f5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/autodiff.h @@ -0,0 +1,99 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include + +namespace torch::jit { + +using value_list = std::vector; +// clang-format off +// Example showcasing how Gradient is constructed: +// +// Let's assume we have a function f, `m` and `n` do not require grad +// (`n` can depend only on `m`): +// y, n = f(x, m) +// +// Now, let's assume that the reverse of f (called f') needs to use values of `x`, `t` and `y`. +// `t` is an intermediate value produced in the body of f, and let's assume that it requires +// grad too. +// +// In this case differentiate(f) will return this: +// y, n, t = f(x, m) // `t` is appended to the output list +// dx = f'(dy, dt, x, t, y) // No `dm` or `dn` because they do not require gradient +// // All needed values from f are prepended to the input list +// +// f_real_outputs = 2 // Only first two outputs were present in f originally +// df_input_vjps = {0, 2} // i.e. connect grad_fn of y and t variables produced by f, +// y t // with y's output_nr = 0 and t's output_nr = 1 +// df_input_captures = {I0, O2, O0} // Order matches the prefix of inputs to df +// x t y +// df_output_vjps = {0} // i.e. connect next_edge[0] of grad_fn to x's (grad_fn, output_nr). +// +// Terminology: vjp = vector-jacobian product +// clang-format on + +struct Gradient { + explicit operator bool() const { + return df != nullptr; + } + std::shared_ptr f; + std::shared_ptr df; + + // Describes how to construct outputs of f from what its graph will return. + // This is necessary because some trailing outputs are intermediates produced + // only to be saved for df (and should be ignored). + size_t f_real_outputs = 0; // initialized for safety. + + // df inputs are split into two sections: vjps (aka grad_outputs) and + // captures. VJPs are "seeds" for the gradient computation given for each + // input capture of an Output kind. Captures are values the need to be saved + // when f is run. We handle inputs specially, because this allows us to avoid + // adding extra vjps as df inputs. + + std::vector df_input_vjps; // Offsets into f's outputs. + // capture can come from inputs or outputs + std::vector df_input_captured_inputs; // Offsets into f's inputs + std::vector df_input_captured_outputs; // Offsets into f's outputs + + // df will produce vjps for a subset of inputs of f that required grad. + // df_output_vjps[idx] == inp_idx means that idx-th output of df produces a + // vjp for inp_idx-th input of f. + std::vector df_output_vjps; // Offsets into f's inputs. + + // How to use gradient to implement a differentiable autograd function: + // When running f: + // - Unwrap input Variables + // - Run f's graph + // - Create grad_fn + // - Wrap outputs in Variables (assume we have a tensor_outputs array): + // outputs = map(Variable, tensor_output) + // for i, offset in enumerate(df_input_vjps): + // outputs[offset].set_grad_fn(grad_fn, output_nr=i) + // - Use df_output_vjps to connect next_edges of grad_fn: + // for idx in df_output_vjps: + // grad_fn.add_next_edge(inputs[idx].gradient_edge()) + // - Save captures for df (care needs to be taken to use SavedVariables for + // inputs and outputs that we will actually return) + // - Return outputs[:f_real_outputs] + // + // When running df: + // - Concatenate received vjps and captured Variables + // - Interpret df + // - Wrap outputs of df into Variables (that don't require grad) +}; +TORCH_API Gradient differentiate(std::shared_ptr& graph); + +// can we take a derivative of this node symbolically? +TORCH_API bool isDifferentiable(const Node* n); +TORCH_API bool isDifferentiable(Graph& g); +TORCH_API bool isZero(Value* v); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/calculate_necessary_args.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/calculate_necessary_args.h new file mode 100644 index 0000000000000000000000000000000000000000..4951616fbded8b83d0cf9d75459a29849c65822e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/calculate_necessary_args.h @@ -0,0 +1,74 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +// Calculates the number of args that need to be passed in. +// Less args may be needed if defaults are provided. +// Returns: {number args needed, number of out args} +inline std::pair CalculateNecessaryArgs( + const std::vector& schema_args, + at::ArrayRef actual_inputs, + bool allow_trailing_out_args) { + if (schema_args.empty()) { + return std::make_pair(0, 0); + } + + // count number of out arguments + int64_t schema_idx = static_cast(schema_args.size()) - 1; + if (allow_trailing_out_args) { + // skip over out arguments in the end. + while (schema_idx >= 0) { + const auto& current_arg = schema_args.at(schema_idx); + if (!current_arg.is_out()) { + break; + } + schema_idx--; + } + } + + int64_t num_out = static_cast(schema_args.size()) - schema_idx - 1; + + if (schema_args.size() < actual_inputs.size()) { + return std::make_pair(actual_inputs.size(), num_out); + } + + // if it is the default args, we reset the index to the last element + if (!allow_trailing_out_args) { + schema_idx = schema_args.size() - 1; + } + // keeps track of trailing unnecessary args + while (schema_idx >= 0) { + // this means it is not default argument, so it is necessary + if (!schema_args.at(schema_idx).default_value().has_value()) { + return std::make_pair(schema_idx + 1, num_out); + } else { + auto schema_value = + schema_args.at(schema_idx).default_value().value().toIValue(); + // non-const value will become nullptr here, so will be marked necessary + // non-const would include prim::ListConstruct, prim::DictConstruct as + // well. + auto actual_value = toIValue(actual_inputs[schema_idx]); + if (!actual_value.has_value()) { + return std::make_pair(schema_idx + 1, num_out); + } + // if the IR has same value as default value of the schema, + // it is not necessary argument. + if (schema_value != actual_value.value()) { + return std::make_pair(schema_idx + 1, num_out); + } + } + schema_idx--; + } + return std::make_pair(0, num_out); +} + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/custom_operator.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/custom_operator.h new file mode 100644 index 0000000000000000000000000000000000000000..07b2ca1264bb178b526eb4d2bb6c0daf0a8f7c78 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/custom_operator.h @@ -0,0 +1,35 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +/// Registration class for new operators. Effectively calls +/// `torch::jit::registerOperator` for every supplied operator, but allows doing +/// so in the global scope when a `RegisterOperators` object is assigned to a +/// static variable. +/// Note: This is *not* the custom operator API. If you want to register custom +/// operators, take a look at torch::RegisterOperators. +struct TORCH_API RegisterOperators { + RegisterOperators() = default; + + /// Registers a vector of already created `Operator`s. + /// The operator element is now optional to filter null ops. It's backward + /// compatible and works for selective operator registration. + explicit RegisterOperators(std::vector> operators) { + for (std::optional& o : operators) { + if (o) { + registerOperator(std::move(o.value())); + } + } + } +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/decomposition_registry.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/decomposition_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..1761821aaeb846a379310913ca9bed4e408e6f72 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/decomposition_registry.h @@ -0,0 +1,38 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +// This file is temporary until native_functions.yaml and derivatives.yaml are +// merged. Ideally this should all go into native_functions.yaml + +#include +#include + +namespace torch::jit { + +TORCH_API std::optional> GetDecomposition( + const FunctionSchema& schema); + +TORCH_API void RegisterDecomposition( + const FunctionSchema& schema, + std::shared_ptr g); + +TORCH_API void RunDecompositions(std::shared_ptr g); + +TORCH_API std::optional GetDecompositionFunction( + const FunctionSchema& schema); + +// For invocation in C++, recommended is to assign to static local variable +TORCH_API Function* GetDecompositionExecutor(const char* schema_literal); + +TORCH_API Function* GetDecompositionExecutor(const FunctionSchema& schema); + +TORCH_API void run_jit_decomposition( + const c10::OperatorHandle& op, + torch::jit::Stack* stack); + +TORCH_API bool has_jit_decomposition(const FunctionSchema& schema); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/decomposition_registry_util.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/decomposition_registry_util.h new file mode 100644 index 0000000000000000000000000000000000000000..87da540f6da8ab34bcff01c70817dcc1411d6862 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/decomposition_registry_util.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API const std::string& GetSerializedDecompositions(); + +TORCH_API const OperatorMap& GetDecompositionMapping(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/exception_message.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/exception_message.h new file mode 100644 index 0000000000000000000000000000000000000000..2c88b716dd9d0917b6f07dc2f2ab135d4f459035 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/exception_message.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +namespace torch::jit { + +struct ExceptionMessage { + ExceptionMessage(const std::exception& e) : e_(e) {} + + private: + const std::exception& e_; + friend std::ostream& operator<<( + std::ostream& out, + const ExceptionMessage& msg); +}; + +inline std::ostream& operator<<( + std::ostream& out, + const ExceptionMessage& msg) { + auto c10_error = dynamic_cast(&msg.e_); + if (c10_error) { + out << c10_error->what_without_backtrace(); + } else { + out << msg.e_.what(); + } + return out; +} + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_executor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..3ed45801284a1f0eae10bff98f09972ff796f781 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_executor.h @@ -0,0 +1,152 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +TORCH_DECLARE_bool(torch_jit_enable_new_executor); + +TORCH_DECLARE_bool(torch_jit_execution_plan_reuse_code_graph); + +namespace torch::jit { +struct GraphExecutorState; +struct Code; + +enum ExecutorExecutionMode { + SIMPLE, + PROFILING, +}; + +struct ExecutionPlan { + ExecutionPlan() = default; + ExecutionPlan(std::shared_ptr graph, std::string function_name) + : code(graph, std::move(function_name)), + graph( + FLAGS_torch_jit_execution_plan_reuse_code_graph + ? code.graph() + : std::move(graph)) {} + + operator bool() const { + return static_cast(graph); + } + + Code code; + std::shared_ptr graph; +}; + +// Notice that those structs don't manage lifetime of their members. +// They are only valid only right after you call getDebugState() and should +// never be used again once another GraphExecutor function is called. + +struct GraphExecutorState { + const Graph* graph = nullptr; + ExecutionPlan fallback; // XXX: members of this field are optional + std::unordered_map execution_plans; +}; + +struct TORCH_API EnableProfilingGuard { + EnableProfilingGuard(); + ~EnableProfilingGuard(); + + private: + bool old_executor_mode = false; + bool old_get_optimize = false; +}; + +struct GraphExecutorImplBase; +struct TORCH_API GraphExecutor { + GraphExecutor() = default; + GraphExecutor(const std::shared_ptr& graph, std::string function_name); + + GraphExecutor( + const std::shared_ptr& graph, + std::string function_name, + ExecutorExecutionMode executor_mode); + + void run(Stack& inputs); + c10::intrusive_ptr runAsync( + Stack& stack, + TaskLauncher taskLauncher = at::launch); + + // `remaining_bailout_depth` stands for the maximum number of profiled and + // specialized recompilations allowed for the current `GraphExecutor`. if + // remaining_bailout_depth is equal to 0, `GraphExecutor` won't perform any + // profiling and specialization. This is also equivalent to the + // SIMPLE_EXECUTOR mode. if remaining_bailout_depth is greater than 0, + // `GraphExecutor` will profile and specialize its input graph based on the + // profiled information whenever a bailout check is failed/triggered, a new + // `GraphExecutor` will be created. This new `GraphExecutor`'s + // remaining_bailout_depth will be reduced by 1. + // If no bailout depth is passed, the depth will be initialized from the + // current global fusion strategy settings. + const ExecutionPlan& getPlanFor( + Stack& inputs, + std::optional remaining_bailout_depth = std::nullopt); + GraphExecutorState getDebugState(); + + void debugFlushCompilationCache(); + + bool isOptimized() const; + + private: + std::shared_ptr pImpl; +}; + +TORCH_API Node* replaceBlockWithFallbackGraph( + Block* b, + ArrayRef inputs); + +// These passes need to run before it is valid to pass to the interpreter +// regardless of whether sizes have been specialized or not. +TORCH_API void runRequiredPasses(const std::shared_ptr& g); + +TORCH_API void debugSetFusionGroupInlining(bool state); +TORCH_API bool getFusionGroupInlining(); + +TORCH_API void debugSetAutodiffSubgraphInlining(bool state); +TORCH_API std::shared_ptr lastExecutedOptimizedGraph(); + +TORCH_API std::atomic& getProfilingMode(); +TORCH_API std::atomic& getExecutorMode(); +TORCH_API std::atomic& getNumProfiledRuns(); +TORCH_API size_t getBailoutDepth(); +TORCH_API bool IsNewExecutorEnabled(); + +struct TORCH_API GraphOptimizerEnabledGuard { + GraphOptimizerEnabledGuard(bool state) + : old_state_(getGraphExecutorOptimize()) { + setGraphExecutorOptimize(state); + } + + ~GraphOptimizerEnabledGuard() { + setGraphExecutorOptimize(old_state_); + } + + bool old_state_; +}; + +namespace detail { + +GraphExecutor* getGradExecutor(Operation& op); + +GraphExecutor* getDifferentiableGraphOpExecutor(Operation& op); + +// for debugging information we expose a way to get the last actually +// run graph. Previous approaches allowed querying the GraphExecutor +// for what graph it would run in certain circumstances (graphFor), but +// this is fragile because we sometimes change how these decisions are made. +// This interface still allows our tests to look at optimized graphs, but +// with less plumbing. +} // namespace detail + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_executor_impl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_executor_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..c9129b02b3fdc278fde42caeeda587895e33b79e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_executor_impl.h @@ -0,0 +1,118 @@ +#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 +#include +#include + +namespace torch::jit { + +void packGradient(const Gradient& gradient, Node* dnode); +bool needsGradient(const std::shared_ptr& graph); +void runOptimization( + std::shared_ptr& graph, + bool unroll_non_constant_loops = true, + bool const_prop_user_classes = true); +void runNondiffOptimization( + std::shared_ptr& graph, + bool strict_fuser_check = false); +void debugSetAutodiffSubgraphInlining(bool state); +bool TORCH_API getAutodiffSubgraphInlining(); + +void debugSetFusionGroupInlining(bool state); +bool getFusionGroupInlining(); + +// Tunable parameters for deciding when to create/keep subgraphs of +// differentiable code +const size_t autodiffSubgraphNodeThreshold = 2; +const size_t autodiffSubgraphInlineThreshold = 5; + +// a Graph can be created via tracing, or via a language-based frontend +// GraphExecutor runs it. It can run the same graph on many different sizes +// and different requires_grad states, and handles specializations for each +// situation. GraphExecutor is completely unaware of tracing or module +// parameters to keep the tracing concerns separated. +struct GraphExecutorImplBase { + static std::shared_ptr prepareGraph( + const std::shared_ptr& graph) { + auto copy = graph->copy(); + EraseShapeInformation(copy); + return copy; + } + + GraphExecutorImplBase( + const std::shared_ptr& graph, + std::string function_name) + : graph(prepareGraph(graph)), + function_name_(std::move(function_name)), + num_inputs(this->graph->inputs().size()), + num_outputs(this->graph->outputs().size()) {} + + // entry point where execution begins + void run(Stack& stack); + c10::intrusive_ptr runAsync( + Stack& stack, + TaskLauncher taskLauncher = at::launch); + + virtual const ExecutionPlan& getPlanFor( + Stack& stack, + std::optional remaining_bailout_depth = std::nullopt) = 0; + virtual GraphExecutorState getDebugState() = 0; + virtual ~GraphExecutorImplBase() = default; + + virtual bool isOptimized() const { + return false; + } + + protected: + friend struct GraphExecutor; + + // The unoptimized starting graph. This field is effectively const, but we + // can't make it so because Graph::copy() is not const (and making it const is + // not that easy at this point). + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr graph; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::string function_name_; + + // If false, we'll run the graph as we get it, without any optimizations. + // Useful for debugging. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const size_t num_inputs; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const size_t num_outputs; + + // GraphExecutors can be accessed from multiple threads, so this thread needs + // to be held every time we access the fallback or plan_cache. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::mutex compile_mutex; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_iterator.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_iterator.h new file mode 100644 index 0000000000000000000000000000000000000000..4d0db56a19b489224168b58ebdc854f4d3ed574c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/graph_iterator.h @@ -0,0 +1,152 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::jit { + +// This class facilitates depth-first iteration over all nodes in a graph. +class DepthFirstGraphNodeIterator { + Node* current_; + + public: + // Constructor. + explicit DepthFirstGraphNodeIterator(std::shared_ptr& graph) + : current_(*(graph->block()->nodes().begin())) {} + + // Moves up and to the next node (may move up recursively). + void move_up() { + if (current_ == nullptr) { + return; + } + // Basically we start from the child block (which is current_) + // and we try to find the block that owns it. Now we need to check + // if that block is the graph root block, or if it is an If/Loop/etc + // block. + // + // If it's the graph root block we can stop because there is no "up" + // but if it is a node (e.g. If/Loop/etc) we need to apply logic + // based on where we are coming from to move to the next block. + // This might mean that we need to traverse up again (e.g. if we've + // reached the end of the else clause in an if block we need to go) + // up to the parent block that contains the if. + // + // Similarly if we've reached the end of the parent block containing + // the else clause we might need to go up again so this is a recursive + // function. + // + // BlockNode (if/loop/with) + // | + // [Block1] ... [Block2] + // | + // [ Node1, Node2, Node3, FromNode] + // + auto parent_block = current_->owningBlock(); + TORCH_INTERNAL_ASSERT(parent_block, "Every node must be owned by a block"); + + // Get the node that owns the parent block. This node has to be an if, + // loop, or with. + auto parent_node = parent_block->owningNode(); + if (parent_node == nullptr) { + // If there's no node that owns this current block then we're at the + // top of the graph and since we're trying to move up we have reached + // the end of the traversal. + current_ = nullptr; + return; + } + + // Check the type of node this root is. + if (parent_node->kind() == prim::If) { + // Need to check if we came from the `then` branch or the `else` branch. + auto* then_block = parent_node->blocks().at(0); + auto* else_block = parent_node->blocks().at(1); + + if (parent_block == else_block) { + // If else block then we move to the next node in the parent block. + current_ = parent_node->next(); + if (current_->kind() == prim::Return) { + move_up(); + } + } else { + // If then block then move to the else block if it is not empty. + TORCH_INTERNAL_ASSERT(parent_block == then_block); + bool else_block_empty = + else_block->nodes().begin() == else_block->nodes().end(); + + if (!else_block_empty) { + current_ = *(else_block->nodes().begin()); + } else { + // Since it's empty we move to the next node. + current_ = parent_node->next(); + if (current_->kind() == prim::Return) { + move_up(); + } + } + } + } else if ( + parent_node->kind() == prim::Loop || + parent_node->kind() == prim::With) { + current_ = parent_node->next(); + if (current_->kind() == prim::Return) { + move_up(); + } + } else { + TORCH_INTERNAL_ASSERT( + false, "Only if/loop/with nodes should have child blocks"); + } + } + + // Moves to the next adjacent node or up in to the parent if that is not + // possible. + void move_next() { + if (current_ == nullptr) { + return; + } + + // Increment to the next node in the current block. + current_ = current_->next(); + + // Check if we're at the end of the block. If so we need + // to move upwards (if it makes sense to). + if (current_->kind() == prim::Return) { + move_up(); + } + } + + // Moves to the next node in the graph into children if it can. + void move_into() { + if (current_ == nullptr) { + return; + } + + // Check if we're currently on a node that contains sub-nodes. + if (current_->kind() == prim::If || current_->kind() == prim::Loop || + current_->kind() == prim::With) { + auto* first_block = current_->blocks().at(0); + current_ = first_block->param_node(); + // Move next will move up and out of the current node if the block is + // empty. `move_up` which is called by `move_next` will handle the + // difference between If, Loop, and With blocks appropriately. + move_next(); + } else { + move_next(); + } + } + + // Get the next Node in the graph. \returns nullptr if there are no nodes + // left. + Node* next() { + auto result = current_; + + // Try move into the existing node to set the next node to be returned. + // This will move to the next node if not possible, or move upwards and + // to the next. + move_into(); + + return result; + } +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/instruction.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/instruction.h new file mode 100644 index 0000000000000000000000000000000000000000..080937ce6d88af4b64ec03ecc9b86eed935756d3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/instruction.h @@ -0,0 +1,104 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { +// instruction look like: +// op_code X, N +// meaning of X, N depend on the op: +// O - index into operator table +// R - index into register table +// I - literal integer +// C - index into constant table +// P - jump offset relative to beginning of current instruction +// F - index into function table +// T - index into the type table, used for guard instructions +// S - index into object slots +// C - index into code table + +#define FORALL_OPCODES(_) \ + _(OP, "O") /* invoke operator X */ \ + _(OPN, "OI") /* invoke vararg operator X with N arguments */ \ + _(LOAD, "R") /* push a value from a register X */ \ + _(MOVE, "R") /* push a value from register X, clearing the register */ \ + _(STOREN, "RI") /* store N values to registers [X, X+N) */ \ + _(STORE, "R") /* store 1 value to registers X */ \ + _(DROP, "") /* drop 1 value from the top of the stack */ \ + _(DROPR, "R") /* clear register X */ \ + _(LOADC, "C") /* push the constant X */ \ + _(JF, "P") /* pop the top of the stack, if false, branch to P */ \ + _(JMP, "P") /* unconditional branch to X */ \ + _(LOOP, "PI") /* perform a loop, X is where to branch if cond is false */ \ + _(RET, "") /* exit execution */ \ + _(WAIT, "") /* wait for a future to be complete */ \ + _(CALL, "F") /* call function X */ \ + _(GUARD, "T") /* check a guard against type_table, true if passes */ \ + _(TYPECHECK, "TN") /* check each type of input[i] against type_table[X+N] */ \ + _(FAIL_GUARD, "T") /* fail a guard, patch back to GUARD */ \ + _(PROFILE_OP, "F") /* get a callback from profile_function_table at X */ \ + _(TAIL_CALL, "F") /* replace current frame with function F */ \ + _(INTERFACE_CALL, "CI") /* call method X on the first argument (of N) */ \ + _(GET_ATTR, "S") /* get attribute from slot X in an Object */ \ + _(SET_ATTR, "S") /* set attribute to slot X in an Object */ \ + _(LIST_UNPACK, "I") /* unpack list expecting length I */ \ + _(TUPLE_CONSTRUCT, "I") /* construct a tuple using X inputs */ \ + _(NAMED_TUPLE_CONSTRUCT, \ + "TI") /* construct a tuple of type X, using N inputs */ \ + _(LIST_CONSTRUCT, "TI") /* construct a list of type X, using N inputs */ \ + _(DICT_CONSTRUCT, "TI") /* construct a dict of type X, using N inputs */ \ + _(CREATE_OBJECT, "T") /* create an object of type X */ \ + _(ISINSTANCE, "TI") /* check object is one of types[X:X+N] */ \ + _(TUPLE_SLICE, "II") /* slice tup[X:(X+N)] */ \ + _(TUPLE_INDEX, "") /* get the value from a tuple at that index */ \ + _(RAISE_EXCEPTION, "") /* throws the exception from Python */ \ + _(DICT_INDEX, "") /* gets the value from the dict for given key */ \ + _(UNCHECKED_CAST, "") /* perform an unchecked cast operation */ \ + _(__IS__, "") /* performs `is` operator from Python */ \ + _(UN_INITIALIZED, \ + "") /* sets default values to variables that are uninitialized */ \ + _(__ISNOT__, "") /* performs `is not` operator from Python */ \ + _(FORMAT, "I") /* performs string format function `f strings` or `{}.format` \ + the number of inputs in stored in X */ \ + _(DEVICE, "") /* invokes aten::device for a Tensor */ \ + _(DTYPE, "") /* invokes aten::dtype for a Tensor */ \ + _(DIM, "") /* invokes aten::dim for a Tensor */ \ + _(__NOT__, "") /* performs `not` operator from Python */ \ + _(TO_LIST, "") /* convert the input to a list */ \ + _(NUM_TO_TENSOR, \ + "") /* performs the conversion of a number/scalar to Tensor */ \ + _(IS_CUDA, "") /* invokes aten::is_cuda for a Tensor */ \ + _(FORK, "CN") /* launch a thread to run code entry x with N inputs */ \ + _(WARN, "I") /* emit a warning with line information */ \ + _(ENTER, "EN") /* enter scope of a contextmanager */ \ + _(EXIT, "EX") /* exit the last entered contextmanager */ \ + _(AWAITABLE, "CN") /* initialize await for code entry x with N inputs */ + +enum OpCode : uint8_t { +#define DEFINE_OP(op, _) op, + FORALL_OPCODES(DEFINE_OP) +#undef DEFINE_OP +}; + +struct Instruction { + OpCode op; + uint8_t unused; + uint16_t N; + int32_t X; + // TODO: check for overflow + Instruction(OpCode op, int32_t X, uint16_t N) + : op(op), unused(0), N(N), X(X) {} +}; +std::ostream& operator<<(std::ostream& out, Instruction inst); + +bool isOpSupportedInMobile(OpCode op); +char const* toString(OpCode op); +OpCode parseOpCode(const char* str); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter.h new file mode 100644 index 0000000000000000000000000000000000000000..b5b5b3da8f19a94d8cf666148595ac0736826769 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter.h @@ -0,0 +1,165 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include +#include +#include +#include + +TORCH_DECLARE_bool(torch_jit_disable_warning_prints); +TORCH_DECLARE_bool(torch_jit_enable_rethrow_caught_exception); + +namespace at { +class Tensor; +TORCH_API void launch(std::function func); +} // namespace at +namespace c10 { +struct IValue; +struct OperatorName; +} // namespace c10 + +namespace torch::jit { + +// The interpreter run Graphs with Tensor inputs and Tensor outputs +// a separate component in the autograd handles unwrapping and wrapping +// variable objects for use in the interpreter. +namespace interpreter { +struct CodeImpl; +} + +struct Node; +struct GraphExecutor; +struct InterpreterStateImpl; +struct Graph; +struct Node; +struct Instruction; +using Stack = std::vector; +using c10::ivalue::Future; +using TaskLauncher = std::function)>; + +bool TORCH_API in_torchscript_runtime(); + +struct TORCH_API Code { + Code() = default; + explicit Code(interpreter::CodeImpl* pImpl); + // remaining_bailout_depth is irrelevant in a `Code` object unless the `Code` + // is directly created by `GraphExecutor` in which case it's likely to contain + // `prim::BailOut`s to control the maximum depth of bailout chains + explicit Code( + const std::shared_ptr& graph, + std::string function_name, + size_t remaining_bailout_depth = 0); + + const std::vector& grad_executors(); + const std::vector& diff_graph_op_executors(); + + explicit operator bool() const { + return pImpl != nullptr; + } + size_t num_inputs() const; + size_t num_outputs() const; + size_t num_bailouts() const; + const std::vector& constant_table() const; + const std::vector& type_table() const; + const std::vector& instructions() const; + const std::unordered_map& op_to_num_specified_args() + const; + const std::vector& instructions_source() const; + void request_bailout(size_t index); + size_t register_size() const; + std::shared_ptr graph() const; + + private: + std::shared_ptr pImpl; + friend struct InterpreterStateImpl; + friend std::ostream& operator<<(std::ostream& out, const Code& code); +}; + +struct TORCH_API MobileCode : Code { + explicit MobileCode( + const std::shared_ptr& graph, + std::string function_name, + bool emit_default_input_instructions = true, + bool support_default_args_before_out = true, + bool emit_promoted_ops = true, + size_t remaining_bailout_depth = 0); +}; + +struct InterpreterState { + TORCH_API InterpreterState( + const Code& code, + TaskLauncher taskLauncher = at::launch); + TORCH_API void run(Stack& stack); + TORCH_API c10::intrusive_ptr runAsync(Stack& stack); + c10::intrusive_ptr getFuture(); + + private: + InterpreterState(c10::intrusive_ptr pImpl); + // Ideally we should use c10::intrusive_ptr for pImpl; + // but intrusive_ptr requires full definition of InterpreterStateImpl, + // which we need to hide in the header. + c10::intrusive_ptr pImpl; + friend struct InterpreterStateImpl; +}; + +// Created by wait() +struct Suspend : public std::exception { + const char* what() const noexcept override { + return "Suspend"; + } + + explicit Suspend(c10::intrusive_ptr future_) + : future(std::move(future_)) {} + + c10::intrusive_ptr future; +}; + +// InterpreterContinuation propagates dist_autograd_context_id +// through (and only through) the forward pass manually, other +// thread local settings are propagated with ThreadLocalState +struct InterpreterContinuation { + InterpreterContinuation( + InterpreterState state_, + Stack stack_, + int64_t dist_autograd_context_id = 0, + std::optional tls_state = std::nullopt) + : state(std::move(state_)), + stack(std::move(stack_)), + tls_state_(std::move(tls_state)) +#ifdef USE_DISTRIBUTED + , + dist_autograd_context_id_(dist_autograd_context_id) +#endif + { + } + + void operator()(); + + private: + InterpreterState state; + Stack stack; + std::optional tls_state_ = std::nullopt; +#ifdef USE_DISTRIBUTED + int64_t dist_autograd_context_id_; +#endif +}; + +// what is the tensors type, including state from the current execution context +// that modifies how the tensor behaves. For instance if no_grad is enabled +// this will cause the TensorType to have requires_grad=False. +TORCH_API at::TensorTypePtr tensorTypeInCurrentExecutionContext( + const at::Tensor& t); + +// current (TLS) TorchScript interpreter callstack +TORCH_API std::vector currentCallstack(); +TORCH_API std::vector currentModuleHierarchy(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/can_emit_inline.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/can_emit_inline.h new file mode 100644 index 0000000000000000000000000000000000000000..65479623bac2d18d83a213a1c95163844462da08 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/can_emit_inline.h @@ -0,0 +1,111 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit::interpreter { +/* +This is an optimization that reduces the number of store/load/move nodes needed +by recognizing that parts of the graph are simple trees like a*x + b*y. When +this happens it is possible to work directly off of the stack by emitting the +tree in a depth-first left-to-right manner: + load a + load x + mul # stack now is a*x + load b + load y + mul # stack now is a*x, b*y + add + +can_emit_inline_[node] == true means that this node participates as a non-root +member of one of these trees. The code emitter will not emit this node when +it is encountered in the node. Instead the node is emitted in a depth first +traversal from where it is used in a tree. + +To participate in a tree a node must have a single use (otherwise it is not +tree-like) and output a single value (for simplicity.) If our IR was functional, +these would be the only constraints. However, many nodes have side effects, so +we must ensure that emitting the nodes in depth first order from the tree's root +_does not reorder the emission of the nodes_. To ensure this, we work backward +from the root of a potential tree, visiting its inputs in reverse depth first +order, while scanning the node list backward (with the block_point node). When +these traversal line up we know it is safe to emit the tree in this way. We +ignore constant nodes, which do not have side effects. +*/ +struct CanEmitInline { + explicit CanEmitInline(Graph& graph) { + scanBlock(graph.block()); + } + bool canInline(Value* v) { + return v->node()->kind() != prim::Param && + // without this a BailOut may float downstream past some later + // BailOut + // and receive a higher jf_index. Then a GUARD instruction + // we generated for the floated BailOut will get popped up from the + // instruction stack + // by the later BailOut in createBailoutBlock and its jf_index + // will become invalid. + v->node()->kind() != prim::TensorExprGroup && + v->node()->kind() != prim::TensorExprDynamicGroup && + v->node()->kind() != prim::StaticSubgraph && + v->node()->kind() != prim::CudaFusionGroup && + v->node()->kind() != prim::FusionGroup && + v->node()->kind() != prim::BailOut && v->uses().size() == 1 && + v->node()->outputs().size() == 1; + } + + Node* previousNonConstant(Node* n) { + do { + n = n->prev(); + } while (n->kind() == prim::Constant); + return n; + } + + Node* scanValue(Node* block_point, Value* v) { + // this node is a candidate for inline, if our reverse scan of the + // node list lines up with the use of v, we know it will be emitted in + // tree order, and we can inlining. Scan continues for further nodes. + if (v->node() == block_point && canInline(v)) { + // since we inlined this node, we may be able to recursively inline + // its inputs, so we continue scanning it + block_point = scanNode(v->node()); + can_emit_inline_[v->node()] = true; + } + // if it does not line up, we can't inline 'v', and will just generate + // a load/move for it. However, other inputs may still appear in tree + // order so we continue the scan of the inputs. + return block_point; + } + + Node* scanNode(Node* n) { + // don't bother to scan nodes we have already determined to be inline + if (can_emit_inline_.count(n)) { + return nullptr; + } + for (auto b : n->blocks()) { + scanBlock(b); + } + Node* block_point = previousNonConstant(n); + for (auto it = n->inputs().rbegin(), end = n->inputs().rend(); it != end; + ++it) { + block_point = scanValue(block_point, *it); + } + return block_point; + } + + void scanBlock(Block* b) { + scanNode(b->return_node()); + for (auto node : b->nodes().reverse()) { + scanNode(node); + } + } + std::unordered_map can_emit_inline_; +}; + +} // namespace torch::jit::interpreter + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/code_impl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/code_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..8b3563f42b919259fd3e682f25f6470ebac6325d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/code_impl.h @@ -0,0 +1,1066 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +TORCH_DECLARE_bool(torch_jit_enable_expanded_stacks); +TORCH_DECLARE_bool(torch_jit_expanded_stacks_mangled); + +namespace torch::jit::interpreter { + +template +Ttarget safe_narrow_cast(Tsource v) { + Ttarget res = static_cast(v); + // Casting it back to check whether it overflew. + if (static_cast(res) != v) { + TORCH_WARN( + "ATTENTION: your model computation is overflowing, safe_narrow_cast<>() failed"); + return v; + } + return res; +} + +// BailoutBlocks are used to temporarily store +// instructions (typically, argument LOADs and TAIL_CALL) +// generated for prim::BailOut nodes +// before they are merged back into +// CodeImpl._instructions_ by insertBailoutBlocks +struct BailoutBlock { + size_t jf_instruction_index; // this node gets patched to jump here on failure + std::vector instructions; // ends in a TAIL_CALL + + explicit BailoutBlock(size_t jf_index) : jf_instruction_index(jf_index) {} +}; + +// for keeping track of the current node +struct WithCurrentNode { + WithCurrentNode(Node** loc, Node* new_value) : loc_(loc), old_value_(*loc_) { + *loc = new_value; + } + ~WithCurrentNode() { + *loc_ = old_value_; + } + + private: + Node** loc_; + Node* old_value_; +}; + +struct NodeSourceInfo { + const char* func_name_{nullptr}; + const char* file_name_{nullptr}; + size_t line_{0}; + NodeSourceInfo() = default; +}; + +struct CodeImpl { + friend struct InterpreterState; + std::vector instructions_; + + const c10::unique_t node_stack_attr_symbol_ = + static_cast(attr::node_stack_idx); + // Expanded inlined stacks as pointers to values in inlined call stack. + std::vector> expanded_node_stacks_; + + // same length as instructions. + // what node in the graph cause this + // instruction to be emitted? + std::vector instructions_source_; + std::vector constant_table_; + std::vector operator_table_; +#ifndef NDEBUG + std::vector full_operator_table_; +#endif + // map<(op name, num inputs), index in operator table>, to avoid duplicates, + // not including vararg operators + std::unordered_map< + std::pair, + int, + std::function& p)>> + operator_table_inv_; + std::vector function_table_; + std::vector> forked_functions_; + std::vector> awaited_functions_; + std::vector type_table_; + std::vector&)>> + profile_function_table_; + + int register_size_ = 0; + size_t n_outputs; + size_t n_inputs; + TypePtr return_type_; + std::string function_name_; + + // We MUST hold onto graph here because some Operators stored in the + // instruction lists have dependencies on meta-data stored in the graph + // that would be dead otherwise. + // It is also very useful for debugging interpreter problems to + // keep this around. + std::shared_ptr graph_; + std::optional> grad_executors_; + std::optional> forward_executors_; + PreprocessGraph preprocess_; + + // map from unique of nodes to register in register table + std::unordered_map value_to_reg_; + + // map from operator name to specified arguments + // Example: for a schema of aten::foo.str + // aten::foo.str(arg0: str="default", arg1: int=0, + // arg2: bool=False, arg3: float=0.0) + // If the usages in a graph is: + // aten::foo("somestr", arg1=0, arg2=True, arg3=0.0) + // aten::foo("somestr", arg1=1, arg2=False, arg3=0.0) + // op_to_num_specified_args_["aten::foo.str"] = 3 + // This is because for all usages, at most 3 args are used. + std::unordered_map op_to_num_specified_args_; + + std::unordered_map op_to_num_out_args_; + + // running count of uses as we emit. When we reach use_count_[v] = + // v.uses().size() we know it is the final use and we can move rather than + // load. + std::unordered_map use_count_; + + Node* current_node_; // used in creation of code to keep track + // of node being emitted + Node* last_inserted_op_ = nullptr; + + // out-of-line jumps for bailouts that are patched in at the end + std::vector bailout_blocks_; + std::vector> bailout_functions_; + size_t remaining_bailout_depth_; + + CodeImpl( + const std::shared_ptr& graph, + std::string function_name, + size_t remaining_bailout_depth, + bool emit_instructions = true) + : operator_table_inv_( + 0, + [](const std::pair& p) { + return std::hash()(p.first) ^ + std::hash()(p.second); + }), + function_name_(std::move(function_name)), + preprocess_(*graph), + current_node_(preprocess_.graph->return_node()), + remaining_bailout_depth_(remaining_bailout_depth) { + graph_ = preprocess_.graph; + n_outputs = graph_->outputs().size(); + if (n_outputs == 1) { + return_type_ = graph->outputs().at(0)->type(); + } else { + return_type_ = TupleType::create( + fmap(graph->outputs(), [](const Value* v) { return v->type(); })); + } + n_inputs = graph_->inputs().size(); + if (emit_instructions) { + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) + run(); + } + } + + virtual ~CodeImpl() = default; + + // since subclass of CodeImpl needs to populate + // op_to_num_specified_args, we separate the calls + // that changes internals of CodeImpl into a separate + // function. + virtual void run() { + emitCodeForBlock(graph_->block()); + insertInstruction(RET); + // we deferred the emission of bailout blocks so they appear at the end + // emit them now and patch up the jumps + insertBailoutBlocks(); + } + + const std::vector& constant_table() const { + return constant_table_; + } + + void request_bailout(size_t index) { + auto count = index; + for (const auto instr_index : c10::irange(instructions_.size())) { + if (instructions_[instr_index].op == GUARD || + instructions_[instr_index].op == FAIL_GUARD) { + if (count-- == 0) { + // patching GUARD to FAIL_GUARD + instructions_[instr_index].op = FAIL_GUARD; + GRAPH_DEBUG( + "Added a bailout request for ", + index, + " at instruction ", + instr_index); + break; + } + } + } + } + + const std::vector& instructions() const { + return instructions_; + } + + const std::unordered_map& op_to_num_specified_args() + const { + return op_to_num_specified_args_; + } + + const std::vector& instructions_source() const { + return instructions_source_; + } + + NodeSourceInfo getSourceInfoFromSourceRange(const SourceRange& range) { + NodeSourceInfo nodeSource; + SourceRange r = range; + if (!FLAGS_torch_jit_expanded_stacks_mangled && range.source()) { + if (auto orig = range.source()->findSourceRangeThatGenerated(r)) { + r = *orig; + } + } + if (r.source()) { + auto lineno = r.source()->lineno_for_offset(r.start()); + nodeSource.line_ = r.source()->lineno_to_source_lineno(lineno); + if (r.source()->filename()) { + nodeSource.file_name_ = r.source()->filename().value().c_str(); + } + } + return nodeSource; + } + + void expandInlinedNodeStack( + const InlinedCallStackPtr& cs, + std::vector* expandedstack) { + auto nodeSourceInfo = getSourceInfoFromSourceRange(cs->source_range()); + nodeSourceInfo.func_name_ = cs->function_name().c_str(); + expandedstack->emplace_back(nodeSourceInfo); + + if (cs->callee()) { + expandInlinedNodeStack(cs->callee().value(), expandedstack); + } + } + + void getNodeStack( + const Node* node, + std::vector* expandedstack) { + if (current_node_->callstack()) { + expandInlinedNodeStack(current_node_->callstack().value(), expandedstack); + } + auto nodeSourceInfo = getSourceInfoFromSourceRange(node->sourceRange()); + expandedstack->emplace_back(nodeSourceInfo); + } + + void insertInstruction(OpCode op, int64_t X = 0, uint64_t N = 0) { + instructions_.emplace_back( + op, + safe_narrow_cast(X), + safe_narrow_cast(N)); + instructions_source_.emplace_back(current_node_); + + if (FLAGS_torch_jit_enable_expanded_stacks && + !current_node_->hasAttribute(attr::node_stack_idx)) { + std::vector expandedStack; + getNodeStack(current_node_, &expandedStack); + auto insertIdx = expanded_node_stacks_.size(); + expanded_node_stacks_.emplace_back(expandedStack); + current_node_->i_(attr::node_stack_idx, insertIdx); + } + + // check that we didn't accidentally emit nodes out of topological order + if (op == OP) { + if (last_inserted_op_ != nullptr && current_node_ != last_inserted_op_ && + current_node_->owningBlock() == last_inserted_op_->owningBlock()) { + TORCH_INTERNAL_ASSERT( + current_node_->isAfter(last_inserted_op_), + *current_node_, + " is not after ", + *last_inserted_op_); + } + last_inserted_op_ = current_node_; + } + } + + void truncateInstructions(size_t size) { + while (instructions_.size() > size) { + instructions_.pop_back(); + instructions_source_.pop_back(); + } + } + + void createBailoutBlock(size_t jf_index) { + bailout_blocks_.emplace_back(jf_index); + auto& bailout_instructions = bailout_blocks_.back().instructions; + + bailout_instructions.insert( + bailout_instructions.end(), + instructions_.begin() + jf_index + 1, + instructions_.end()); + truncateInstructions(jf_index + 1); + } + + int allocRegs(at::ArrayRef vs) { + int result = register_size_ + 1; + for (Value* v : vs) { + AT_ASSERT(value_to_reg_.count(v) == 0); + value_to_reg_[v] = ++register_size_; + } + return result; + } + + int registerFor(Value* v) { + return value_to_reg_.at(v); + } + + void emitUse(Value* input, bool drop) { + // drop - if true, we are not actually going to use this thing + // and we can short circuit doing many instructions here + // by either clearing the register (DROPR) or just popping the stack + // (DROP) + if (preprocess_.can_emit_inline[input->node()]) { + emitNode(input->node()); + if (drop) { + insertInstruction(DROP); + } + } else { + int reg = registerFor(input); + bool moved = input->uses().size() == ++use_count_[input]; + + OpCode op{}; + if (input->node()->kind() == prim::Constant) { + op = LOADC; + } else if (moved) { + op = MOVE; + } else { + op = LOAD; + } + + if (drop) { + op = DROPR; + } + insertInstruction(op, reg); + } + } + + void emitLoadInputs(at::ArrayRef inputs) { + for (Value* input : inputs) { + emitUse(input, false); + } + } + + void emitLoadInputs(at::ArrayRef inputs, int num_include) { + int count = 0; + for (Value* input : inputs) { + if (count < num_include) { + emitUse(input, false); + count++; + } + } + } + + void emitLoadInputs(at::ArrayRef inputs, size_t start, size_t end) { + for (size_t i = start; i < end; i++) { + emitUse(inputs[i], false); + } + } + + virtual void emitOperator(Node* node) { + emitLoadInputs(node->inputs()); + const Operator& op = node->getOperator(); + int num_inputs = node->inputs().size(); + bool is_vararg = op.schema().is_vararg(); + + int operation_index = add_to_operator_table( + op, + node, + c10::toString(op.schema().operator_name()), + num_inputs, + is_vararg); + + if (op.hasOperation() && is_vararg) { + insertInstruction(OPN, operation_index, num_inputs); + } else { + insertInstruction(OP, operation_index); + } + } + + void emitWait(Node* node) { + emitLoadInputs(node->inputs()); + insertInstruction(WAIT); + } + + void emitDrop(at::ArrayRef to_drop) { + for (Value* input : to_drop) { + emitUse(input, true); + } + } + + void emitStoreOutputs(Node* node) { + size_t N = node->outputs().size(); + if (N == 0) { + return; + } + int regs = allocRegs(node->outputs()); + if (N == 1) { + insertInstruction(STORE, regs); + } else { + insertInstruction(STOREN, regs, node->outputs().size()); + } + } + + int insertConstant(IValue value) { + int result = constant_table_.size(); + constant_table_.emplace_back(std::move(value)); + return result; + } + + virtual void emitOperatorOrInstruction( + Node* node, + OpCode op, + int64_t X = 0, + uint64_t N = 0, + bool emit_inputs = true) { + if (emit_inputs) { + emitLoadInputs(node->inputs()); + } + insertInstruction(op, X, N); + } + + void emitFormat(Node* node) { + emitOperatorOrInstruction(node, FORMAT, node->inputs().size(), 0); + } + + void checkNodeAndEmit(Node* node) { + // check if the node should be emitted as instruction or operator + const Operator& op = node->getOperator(); + std::string unique_op_name = c10::toString(op.schema().operator_name()); + if (unique_op_name.find("aten::__getitem__.Dict") == 0) { + // __get_item__ overloaded operator for Dict + // needs to be emitted an instruction + emitOperatorOrInstruction(node, DICT_INDEX); + } else { + emitOperator(node); + } + } + + void emitConstant(Node* node) { + if (node->output()->type()->kind() == FunctionType::Kind) { + return; + } + // constants are just put in the constant table + value_to_reg_[node->output()] = + insertConstant(toIValue(node->output()).value()); + } + + void emitIf(Node* node) { + emitLoadInputs(node->inputs()); + size_t start_if = instructions_.size(); + insertInstruction(JF, 0); // dummy offset to be filled in + emitCodeForBlock(node->blocks().at(0)); + insertInstruction(JMP, 0); // dummy offset + size_t start_else = instructions_.size(); + instructions_[start_if].X = start_else - start_if; + emitCodeForBlock(node->blocks().at(1)); + instructions_[start_else - 1].X = instructions_.size() - (start_else - 1); + } + + void emitLoop(Node* loop) { + insertInstruction(LOADC, insertConstant(0)); + emitLoadInputs(loop->inputs()); + size_t start = instructions_.size(); + insertInstruction(LOOP, 0, loop->inputs().size()); // dummy offset + emitCodeForBlock(loop->blocks().at(0)); + insertInstruction(JMP, start - instructions_.size()); + instructions_[start].X = instructions_.size() - start; + } + + void emitCall(Function* func, at::ArrayRef inputs) { + emitLoadInputs(inputs); + insertInstruction(CALL, function_table_.size()); + function_table_.emplace_back(func); + } + + void emitNodeAtBlockLevel(Node* node) { + WithCurrentNode guard(¤t_node_, node); + switch (node->kind()) { + case prim::Constant: + emitConstant(node); + break; + case prim::Return: + emitLoadInputs(node->inputs()); + break; + default: + if (!preprocess_.can_emit_inline[node]) { + emitNode(node); + emitStoreOutputs(node); + } + break; + } + } + + size_t emitType(TypePtr t) { + size_t r = type_table_.size(); + type_table_.emplace_back(std::move(t)); + return r; + } + + void emitTypeCheck(Node* node) { + auto num_inputs = node->inputs().size(); + + // Check that TypeCheck has at least one input. + TORCH_INTERNAL_ASSERT( + num_inputs && num_inputs + 1 == node->outputs().size()); + emitLoadInputs(node->inputs()); + + // Emit the expected type. + size_t types_start = type_table_.size(); + auto types = node->tys(attr::types); + for (const auto i : c10::irange(num_inputs)) { + emitType(types[i]); + } + insertInstruction(TYPECHECK, types_start, num_inputs); + } + + size_t emitGuard(Node* node) { + // unoptimized graph is at index 0 + // guarded input is at index 1 + // the rest of args follow + emitLoadInputs(node->inputs().slice(1, 1)); + insertInstruction(GUARD, emitType(node->outputs().at(0)->type())); + insertInstruction(JF, 0 /* to be patched */); + return instructions_.size() - 1; + } + + void emitBailOut(Node* node) { + auto jf_index = emitGuard(node); + auto unoptimized_graph = node->inputs().at(0)->node()->g(attr::Subgraph); + // note, guaded input is already loaded onto the stack + // for GUARD instruction + emitLoadInputs(node->inputs().slice(2)); + insertInstruction(TAIL_CALL, function_table_.size()); + TORCH_INTERNAL_ASSERT(node->kind() == prim::BailOut); + auto bailout_index = node->i(attr::index); + TORCH_INTERNAL_ASSERT(bailout_index >= 0); + + auto build_bailout_graph = [bailout_index, + unoptimized_graph](GraphFunction& func) { + BuildBailOutGraphFrom(bailout_index, unoptimized_graph, func.graph()); + }; + + auto empty_graph = std::make_shared(); + auto func = std::make_unique( + "bailout", empty_graph, build_bailout_graph); + function_table_.emplace_back(func.get()); + bailout_functions_.emplace_back(std::move(func)); + createBailoutBlock(jf_index); + } + + void emitProfile(Node* node) { + emitLoadInputs(node->inputs()); + insertInstruction(PROFILE_OP, profile_function_table_.size()); + if (node->cast()) { + profile_function_table_.push_back(node->cast()->getCallback()); + } else if (node->cast()) { + profile_function_table_.push_back( + node->cast()->getCallback()); + } else { + TORCH_INTERNAL_ASSERT(false); + } + } + + void emitGetAttr(Node* node) { + emitLoadInputs(node->inputs()); + const auto type = node->input()->type()->expect(); + const auto& field = node->s(attr::name); + const auto slot = type->getAttributeSlot(field); + insertInstruction(GET_ATTR, slot); + } + + void emitSetAttr(Node* node) { + emitLoadInputs(node->inputs()); + const auto type = node->inputs().at(0)->type()->expect(); + const auto& field = node->s(attr::name); + const auto slot = type->getAttributeSlot(field); + insertInstruction(SET_ATTR, slot); + } + + void insertBailoutBlocks() { + for (const BailoutBlock& block : bailout_blocks_) { + TORCH_INTERNAL_ASSERT(instructions_[block.jf_instruction_index].op == JF) + instructions_[block.jf_instruction_index].X = + instructions_.size() - block.jf_instruction_index; + instructions_.insert( + instructions_.end(), + block.instructions.begin(), + block.instructions.end()); + instructions_source_.insert( + instructions_source_.end(), + block.instructions.size(), + instructions_source_[block.jf_instruction_index]); + } + } + void emitInterfaceCall( + std::string method_name_str, + c10::ArrayRef inputs) { + emitLoadInputs(inputs); + auto method_name = insertConstant(std::move(method_name_str)); + insertInstruction(INTERFACE_CALL, method_name, inputs.size()); + } + + void emitListUnpack(Node* node) { + emitLoadInputs(node->inputs()); + insertInstruction(LIST_UNPACK, node->outputs().size()); + } + + void emitTupleConstruct(Node* node) { + bool named = + node->output()->type()->expectRef().name().has_value(); + if (named) { + emitContainerConstruct(NAMED_TUPLE_CONSTRUCT, node); + } else { + emitLoadInputs(node->inputs()); + insertInstruction(TUPLE_CONSTRUCT, node->inputs().size()); + } + } + + void emitContainerConstruct(OpCode op, Node* node) { + emitLoadInputs(node->inputs()); + insertInstruction( + op, emitType(node->output()->type()), node->inputs().size()); + } + + void emitCreateObject(Node* node) { + insertInstruction(CREATE_OBJECT, emitType(node->output()->type())); + } + void emitIsinstance(Node* node) { + emitLoadInputs(node->inputs()); + std::vector types = node->tys(attr::types); + size_t types_start = type_table_.size(); + for (const auto& typ : types) { + emitType(typ); + } + insertInstruction(ISINSTANCE, types_start, types.size()); + } + + void emitTupleSlice(Node* node) { + emitLoadInputs(node->inputs()); + int64_t beg_ind = node->i(attr::beg); + int64_t end_ind = node->i(attr::end); + insertInstruction(TUPLE_SLICE, beg_ind, end_ind - beg_ind); + } + + void emitFork(Node* node) { + emitLoadInputs(node->inputs()); + auto forked_fn = std::make_unique( + "", node->g(attr::Subgraph), nullptr); + forked_functions_.emplace_back(std::move(forked_fn)); + function_table_.emplace_back(forked_functions_.back().get()); + insertInstruction(FORK, function_table_.size() - 1, node->inputs().size()); + } + + void emitAwaitable(Node* node) { + emitLoadInputs(node->inputs()); + auto await_fn = std::make_unique( + "", node->g(attr::Subgraph), nullptr); + awaited_functions_.emplace_back(std::move(await_fn)); + function_table_.emplace_back(awaited_functions_.back().get()); + insertInstruction( + AWAITABLE, function_table_.size() - 1, node->inputs().size()); + } + + void emitWarn(Node* node) { + if (FLAGS_torch_jit_disable_warning_prints) { + return; + } + + emitLoadInputs(node->inputs()); + int32_t idx = -1; + if (node->hasAttribute(attr::warn_id)) { + idx = static_cast(node->i(attr::warn_id)); + } + insertInstruction(WARN, idx); + } + + void emitEnter(Node* node) { + emitLoadInputs(node->inputs()); + insertInstruction(ENTER); + } + + void emitExit(Node* /* node */) { + insertInstruction(EXIT); + } + + void emitNode(Node* node) { + WithCurrentNode guard(¤t_node_, node); + switch (node->kind()) { + default: + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) + checkNodeAndEmit(node); + // emitOperator(node); + break; + case prim::RaiseException: + emitOperatorOrInstruction(node, RAISE_EXCEPTION); + break; + case prim::TupleIndex: + emitOperatorOrInstruction(node, TUPLE_INDEX); + break; + case prim::Drop: + emitDrop(node->inputs()); + break; + case prim::Constant: + emitConstant(node); + break; + case prim::If: + emitIf(node); + break; + case prim::Loop: + emitLoop(node); + break; + case aten::wait: + emitWait(node); + break; + case prim::Param: + break; + case prim::CallFunction: + emitCall( + node->inputs().at(0)->type()->expectRef().function(), + node->inputs().slice(1)); + break; + case prim::CallMethod: + if (auto class_type = node->inputs().at(0)->type()->cast()) { + emitCall(&class_type->getMethod(node->s(attr::name)), node->inputs()); + } else { + emitInterfaceCall(node->s(attr::name), node->inputs()); + } + break; + case prim::TypeCheck: + emitTypeCheck(node); + break; + case prim::BailOut: + emitBailOut(node); + break; + case prim::profile_ivalue: + case prim::profile: + emitProfile(node); + break; + case prim::GetAttr: + emitGetAttr(node); + break; + case prim::SetAttr: + emitSetAttr(node); + break; + case prim::ListUnpack: + emitListUnpack(node); + break; + case prim::TupleConstruct: + emitTupleConstruct(node); + break; + case prim::ListConstruct: + emitContainerConstruct(LIST_CONSTRUCT, node); + break; + case prim::DictConstruct: + emitContainerConstruct(DICT_CONSTRUCT, node); + break; + case prim::CreateObject: + emitCreateObject(node); + break; + case prim::isinstance: + emitIsinstance(node); + break; + case prim::TupleSlice: + emitTupleSlice(node); + break; + case prim::fork: + emitFork(node); + break; + case prim::awaitable: + emitAwaitable(node); + break; + case aten::warn: + emitWarn(node); + break; + case prim::Enter: + emitEnter(node); + break; + case prim::Exit: + emitExit(node); + break; + case prim::Uninitialized: + emitOperatorOrInstruction(node, UN_INITIALIZED, 0, 0, false); + break; + case prim::dtype: + emitOperatorOrInstruction(node, DTYPE); + break; + case prim::device: + emitOperatorOrInstruction(node, DEVICE); + break; + case aten::dim: + emitOperatorOrInstruction(node, DIM); + break; + case prim::is_cuda: + emitOperatorOrInstruction(node, IS_CUDA); + break; + case aten::__not__: + emitOperatorOrInstruction(node, __NOT__); + break; + case aten::format: + emitFormat(node); + break; + case aten::__is__: + emitOperatorOrInstruction(node, __IS__); + break; + case aten::__isnot__: + emitOperatorOrInstruction(node, __ISNOT__); + break; + case prim::NumToTensor: + emitOperatorOrInstruction(node, NUM_TO_TENSOR); + break; + case prim::tolist: + emitOperatorOrInstruction(node, TO_LIST); + break; + } + } + + void emitCodeForBlock(Block* block) { + emitNodeAtBlockLevel(block->param_node()); + for (auto node : block->nodes()) { + emitNodeAtBlockLevel(node); + } + emitNodeAtBlockLevel(block->return_node()); + } + + const std::vector& grad_executors() { + if (!grad_executors_) { + grad_executors_.emplace(); + for (Operation& op : operator_table_) { + if (auto executor = detail::getGradExecutor(op)) { + grad_executors_->push_back(executor); + } + } + } + return *grad_executors_; + } + + const std::vector& diff_graph_op_executors() { + if (!forward_executors_) { + forward_executors_.emplace(); + for (Operation& op : operator_table_) { + if (auto executor = detail::getDifferentiableGraphOpExecutor(op)) { + forward_executors_->push_back(executor); + } + } + } + return *forward_executors_; + } + + void dump(std::ostream& out, size_t i) const { + out << i << ' ' << instructions_[i]; + if (instructions_[i].op == OP || instructions_[i].op == CALL || + instructions_[i].op == OPN) { + out << " # " << *instructions_source_[i]; + } else { + out << '\n'; + } + } + + void dump(std::ostream& out) const { + out << *graph_ << '\n'; + for (const auto i : c10::irange(instructions_.size())) { + dump(out, i); + } + } + + /** + * Add an operation to operator_table_ if not a duplicate and return its index + */ + int add_to_operator_table( + const Operator& op, + const Node* node, + const std::string& op_name, + const int num_inputs, + const bool is_vararg) { + int size = operator_table_.size(); + + const Operation& oper = op.getOperation(node); + + if (!is_vararg) { + std::pair key(op_name, num_inputs); + auto found = operator_table_inv_.find(key); + + if (found != operator_table_inv_.end()) { + return found->second; + } + + operator_table_inv_.emplace(key, size); + } + + operator_table_.emplace_back(oper); +#ifndef NDEBUG + full_operator_table_.emplace_back(op); +#endif + return size; + } + + inline void assert_stack_size( + int32_t instruction_index, + size_t init_size, + size_t actual_size) const { +#ifndef NDEBUG + const auto& schema = full_operator_table_[instruction_index].schema(); + int64_t expected_size = static_cast(init_size) - + static_cast(schema.arguments().size()) + + static_cast(schema.returns().size()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + static_cast(expected_size) == actual_size || + schema.is_varret() || schema.is_vararg(), + "Expected to find ", + expected_size, + " values on the stack, but found ", + actual_size, + " on the stack after ", + toString(full_operator_table_[instruction_index].schema())); +#endif + } +}; + +struct MobileCodeImpl : CodeImpl { + MobileCodeImpl( + const std::shared_ptr& graph, + std::string function_name, + bool emit_default_input_instructions, + bool support_default_args_before_out, + bool emit_promoted_ops, + size_t remaining_bailout_depth) + : CodeImpl( + graph, + std::move(function_name), + remaining_bailout_depth, + false), + emit_default_input_instructions_(emit_default_input_instructions), + support_default_args_before_out_(support_default_args_before_out), + emit_promoted_ops_(emit_promoted_ops) { + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) + run(); + } + + void run() override { + process_ops_for_mobile(); + emitCodeForBlock(graph_->block()); + insertInstruction(RET); + // we deferred the emission of bailout blocks so they appear at the end + // emit them now and patch up the jumps + insertBailoutBlocks(); + } + + void process_ops_for_mobile() { + DepthFirstGraphNodeIterator graph_it(graph_); + Node* node = graph_it.next(); + while (node) { + if (node->maybeOperator()) { + auto op_schema = node->getOperator().schema(); + // skip if schema has vararg + if (!op_schema.is_vararg()) { + auto specifiedArgs = CalculateNecessaryArgs( + op_schema.arguments(), + node->inputs(), + support_default_args_before_out_); + + size_t numInclude = specifiedArgs.first + + (support_default_args_before_out_ ? specifiedArgs.second : 0); + auto unique_name = !op_schema.overload_name().empty() + ? op_schema.name() + "." + op_schema.overload_name() + : op_schema.name(); + auto it = op_to_num_specified_args_.insert( + std::pair(unique_name, 0)); + op_to_num_out_args_.insert(std::pair( + unique_name, specifiedArgs.second)); + auto prev_value = it.first->second; + it.first->second = std::max(numInclude, prev_value); + } + } + node = graph_it.next(); + } + } + + private: + void emitOperator(Node* node) override { + if (emit_default_input_instructions_) { + CodeImpl::emitOperator(node); + } else { + const Operator& op = node->getOperator(); + std::string unique_op_name = c10::toString(op.schema().operator_name()); + int num_inputs = node->inputs().size(); + bool is_vararg = op.schema().is_vararg(); + + if (op.hasOperation() && is_vararg) { + emitLoadInputs(node->inputs()); + int operation_index = add_to_operator_table( + op, + node, + unique_op_name, + num_inputs, + /* is_vararg */ true); + insertInstruction(OPN, operation_index, num_inputs); + } else { + auto num_include = num_inputs; + auto it = op_to_num_specified_args_.find(unique_op_name); + if (it != op_to_num_specified_args_.end()) { + num_include = it->second; + } + if (support_default_args_before_out_) { + auto num_out = op_to_num_out_args_.find(unique_op_name)->second; + auto num_specified_before_out = num_include - num_out; + emitLoadInputs(node->inputs(), 0, num_specified_before_out); + emitLoadInputs( + node->inputs(), + node->inputs().size() - num_out, + node->inputs().size()); + } else { + emitLoadInputs(node->inputs(), num_include); + } + int operation_index = add_to_operator_table( + op, node, unique_op_name, num_inputs, is_vararg); + insertInstruction(OP, operation_index); + } + } + } + + void emitOperatorOrInstruction( + Node* node, + OpCode op, + int64_t X = 0, + uint64_t N = 0, + bool emit_inputs = true) override { + if (emit_promoted_ops_) { + CodeImpl::emitOperatorOrInstruction(node, op, X, N, emit_inputs); + } else { + CodeImpl::emitOperator(node); + } + } + + // To support forward compatibility for bytecode version bump from v5 to v6 + bool emit_default_input_instructions_; + // To support forward compatibility for bytecode version bump from v6 to v7 + bool support_default_args_before_out_; + // To support forward compatibility for bytecode version bump from v7 to v8 + bool emit_promoted_ops_; +}; + +} // namespace torch::jit::interpreter + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/frame.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/frame.h new file mode 100644 index 0000000000000000000000000000000000000000..16b4efc0497fdf3b943e52075ae8c2129ddc1caf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/frame.h @@ -0,0 +1,45 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include + +namespace torch::jit::interpreter { + +// A Frame captures function's state +// (e.g. `pc` and `base_pointer`) +// Each Frame corresponds to a call to a `Frame::function` +// which has not yet returned +// The arguments for `Frame::function` +// are located at [base_pointer + arg_number] +struct Frame { + std::shared_ptr function; + // program counter corresponds to the index + // of the currently executed instruction + size_t pc; + // marks the start index of the frame + // base_pointer is used by TAIL_CALL + // to replace the current frame + // with a frame of a bailout graph + size_t base_pointer; + + // unique to every frame with prim::profile across all threads + std::optional id; + + // RecordFunction object associated with this frame + std::unique_ptr record_function; + + // symbol table for a frame + ShapeSymbolTable symbols2dims; + + static size_t genId(); +}; + +} // namespace torch::jit::interpreter + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/preprocess_graph.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/preprocess_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..62cb9e5367ba77f9c9e364f0cd775cca48039952 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/interpreter/preprocess_graph.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::jit::interpreter { + +// pre-processing that happens once per graph +struct PreprocessGraph { + explicit PreprocessGraph(Graph& g); + + // Outputs of the preprocessing: + std::shared_ptr graph; + std::unordered_map can_emit_inline; +}; + +} // namespace torch::jit::interpreter + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/jit_exception.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/jit_exception.h new file mode 100644 index 0000000000000000000000000000000000000000..1ce95c6271f6f2ec91155d36793e2769f1da0fa4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/jit_exception.h @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include + +namespace torch::jit { + +struct TORCH_API JITException : public std::runtime_error { + explicit JITException( + const std::string& msg, + std::optional python_class_name = std::nullopt, + std::optional original_msg = std::nullopt); + + std::optional getPythonClassName() const { + return python_class_name_; + } + + // the original msg if this is from a python exception. The interpreter has + // changed the original message by adding "The following operation failed in + // the TorchScript interpreter." in front of it in the handleError function. + std::optional getOriginalMsg() const { + return original_msg_; + } + + static const std::string& getCaughtOriginalMsg(); + static const std::string& getCaughtPythonClassName(); + static void setCaughtOriginalMsg(const std::string& msg); + static void setCaughtPythonClassName(const std::string& pythonClassName); + + private: + std::optional python_class_name_; + std::optional original_msg_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/jit_trace.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/jit_trace.h new file mode 100644 index 0000000000000000000000000000000000000000..d6c7d15e94c0785223a7e96b5e02981c5cc4c3c2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/jit_trace.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#include + +namespace torch::jit { +TORCH_API std::shared_ptr TraceGraph( + const std::shared_ptr& graph, + Stack& stack); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/logging.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/logging.h new file mode 100644 index 0000000000000000000000000000000000000000..b56c20b3ba24fdedd04c9e31b3700b8d98057680 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/logging.h @@ -0,0 +1,94 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include + +namespace torch::jit::logging { + +class LoggerBase { + public: + TORCH_API virtual void addStatValue( + const std::string& stat_name, + int64_t val) = 0; + virtual ~LoggerBase() = default; +}; + +TORCH_API LoggerBase* getLogger(); +TORCH_API LoggerBase* setLogger(LoggerBase* logger); + +// No-op logger. This is the default and is meant to incur almost no runtime +// overhead. + +class NoopLogger : public LoggerBase { + public: + void addStatValue( + const std::string& stat_name [[maybe_unused]], + int64_t val [[maybe_unused]]) override {} + ~NoopLogger() override = default; +}; + +// Trivial locking logger. Pass in an instance of this to setLogger() to use it. +// This keeps track of the sum of all statistics. +// +// NOTE: this is not written in a scalable way and should probably only be used +// in the single-threaded case or for testing. +class TORCH_API LockingLogger : public LoggerBase { + public: + void addStatValue(const std::string& stat_name, int64_t val) override; + virtual int64_t getCounterValue(const std::string& name) const; + enum class AggregationType { SUM = 0, AVG = 1 }; + void setAggregationType(const std::string& stat_name, AggregationType type); + ~LockingLogger() override = default; + + private: + mutable std::mutex m; + struct RawCounter { + RawCounter() = default; + int64_t sum{0}; + size_t count{0}; + }; + std::unordered_map raw_counters; + std::unordered_map agg_types; +}; + +// Make this struct so the timer internals are opaque to the user. +struct JITTimePoint { + std::chrono::time_point point; +}; + +TORCH_API JITTimePoint timePoint(); +TORCH_API void recordDurationSince( + const std::string& name, + const JITTimePoint& tp); + +namespace runtime_counters { +constexpr const char* GRAPH_EXECUTORS_CONSTRUCTED = + "pytorch_runtime.graph_executors_constructed"; +constexpr const char* GRAPH_EXECUTOR_INVOCATIONS = + "pytorch_runtime.graph_executor_invocations"; +constexpr const char* EXECUTION_PLAN_CACHE_HIT = + "pytorch_runtime.execution_plan_cache_hit"; +constexpr const char* EXECUTION_PLAN_CACHE_MISS = + "pytorch_runtime.execution_plan_cache_miss"; + +inline std::vector allRuntimeCounters() { + return { + GRAPH_EXECUTORS_CONSTRUCTED, + GRAPH_EXECUTOR_INVOCATIONS, + EXECUTION_PLAN_CACHE_HIT, + EXECUTION_PLAN_CACHE_MISS}; +} + +} // namespace runtime_counters + +} // namespace torch::jit::logging + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/operator.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/operator.h new file mode 100644 index 0000000000000000000000000000000000000000..619965550581c0ebe99a436aea2de536b0c2868c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/operator.h @@ -0,0 +1,348 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// in memory description of all ATen Ops similar to Caffe2 schema +// once C10 exists this can be removed, or stubbed out, but we need +// it now to implement correct semantic checking for script +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +struct Node; +using ::c10::Argument; +using ::c10::FunctionSchema; +using ::c10::Symbol; + +using OperationCreator = Operation (*)(const Node*); + +namespace { +const std::array kJitOnlyOperatorTags = { + at::Tag::pt2_compliant_tag}; +} + +/* + * Note: JIT relies on Operator instances having static lifetime, because + * it for example stores a non-owning FunctionSchema* pointer in the Node class, + * which points to the function schema stored in the Operator instance. + * Also, jit::Operator is meant to store more operator related information like + * symbolic derivatives, which also requires them to have static lifetime + * so that changes to symbolic derivatives are remembered. + * + * Currently, the JIT operator library contains a jit::Operator instance + * with a wrapper for each c10 operator. The c10 operator library registers + * those wrappers using listeners in register_c10_ops.cpp. + * TODO Instead of doing it this way, we should only have pure-jit ops in + * the jit library but have the JIT operator lookup look into the c10 library + * too. + */ + +// An Operator is a thin wrapper around either a pure JIT operator (e.g. prim +// ops) or a c10 operator, allowing some common operations and abstracting away +// the concrete operator nature. +struct TORCH_API Operator { + private: + struct C10Operator final { + c10::OperatorHandle handle_; + Operation op_; + }; + struct UnparsedFunctionSchema final { + std::string schema_string_; + mutable std::optional alias_analysis_; + }; + struct JitOnlyOperator final { + // The only valid transition for schema_ is from right->left, i.e. + // when the schema gets parsed. + mutable std::variant schema_; + + std::variant op_; + }; + + public: + Operator(c10::OperatorHandle opHandle, Operation operation) + : op_(C10Operator{std::move(opHandle), std::move(operation)}) {} + + Operator( + std::string schema, + Operation op, + c10::AliasAnalysisKind alias_analysis) + : op_(JitOnlyOperator{ + UnparsedFunctionSchema{std::move(schema), alias_analysis}, + Operation(std::move(op))}) {} + + Operator( + std::string name, + std::string overload_name, + std::vector arguments, + std::vector returns, + Operation op, + c10::AliasAnalysisKind alias_analysis) + : op_(JitOnlyOperator{ + FunctionSchema(varArgSchemaWithName( + std::move(name), + std::move(overload_name), + std::move(arguments), + std::move(returns), + alias_analysis)), + std::move(op)}) {} + + Operator( + std::string schema, + OperationCreator op_creator, + c10::AliasAnalysisKind alias_analysis) + : op_(JitOnlyOperator{ + UnparsedFunctionSchema{std::move(schema), alias_analysis}, + op_creator}) {} + + // Helper constructor to register `op` to run + // run for _every_ IR Node where n.kind() == name, regardless of arguments. + // This is accomplished by marking the schema varargs and having no required + // arguments. + Operator( + Symbol name, + OperationCreator op_creator, + c10::AliasAnalysisKind alias_analysis) + : op_(JitOnlyOperator{ + FunctionSchema(varArgSchemaWithName(name, alias_analysis)), + op_creator}) {} + + Operation getOperation(const Node* node = nullptr) const { + return std::visit( + c10::overloaded( + [](const C10Operator& op) { return op.op_; }, + [node](const JitOnlyOperator& op) { + return std::visit( + c10::overloaded( + [](const Operation& op) { return op; }, + [node](const OperationCreator& op_creator) { + return op_creator(node); + }), + op.op_); + }), + op_); + } + + Operation getOperationForDispatchKey(c10::DispatchKey dk) const { + // TODO: some sort of caching mechanism? + return std::visit( + c10::overloaded( + [dk](const C10Operator& op) { + return Operation([op, dk](Stack& stack) { + op.handle_.callBoxedForDispatchKey(dk, stack); + }); + }, + [](const JitOnlyOperator& op) { + TORCH_CHECK( + false, + "calling a JIT operator for dispatch key is not supported"); + return Operation(nullptr); + }), + op_); + } + + const FunctionSchema& schema() const { + return std::visit( + c10::overloaded( + [](const C10Operator& op) -> const FunctionSchema& { + return op.handle_.schema(); + }, + [](const JitOnlyOperator& op) -> const FunctionSchema& { + // we lazily parse schema initialized from strings so that + // we do less work during static operator registration + if (op.schema_.index() == 1) { + auto& unmaterializedSchema = + std::get(op.schema_); + FunctionSchema schema = + parseSchema(unmaterializedSchema.schema_string_); + if (unmaterializedSchema.alias_analysis_.has_value()) { + // TODO What if it gets set later? + schema.setAliasAnalysis( + *unmaterializedSchema.alias_analysis_); + } + op.schema_ = std::move(schema); + } + return std::get(op.schema_); + }), + op_); + } + + c10::ArrayRef getTags() const { + return std::visit( + c10::overloaded( + [](const C10Operator& op) { return op.handle_.getTags(); }, + [](const JitOnlyOperator& op) { + // JitOnlyOperators don't have an c10::OperatorHandle or a way to + // specify tags. We're grandfathering them all into + // pt2_compliant_tag, but for anything else, please just stop + // using JitOnlyOperator. + return c10::ArrayRef(kJitOnlyOperatorTags); + }), + op_); + } + + bool isC10Op() const { + return op_.index() == 0; + } + + c10::AliasAnalysisKind aliasAnalysisKind() const { + const FunctionSchema& schemaRef = schema(); + c10::AliasAnalysisKind alias_analysis = schemaRef.aliasAnalysis(); + + TORCH_CHECK( + alias_analysis == AliasAnalysisKind::FROM_SCHEMA || + !schemaRef.hasAnyAliasInfo(), + "In operator registration: Tried to register operator ", + schemaRef, + " with aliasing information in the schema but without AliasAnalysisKind::FROM_SCHEMA."); + return alias_analysis; + } + + bool hasOperation() const { + return std::visit( + c10::overloaded( + [](const C10Operator&) { return true; }, + [](const JitOnlyOperator& op) { return op.op_.index() == 0; }), + op_); + } + + private: + static FunctionSchema varArgSchemaWithName( + Symbol name, + AliasAnalysisKind alias_analysis) { + auto result = FunctionSchema( + name, + "", + {}, + {}, + /*is_vararg*/ true, + /*is_varret*/ true); + result.setAliasAnalysis(alias_analysis); + return result; + } + + static FunctionSchema varArgSchemaWithName( + std::string name, + std::string overload_name, + std::vector arguments, + std::vector returns, + AliasAnalysisKind alias_analysis) { + auto result = FunctionSchema( + std::move(name), + std::move(overload_name), + std::move(arguments), + std::move(returns), + /*is_vararg*/ false, + /*is_varret*/ false); + result.setAliasAnalysis(alias_analysis); + return result; + } + + std::variant op_; +}; + +TORCH_API std::string canonicalSchemaString(const FunctionSchema& schema); + +TORCH_API const std::vector> getAllOperators(); +TORCH_API const std::vector>& getAllOperatorsFor( + Symbol name); +// Returns operators in the order which OpOverloadPacket resolves them. +TORCH_API std::vector> getAllSortedOperatorsFor( + Symbol name); + +// given a operator with an overload name, find the specific operator related to +// it, may return nullptr if no operator exists. +TORCH_API std::shared_ptr findOperatorFor( + const c10::OperatorName& full_name); + +TORCH_API std::vector findSimilarOperators(Symbol input_op); + +TORCH_API void registerOperator(Operator&& op); +TORCH_API void deregisterOperator(const FunctionSchema& schema); + +// XXX: this function is meant to be used with string literals only! +TORCH_API std::shared_ptr getOperatorForLiteral( + const char* signature); + +// Ensure the thing that registers c10 ops is defined. +// Otherwise, our registry will not have c10 ops. You can run into this +// scenario if you're querying registered ops during static init. +// +// This fn is defined in register_c10_ops.cpp +TORCH_API void ensure_c10_registerer_defined(); + +// Used to assert that unschematized operators have an analysis method written +TORCH_API bool aliasAnalysisHasSpecialCaseFor(c10::Symbol sym); + +// A factory function to generate an optional operator. It has two +// instantiations depending on the template bool arg value. The arg can be a +// compile-time function for the selective op registration based on schema +// string. +template +std::optional OperatorGenerator( + const char* schema_str, + Func&& op, + AliasAnalysisKind alias_analysis) { + return std::optional(Operator( + std::string(schema_str), std::forward(op), alias_analysis)); +} + +template +std::optional OperatorGenerator( + torch::detail::SelectiveStr schema_str, + Func&& op, + AliasAnalysisKind alias_analysis) { + return OperatorGenerator( + static_cast(schema_str), + std::forward(op), + alias_analysis); +} + +template +std::optional OperatorGenerator( + torch::detail::SelectiveStr schema_str, + Func&& op, + AliasAnalysisKind alias_analysis) { + return std::nullopt; +} + +template +std::optional OperatorGenerator( + const std::string name, + const std::string overload_name, + const std::vector arguments, + const std::vector returns, + Func&& op, + AliasAnalysisKind alias_analysis) { + return std::optional(Operator( + name, + overload_name, + arguments, + returns, + std::forward(op), + alias_analysis)); +} + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/operator_options.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/operator_options.h new file mode 100644 index 0000000000000000000000000000000000000000..ade935e052b07e79dcbd722407422538c2ea3c68 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/operator_options.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +using AliasAnalysisKind = c10::AliasAnalysisKind; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/print_handler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/print_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..911e9bc905ce609ce146090b24c684e370d08660 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/print_handler.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit { + +using PrintHandler = void (*)(const std::string&); + +TORCH_API PrintHandler getDefaultPrintHandler(); +TORCH_API PrintHandler getPrintHandler(); +TORCH_API void setPrintHandler(PrintHandler ph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/profiling_graph_executor_impl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/profiling_graph_executor_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..f9d0e095fda6c885785b7e819a04ed871d13ab5f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/profiling_graph_executor_impl.h @@ -0,0 +1,83 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +TORCH_DECLARE_bool(torch_jit_static_then_dynamic); + +TORCH_DECLARE_bool(torch_jit_always_dynamic); + +C10_DECLARE_bool(torch_jit_release_profiling_graph_after_optimization); +C10_DECLARE_int32(torch_jit_release_profiling_graph_delay_in_seconds); +C10_DECLARE_int64(torch_jit_num_profiled_runs); +C10_DECLARE_int64(torch_jit_bailout_depth); + +namespace torch::jit { + +TORCH_API void runNooptPassPipeline(std::shared_ptr& graph); + +struct TORCH_API ProfilingGraphExecutorImpl : public GraphExecutorImplBase { + ProfilingGraphExecutorImpl( + const std::shared_ptr& graph, + std::string function_name); + + const ExecutionPlan& getPlanFor( + Stack& stack, + std::optional remaining_bailout_depth) override; + GraphExecutorState getDebugState() override; + ~ProfilingGraphExecutorImpl() override = default; + + void debugFlushCompilationCache(); + + bool isOptimized() const override { + return optimized_plan_.has_value(); + } + + private: + const ExecutionPlan& getOptimizedPlanFor( + Stack& stack, + std::optional remaining_bailout_depth); + void runProfilingInsensitiveOptimizations(std::shared_ptr& graph); + void runProfilingOptimizations( + std::shared_ptr& graph, + size_t remaining_depth); + void replaceFallbackGraphWithFallbackFunction(Block* b); + FusionBehavior getCurrentBehavior(size_t remaining_depth); + size_t getInstantiatedBailoutDepth(); + void runNoGradOptimizations( + std::shared_ptr& graph, + size_t remaining_bailout_depth); + void runFinalOptimizations(std::shared_ptr& graph); + + void clearTheGraphCompilationIntermediateGraphs(); + + std::unique_ptr pr_; + std::optional + profiling_plan_; // plan to run in order to profiling the code + std::optional optimized_plan_; + FusionStrategy fusion_strategy_; + + // this plan is used if getGraphExecutorOptimize is unset + std::optional fallback_plan_; + // fallback functions are inserted for tensorexpr fusion groups + // and by specialize_autogradzero. Whenever, at runtime, input + // tensor don't match profiled properties, fallback functions are called + // They are the deoptimized version of the logic in fusion groups + // and/or autograd. + // The fallback functions are owned by a GraphExecutor instance + // They only exist in the optimized graph which is a private property + // of the GraphExecutor and only shared with InterpreterState + std::vector> fallback_functions_; + std::optional remaining_bailout_depth_; + // The time the optimized_plan_ is created. + int32_t time_optimized_plan_created_ = 0; + // Has the extra memory used by the graph for profiling is released? + bool is_graph_extra_memory_released_ = false; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/profiling_record.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/profiling_record.h new file mode 100644 index 0000000000000000000000000000000000000000..a72e67bd31d3b530b6118251c78b7fdea7f69564 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/profiling_record.h @@ -0,0 +1,211 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +// We would like to assign each position/axis of a tensor an abstract size +// * For each `tensor` we have a profiled `Value` of a `TensorType` describing +// the properties of the `tensor`. +// * `TensorType` has a property called `symbolic_sizes_` to describe observed +// `tensor.sizes()` +// * `symbolic_sizes_` is a vector of abstract sizes (or +// `std::vector`) where +// * `ShapeSymbol`at `symbolic_sizes_[i]` describes the size value +// (`Dimension`) at `tensor.sizes()[i]` +// * We may see the same `Dimension` at different positions `i` in +// `tensor.sizes()` or even in different `tensor` +// * First, we would like associate the same `ShapeSymbol` to the same +// `Dimension` across **one** profiling execution or run of a TorchScript +// function. +// * The same `ShapeSymbol`s in different positions of `symbolic_shapes_` in +// possibly different `TensorType`s (i.e. `TensorType`s for different +// profiled values) form an implicit set. The elements of such a set are +// called *dimension locations*. +// * These sets allow us to track how the shapes of input arguments of some +// operation relate to operation's output shapes as the input and output +// shapes might share the same `ShapeSymbol`s +// * For **every** profiling run, we would like to maintain the invariant that +// *the same `ShapeSymbol` is always associated with the same `Dimension`*. +// * To maintain this invariant we merge the profiling information from all +// profiling runs, +// * For every two runs, we iterate over all `symbic_shapes_` and compare +// their `ShapeSymbol`s in the same position. +// * if we observe that for every dimension location that has +// the`ShapeSymbol S1` in run #1 there is **only one** `ShapeSymbol S2` in +// the same dimension location in run #2, we conclude that the invariant +// holds. +// * However, if we observe some dimension locations in run #2 have +// `ShapeSymbol S2` and the other ones have `ShapeSymbol S3` we would like +// to partition the virtual set of dimension locations associated with +// `ShapeSymbol S1` into two new subsets, so the invariant holds. +// * The partitioning works by assigning a new symbol to the dimension +// locations (associated with `ShapeSymbol S1`) that have `ShapeSymbol S2` +// and another new symbol to the dimension locations that have `ShapeSymbol +// S3`. In other words, +// * Subset #1 will consist of the dimension locations that in run #2 have +// `ShapeSymbol S2` and will have `ShapeSymbol S4` in those dimension +// locations +// * Subset #2 will consist of the dimension locations that in run #2 have +// `ShapeSymbol S4` and will have `ShapeSymbol S5` in those dimension +// locations +// * The effective result of merging the profiling information from two runs +// is new `TensorTypes` whose `symbolic_sizes_` /dimension locations have +// either `ShapeSymbol S4` or `ShapeSymbol S5`. +// * Partitioning can be done even before we have seen all the dimension +// locations associated with `ShapeSymbol S1` +// * We use `getSymbolInSet` of `ShapeSymbolTable` to remember all +// `ShapeSymbols` from run #2 we observed in the dimension locations +// associated with `ShapeSymbol S1` . +// * For every `ShapeSymbol` from run #2 in the dimension location +// associated with `ShapeSymbol S1` `getSymbolInSet` returns a symbol +// that we assign to the dimension location in a new TensorType. +// * It's important to point out that the same `ShapeSymbol S2` from run +// #2 in two dimension locations that have different `ShapeSymbol`s in +// run #1 are different! These dimension locations will belong to +// different subsets and have different `ShapeSymbol`s after merge. +// * On the other hand, for the same `ShapeSymbol S2` in two dimension +// locations that have `ShapeSymbol S1` in run #1`getSymbolInSet` will +// return the same symbol. + +namespace torch::jit { + +using ::c10::TensorTypePtr; +using Dimension = int64_t; + +TORCH_API void RegisterProfilingNode( + const std::function& /*func*/); + +struct ProfilingRecord; + +// `SetPartitioningHelper` is used to maintain the following invariant: +// For **every** profiling run, *the same `ShapeSymbol` is always associated +// with the same `Dimension`*. +// while merging the profiling information from multiple runs. +struct SetPartitioningHelper { + std::map> + sets2subsets_; + + // `partitionSetByDimension` partitions a virtual set + // of dimension locations associated with ShapeSymbol `symbol` into subsets. + // Partitioning is equivalent to giving (or renaming) a particular + // dimension location a new `ShapeSymbol`. + // The same `Dimension` value in different dimension locations + // that used to have `symbol` will receive the same + // new `ShapeSymbol`, effectively forming a new set. + c10::ShapeSymbol partitionSetByDimension( + Dimension new_size, + c10::ShapeSymbol symbol) { + auto& dims2symbols = getSetForSymbol(symbol); + + if (dims2symbols.count(new_size) == 0) { + auto new_sym = c10::ShapeSymbol::newSymbol(); + dims2symbols[new_size] = new_sym; + return new_sym; + } + + return dims2symbols[new_size]; + } + + private: + std::map& getSetForSymbol(c10::ShapeSymbol s) { + auto& set = sets2subsets_[s]; + // N.B. adding a mapping { s.static_size(), s } + // makes sure we preserve the fact that + // some dimension values remain the same + // across all profiled runs + if (s.is_static()) { + set.insert({s.static_size(), s}); + } + return set; + } +}; + +// ShapeSymbolTable is used by Interpreter +// to assign dimension values to ShapeSymbols +// and fail a guard if the same symbol +// is assigned more than one dimension value. +struct ShapeSymbolTable { + // N.B. we treat static symbols as always assigned + // to themselves + bool isBound(c10::ShapeSymbol s) { + if (s.is_static()) { + return true; + } + return data_.count(s) != 0; + } + + // N.B. we treat static symbols as always assigned + // to themselves + Dimension getValue(c10::ShapeSymbol s) { + if (s.is_static()) { + return s.static_size(); + } + return data_[s]; + } + void assign(c10::ShapeSymbol s, Dimension v) { + TORCH_INTERNAL_ASSERT(!s.is_static()); + data_[s] = v; + } + std::map data_; + // Tries to assign dimension values from `new_sizes` to + // `ShapeSymbol`s `sym_shapes`. + // Returns `true` if every dimension value from `new_sizes` + // can be assigned to the corresponding `ShapeSymbol` from + // `sym_shapes` + // A dimension value can be assigned to a `ShapeSymbol` + // * if the symbol isn't assigned yet any dimension value + // * if the symbol is assigned and its value is equal to + // the dimension value from `new_sizes` + bool bindSymbolicShapes( + at::IntArrayRef new_sizes, + const c10::SymbolicShape& sym_shapes); +}; + +struct ProfilingRecord { + // N.B. ProfilingRecord's copy and move c-tor are disabled, so we won't + // end up accidentally copying or moving ProfilingRecords whose addresses + // are captured in callbacks_ + ProfilingRecord(const ProfilingRecord&) = delete; + ProfilingRecord(ProfilingRecord&&) noexcept = delete; + TORCH_API static std::unique_ptr instrumentGraph( + const std::shared_ptr& graph); + TORCH_API static void removeProfilingNodes(Block* b); + TORCH_API static void removeProfileCounter(Block* b); + + std::shared_ptr profiled_graph_; + mutable std::mutex mutex_; + size_t profiling_count_; + + bool ready() const; + + std::shared_ptr graph() const { + return profiled_graph_; + } + + TORCH_API ProfileIValueOp* createProfileIValueNode(Value* in_val); + TORCH_API ProfileIValueOp* createProfileIValueNode(ArrayRef inputs); + + private: + ProfileOp* createProfileNode( + const std::function& fp, + at::ArrayRef inputs); + void instrumentBlock(Block* block); + void insertShapeProfile(Node* n, size_t offset, const TypePtr& input_type); + ProfilingRecord(std::shared_ptr g); +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/register_ops_utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/register_ops_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..4c6c441a5a9cd0ec0e90e6b13c035f35e9a3ea67 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/register_ops_utils.h @@ -0,0 +1,888 @@ +#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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { +constexpr inline c10::AliasAnalysisKind aliasAnalysisFromSchema() { + return c10::AliasAnalysisKind::FROM_SCHEMA; +} + +constexpr inline c10::AliasAnalysisKind aliasAnalysisConservative() { + return c10::AliasAnalysisKind::CONSERVATIVE; +} + +constexpr inline c10::AliasAnalysisKind aliasAnalysisSpecialCase() { + return c10::AliasAnalysisKind::INTERNAL_SPECIAL_CASE; +} + +template +c10::List make_result_list(const TypePtr& elemType) { + return c10::List(); +} + +template <> +c10::impl::GenericList make_result_list(const TypePtr& elemType); + +// As described in https://docs.python.org/3/library/functions.html#round +// When a number is exactly halfway between two integers, python builtin round +// function will round to even number. We use round(x/2)*2 to handle the +// special halfway case. For positive 'x', round(x/2)*2 = +// round((x_e + x_r)/2)*2 = x_e + round(x_r/2)*2, where x_e is an even integer, +// x_r is either 0.5 of 1.5, round(x_r/2)*2 results a 0 or 2, so the final +// result will always be a even number. Due to symmetricity, it also applies to +// negative cases. +inline double round_to_even(double a) { + return a - std::floor(a) == 0.5 ? (std::round(a * 0.5) * 2.0) : std::round(a); +} + +// using the rules from python_arg_parser FunctionParameter::check +// tensor cannot have grad set, tensor must be 0 dim, +// and if the dest is an int the source must be integral type +void checkImplicitTensorToNum(const at::Tensor& t, bool toInt); + +[[maybe_unused]] static int64_t floordiv(int64_t a, int64_t b) { + if (b == 0) { + throw std::runtime_error("division by 0"); + } + if ((a > 0) == (b > 0)) { + // simple case, both have same sign + return a / b; + } else { + // in python division rounds down, it doesn't not truncate like in c++ + auto r = lldiv(a, b); + return (r.rem) ? r.quot - 1 : r.quot; + } +} +TORCH_API void checkDoubleInRange(double a); +[[maybe_unused]] static int64_t floor(double a) { + checkDoubleInRange(a); + return std::floor(a); +} +[[maybe_unused]] static int64_t ceil(double a) { + checkDoubleInRange(a); + return std::ceil(a); +} + +[[maybe_unused]] static int64_t gcd(int64_t a, int64_t b) { + while (b != 0) { + int64_t r = a % b; + a = b; + b = r; + } + // in python gcd returns non-negative values + return std::abs(a); +} + +int64_t partProduct(int n, int m); + +void loop(int n, int64_t& p, int64_t& r); + +int nminussumofbits(int v); + +int64_t factorial(int n); +static const double degToRad = std::acos(-1.0) / 180.0; +static const double radToDeg = 180.0 / std::acos(-1.0); +double degrees(double x); +double radians(double x); + +// Convert an python index (which may be negative) into an index usable for a +// C++ container + +// Equivalent to list.at(idx) +template +auto getItem(const c10::List& list, int64_t idx) { + const int64_t list_size = list.size(); + const int64_t normalized_idx = normalizeIndex(idx, list_size); + if (normalized_idx < 0 || normalized_idx >= list_size) { + throw std::out_of_range("list index out of range"); + } + return list.get(normalized_idx); +} + +template +void setItem(const c10::List& list, int64_t idx, T&& value) { + const int64_t list_size = list.size(); + const int64_t normalized_idx = normalizeIndex(idx, list_size); + if (normalized_idx < 0 || normalized_idx >= list_size) { + throw std::out_of_range("list index out of range"); + } + list.set(normalized_idx, std::forward(value)); +} + +void listAppend(Stack& stack); + +void listReverse(Stack& stack); + +template +void minList(Stack& stack) { + c10::List a = pop(stack).to>(); + c10::List b = pop(stack).to>(); + + size_t min_size = std::min(a.size(), b.size()); + for (const auto i : c10::irange(min_size)) { + if (a[i] == b[i]) { + continue; + } + + push(stack, a[i] < b[i] ? a : b); + return; + } + + push(stack, b.size() < a.size() ? b : a); +} + +template +void maxList(Stack& stack) { + c10::List a = pop(stack).to>(); + c10::List b = pop(stack).to>(); + + size_t min_size = std::min(a.size(), b.size()); + for (const auto i : c10::irange(min_size)) { + if (a[i] == b[i]) { + continue; + } + + push(stack, a[i] > b[i] ? a : b); + return; + } + + push(stack, b.size() > a.size() ? b : a); +} + +void listPopImpl(Stack& stack, const char* empty_message); + +void listPop(Stack& stack); + +void listClear(Stack& stack); + +void listDelete(Stack& stack); + +void listInsert(Stack& stack); + +template +void listRemove(Stack& stack) { + T elem = pop(stack).to(); + c10::List list = pop(stack).to>(); + + auto pos = std::find(list.begin(), list.end(), elem); + + if (pos != list.end()) { + list.erase(pos); + } else { + TORCH_CHECK(false, "list.remove(x): x not in list"); + } +} + +template +void listMin(Stack& stack) { + c10::List list = pop(stack).to>(); + size_t list_size = list.size(); + if (list_size == 0) { + throw std::runtime_error("min() arg is an empty sequence"); + } + + T min_elem = list[0]; + for (const auto i : c10::irange(1, list_size)) { + T elem = list[i]; + min_elem = elem < min_elem ? elem : min_elem; + } + + stack.push_back(min_elem); +} + +template +void listMax(Stack& stack) { + c10::List list = pop(stack).to>(); + size_t list_size = list.size(); + if (list_size == 0) { + throw std::runtime_error("max() arg is an empty sequence"); + } + + T max_elem = list[0]; + for (const auto i : c10::irange(1, list_size)) { + T elem = list[i]; + max_elem = elem > max_elem ? elem : max_elem; + } + + stack.push_back(max_elem); +} + +template <> +void listRemove(Stack& stack); + +template +void listIndex(Stack& stack) { + T elem = pop(stack).to(); + c10::List list = pop(stack).to>(); + + auto pos = std::find(list.begin(), list.end(), elem); + + if (pos != list.end()) { + push(stack, static_cast(std::distance(list.begin(), pos))); + } else { + TORCH_CHECK(false, "'", elem, "' is not in list"); + } +} + +template <> +void listIndex(Stack& stack); + +template +void listCount(Stack& stack) { + T elem = pop(stack).to(); + c10::List list = pop(stack).to>(); + + const int64_t count = std::count(list.begin(), list.end(), elem); + push(stack, count); +} + +template <> +void listCount(Stack& stack); + +void listExtend(Stack& stack); + +void listCopy(Stack& stack); + +void listSelect(Stack& stack); + +void listLen(Stack& stack); + +template +void listEq(Stack& stack) { + c10::List b = pop(stack).to>(); + c10::List a = pop(stack).to>(); + push(stack, a == b); +} + +template +void listNe(Stack& stack) { + c10::List b = pop(stack).to>(); + c10::List a = pop(stack).to>(); + push(stack, a != b); +} + +inline bool tensor_list_equal( + const c10::List& a, + const c10::List& b) { + if (a.size() != b.size()) { + return false; + } + + for (const auto i : c10::irange(a.size())) { + const at::Tensor& a_element = a[i]; + const at::Tensor& b_element = b[i]; + // This preserves Python's semantics, which uses eq() to compare two + // elements, then passes the result to bool(). + // see: https://docs.python.org/3.4/reference/datamodel.html#object.__ge__ + const auto cmp_result = a_element.eq(b_element); + if (!at::native::is_nonzero(cmp_result)) { + return false; + } + } + + return true; +} + +// Specialization for at::Tensor, since it doesn't define operator== +template <> +void listEq(Stack& stack); + +// Specialization for at::Tensor, since it doesn't define operator== +template <> +void listNe(Stack& stack); + +void listList(Stack& stack); + +template +void listContains(Stack& stack) { + auto key = pop(stack).to(); + auto list = pop(stack).to>(); + // NOLINTNEXTLINE(performance-implicit-conversion-in-loop) + for (const T& item : list) { + if (item == key) { + push(stack, true); + return; + } + } + push(stack, false); +} + +void listAdd(Stack& stack); + +void listInplaceAdd(Stack& stack); + +void listMulIntLeftInPlace(Stack& stack); + +void listMulIntLeft(Stack& stack); + +void listMulIntRight(Stack& stack); + +void listSlice(Stack& stack); + +template +void listSort(Stack& stack) { + bool reverse = pop(stack).toBool(); + c10::List list = pop(stack).to>(); + std::sort(list.begin(), list.end(), [reverse](const T& a, const T& b) { + // FBCode errors without this check - "strict weak ordering" + // TODO: remove when possible, since it just slows down + // sorting and doesn't do anything useful + if (a == b) { + return false; + } + return (a < b) != reverse; + }); +} + +// Specialization for at::Tensor +template <> +void listSort(Stack& stack); + +template +void listCopyAndSort(Stack& stack) { + c10::List list = pop(stack).to>(); + auto list_copied = list.copy(); + std::sort(list_copied.begin(), list_copied.end(), [](const T& a, const T& b) { + // "strict weak ordering" issue - see other sort + if (a == b) { + return false; + } + return a < b; + }); + push(stack, list_copied); +} + +// Specialization for at::Tensor +template <> +void listCopyAndSort(Stack& stack); + +void listSetItem(Stack& stack); + +struct OperatorGeneratorArgs { + const char* schema_str; + bool isOperationCreator; + union { + void (*operation)(Stack&); + OperationCreator operationCreator; + }; + AliasAnalysisKind aliasAnalysis; + + explicit constexpr OperatorGeneratorArgs( + torch::detail::SelectiveStr schema_str, + void (*op)(Stack&), + AliasAnalysisKind aa) + : schema_str(schema_str), + isOperationCreator(false), + operation(op), + aliasAnalysis(aa) {} + + explicit constexpr OperatorGeneratorArgs( + torch::detail::SelectiveStr schema_str, + OperationCreator opCreator, + AliasAnalysisKind aa) + : schema_str(schema_str), + isOperationCreator(true), + operationCreator(opCreator), + aliasAnalysis(aa) {} + + template + explicit constexpr OperatorGeneratorArgs( + torch::detail::SelectiveStr /*unused*/, + Args... /*unused*/) + : schema_str(nullptr), + isOperationCreator(false), + operation(nullptr), + aliasAnalysis(AliasAnalysisKind::INTERNAL_SPECIAL_CASE) {} +}; + +#define DEFINE_GENERIC_BINARY_OP( \ + aten_op, op, int_float_result, complex_result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op \ + ".int_int(int a, int b) -> " #int_float_result), \ + [](Stack& stack) { \ + int64_t a, b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA( \ + #aten_op \ + ".float_float(float a, float b) -> " #int_float_result), \ + [](Stack& stack) { \ + double a, b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA( \ + #aten_op \ + ".complex_complex(complex a, complex b) -> " #complex_result), \ + [](Stack& stack) { \ + c10::complex a, b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) + +// define implementations for primitive number ops +#define DEFINE_GENERIC_OP(aten_op, int_op, float_op, int_result, float_result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".int(int a, int b) -> " #int_result), \ + [](Stack& stack) { \ + int64_t a, b; \ + pop(stack, a, b); \ + push(stack, int_op); \ + }, \ + aliasAnalysisFromSchema()), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA( \ + #aten_op ".float(float a, float b) -> " #float_result), \ + [](Stack& stack) { \ + double a, b; \ + pop(stack, a, b); \ + push(stack, float_op); \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_INT_FLOAT_OP(aten_op, op, result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op \ + ".int_float(int a, float b) -> " #result), \ + [](Stack& stack) { \ + int64_t a; \ + double b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op \ + ".float_int(float a, int b) -> " #result), \ + [](Stack& stack) { \ + double a; \ + int64_t b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_INT_OP(aten_op, op) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".int(int a, int b) -> int"), \ + [](Stack& stack) { \ + int64_t a, b; \ + pop(stack, a, b); \ + push(stack, op); /* NOLINT(hicpp-signed-bitwise) */ \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_STR_CMP_OP(aten_op, op) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".str(str a, str b) -> bool"), \ + [](Stack& stack) { \ + auto b = pop(stack).toStringRef(); \ + auto a = pop(stack).toStringRef(); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) + +// define a primitive op over Scalar operands. +// it's necessary to register this overload following +// int/float variations to avoid trapping Scalar args +// in unintended implicit conversions +#define DEFINE_SCALAR_BINARY_OP_AVOID_COLLISION_GENERIC( \ + aten_op, int_op, float_op, result, string_val) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op string_val \ + "(Scalar a, Scalar b) -> " #result), \ + [](Stack& stack) { \ + IValue x, y; \ + pop(stack, x, y); \ + if (x.isDouble()) { \ + if (y.isDouble()) { \ + double a = x.toDouble(); \ + double b = y.toDouble(); \ + push(stack, float_op); \ + } else { \ + double a = x.toDouble(); \ + int64_t b = y.toInt(); \ + push(stack, float_op); \ + } \ + } else { \ + if (y.isDouble()) { \ + int64_t a = x.toInt(); \ + double b = y.toDouble(); \ + push(stack, float_op); \ + } else { \ + int64_t a = x.toInt(); \ + int64_t b = y.toInt(); \ + push(stack, int_op); \ + } \ + } \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_SCALAR_BINARY_OP(aten_op, int_op, float_op, result) \ + DEFINE_SCALAR_BINARY_OP_AVOID_COLLISION_GENERIC( \ + aten_op, int_op, float_op, result, "") + +#define DEFINE_SCALAR_BINARY_OP_AVOID_COLLISION( \ + aten_op, int_op, float_op, result) \ + DEFINE_SCALAR_BINARY_OP_AVOID_COLLISION_GENERIC( \ + aten_op, int_op, float_op, result, ".Scalar_Scalar") + +#define DEFINE_BINARY_OP(aten_op, op) \ + DEFINE_GENERIC_OP(aten_op, op, op, int, float), \ + DEFINE_INT_FLOAT_OP(aten_op, op, float), \ + DEFINE_SCALAR_BINARY_OP(aten_op, op, op, Scalar) + +#define DEFINE_BINARY_FLOAT_OP(aten_op, op) \ + DEFINE_GENERIC_OP(aten_op, op, op, float, float), \ + DEFINE_INT_FLOAT_OP(aten_op, op, float), \ + DEFINE_SCALAR_BINARY_OP(aten_op, op, op, float) + +#define DEFINE_COMPARISON_OP(aten_op, op) \ + DEFINE_GENERIC_OP(aten_op, op, op, bool, bool), \ + DEFINE_INT_FLOAT_OP(aten_op, op, bool), \ + DEFINE_SCALAR_BINARY_OP(aten_op, op, op, bool), \ + DEFINE_STR_CMP_OP(aten_op, op) + +#define DEFINE_UNARY_INT_OP(aten_op, op, result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".int(int a) -> " #result), \ + [](Stack& stack) { \ + int64_t a; \ + pop(stack, a); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_UNARY_FLOAT_OP(aten_op, op, result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".float(float a) -> " #result), \ + [](Stack& stack) { \ + double a; \ + pop(stack, a); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_UNARY_OP(aten_op, op, int_result, float_result) \ + DEFINE_UNARY_INT_OP(aten_op, op, int_result), \ + DEFINE_UNARY_FLOAT_OP(aten_op, op, float_result), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".Scalar(Scalar a) -> Scalar"), \ + [](Stack& stack) { \ + IValue x; \ + pop(stack, x); \ + if (x.isDouble()) { \ + double a = x.toDouble(); \ + push(stack, static_cast(op)); \ + } else { \ + int64_t a = x.toInt(); \ + push(stack, static_cast(op)); \ + } \ + }, \ + aliasAnalysisFromSchema()) +#define DEFINE_BOOL_OP(aten_op, op) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".bool(bool a, bool b) -> bool"), \ + [](Stack& stack) { \ + bool a, b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) +#define DEFINE_STRING_OP(op_name, string_op, result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#op_name ".str(str a, str b) ->" #result), \ + [](Stack& stack) { \ + auto b = pop(stack).toStringRef(); \ + auto a = pop(stack).toStringRef(); \ + push(stack, string_op); \ + }, \ + aliasAnalysisFromSchema()) + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +#define DEFINE_UNARY_COMPLEX_OP(aten_op, op, result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".complex(complex a) -> " #result), \ + [](Stack& stack) { \ + c10::complex a; \ + pop(stack, a); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) + +// Some complex unary ops (like abs, angle) return real valued output, but most +// other unary ops return complex valued output. So, this macro is used in the +// former case where we can explicitly pass complex_result_cast argument, which +// is set to c10::complex in the macro `DEFINE_UNARY_OP_WITH_COMPLEX` +// defined below. +#define DEFINE_UNARY_OP_WITH_COMPLEX_CAST( \ + aten_op, \ + op, \ + int_result, \ + float_result, \ + complex_result, \ + complex_result_cast) \ + DEFINE_UNARY_INT_OP(aten_op, op, int_result), \ + DEFINE_UNARY_FLOAT_OP(aten_op, op, float_result), \ + DEFINE_UNARY_COMPLEX_OP(aten_op, op, complex_result), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".Scalar(Scalar a) -> Scalar"), \ + [](Stack& stack) { \ + IValue x; \ + pop(stack, x); \ + if (x.isDouble()) { \ + double a = x.toDouble(); \ + push(stack, static_cast(op)); \ + } else if (x.isComplexDouble()) { \ + c10::complex a = x.toComplexDouble(); \ + push(stack, static_cast(op)); \ + } else { \ + int64_t a = x.toInt(); \ + push(stack, static_cast(op)); \ + } \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_UNARY_OP_WITH_COMPLEX(aten_op, op, int_result, float_result) \ + DEFINE_UNARY_OP_WITH_COMPLEX_CAST( \ + aten_op, op, int_result, float_result, complex, c10::complex) + +#define DEFINE_GENERIC_OP_WITH_COMPLEX( \ + aten_op, \ + int_op, \ + float_op, \ + complex_op, \ + int_result, \ + float_result, \ + complex_result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op ".int(int a, int b) -> " #int_result), \ + [](Stack& stack) { \ + int64_t a, b; \ + pop(stack, a, b); \ + push(stack, int_op); \ + }, \ + aliasAnalysisFromSchema()), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA( \ + #aten_op ".complex(complex a, complex b) -> " #complex_result), \ + [](Stack& stack) { \ + c10::complex a, b; \ + pop(stack, a, b); \ + push(stack, complex_op); \ + }, \ + aliasAnalysisFromSchema()), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA( \ + #aten_op ".float(float a, float b) -> " #float_result), \ + [](Stack& stack) { \ + double a, b; \ + pop(stack, a, b); \ + push(stack, float_op); \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_INT_COMPLEX_OP(aten_op, op, result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op \ + ".int_complex(int a, complex b) -> " #result), \ + [](Stack& stack) { \ + int64_t a; \ + c10::complex b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA( \ + #aten_op ".complex_int(complex a, int b) -> " #result), \ + [](Stack& stack) { \ + c10::complex a; \ + int64_t b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_FLOAT_COMPLEX_OP(aten_op, op, result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA( \ + #aten_op ".float_complex(float a, complex b) -> " #result), \ + [](Stack& stack) { \ + double a; \ + c10::complex b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()), \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA( \ + #aten_op ".complex_float(complex a, float b) -> " #result), \ + [](Stack& stack) { \ + c10::complex a; \ + double b; \ + pop(stack, a, b); \ + push(stack, op); \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX_AVOID_COLLISION_GENERIC( \ + aten_op, int_op, float_op, complex_op, result, string_val) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op string_val \ + "(Scalar a, Scalar b) -> " #result), \ + [](Stack& stack) { \ + IValue x, y; \ + pop(stack, x, y); \ + if (x.isComplexDouble()) { \ + c10::complex a = x.toComplexDouble(); \ + if (y.isComplexDouble()) { \ + c10::complex b = y.toComplexDouble(); \ + push(stack, complex_op); \ + } else if (y.isDouble()) { \ + double b = y.toDouble(); \ + push(stack, complex_op); \ + } else { \ + int64_t b = y.toInt(); \ + push(stack, complex_op); \ + } \ + } else if (x.isDouble()) { \ + double a = x.toDouble(); \ + if (y.isComplexDouble()) { \ + c10::complex b = y.toComplexDouble(); \ + push(stack, complex_op); \ + } else if (y.isDouble()) { \ + double b = y.toDouble(); \ + push(stack, float_op); \ + } else { \ + int64_t b = y.toInt(); \ + push(stack, float_op); \ + } \ + } else { \ + int64_t a = x.toInt(); \ + if (y.isComplexDouble()) { \ + c10::complex b = y.toComplexDouble(); \ + push(stack, complex_op); \ + } else if (y.isDouble()) { \ + double b = y.toDouble(); \ + push(stack, float_op); \ + } else { \ + int64_t b = y.toInt(); \ + push(stack, int_op); \ + } \ + } \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX_WITHOUT_INT_COMPLEX_PAIR( \ + aten_op, int_op, float_op, complex_op, result) \ + OperatorGeneratorArgs( \ + TORCH_SELECTIVE_SCHEMA(#aten_op "(Scalar a, Scalar b) -> " #result), \ + [](Stack& stack) { \ + IValue x, y; \ + pop(stack, x, y); \ + if (x.isComplexDouble()) { \ + c10::complex a = x.toComplexDouble(); \ + if (y.isComplexDouble()) { \ + c10::complex b = y.toComplexDouble(); \ + push(stack, complex_op); \ + } else if (y.isDouble()) { \ + double b = y.toDouble(); \ + push(stack, complex_op); \ + } \ + } else if (x.isDouble()) { \ + double a = x.toDouble(); \ + if (y.isComplexDouble()) { \ + c10::complex b = y.toComplexDouble(); \ + push(stack, complex_op); \ + } else if (y.isDouble()) { \ + double b = y.toDouble(); \ + push(stack, float_op); \ + } else { \ + int64_t b = y.toInt(); \ + push(stack, float_op); \ + } \ + } else { \ + int64_t a = x.toInt(); \ + if (y.isDouble()) { \ + double b = y.toDouble(); \ + push(stack, float_op); \ + } else if (y.isInt()) { \ + int64_t b = y.toInt(); \ + push(stack, int_op); \ + } \ + } \ + }, \ + aliasAnalysisFromSchema()) + +#define DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX( \ + aten_op, int_op, float_op, complex_op, result) \ + DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX_AVOID_COLLISION_GENERIC( \ + aten_op, int_op, float_op, complex_op, result, "") + +#define DEFINE_BINARY_OP_WITH_COMPLEX(aten_op, op) \ + DEFINE_GENERIC_OP_WITH_COMPLEX(aten_op, op, op, op, int, float, complex), \ + DEFINE_INT_COMPLEX_OP(aten_op, op, complex), \ + DEFINE_FLOAT_COMPLEX_OP(aten_op, op, complex), \ + DEFINE_INT_FLOAT_OP(aten_op, op, float), \ + DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX(aten_op, op, op, op, Scalar) + +#define DEFINE_COMPARISON_OP_WITH_COMPLEX(aten_op, op) \ + DEFINE_GENERIC_OP_WITH_COMPLEX(aten_op, op, op, op, bool, bool, bool), \ + DEFINE_INT_FLOAT_OP(aten_op, op, bool), \ + DEFINE_FLOAT_COMPLEX_OP(aten_op, op, bool), \ + DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX_WITHOUT_INT_COMPLEX_PAIR( \ + aten_op, op, op, op, bool), \ + DEFINE_STR_CMP_OP(aten_op, op) + +TORCH_API at::Generator make_generator_for_device( + c10::Device device, + std::optional seed = std::nullopt); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/script_profile.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/script_profile.h new file mode 100644 index 0000000000000000000000000000000000000000..04db7ab64ca4c0a2849ca29da6c4b7ad823d4eef --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/script_profile.h @@ -0,0 +1,108 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace torch::jit { +namespace profiling { + +struct Datapoint { + using Timepoint = std::chrono::time_point; + SourceRange sourceRange; + Timepoint start; + Timepoint end; + + explicit Datapoint(SourceRange sr) + : sourceRange(std::move(sr)), start(std::chrono::steady_clock::now()) {} +}; + +class TORCH_API InstructionSpan { + public: + explicit InstructionSpan(Node& /*node*/); + ~InstructionSpan(); + InstructionSpan(InstructionSpan&&) = delete; + InstructionSpan& operator=(InstructionSpan&&) = delete; + + private: + std::unique_ptr datapoint_; +}; + +bool TORCH_API isProfilingOngoing(); + +} // namespace profiling + +struct TORCH_API InstructionStats : public CustomClassHolder { + int64_t count{0}; + std::chrono::nanoseconds duration{0}; +}; + +class TORCH_API SourceStats : public CustomClassHolder { + public: + using LineMap = c10::Dict>; + + SourceStats(SourceRef source, const LineMap& lineMap) + : source_(std::move(source)), lineMap_(lineMap) {} + + const SourceRef& getSourceRef() const { + return source_; + } + + const LineMap& getLineMap() const { + return lineMap_; + } + + private: + SourceRef source_; + LineMap lineMap_; +}; + +/** + * ScriptProfile is an underlying C++ implementation for TorchScript profiling. + * The profiling section is specified by calling enable() and disable(): + * + * ... + * scriptProfile.enable(); + * ... + * (scripts) + * ... + * scriptProfile.disable(); + * ... + * + * NOTE: you cannot attach the profiler while the script is running. + * + * To retrieve collected runtime data, users may call dumpStats() and do + * arbitrary filtering on the data they want. Note that dumpStats() should + * not be called inside a profiling section. + * In general, stats are aggregated per source function body, and then by line + * number. + */ +class TORCH_API ScriptProfile : public CustomClassHolder { + // Aggregates datapoints by function source id, then by line number. + using LineMap = std::map; + using SourceMap = std::map>; + + public: + void enable(); + void disable(); + const SourceMap& dumpStats(); + void addDatapoint(std::shared_ptr /*datapoint*/); + ~ScriptProfile() override; + + private: + bool enabled_{false}; + std::vector> datapoints_; + SourceMap sourceMap_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/serialized_shape_function_registry.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/serialized_shape_function_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..d690b7e1a4eedb8ddd14ef9f52780ea6e8940602 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/serialized_shape_function_registry.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API const std::string& GetSerializedShapeFunctions(); + +TORCH_API const OperatorMap& GetShapeFunctionMappings(); + +TORCH_API const OperatorMap>& +GetBoundedShapeMappings(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/shape_function_registry.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/shape_function_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..c2f8ed5907bea4a2a241b9187236203ae04965f9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/shape_function_registry.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API const std::string& GetSerializedFuncs(); + +TORCH_API const OperatorMap& GetFuncMapping(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/simple_graph_executor_impl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/simple_graph_executor_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..81244822f5a6521b01968b0789070827fad76820 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/simple_graph_executor_impl.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::jit { + +struct TORCH_API SimpleGraphExecutorImpl : public GraphExecutorImplBase { + SimpleGraphExecutorImpl( + const std::shared_ptr& graph, + std::string function_name); + + const ExecutionPlan& getPlanFor( + Stack& stack, + std::optional remaining_bailout_depth) override; + GraphExecutorState getDebugState() override; + ~SimpleGraphExecutorImpl() override = default; + + private: + std::optional execution_plan_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/slice_indices_adjust.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/slice_indices_adjust.h new file mode 100644 index 0000000000000000000000000000000000000000..5c386e8728c02f2a83fd9cd97efc78663f989463 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/slice_indices_adjust.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +// Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +// 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software +// Foundation; All Rights Reserved +// +// Stolen (with appropriate modifications) by @agolynski +// (https://github.com/pytorch/pytorch/pull/33019) from cpython repo +// Objects/sliceobject.c with comment: this is harder to get right than you +// might think +// +// This adjusts indexes according to python list semantics and returns number +// of elements in the resulting list. +TORCH_API int64_t slice_indices_adjust( + int64_t length, + int64_t* start, + int64_t* stop, + int64_t step); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/ProcessedNodeInputs.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/ProcessedNodeInputs.h new file mode 100644 index 0000000000000000000000000000000000000000..17742bab4f2e11bd6ddd909c3406a9c5a759bbf0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/ProcessedNodeInputs.h @@ -0,0 +1,246 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +#include +#include + +/** + * Packed representation of input indices for ProcessedNode. + */ +class ProcessedNodeInputs { + private: + // This keeps the size usage for inputs + outputs down to 16 bytes; + // we use 12 bytes, and then two 2-byte integers are used to store + // the outputs. + static constexpr size_t kMaxInlineInputs = 5; + + public: + ProcessedNodeInputs() : ProcessedNodeInputs(0) {} + + explicit ProcessedNodeInputs(size_t size) { + TORCH_DCHECK_LT(size, (1 << 16)); + if (size <= kMaxInlineInputs) { + repr_.inline_repr_.size = size; + } else { + new (&repr_.outline_repr_) HeapArrayPtr(size); + } + } + + uint16_t operator[](uint16_t idx) const { + // NOLINTNEXTLINE(*const-cast*) + return (*const_cast(this))[idx]; + } + + uint16_t& operator[](uint16_t idx) { + if (C10_LIKELY(repr_.is_inline())) { + TORCH_DCHECK_LT(idx, repr_.inline_repr_.size); + return repr_.inline_repr_.inputs[idx]; + } else { + return repr_.outline_repr_[idx]; + } + } + + [[nodiscard]] uint16_t size() const { + if (C10_LIKELY(repr_.is_inline())) { + return repr_.inline_repr_.size; + } else { + return repr_.outline_repr_.size(); + } + } + + [[nodiscard]] bool empty() const { + return size() == 0; + } + + private: + class HeapArrayPtr { + public: + HeapArrayPtr() = default; + ~HeapArrayPtr() = default; + + explicit HeapArrayPtr(uint16_t size) : array_(alloc(size)) {} + + HeapArrayPtr(const HeapArrayPtr& rhs) : array_(alloc(rhs.size())) { + if (rhs.array_) { + std::memcpy( + array_.get(), + rhs.array_.get(), + (rhs.size() + 1) * sizeof(uint16_t)); + } + } + + HeapArrayPtr& operator=(const HeapArrayPtr& rhs) { + if (&rhs == this) { + return *this; + } + + if (size() != rhs.size()) { + array_ = alloc(rhs.size()); + } + + if (rhs.array_) { + std::memcpy( + array_.get(), + rhs.array_.get(), + (rhs.size() + 1) * sizeof(uint16_t)); + } + return *this; + } + + HeapArrayPtr(HeapArrayPtr&&) noexcept = default; + HeapArrayPtr& operator=(HeapArrayPtr&&) noexcept = default; + + [[nodiscard]] bool empty() const { + return size() != 0; + } + + [[nodiscard]] uint16_t size() const { + return array_ ? array_[0] : 0; + } + + uint16_t operator[](uint16_t idx) const { + TORCH_DCHECK_LT(idx, size()); + return array_[idx + 1]; + } + + uint16_t& operator[](uint16_t idx) { + TORCH_DCHECK_LT(idx, size()); + return array_[idx + 1]; + } + + private: + // NOLINTNEXTLINE(modernize-avoid-c-arrays) + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays) + std::unique_ptr array_; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays) + // NOLINTNEXTLINE(modernize-avoid-c-arrays) + static std::unique_ptr alloc(uint16_t num_elts) { + if (num_elts) { + auto result = std::make_unique(num_elts + 1); + result[0] = num_elts; + return result; + } else { + return nullptr; + } + } + }; + + // We want ProcessedNode to be able to pack two more `uint16_t` + // fields after its ProcessedNodeInputs, and we'll end up being + // aligned to an 8-byte boundary anyway. We could avoid this pragma + // at the cost of having to move ProcessedNode::outputs_offset_ and + // ProcessedNode::num_outputs_ into this class, which would be + // awkward. +#pragma pack(push, 2) + union Repr { + [[nodiscard]] bool is_inline() const { + uint8_t tag = 0; + // Use of reinterpret_cast to pointer to char or unsigned char + // is defined behavior; see + // https://en.cppreference.com/w/cpp/language/reinterpret_cast . + std::memcpy(&tag, reinterpret_cast(this), 1); + // HeapArrayPtr will be represented as a plain old pointer, + // which will have alignment to at least a 2-byte boundary + // (because it's uint16_t*) and more likely an 8- or 16-byte + // boundary because malloc will tend to just align everything to + // one of those. So, we just set tag to 1 when inline_repr_ is + // active so as to be able to differentiate the two. + return (tag & 1) != 0; + } + + // NOLINTNEXTLINE(modernize-use-equals-default) + Repr() {} + + ~Repr() { + destroyIfOutline(); + } + + Repr(const Repr& rhs) { + if (rhs.is_inline()) { + std::memcpy(&inline_repr_, &rhs.inline_repr_, sizeof(inline_repr_)); + } else { + new (&outline_repr_) OutlineRepr(rhs.outline_repr_); + } + } + + Repr& operator=(const Repr& rhs) { + if (&rhs == this) { + return *this; + } + if (rhs.is_inline()) { + destroyIfOutline(); + new (&inline_repr_) InlineRepr(); + std::memcpy(&inline_repr_, &rhs.inline_repr_, sizeof(inline_repr_)); + } else { + if (is_inline()) { + new (&outline_repr_) OutlineRepr(rhs.outline_repr_); + } else { + outline_repr_ = rhs.outline_repr_; + } + } + return *this; + } + + Repr(Repr&& rhs) noexcept { + if (rhs.is_inline()) { + std::memcpy(&inline_repr_, &rhs.inline_repr_, sizeof(inline_repr_)); + } else { + new (&outline_repr_) OutlineRepr(std::move(rhs.outline_repr_)); + } + } + + Repr& operator=(Repr&& rhs) noexcept { + if (&rhs == this) { + return *this; + } + + if (rhs.is_inline()) { + destroyIfOutline(); + new (&inline_repr_) InlineRepr(); + std::memcpy(&inline_repr_, &rhs.inline_repr_, sizeof(inline_repr_)); + } else { + if (is_inline()) { + new (&outline_repr_) OutlineRepr(std::move(rhs.outline_repr_)); + } else { + outline_repr_ = std::move(rhs.outline_repr_); + } + } + + return *this; + } + + struct InlineRepr { + uint8_t tag = 0x1; + uint8_t size{}; + uint16_t inputs[kMaxInlineInputs]{}; + }; + + using OutlineRepr = HeapArrayPtr; + + InlineRepr inline_repr_{}; + OutlineRepr outline_repr_; + + private: + void destroyIfOutline() { + if (!is_inline()) { + outline_repr_.~OutlineRepr(); + } + } + } repr_; +#pragma pack(pop) +}; + +static_assert( + sizeof(ProcessedNodeInputs) == 12, + "ProcessedNodeInputs has the wrong size!"); + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/fusion.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..3009ca031cf304074424eb64b52e07fa0937978c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/fusion.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void fuseStaticSubgraphs( + std::shared_ptr graph, + size_t min_size); + +TORCH_API void performTensorExprFusion( + std::shared_ptr graph, + std::vector sample_inputs); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/impl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/impl.h new file mode 100644 index 0000000000000000000000000000000000000000..7ace18127095dba25390c7bda2b448e2b55fd504 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/impl.h @@ -0,0 +1,1153 @@ +#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 + +#ifdef FBCODE_CAFFE2 +#include +#include +#endif + +namespace torch::jit { + +TORCH_API bool canEnableStaticRuntime( + const std::shared_ptr& graph); + +TORCH_API std::string dumpValueSet( + const c10::FastSet& value_set, + const char* set_name = ""); + +inline bool doesNotHeapAllocateWhenStoredInIValue(const Type& type) { + switch (type.kind()) { + // NOTE: NumberType may allocate because it includes complex. + case TypeKind::NoneType: + case TypeKind::IntType: + case TypeKind::FloatType: + case TypeKind::BoolType: + case TypeKind::DeviceObjType: + case TypeKind::StreamObjType: + return true; + default: + return false; + } +} + +inline c10::Symbol getStaticRuntimeMetadataSymbol() { + return Symbol::attr("static_runtime::metadata"); +} + +inline bool borrowsOutputs(c10::Symbol kind) { + static const std::array symbols_with_borrowed_outputs = { + c10::Symbol::fromQualString("static_runtime::select_tensor"), + c10::Symbol::fromQualString("static_runtime::dict_unpack"), + c10::Symbol::fromQualString("static_runtime::VarTupleUnpack"), + c10::Symbol::fromQualString("prim::IfThenElse"), + }; + return std::find( + symbols_with_borrowed_outputs.begin(), + symbols_with_borrowed_outputs.end(), + kind) != symbols_with_borrowed_outputs.end(); +} + +// Group values used by `graph` into three categories: +// +// - output_aliases: +// values that are either outputs or contain aliases of outputs +// - external_aliases: +// values that are inputs, constants, or their aliases. +// The output aliases that end up here are as a result of aliasDb failing to +// recognize them as outputs due to collection object (e.g., Tuple) aliasing +// inputs. +// Values that don't show up in output_aliases or external_aliases are created +// and consumed within the graph. +class ValueGroup { + public: + explicit ValueGroup() = default; + void init(const Block& block, const AliasDb& db); + + bool isExternalAlias(const Value* value) const { + return external_aliases_.find(value) != external_aliases_.end(); + } + + bool isOutputAlias(const Value* value) const { + return output_aliases_.find(value) != output_aliases_.end(); + } + + bool isAlwaysAlive(const Value* value) const { + return isExternalAlias(value) || isOutputAlias(value); + } + + std::string toString() const { + return c10::str( + dumpValueSet(output_aliases_, "ValueGroup::output_aliases_"), + "\n", + dumpValueSet(external_aliases_, "ValueGroup::external_aliases_")); + } + + private: + c10::FastSet output_aliases_; + c10::FastSet external_aliases_; +}; + +class TORCH_API ManagedTensorRanges { + public: + ManagedTensorRanges() = default; + ManagedTensorRanges( + Block& block, + const AliasDb& alias_db, + const c10::FastSet& managed_tensor_values); + + // If true, then this node is the last use of at least one + // managed tensor. availableTensorValuesAfterNode(node) will return a vector + // of the managed tensors that are available for reuse + // in the nodes following this one. + bool nodeFreesManagedTensors(Node* node) const; + const std::vector& availableTensorValuesAfterNode( + Node* node) const; + + // For testing. True if v1 and v2 are both mutable types and have lifetimes + // that overlap. + bool lifetimesOverlap(const Value* v1, const Value* v2) const; + + private: + struct Lifetime { + Lifetime(size_t start_, size_t end_) : start(start_), end(end_) {} + size_t start; + size_t end; + }; + + // Returns nullptr if we are not tracking the lifetime of value + Lifetime* getLifetime(const Value* value); + const Lifetime* getLifetime(const Value* value) const; + // Collect all values in the input that have tracked lifetimes. + // A value's lifetime may not be tracked if it is a graph input + // or immutable type (containers with at least one mutable + // type are mutable) + std::vector collectValuesWithTrackedLifetimes( + at::ArrayRef values); + void extendLifetime(Value* input, size_t new_end); + void extendInputLifetime(Node* node, size_t new_end); + + // Maps Node* to the set of managed tensors that are now available + // for reuse after this node. + c10::FastMap> node_to_newly_free_tensors_; + // Maps each Value* to its lifetime (start node index, end node index) + c10::FastMap value_lifetimes_; +}; + +struct TORCH_API StaticModuleOptions { + // enabling out variant allows Static Runtime to do memory planning + bool enable_out_variant{true}; + // to reuse tensor storage for tensors whose live-range do not overlap to + // reduce memory footprint (enable_out_variant must be true) + bool optimize_memory{true}; + // to batch allocate tensor storage for output tensors of the + // graph, where storage is deallocated outside static runtime + // (enable_out_variant must be true) + bool manage_output_tensors{false}; + // Gates the ReplaceWithCopy pass, which replaces ops that + // sometimes alias their outputs with out variants that + // always copy (so the output may participate in memory planning). + // Since replacing with copies is done after TensorExpr fusion, the + // resulting graph does not conform to the assumptions made in the fuser. + // So, even if this flag is turned on, the ReplaceWithCopy pass will not + // be executed if TensorExpr fusion is enabled. + bool use_copy_variants{true}; + // Gates the ReplaceWithMaybeCopy pass, which replaces ops that + // sometimes alias their outputs with subgraphs that include an out + // variant. + // For the same reason as `use_copy_variants`, the ReplaceWithMaybeCopy pass + // will not be executed if TensorExpr fusion is enabled, even if this flag + // is turned on. + bool use_maybe_copy_variants{true}; + // enable TensorExpr fusion of ops at model loading time + bool enable_tensorexpr_fusion{false}; +}; + +/* + Responsible for plugging StaticRuntime metadata onto the + IR nodes. StaticRuntimeMetdata extends CustomClassHolder + which can be casted to IValue and attached to IR node. + This is needed to pass parent graph metadata to forked + graph in presence of prim::fork operator +*/ +class TORCH_API StaticRuntimeMetadata : public torch::CustomClassHolder { + public: + explicit StaticRuntimeMetadata(const StaticModuleOptions& opts) + : opts_(opts) {} + + const StaticModuleOptions& get_opts() { + return opts_; + } + + private: + StaticModuleOptions opts_; +}; + +/// The static runime supports two execution modes. +/// +/// Mode 1: single-threaded with no parallelism except for intra-op parallelism +/// For this mode, you can do either: +/// @code +/// // m is a TorchScript module +/// auto module = StaticModule(m, opts); +/// auto output = module(args, kwargs); +/// @endcode +/// +/// or +/// +/// @code +/// // g is the TorchScript graph +/// auto module = StaticModule(g, opts); +/// auto output = module(args, kwargs); +/// @endcode +/// +/// Mode 2: similar to data parallelism, run the same model for different inputs +/// on different threads at the same time. +/// You should have one StaticModule per model, and one StaticRuntime instance +/// per running thread. To avoiding creating StaticRuntimes on the fly, use a +/// synchronized stack (i.e. boost::lockfree::stack) to cache all the +/// StaticRuntime instances in your code. +/// @code +/// // initialization +/// auto module = std::make_shared(m, opts); +/// +/// // 128 is good for most cases. Pick a number that works for you +/// boost::lockfree::stack, +/// boost::lockfree::fixed_sized> pool(128); +/// +/// // inference +/// std::shared_ptr runtime = nullptr; +/// pool.pop(runtime); +/// if (!runtime) { +/// // holds a reference to the underlying module +/// // but does its own memory management +/// runtime = std::make_shared(*module); +/// } +/// auto output = runtime(args, kwargs); +/// pool.push(runtime); +/// @endcode +/// +class MemoryPlanner; +class StaticNodeInfo; +class ProcessedNode; +class StaticRuntime; + +using SROperator = std::function; + +#ifdef FBCODE_CAFFE2 +struct TORCH_API SROperatorObserver { + using OperatorCallback = void (*)(const Node*); + OperatorCallback startCb = nullptr; + OperatorCallback endCb = nullptr; + + static void setCurrentThreadObserver(SROperatorObserver* observer); + static SROperatorObserver* getCurrentThreadObserver(); + static void onStart(const Node* name); + static void onEnd(const Node* name); +}; +#endif + +class TORCH_API ProcessedFunction { + public: + ProcessedFunction( + Node* node, + bool enable_out_variant, + bool check_memory_overlap); + + enum class Kind : uint8_t { + kOutVariant, + kNativeFunction, + kInterpreterFallback, + }; + + void run(ProcessedNode* pnode) const { + return f_(pnode); + } + + Kind kind() const { + return kind_; + } + + bool checkMemoryOverlap() const { + return check_memory_overlap_; + } + + size_t num_outputs() const { + return num_outputs_; + } + + private: + SROperator f_; + Kind kind_{ProcessedFunction::Kind::kOutVariant}; + bool check_memory_overlap_{false}; + size_t num_outputs_{0}; +}; + +// A `BlockInfo` instance stores all of the shared state that each +// `BlockRunner` will need to access. Most of this information is +// read-only and shared between threads. +// - Each `BlockInfo` corresponds to one block in the graph. +// - Each `BlockInfo` may be used by multiple block runners (when there are many +// threads). +// - All of the `BlockInfo`s are stored in a vector in the `StaticModule` and +// are initialized during `StaticModule` construction. +// - Most of the information stored is used to initialize the block's memory +// planner. +class BlockInfo { + public: + BlockInfo(uint32_t input_idx, Block& block); + + void set_nodes( + std::vector nodes, + const c10::FastMap& node_has_out_variant); + + const std::vector& nodes() const { + return nodes_; + } + + size_t num_nodes() const; + + size_t num_inputs() const { + return block_.inputs().size(); + } + + size_t num_outputs() const { + return block_.outputs().size(); + } + + graph_node_list node_ptrs() const { + return block_.nodes(); + } + + void set_output_indices(std::vector indices) { + output_indices_ = std::move(indices); + } + + const std::vector& block_output_indices() const { + return output_indices_; + } + + auto block_inputs_idx() const { + return input_idx_; + } + + bool node_is_optimizable_container_type(const Node* node) const { + return node_is_optimizable_container_type_.find(node) != + node_is_optimizable_container_type_.end(); + } + + bool value_is_managed_tensor(const Value* value) const { + return managed_tensor_values_.find(value) != managed_tensor_values_.end(); + } + + bool value_is_leaked_container(const Value* value) const { + return leaked_values_.find(value) != leaked_values_.end(); + } + + const ValueGroup& value_group() const { + return value_group_; + } + + const ManagedTensorRanges& managed_tensor_ranges() const { + return managed_tensor_ranges_; + } + + void init_value_group(const AliasDb& alias_db) { + value_group_.init(block_, alias_db); + } + + void prepare_for_memory_planner( + const AliasDb& alias_db, + const StaticModuleOptions& opt); + + const auto& managed_output_tensor_values() const { + return managed_output_tensor_values_; + } + + const auto& managed_tensor_values() const { + return managed_tensor_values_; + } + + const auto& leaked_values() const { + return leaked_values_; + } + + private: + std::vector nodes_; + + ValueGroup value_group_; + + c10::FastSet node_is_optimizable_container_type_; + c10::FastSet managed_tensor_values_; + c10::FastSet managed_output_tensor_values_; + c10::FastSet leaked_values_; + + ManagedTensorRanges managed_tensor_ranges_; + + // The index of this block's inputs in the shared values_ array. + const uint16_t input_idx_; + // The indices of this block's outputs in the shared values_ array. + std::vector output_indices_; + Block& block_; +}; + +class TORCH_API StaticModule { + public: + explicit StaticModule( + const std::shared_ptr& g, + const StaticModuleOptions& opts = StaticModuleOptions(), + std::vector sample_inputs = {}); + + explicit StaticModule( + const torch::jit::Module& m, + bool is_frozen = false, + const StaticModuleOptions& opts = StaticModuleOptions(), + std::vector sample_inputs = {}); + + private: + explicit StaticModule( + std::pair, std::optional> + graph_and_module, + const StaticModuleOptions& opts); + + public: + using KeywordArgs = std::unordered_map; + c10::IValue operator()( + const std::vector& args, + const KeywordArgs& kwargs = KeywordArgs()); + c10::IValue operator()( + std::vector&& args, + const KeywordArgs& kwargs = KeywordArgs()); + + const Graph& graph() const { + return *graph_; + } + + const Module& module() const { + DCHECK(module_.has_value()); + return *module_; + } + + const StaticModuleOptions& opts() const; + + size_t num_inputs() const; + size_t num_outputs() const; + + size_t num_constants() const { + return constants_.size(); + } + + size_t num_intermediate_values() const { + return num_intermediate_values_; + } + + size_t total_num_values() const { + return num_inputs() + num_constants() + num_intermediate_values(); + } + + [[nodiscard]] const std::vector& output_indices() const { + return output_indices_; + } + + const std::vector& constants() const { + return constants_; + } + + const BlockInfo& block_info(Block* block) const { + return block_infos_.at(block); + } + + Block* root_block() const { + return graph_->block(); + } + + private: + friend class StaticRuntime; + friend class BlockRunner; + + public: + auto num_nodes() const { + return std::accumulate( + block_infos_.begin(), + block_infos_.end(), + 0, + [](size_t sum, const auto& block_and_info) { + auto& block_info = block_and_info.second; + return sum + block_info.num_nodes(); + }); + } + + [[nodiscard]] Node* findNodeWithKindForTesting(const std::string& kind) const; + + const std::optional& schema() const { + return schema_; + } + + bool first_input_is_self() const { + return module_.has_value(); + } + + StaticRuntime& runtime(); + + // See [Shared values array] + size_t value_buffer_size() const { + return value_buffer_size_; + } + + private: + // Recursively prepares the BlockInfo array. + // - Populates `value_to_index` with the indices of each intermediate value + // - Returns the number of Value* processed, including sub-blocks. + size_t prepareBlockInfo( + Block* block, + const size_t start_idx, + c10::FastMap& value_to_index); + + void prepareFunctionsAndConstants( + Block* block, + const AliasDb& alias_db, + c10::FastMap& value_to_index); + + // Recursively traverse the graph and attach SR metadata + // to the prim::fork nodes as additional attributes + void attachNodeMetadata(Block* block); + + // Recurses on sub-blocks and populates the array of ProcessedNodes + // Returns (number of nodes processed, number of blocks processed) + size_t prepareStaticNodeInfos( + Block* block, + const c10::FastMap& value_to_index, + const AliasDb& alias_db, + size_t node_idx = 0); + + // Initialize various attributes that the memory planner will need. + // To be called at the tail of the ctor. + void prepareForMemoryPlanner(); + + StaticModuleOptions opts_; + // metadata that is stored in IR nodes as attribute + at::intrusive_ptr sr_metadata_; + std::shared_ptr graph_; + std::optional module_; + std::optional schema_; + std::unique_ptr cached_runtime_; + + // Bookkeeping for creating new StaticRuntime instances + // IValue table (defined by prim::Constant nodes) + std::vector constants_; + // The functions to be called by corresponding ProcessedNode. + std::vector functions_; + // A list of pre-processed nodes from which ProcessedNode are created per + // StaticRuntime instance. + std::vector nodes_; + // Indices of graph outputs in the single values array. + std::vector output_indices_; + + size_t num_intermediate_values_ = 0; + + // Includes self if module_ != std::nullopt. + // Note that we might have num_inputs_ == 0 even if the schema has a `self` + // argument. In this case, `self` isn't used in the graph, but the schema + // includes it anyways to be consistent with the JIT interpreter. + size_t num_inputs_; + // See `BlockInfo` definition. The blocks are stored in depth-first order. + c10::FastMap block_infos_; + size_t value_buffer_size_ = 0; +}; + +// `BlockRunner` contains the core runtime logic. Each block runner +// corresponds to one block in the graph and has its own memory planner. +// `StaticRuntime` will initialize all `BlockRunner`s +// upon construction. Each block runner only directly executes nodes from its +// block. Special ops with sub-blocks like `prim::If` may have +// `BlockRunner`s stored in their `ProcessedNode`s; these +// sub-blocks get executed in the op's implementation. +// `StaticRuntime` stores a vector of IValues that all +// `BlockRunner`s share. This vector is used to store all +// constants, inputs, and intermediate tensors. +class TORCH_API BlockRunner { + public: + BlockRunner( + const StaticModule& sm, + IValue* values, + Block* block, + torch::jit::TaskLauncher* launcher, + bool is_root_block = false); + BlockRunner(BlockRunner&&) noexcept; + BlockRunner& operator=(BlockRunner&&) = delete; + ~BlockRunner(); + + C10_DISABLE_COPY_AND_ASSIGN(BlockRunner); + + using KeywordArgs = std::unordered_map; + c10::IValue operator()( + const std::vector& args, + const KeywordArgs& kwargs = KeywordArgs()); + c10::IValue operator()( + std::vector&& args, + const KeywordArgs& kwargs = KeywordArgs()); + + c10::intrusive_ptr runAsync( + const std::vector& args, + const KeywordArgs& kwargs); + + c10::intrusive_ptr runAsync( + std::vector&& args, + const KeywordArgs& kwargs); + + void benchmark( + const std::vector>& args_list, + const std::vector& kwargs_list, + const uint32_t warmup_runs, + const uint32_t main_runs, + bool print_per_node_time = false, + bool generate_ai_pep_output = false); + + struct IndividualMetrics { + float setup_time{0.0}; + float memory_alloc_time{0.0}; + float memory_dealloc_time{0.0}; + float output_dealloc_time{0.0}; + float first_iter_time{0.0}; + float total_time{0.0}; + size_t out_nodes_count{0}; + size_t total_nodes_count{0}; + std::vector time_per_node; + std::unordered_map time_per_node_type; + std::unordered_map percent_per_node_type; + std::unordered_map instances_per_node_type; + std::unordered_set out_nodes; + std::unordered_set native_nodes; + }; + + IndividualMetrics benchmark_individual_ops( + const std::vector>& args_list, + const std::vector& kwargs_list, + const uint32_t warmup_runs, + const uint32_t main_runs); + + // Input is readwrite + IValue& Input(uint32_t i) { + TORCH_DCHECK_LT(i, block_info_.num_inputs()); + return values_[i + block_info_.block_inputs_idx()]; + } + + // Output is readonly. The writing process happens inside ProcessedNodes + [[nodiscard]] const IValue& Output(uint32_t i) const { + DCHECK(i < outputs_.size()); + return *outputs_[i]; + } + + const std::vector outputs() const { + return outputs_; + } + + const std::vector& nodes() const { + return nodes_; + } + + std::vector& nodes() { + return nodes_; + } + + graph_node_list node_ptrs() const { + return block_info_.node_ptrs(); + } + + const Graph& graph() const { + return static_module_.graph(); + } + + const MemoryPlanner* get_memory_planner() const { + return planner_.get(); + } + + bool check_for_memory_leak( + bool output_returned = true, + bool recurse_on_sub_blocks = false); + + // WARNING: Deallocate managed output tensors. A client receiving Static + // Runtime-managed Tensors needs to be very careful to call + // `StaticRuntime::deallocateOutputTensors` after all references of output + // Tensors are gone. + void deallocateOutputTensors(); + + bool checkOutputTensorMemoryLeaks(); + + bool isManagedOutputTensor(const IValue& ivalue) const; + bool isManagedOutputTensorValue(const Value* value) const; + + void disableManageOutputTensors(); + + // This is the fallback path taken if we can't construct the memory planner + // on the first iteration. + // IMPORTANT: Nothing here should be able to throw!!! + // This function can be called from the (implicitly) `noexcept` destructor + // of Deallocator, meaning that std::terminate will be called + // if any exception escapes. Even if resetMemory and ~Deallocator were + // `noexcept(false)`, it's possible that when ~Deallocator is called, the + // stack is already unwinding, so there's still danger of calling + // std::terminate. + void resetMemory() noexcept; + + private: + // A helper object that invokes memory planner deallocation code + // when destructed. + class Deallocator { + public: + explicit Deallocator(BlockRunner& block_runner) + : block_runner_(block_runner) {} + + Deallocator(Deallocator&&) = default; + Deallocator(const Deallocator&) = default; + Deallocator& operator=(const Deallocator&) = delete; + Deallocator& operator=(Deallocator&&) = delete; + ~Deallocator(); + + void setFinished() { + finished_ = true; + } + + private: + void cleanupImpl(); + + bool finished_ = false; + BlockRunner& block_runner_; + }; + + template + c10::IValue run_impl(IValueList&& args, const KeywordArgs& kwargs); + + template + c10::IValue run_impl_record_functions( + IValueList&& args, + const KeywordArgs& kwargs); + + template + c10::intrusive_ptr run_impl_async( + IValueList&& args, + const KeywordArgs& kwargs); + + template + c10::intrusive_ptr run_impl_record_functions_async( + IValueList&& args, + const KeywordArgs& kwargs); + + // helper method for copying input args/kwargs into inputs_ + template + void set_inputs(IValueList&& args, const KeywordArgs& kwargs); + + // Set Input(idx) to args[idx]. Invoked by set_inputs. Copies or moves + // depending on overload. + void set_arg(const size_t idx, std::vector&& args); + void set_arg(const size_t idx, const std::vector& args); + + // Set Input(idx) to arg. Always copies. Used for kwargs. + void set_arg(const size_t idx, const IValue& arg); + + bool fast_check_and_correct_overlap_with( + ProcessedNode& n, + c10::IValue& tensor_ival); + void verify_and_correct_memory_overlap(ProcessedNode& n); + + // clean up owning refs of input IValues + void clean_up_input_ivalues() noexcept { + for (const auto idx : c10::irange(block_info_.num_inputs())) { + values_[idx + inputs_begin_] = IValue(); + } + } + + void clean_up_intermediate_ivalues() noexcept; + + IValue move_outputs_to_tuple(uint32_t num_outputs); + + void create_memory_planner(); + + float benchmark_model( + const std::vector>& args_list, + const std::vector& kwargs_list, + const uint32_t warmup_runs, + const uint32_t main_runs); + + void display_nodes( + const std::vector& args, + const KeywordArgs& kwargs); + + const StaticModule& static_module_; + const BlockInfo& block_info_; + + const bool is_root_block_; + // Cache this so we don't have to call static_module_.first_input_is_self() + const bool first_input_is_self_; + // Index of the start of this blocks inputs in the shared values_ array. + const uint16_t inputs_begin_; + + bool manage_output_tensors_enabled_ = false; + std::unique_ptr planner_; + // [Shared values array] + // ProcessedNodes reference their inputs and outputs with + // offsets into this array, which saves memory. + // All BlockRunners share the same array. The layout is as + // follows: + // [constants][block_0][block_1]...[block_N] + // Note that constants from all blocks are pooled together at the start. + // The block ordering is depth-first. + // Each block is further divided into inputs and intermediates: + // [block_i] = [inputs_i][intermediates_i] + // Each BlockRunner knows where its inputs start. Each ProcessedNode + // knows how to find the indices of its outputs/inputs in this array. + IValue* values_; + + std::vector outputs_; + std::vector nodes_; +}; + +class TORCH_API StaticNodeInfo { + public: + StaticNodeInfo( + Node* n, + ProcessedFunction* fn, + ProcessedNodeInputs inputs, + uint16_t outputs_offset); + + Node* node() const { + return node_; + } + + size_t num_outputs() const { + DCHECK(fn_ != nullptr); + return fn_->num_outputs(); + } + + bool has_out_variant() const { + return fn_->kind() == ProcessedFunction::Kind::kOutVariant; + } + + private: + friend class ProcessedNode; + + Node* node_; + const ProcessedFunction* fn_; + ProcessedNodeInputs inputs_; + uint16_t outputs_offset_; +}; + +inline size_t BlockInfo::num_nodes() const { + return nodes_.size(); +} + +/* + ProcessedNodeMetadata class wraps the possible metadata + for ProcessedNode. Depending upon the nature of op, processedNode + can have one of the below possibilities of metadata: + - prim::If/prim::Loop ops contains block_runners_ as their metadata + - prim::fork op contains TaskLauncher (std::function) responsible for + execution of forked subgraph +*/ +class TORCH_API ProcessedNodeMetadata { + public: + ProcessedNodeMetadata( + std::vector runners, + torch::jit::TaskLauncher* launcher) + : block_runners_(std::move(runners)), launcher_(launcher) {} + + ProcessedNodeMetadata() : launcher_(nullptr) {} + + // deleted copy ctor/assignment as standard containers (vector) always + // have copy constructors, but their instantiation is not well-formed + // if the contained type (BlockRunner) is not copyable + ProcessedNodeMetadata(const ProcessedNodeMetadata&) = delete; + ProcessedNodeMetadata& operator=(const ProcessedNodeMetadata&) = delete; + ProcessedNodeMetadata(ProcessedNodeMetadata&&) = delete; + ProcessedNodeMetadata&& operator=(ProcessedNodeMetadata&&) = delete; + ~ProcessedNodeMetadata() = default; + + std::vector& block_runners() { + return block_runners_; + } + + void set_block_runners(std::vector runners) { + block_runners_ = std::move(runners); + } + + void set_launcher(torch::jit::TaskLauncher* launcher) { + launcher_ = launcher; + } + + torch::jit::TaskLauncher* launcher() { + return launcher_; + } + + private: + std::vector block_runners_; + torch::jit::TaskLauncher* launcher_; +}; + +class TORCH_API ProcessedNode { + public: + ProcessedNode() = default; + + ProcessedNode(const StaticNodeInfo& other, IValue* values) + : node_(other.node_), + fn_(other.fn_), + inputs_(other.inputs_), + outputs_offset_(other.outputs_offset_), + values_(values), + metadata_(nullptr) {} + + // These should be noexcept, but some Android build is failing + // saying the noexcept specification doesn't match the calculated + // one. Maybe std::variant is throwing it off? + ProcessedNode(ProcessedNode&&) = default; + + ProcessedNode(const ProcessedNode&) = delete; + ProcessedNode& operator=(const ProcessedNode& other) = delete; + ProcessedNode& operator=(ProcessedNode&&) = default; + ~ProcessedNode() = default; + + void run(); + + Node* node() const { + return node_; + } + + // Input is readonly + [[nodiscard]] const IValue& Input(uint32_t i) const { + return values_[inputs_[i]]; + } + + // Output is readwrite + IValue& Output(uint32_t i) { + DCHECK(i < num_outputs()); + return values_[outputs_offset_ + i]; + } + + [[nodiscard]] const IValue& Output(uint32_t i) const { + DCHECK(i < num_outputs()); + return values_[outputs_offset_ + i]; + } + + uint32_t num_outputs() const { + DCHECK(fn_ != nullptr); + return static_cast(fn_->num_outputs()); + } + + [[nodiscard]] c10::ArrayRef outputs() const { + return c10::ArrayRef( + values_ + outputs_offset_, num_outputs()); + } + + [[nodiscard]] uint16_t num_inputs() const { + return inputs_.size(); + } + + std::vector inputs_ivalue_vec() const; + + bool has_out_variant() const { + return fn_->kind() == ProcessedFunction::Kind::kOutVariant; + } + + bool has_native() const { + return fn_->kind() == ProcessedFunction::Kind::kNativeFunction; + } + +#ifndef PYTORCH_DISABLE_PER_OP_PROFILING + const char* get_op_name() const { + return node_->kind().toQualString(); + } +#endif + + bool check_outputs_for_memory_overlap() const { + return fn_->checkMemoryOverlap(); + } + + void set_outputs_memory_overlap_detected() { + overlap_detected_ = true; + } + + bool outputs_memory_overlap_detected() { + return overlap_detected_; + } + + bool check_and_correct_overlap_with( + const at::Tensor& input, + c10::IValue& output); + void verify_and_correct_memory_overlap(); + + void set_values(IValue* values) { + DCHECK(values_ == nullptr); + values_ = values; + } + + [[nodiscard]] uint16_t output_ivalue_index(uint16_t i) const { + DCHECK(i < num_outputs()); + return outputs_offset_ + i; + } + // used in debug mode + bool verify_no_memory_overlap(bool force_check = false) const; + + // returns pointer to ProcessedNodeMetadata or nullptr if no object is owned + ProcessedNodeMetadata* metadata() { + return metadata_.get(); + } + + // attach block_runner to metadata of ProcessedNode + void set_metadata(std::vector block_runners) { + if (metadata_ == nullptr) { + metadata_ = std::make_unique(); + } + metadata_->set_block_runners(std::move(block_runners)); + } + + // attach TaskLauncher to metadata of ProcessedNode + void set_metadata(torch::jit::TaskLauncher* launcher) { + if (metadata_ == nullptr) { + metadata_ = std::make_unique(); + } + metadata_->set_launcher(launcher); + } + + private: + [[nodiscard]] bool verify_outputs_dont_overlap_each_other() const; + + [[nodiscard]] bool verify_inputs_dont_overlap_outputs(bool force_check) const; + + Node* node_{nullptr}; + const ProcessedFunction* fn_{nullptr}; + ProcessedNodeInputs inputs_; + uint16_t outputs_offset_{0}; + bool overlap_detected_{false}; + IValue* values_ = nullptr; // unowned + // Metadata for ProcessedNode. + // 1. prim::If/Loop nodes contains sub-blocks as metadata + // 2. prim::fork nodes contains custom executor for async execution + std::unique_ptr metadata_; +}; + +// `StaticRuntime` is the owner of the array of IValues (used for constants, +// inputs, and intermediate tensors) that all `BlockRunner`s share. +// Upon construction, it initializes all block runners. `operator()` simply +// forwards the inputs to the top-level block runner. Each `StaticRuntime` +// instance corresponds to one `StaticModule`. Multiple `StaticRuntime` +// instances can be created; this is useful for multi-threaded execution, since +// `operator()` is not thread-safe. +class TORCH_API StaticRuntime { + public: + explicit StaticRuntime(const StaticModule& sm); + + using KeywordArgs = std::unordered_map; + c10::IValue operator()( + const std::vector& args, + const KeywordArgs& kwargs = KeywordArgs()); + c10::IValue operator()( + std::vector&& args, + const KeywordArgs& kwargs = KeywordArgs()); + + // runAsync performs inline execution of graph on + // caller thread and async execution on taskLauncher + // If no custom taskLauncher is specified, execution is done + // on inter-op thread pool. + c10::intrusive_ptr runAsync( + const std::vector& args, + const KeywordArgs& kwargs = KeywordArgs(), + torch::jit::TaskLauncher taskLauncher = at::launch); + + c10::intrusive_ptr runAsync( + std::vector&& args, + const KeywordArgs& kwargs = KeywordArgs(), + torch::jit::TaskLauncher taskLauncher = at::launch); + + bool check_for_memory_leak(bool output_returned = true); + bool checkOutputTensorMemoryLeaks(); + + void deallocateOutputTensors(); + bool isManagedOutputTensor(const IValue& ivalue) const; + void disableManageOutputTensors(); + + // Gets the top-level memory planner. Used for testing. + const MemoryPlanner* get_memory_planner() const; + + void benchmark( + const std::vector>& args_list, + const std::vector& kwargs_list, + const uint32_t warmup_runs, + const uint32_t main_runs, + bool print_per_node_time = false, + bool generate_ai_pep_output = false) { + block_->benchmark( + args_list, + kwargs_list, + warmup_runs, + main_runs, + print_per_node_time, + generate_ai_pep_output); + } + + using IndividualMetrics = BlockRunner::IndividualMetrics; + + IndividualMetrics benchmark_individual_ops( + const std::vector>& args_list, + const std::vector& kwargs_list, + const int warmup_runs, + const int main_runs) { + return block_->benchmark_individual_ops( + args_list, kwargs_list, warmup_runs, main_runs); + } + + private: + // An array of IValues with unchanging size/data ptr. + class IValueArray { + public: + IValueArray() = default; + explicit IValueArray(size_t size) : array_(allocate(size)), size_(size) {} + + IValue* data() const { + return array_.get(); + } + + size_t size() const { + return size_; + } + + private: + // NOLINTNEXTLINE(modernize-avoid-c-arrays) + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays) + static std::unique_ptr allocate(size_t size) { + if (size) { + return std::make_unique(size); + } + return nullptr; + } + + // NOLINTNEXTLINE(modernize-avoid-c-arrays) + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays) + std::unique_ptr array_ = nullptr; + size_t size_ = 0; + }; + + std::unique_ptr block_; + // for execution of async operations present in graph + torch::jit::TaskLauncher async_task_launcher_; + IValueArray values_; +}; + +} // namespace torch::jit +C10_DECLARE_bool(static_runtime_disable_debug_memory_overlap_check); + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/init.h new file mode 100644 index 0000000000000000000000000000000000000000..d39c7141cb007a050e10d9a7d7588fa8a1ca0604 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/init.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::jit { + +void initStaticModuleBindings(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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/memory_planner.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/memory_planner.h new file mode 100644 index 0000000000000000000000000000000000000000..f2d5d34a57eaff8b256be9a6e11d0c7bd2bcb0bb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/memory_planner.h @@ -0,0 +1,303 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// A StorageGroup represents a collection of tensors that share backing storage. +class StorageGroup { + public: + // Every storage group must contain at least one tensor. + explicit StorageGroup(at::Tensor* tensor) : group_{tensor} {} + + void addTensor(at::Tensor* tensor) { + group_.push_back(tensor); + } + + const std::vector& group() const { + return group_; + } + + size_t maxTensorSize() const { + return max_tensor_size_; + } + + void setMaxTensorSize(size_t new_size) { + max_tensor_size_ = new_size; + } + + size_t numManagedTensors() const { + return group_.size(); + } + + private: + // The size attribute represents the amount of memory that will be + // allocated for all tensors in this storage group. Initially it + // is zero, eventually it gets updated by the MemoryPlanner. + size_t max_tensor_size_ = 0; + std::vector group_; +}; + +// A contiguous buffer of `StorageImpl`s +class ManagedStorages { + public: + ManagedStorages(); + + ~ManagedStorages(); + + void allocate(size_t capacity); + + void deallocate(); + + bool is_allocated() const { + return storages_ != nullptr; + } + + // Append a new StorageImpl to the buffer. The new StorageImpl is given the + // same size and allocator as `storageImpl` argument + void append(at::StorageImpl& storageImpl); + + at::StorageImpl& operator[](size_t idx) { + TORCH_INTERNAL_ASSERT(storages_ != nullptr); + return storages_[idx]; + } + + const at::StorageImpl& operator[](size_t idx) const { + TORCH_INTERNAL_ASSERT(storages_ != nullptr); + return storages_[idx]; + } + + size_t size() const { + return size_; + } + + bool empty() const { + return size_ == 0; + } + + size_t capacity() const { + return capacity_; + } + + private: + // We will use placement-new to add new storages to this buffer + at::StorageImpl* storages_; + + // Current number of storages that have been placed into the storage buffer + size_t size_; + + // Total allocated capacity of the storage buffer + size_t capacity_; +}; + +TORCH_API std::vector assignStorageToManagedTensors( + graph_node_list nodes, + const ManagedTensorRanges& ranges, + const c10::FastMap& tensor_value_to_tensor); + +// There are three types of ops in a processed graph in Static Runtime: +// 1. op with _out variant +// 2. view-producing op +// 3. tensor-producing op (could be replaced with type 1 by adding the _out +// variant to Static Runtime) +// In Static Runtime, type 2 ops are replaced with their corresponding copy +// versions when enable_out_variant is enabled and become type 1 ops.The memory +// planner only manages tensors that are outputs of type 1 ops. For type 3, the +// output tensors are allocated inside the operator and can't be directly +// managed by memory planner. +// +// Memory planner tries to minimize the number of memory allocations by +// tracking the output tensors of ops with _out variants with unique DataPtr +// (part of StorageImpl). It tries to do this in several steps: +// 1. record the max memory usage for each Tensor with unique DataPtr at the +// end of each iteration +// 2. in the next iteration, allocate the buffer for the max total usage and +// compute the offset of each allocation with regard to the single memory +// buffer, optionally reusing memory. In the first iteration, we rely on +// the default allocator for memory allocation. +// 3. free the buffer at the end of each iteration +// Steps 1 and 3 are handled by `deallocate()`, and step 2 by `allocate()`. +// Only models with simple output types are supported, i.e. None, Tensor or +// List/Tuple/Dict of Tensors. Complex output types such as List of Lists are +// not supported. +// +// Additional Optimizations: +// +// [Borrowed IValue Outputs] +// A few native ops (notably, `static_runtime::dict_unpack` and +// `static_runtime::VarTupleUnpack`) simply unpack IValues to a bunch of +// outputs without modification. For example, `dict_unpack` does the following: +// for each key in inputs: +// output[i] = dict_input[key] +// To avoid refcount bumps, the outputs of these ops are non-owning references. +// This requires special logic in the memory planner - when adding an op that +// borrows outputs, be sure that the memory planner is updated accordingly! +// +// [Managed Output Tensors] +// The memory planner is able to manage output tensors if the appropriate +// `StaticModuleOptions` are set. However, the memory planner handles output +// tensors separately from regular intermediate tensors: +// 1. They don't participate in memory reuse. +// 2. The memory planner cannot reclaim their backing storage until they have +// been explicitly freed by the client. + +class MemoryPlanner { + public: + MemoryPlanner( + BlockRunner* block_runner, + const BlockInfo& block_info, + bool enable_out_variant, + bool manage_output_tensors); + + // disable copying and moving + MemoryPlanner(const MemoryPlanner&) = delete; + MemoryPlanner& operator=(const MemoryPlanner&) = delete; + MemoryPlanner(MemoryPlanner&&) = delete; + MemoryPlanner& operator=(MemoryPlanner&&) = delete; + virtual ~MemoryPlanner() = default; + + void allocate(); + void deallocate(); + void deallocateOutputTensors(); + + size_t total_num_managed_tensors() const { + return num_managed_tensors_; + } + + size_t total_reused_tensors() const { + return reused_tensors_; + } + + size_t total_num_managed_output_tensors() const { + return managed_output_tensors_.size(); + } + + [[nodiscard]] size_t total_num_unmanaged() const { + return num_unmanaged_non_scalars() + num_unmanaged_scalars(); + } + + [[nodiscard]] size_t num_unmanaged_non_scalars() const { + return unmanaged_ivalues_.size() + unmanaged_borrowed_ivalues_.size(); + } + + [[nodiscard]] size_t num_unmanaged_scalars() const { + return num_unmanaged_scalar_ivalues_; + } + + size_t total_managed() const { + return managed_bytes_; + } + + size_t numOutputBufferBytes() const { + return output_buffer_bytes_; + } + + // Check if `ivalue` is contained as a managed tensor. Only used in DCHECK(). + bool isManagedOutputTensor(const IValue& ivalue) const { + if (!output_buffer_ || // output buffer got already deallocated. + output_buffer_bytes_ == 0 || // memory planning is not yet initialized. + !ivalue.isTensor() // a non-tensor is never managed + ) { + return false; + } + const auto& tensor = ivalue.toTensor(); + if (!tensor.has_storage() || !tensor.storage().data_ptr()) { + return false; + } + // TODO: Improve this once D31357486 is landed. + uint8_t* tensor_ptr = + static_cast(tensor.storage().data_ptr().get()); + uint8_t* buffer_start = static_cast(output_buffer_.get()); + uint8_t* buffer_end = buffer_start + output_buffer_bytes_; + return buffer_start <= tensor_ptr && tensor_ptr < buffer_end; + } + + bool isManagedStorageImpl(const at::StorageImpl* impl) const { + if (storages_.empty()) { + return false; + } + // Comparing pointers that aren't within the same array is + // UB. We're doing fancy memory allocation stuff, so we cast to an + // integer type and carry on. + const auto impl_p = reinterpret_cast(impl); + const auto start = reinterpret_cast(&storages_[0]); + const auto end = + reinterpret_cast(&storages_[0] + storages_.size()); + return impl_p >= start && impl_p < end; + } + + bool overlapWithInternalBuffer(void* data_ptr) { + return buffer_start_ <= data_ptr && data_ptr < buffer_end_; + } + + protected: + uint8_t* allocateBuffer(size_t num_bytes); + + size_t managed_bytes_{0}; + size_t reused_tensors_{0}; + + // We allocate StorageImpls ourselves so that 1) we don't have to do + // an extra two loads per Tensor (which will likely miss in the CPU + // data cache) first reading the Storage (i.e., StorageImpl pointer) + // from the TensorImpl object and then second dereferencing it and + // 2) our memory access pattern during allocate() has high locality. + // We don't have any guarantee that the model doesn't change the + // Storage for managed tensors out from under us during execution, + // so we have to check the StorageImpls each time we deallocate. + ManagedStorages storages_; + + // Contains the size (in bytes) of the data to be allocated for each storage + std::vector storages_nbytes_; + + private: + // ivalues created in one run but not managed by MemoryPlanner + std::vector unmanaged_ivalues_; + + // Special class of unmanaged values: some native ops create IValues + // in a "borrowed" state that can and must be cleaned up without a + // reference count decrement. + std::vector unmanaged_borrowed_ivalues_; + + // Even more special class of unmanaged values: if select_tensor + // outputs are outputs of the graph, then they need to be restored + // to an ordinary "strong reference" state. + std::vector borrowed_ivalues_needing_incref_; + + std::vector> managed_output_tensors_; + at::DataPtr buffer_; // allocated each time we call Run() + uint8_t* buffer_start_{nullptr}; + uint8_t* buffer_end_{nullptr}; + size_t num_managed_tensors_{0}; + size_t num_unmanaged_scalar_ivalues_{0}; + + at::DataPtr output_buffer_; + size_t output_buffer_bytes_{0}; + + virtual void allocateManagedTensors() = 0; + virtual void deallocateManagedTensors() = 0; + + void allocateOutputTensors(); +}; + +class StandardMemoryPlanner : public MemoryPlanner { + public: + StandardMemoryPlanner( + BlockRunner* block_runner, + const BlockInfo& block_info, + bool enable_out_variant, + bool manage_output_tensors, + bool optimize_memory); + + protected: + void allocateManagedTensors() override; + void deallocateManagedTensors() override; + + std::vector managed_tensors_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/ops.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/ops.h new file mode 100644 index 0000000000000000000000000000000000000000..eee8b1d798cbd2d60a324d482216ec7584d08ec3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/ops.h @@ -0,0 +1,192 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace at::native { +at::Tensor& reshape_copy_out( + at::Tensor& out, + const at::Tensor& self, + const at::DimVector& proposed_shape, + bool infer_size = true); +at::Tensor& to_copy_out( + Tensor& out, + const Tensor& self, + bool non_blocking, + bool copy_strides, + std::optional memory_format); +} // namespace at::native + +namespace torch::jit { + +using SROpFunctor = SROperator (*)(Node* n); +struct SROperatorFunctor { + virtual SROperator Generate(Node* /*unused*/) { + SROperator out; + return out; + } + virtual ~SROperatorFunctor() = default; +}; + +TORCH_DECLARE_REGISTRY(SROperatorRegistry, SROperatorFunctor); + +#define REGISTER_OPERATOR_FUNCTOR(name, id, ...) \ + struct SROperatorFunctor_##id : public SROperatorFunctor { \ + SROpFunctor fn = __VA_ARGS__; \ + SROperator Generate(Node* n) override { \ + return fn(n); \ + } \ + }; \ + C10_REGISTER_CLASS(SROperatorRegistry, name, SROperatorFunctor_##id) + +TORCH_DECLARE_REGISTRY(SRNativeOperatorRegistry, SROperatorFunctor); +#define REGISTER_NATIVE_OPERATOR_FUNCTOR(name, id, ...) \ + struct SRNativeOperatorFunctor_##id : public SROperatorFunctor { \ + SROpFunctor fn = __VA_ARGS__; \ + SROperator Generate(Node* n) override { \ + return fn(n); \ + } \ + }; \ + C10_REGISTER_CLASS( \ + SRNativeOperatorRegistry, name, SRNativeOperatorFunctor_##id) + +inline at::Tensor create_empty_from(const at::Tensor& t) { + return at::detail::empty_cpu( + {0}, + c10::typeMetaToScalarType(t.dtype()), + t.layout(), + t.device(), + std::nullopt, + std::nullopt); +} + +inline at::Tensor create_empty_from( + at::IntArrayRef sizes, + const at::Tensor& t) { + return at::detail::empty_cpu( + sizes, + c10::typeMetaToScalarType(t.dtype()), + t.layout(), + t.device(), + std::nullopt, + std::nullopt); +} + +inline at::Tensor create_empty(c10::ScalarType dtype) { + return at::detail::empty_cpu( + {0}, dtype, std::nullopt, std::nullopt, std::nullopt, std::nullopt); +} + +inline at::Tensor create_empty_from( + const at::Tensor& t, + c10::ScalarType dtype) { + return at::detail::empty_cpu( + {0}, dtype, t.layout(), t.device(), std::nullopt, std::nullopt); +} + +inline at::Tensor create_empty_from(const at::Tensor& t, c10::Layout layout) { + return at::detail::empty_cpu( + {0}, + c10::typeMetaToScalarType(t.dtype()), + layout, + t.device(), + std::nullopt, + std::nullopt); +} + +inline at::Tensor create_empty_from(const at::Tensor& t, c10::Device device) { + return at::detail::empty_cpu( + {0}, + c10::typeMetaToScalarType(t.dtype()), + t.layout(), + device, + std::nullopt, + std::nullopt); +} + +inline at::Tensor create_empty_from( + const at::Tensor& t, + c10::MemoryFormat memory_format) { + return at::detail::empty_cpu( + {0}, + c10::typeMetaToScalarType(t.dtype()), + t.layout(), + t.device(), + std::nullopt, + memory_format); +} + +inline at::Tensor create_empty_from( + const at::Tensor& t, + c10::ScalarType dtype, + c10::MemoryFormat memory_format) { + return at::detail::empty_cpu( + {0}, dtype, t.layout(), t.device(), std::nullopt, memory_format); +} + +inline bool checkResizedDataPtr(at::Tensor& t) { + auto const prev_data_ptr = t.data_ptr(); + t.resize_({0}); + return prev_data_ptr == t.data_ptr(); +} + +inline void fastResizeToZero(at::Tensor& t) { + t.unsafeGetTensorImpl()->set_sizes_contiguous({0}); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(checkResizedDataPtr(t)); +} + +// check if an op has an out variant registered in Static Runtime +bool opIsRegistered(const c10::Symbol& op_name); +// check if Static Runtime can run an op natively. +// prim ops that are implemented directly in the jit interpreter are implemented +// as native ops in Static Runtime +bool nativeOpIsRegistered(const c10::Symbol& op_name); + +bool canReuseInputsOutputs( + Node* n, + const c10::FastMap& node_has_out_variant); +bool isOptimizableContainerType( + Node* n, + const c10::FastMap& node_has_out_variant); + +SROperator getOutOfPlaceOperation(Node* n); +SROperator getNativeOperation(Node* n); + +bool hasVarArgs(Node* n); + +inline std::string PrintNode(const Node* node) { + std::ostringstream ss; + node->print(ss, 0, nullptr, false); + return ss.str(); +} + +inline void LogAndDumpSchema(const Node* node) { + VLOG(1) << "Found schema mismatch for: " << node->schema(); +} + +inline bool sr_schema_check(torch::jit::Node* /*unused*/) { + return true; +} + +template +bool sr_schema_check( + torch::jit::Node* node, + Schema&& first, + Schemas&&... rest) { + auto is_match = node->matches(first) || sr_schema_check(node, rest...); + if (!is_match) { + torch::jit::LogAndDumpSchema(node); + } + return is_match; +} + +bool sr_schema_check_kind(torch::jit::Node* node, c10::Symbol node_kind); +} // namespace torch::jit + +C10_DECLARE_bool(static_runtime_enable_fast_math); + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/passes.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..2169e4775263a39000b236828336d98ebb18f271 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/passes.h @@ -0,0 +1,96 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::jit { + +TORCH_API void FuseInferenceOpsForSparseNN( + std::shared_ptr& graph); + +TORCH_API void EliminateTrivialEquallySplit( + std::shared_ptr& graph); + +TORCH_API void FuseListUnpack(std::shared_ptr& graph); + +// If outputs_are_immutable is set to false, don't replace the view ops that +// produce aliases of graph outputs with the copy version. +TORCH_API void ReplaceWithCopy( + std::shared_ptr& graph, + bool outputs_are_immutable = true); + +TORCH_API void ReplacePermuteWithCopy( + std::shared_ptr& graph, + bool outputs_are_immutable = true); + +TORCH_API void ReplaceWithMaybeCopy( + std::shared_ptr& graph, + bool outputs_are_immutable = true); + +TORCH_API void RemoveImmutableInputDictLookups( + std::shared_ptr& graph); + +TORCH_API bool graphHasOp(std::shared_ptr& graph, const char* op_name); + +TORCH_API bool forwardHasOp(const Module& module, const char* op_name); + +TORCH_API void FuseSignLog1P(std::shared_ptr& graph); + +TORCH_API void UseVariadicTupleUnpack(const std::shared_ptr& graph); + +// c10::Symbol::fromQualString is a bit long to type everywhere, and +// we can't use a `using` statement since it's a static class function. +inline c10::Symbol fromQualString(const std::string& qual_string) { + return c10::Symbol::fromQualString(qual_string); +} + +// [Create owned refs for special values] +// StaticRuntimeBlockRunner moves its outputs to the return value at the end of +// run_impl. However, there's a corner case where this can cause problems. If +// we return a constant, then the only reference in the constants_ array can +// be destroyed by this move. +// We could add special logic to handle this in run_impl. But since this is a +// relatively rare corner case, it's simpler to just add an op that does nothing +// but create an owned reference to its input. This owned reference can be +// safely moved out of StaticRuntimeBlockRunner. Note that for scalars, +// this actually does a copy. +// Note that we have to do the same thing if we are returning a value from an +// outer scope in a sub-block. +TORCH_API void CreateOwnedRefsForSpecialValues(Graph& graph); + +// [Force non-empty outputs] +// It is technically possible for sub-blocks to not return anything. This is +// problematic for StaticRuntimeBlockRunner because it assumes that at least one +// output is being returned. Rather than slowing down SR with special logic for +// this corner case, we simply force blocks that return nothing to return None. +TORCH_API void ForceNonEmptyOutputs(Graph& graph); + +TORCH_API void UseVariadicGroupedAccessor(const std::shared_ptr& graph); + +TORCH_API void EliminateExtraPermuteOps(std::shared_ptr& graph); + +TORCH_API void EliminateNoOpSlice(std::shared_ptr& graph); + +TORCH_API void UseSplitAndSqueeze(std::shared_ptr& graph); + +// [Remove unnecessary outputs]] +// Removes outputs to reduce compute when it is not used later in the graph. +// Currently used to remove the max_indices output of embedding_bag, which +// isn't necessary to compute the main output. +TORCH_API void RemoveUnnecessaryOutputs(std::shared_ptr& graph); + +TORCH_API void RemoveUnnecessaryEmbeddingBagOutputs( + std::shared_ptr& graph); + +TORCH_API void FuseClampNaNToNum(std::shared_ptr& graph); + +TORCH_API void UseInPlaceGetRealInputsFromOptionalInputsV2( + std::shared_ptr& graph); + +TORCH_API void PrepackWeights(std::shared_ptr& graph); + +} // namespace torch::jit + +C10_DECLARE_bool(enable_clip_ranges_gather_fusions); + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/processed_node_wrapper.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/processed_node_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..634dc574e72f47fa1ea683a7eb37145f0f60f5ff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/processed_node_wrapper.h @@ -0,0 +1,216 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +// The following class facilitates code reuse between ProcessedNodeInputWrapper +// and ProcessedNodeOutputWrapper via CRTP +template +class ProcessedNodeWrapperBase { + public: + class ProcessedNodeWrapperBaseIter { + public: + using iterator_category = std::forward_iterator_tag; + using value_type = at::Tensor; + using difference_type = size_t; + using pointer = const at::Tensor*; + using reference = const at::Tensor&; + + ProcessedNodeWrapperBaseIter() = default; + + ProcessedNodeWrapperBaseIter( + const DerivedWrapper* container, + size_t start_idx) + : container_(container), idx_(start_idx) {} + + ProcessedNodeWrapperBaseIter& operator++() { + TORCH_DCHECK_NE(idx_, container_->size()); + ++idx_; + return *this; + } + + ProcessedNodeWrapperBaseIter operator++(int) { + ProcessedNodeWrapperBaseIter old = *this; + ++(*this); + return old; + } + + reference operator*() const { + TORCH_CHECK(container_ != nullptr); + return (*container_)[idx_]; + } + + pointer operator->() const { + TORCH_CHECK(container_ != nullptr); + return &(*container_)[idx_]; + } + + friend bool operator==( + ProcessedNodeWrapperBaseIter lhs, + ProcessedNodeWrapperBaseIter rhs) { + TORCH_DCHECK_EQ(lhs.container_, rhs.container_); + return lhs.idx_ == rhs.idx_; + } + + friend bool operator!=( + ProcessedNodeWrapperBaseIter lhs, + ProcessedNodeWrapperBaseIter rhs) { + return !(lhs == rhs); + } + + private: + const DerivedWrapper* container_ = nullptr; + size_t idx_ = 0; + }; + + // NB: to mimic the behavior of at::ArrayRef, both iterators are + // the const version. + using iterator = ProcessedNodeWrapperBaseIter; + using const_iterator = ProcessedNodeWrapperBaseIter; + using size_type = size_t; + using value_type = at::Tensor; + + explicit ProcessedNodeWrapperBase(ProcessedNode& pnode) : pnode_(pnode) {} + + iterator begin() { + return ProcessedNodeWrapperBaseIter(static_cast(this), 0); + } + iterator end() { + return ProcessedNodeWrapperBaseIter( + static_cast(this), + static_cast(this)->size()); + } + + const_iterator begin() const { + return ProcessedNodeWrapperBaseIter( + static_cast(this), 0); + } + const_iterator end() const { + return ProcessedNodeWrapperBaseIter( + static_cast(this), + static_cast(this)->size()); + } + + const_iterator cbegin() const { + return ProcessedNodeWrapperBaseIter( + static_cast(this), 0); + } + const_iterator cend() const { + return ProcessedNodeWrapperBaseIter( + static_cast(this), + static_cast(this)->size()); + } + + bool empty() const { + return static_cast(this)->size() == 0; + } + + protected: + ProcessedNode& pnode_; +}; + +// A ProcessedNodeWrapperBase lets us use ProcessedNode directly in a context +// where a container of IValues is expected. This trick is handy for avoiding +// refcount bumps in perf-sensitive native ops. For example, suppose we have an +// op that takes a list of tensors as an argument and we've turned the op into a +// variadic variant in static runtime. To use the PyTorch library implementation +// of the op, we would have to pack the variadic arguments into a list: +// std::vector tensor_list; +// tensor_list.reserve(pnode->num_outputs()); +// for (const auto i : c10::irange(pnode->num_inputs()) +// tensor_list.push_back(pnode->Input(i).toTensor()); +// op_impl(tensor_list); +// Using ProcessedNodeWrapperBase, we can avoid this round of refcount bumps. +// All we need to do is turn `op_impl` into a template and pass it +// ProcessedNodeInputWrapper(*pnode)! +class ProcessedNodeInputWrapper + : public ProcessedNodeWrapperBase { + public: + // The last `back_elements_ignored` elements are not considered. + // Same for the first `front_elements_ignored` elements. + // This is useful for ops where + // only the first N elements are tensors (N < inputs.size()). + // For instance, the last argument to VarStack is an integer dimension. + explicit ProcessedNodeInputWrapper( + ProcessedNode& pnode, + size_t front_elements_ignored = 0, + size_t back_elements_ignored = 1) + : ProcessedNodeWrapperBase(pnode), + front_elements_ignored_(front_elements_ignored), + back_elements_ignored_(back_elements_ignored) { + TORCH_CHECK(front_elements_ignored_ <= pnode_.num_inputs()); + TORCH_CHECK( + back_elements_ignored_ <= + pnode_.num_inputs() - front_elements_ignored_); + } + + size_t size() const { + return pnode_.num_inputs() - back_elements_ignored_ - + front_elements_ignored_; + } + + const at::Tensor& operator[](size_t idx) const { + TORCH_CHECK(idx < size()); + return pnode_.Input(front_elements_ignored_ + idx).toTensor(); + } + + const at::Tensor& front() const { + TORCH_CHECK( + !empty(), + "Attempted to access front() of empty ProcessedNodeInputWrapper"); + return pnode_.Input(front_elements_ignored_).toTensor(); + } + + const at::Tensor& back() const { + TORCH_CHECK( + !empty(), + "Attempted to access back() of empty ProcessedNodeInputWrapper"); + return pnode_.Input(pnode_.num_inputs() - back_elements_ignored_ - 1) + .toTensor(); + } + + private: + size_t front_elements_ignored_; + size_t back_elements_ignored_; +}; + +// Similar to ProcessedNodeInputWrapper, but wraps outputs and allows for +// writing. +class ProcessedNodeOutputWrapper + : public ProcessedNodeWrapperBase { + public: + using ProcessedNodeWrapperBase< + ProcessedNodeOutputWrapper>::ProcessedNodeWrapperBase; + + size_t size() const { + return pnode_.num_outputs(); + } + + at::Tensor& operator[](size_t idx) const { + TORCH_CHECK(idx < size()); + return pnode_.Output(idx).toTensor(); + } + + at::Tensor& front() const { + TORCH_CHECK( + !empty(), + "Attempted to access front() of empty ProcessedNodeOutputWrapper"); + return pnode_.Output(0).toTensor(); + } + + at::Tensor& back() const { + TORCH_CHECK( + !empty(), + "Attempted to access back() of empty ProcessedNodeOutputWrapper"); + return pnode_.Output(size() - 1).toTensor(); + } +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/static_method.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/static_method.h new file mode 100644 index 0000000000000000000000000000000000000000..26d9043555d6575b127dac18735da727036d8a6f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/static_method.h @@ -0,0 +1,53 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +class StaticMethod : public torch::IMethod { + public: + StaticMethod( + std::shared_ptr static_module, + std::string method_name) + : static_module_(std::move(static_module)), + method_name_(std::move(method_name)) { + TORCH_CHECK(static_module_); + } + + c10::IValue operator()( + std::vector args, + const IValueMap& kwargs = IValueMap()) const override { + return (*static_module_)(std::move(args), kwargs); + } + + const std::string& name() const override { + return method_name_; + } + + protected: + void setArgumentNames( + std::vector& argument_names_out) const override { + const auto& schema = static_module_->schema(); + CAFFE_ENFORCE(schema.has_value()); + const auto& arguments = schema->arguments(); + argument_names_out.clear(); + argument_names_out.reserve(arguments.size()); + std::transform( + arguments.begin(), + arguments.end(), + std::back_inserter(argument_names_out), + [](const c10::Argument& arg) -> std::string { return arg.name(); }); + } + + private: + std::shared_ptr static_module_; + std::string method_name_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/te_wrapper.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/te_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..b359ca7db890fbae81cad1a1bd34ca7cb1977d8a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/static/te_wrapper.h @@ -0,0 +1,49 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +class TEWrapper { + public: + TEWrapper() = default; + void call(const std::vector& args); + + template + bool checkInput(const at::Tensor& t) { +#ifdef TORCH_ENABLE_LLVM + return t.is_contiguous() && t.dtype().Match(); +#else + return false; +#endif + } + +#ifdef TORCH_ENABLE_LLVM + void update(std::unique_ptr&& cg_); +#endif + + private: +#ifdef TORCH_ENABLE_LLVM + std::unique_ptr cg; +#endif +}; + +std::shared_ptr createDiv(); +std::shared_ptr createLogit(); +std::shared_ptr createRelu(); +std::shared_ptr createTanh(); +std::shared_ptr createSigmoid(); +std::shared_ptr createSignedLog1p(); +std::shared_ptr createClamp(); +std::shared_ptr createClampNanToNum(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_script.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_script.h new file mode 100644 index 0000000000000000000000000000000000000000..48732494fef63473ce22ca94d4015a3c18dac5fb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_script.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +// This file is temporary until native_functions.yaml and derivatives.yaml are +// merged. Ideally this should all go into native_functions.yaml + +#include +#include +#include + +namespace torch::jit { +struct GradientPair { + std::shared_ptr forward; + std::shared_ptr backward; +}; + +TORCH_API std::optional gradientInfoForSchema( + const FunctionSchema& schema); +TORCH_API bool hasGradientInfoForSchema(const FunctionSchema& schema); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_shape_registry.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_shape_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..9f2ea5b6ae517a455878b178ceea1d3aaf2f86f2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_shape_registry.h @@ -0,0 +1,74 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +// This file is temporary until native_functions.yaml and derivatives.yaml are +// merged. Ideally this should all go into native_functions.yaml + +#include +#include + +namespace torch::jit { + +/* +ADDING A NEW SHAPE GRAPH: +- For one node schema, there is one corresponding registered shape compute +graph. The schema of the graph should be the same except for Tensor arguments. +For every Tensor input in operator schema, there should be a List[int] +corresponding to that Tensor's shape. For example: "aten::linear(Tensor input, +Tensor weight, Tensor? bias=None) -> Tensor" ==> def linear(input: List[int], +weight: List[int], bias: Optional[List[int]]) + +Additionally, arguments which are unused at the end of the schema may be left +off. This allows sharing a single graph for multiple function schemas, such as +unary operators with different trailing arguments that do not affect the output +shape. + +The shape graph should return a new, unaliased List[int] (or tuple of lists for +multiple returns) and should not modify any input lists. This allows the shape +graphs to be composed and executed. + +The shape analysis (particularly for non-complete, or symbolic shapes) works by +partially evaluating the JIT IR. It may be possible for a Graph to be registered +that we cannot currently partially evaluate. If this happens, please file an +issue. There are lints registered to avoid particular known patterns (continue +or break or early return in a loop). Those may be improved in the future, please +file an issue if necessary. + +To debug (and write initially) the recommended flow is to define these functions +in python and iterate there. Functions should be added to +torch/jit/_shape_functions. + +To test operators, the preferred flow is through OpInfos, with +`assert_jit_shape_analysis=True`. If this is not feasible, you can look at tests +in `test_symbolic_shape_analysis.py` such as `test_adaptive_avg_pool2d`. + +Operators which take in a list of tensors, such as concat, are not yet +supported. Concat has been special cased and could be generalized as needed. +Please file an issue. +*/ + +struct BoundedShapeGraphs { + std::shared_ptr lower_bound; + std::shared_ptr upper_bound; +}; + +TORCH_API void RegisterShapeComputeGraphForSchema( + const FunctionSchema& schema, + const std::shared_ptr& g); + +TORCH_API std::optional> shapeComputeGraphForSchema( + const FunctionSchema& schema); + +TORCH_API std::optional boundedGraphsForSchema( + const FunctionSchema& schema); + +TORCH_API std::vector RegisteredShapeComputeSchemas(); + +TORCH_API void LintShapeComputeGraph( + const FunctionSchema* schema, + const std::shared_ptr& graph); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_shape_registry_util.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_shape_registry_util.h new file mode 100644 index 0000000000000000000000000000000000000000..324cfc5bf4f25f98004fe54a08dced86cfc318c9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/symbolic_shape_registry_util.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +// This file is temporary until native_functions.yaml and derivatives.yaml are +// merged. Ideally this should all go into native_functions.yaml + +#include +#include + +namespace torch::jit { + +TORCH_API const OperatorMap& get_tensorexpr_elementwise_set(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/vararg_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/vararg_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..45c5c94e9b37b9b84e5a79822258d163f2262fcf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/vararg_functions.h @@ -0,0 +1,46 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +namespace torch::jit { + +void tupleUnpack(Stack& stack); + +void format(Stack& stack, size_t num_inputs); + +void einsum(Stack& stack, size_t num_inputs); + +void percentFormat(Stack& stack, size_t num_inputs); + +void listUnpack(Stack& stack, size_t num_outputs); + +void tupleConstruct(Stack& stack, size_t num_inputs); + +void namedTupleConstruct(Stack& stack, c10::TypePtr type, size_t num_inputs); + +void listConstruct(Stack& stack, const c10::Type& list_type, size_t num_inputs); + +void dictConstruct(Stack& stack, const c10::Type& type, size_t num_inputs); + +// as weak_ref will create a Object with a non-owning CompilationUnit reference, +// for use as a constant in the Graph to avoid a reference cycle +void createObject( + Stack& stack, + const at::ClassTypePtr& type, + bool as_weak_ref = false); + +void isinstance(Stack& stack, at::ArrayRef types); + +void tupleSlice(Stack& stack, size_t begin, size_t end); + +void dequantize(Stack& stack); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/variable_tensor_list.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/variable_tensor_list.h new file mode 100644 index 0000000000000000000000000000000000000000..335992c91015ae68f444be5f4f98a3173fe9a317 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/runtime/variable_tensor_list.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::jit { + +// a wrapper to mark places where we expect all the at::Tensors to be +// variables +struct variable_tensor_list : public std::vector { + variable_tensor_list() = default; + template + variable_tensor_list(InputIt first, InputIt last) + : std::vector(first, last) {} + explicit variable_tensor_list(std::vector&& tensor) + : std::vector(std::move(tensor)) {} +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h new file mode 100644 index 0000000000000000000000000000000000000000..afccfce9cdfb397f7f57c33780a8c97d8a31890c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h @@ -0,0 +1,94 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +#include + +#include + +namespace c10 { +struct IValue; +} + +namespace torch::jit { + +class Pickler; +class InlinedCallStackSerializer { + public: + // Serialize InlinedCallStack as + // SerializedInlinedCallStack = + // [module_info, source range tag, SerializedInlinedCallStack] + // module_info = [ClassType.qualifiedName, instance_name] + // source_range_tag = unique source range id + c10::IValue serialize( + const InlinedCallStackPtr& cs_ptr, + const SourceRangeTagMap& source_range_tags); + + private: + // module_info = [ClassType.qualifiedName, instance_name] + c10::IValue serialize_module_instance_info( + const std::optional& m); + + // This caches serialized inlined callstack ptr, since many + // InlinedCallStackPtr can refer to the same one. + ska::flat_hash_map + serialized_inlined_callstack_; + // This caches serialized module instance info. + // There might be many nodes that are part of the same + // parent, grandparent etc. module. + ska::flat_hash_map serialized_module_instance_info_; +}; + +class TORCH_API CallStackDebugInfoPickler { + public: + CallStackDebugInfoPickler() = default; + + std::vector pickle( + const std::unordered_map& callstack_ptrs, + const SourceRangeTagMap& source_range_tags); + + private: + InlinedCallStackSerializer css_; +}; + +class InlinedCallStackDeserializer { + public: + InlinedCallStackPtr deserialize( + const c10::IValue& iv, + const ska::flat_hash_map& source_range_map, + const std::shared_ptr& cu); + + private: + std::optional deserialize_module_instance_info( + const c10::IValue& iv, + const std::shared_ptr& cu); + + ska:: + flat_hash_map, InlinedCallStackPtr> + cached_inlined_callstacks_; + ska::flat_hash_map, ModuleInstanceInfo> + cached_module_instance_info_; +}; + +class TORCH_API CallStackDebugInfoUnpickler { + public: + ska::flat_hash_map unpickle( + const at::DataPtr& data, + size_t size, + const ska::flat_hash_map& source_range_map, + const std::shared_ptr& cu); + + private: + InlinedCallStackDeserializer csds_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export.h new file mode 100644 index 0000000000000000000000000000000000000000..d8778cb81b160e3f53680843dbe2b89fea97e0a6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export.h @@ -0,0 +1,283 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ONNX_NAMESPACE { +class ModelProto; +} + +namespace torch::jit { + +// This map is used to keep track of parameters that should be exported +// externally. When `defer_weight_export` is true, the returned map contains +// kv pairs that map {external reference name} -> {at::Tensor to be exported}. +// It is the responsibility of the caller to export these appropriately. +// +// For example, when exporting to a zip archive, the caller may write out files +// for each entry in the export map, with the filename being the key and the +// file contents being the raw tensor data. +using RawDataExportMap = std::unordered_map; + +using SymbolDimMap = std::map; +using DimSymbolMap = std::map; + +using NodeNameMap = std::unordered_map; + +// Used for modularized export settling function and node attributes. +using NodeAttrNameMap = std:: + unordered_map>; + +TORCH_API std::tuple< + std::shared_ptr<::ONNX_NAMESPACE::ModelProto>, + RawDataExportMap, + SymbolDimMap, + bool, + NodeNameMap> +export_onnx( + const std::shared_ptr& graph, + const std::map& initializers, + int64_t onnx_opset_version, + const std::unordered_map< + std::string, + std::unordered_map>& dynamic_axes, + bool defer_weight_export = false, + ::torch::onnx::OperatorExportTypes operator_export_type = + ::torch::onnx::OperatorExportTypes::ONNX, + bool strip_doc_string = true, + bool keep_initializers_as_inputs = true, + const std::map& custom_opsets = {}, + bool add_node_names = true, + bool use_external_data_format = false, + const std::string& onnx_file_path = std::string(), + const NodeAttrNameMap& node_attr_to_name = {}); + +TORCH_API std::string serialize_model_proto_to_string( + const std::shared_ptr<::ONNX_NAMESPACE::ModelProto>& model_proto); + +TORCH_API void check_onnx_proto(const std::string& proto_string); + +// Serializer for both oldsyle and unified format TorchScript serialization +class TORCH_API ScriptModuleSerializer { + public: + explicit ScriptModuleSerializer( + caffe2::serialize::PyTorchStreamWriter& export_writer) + : writer_(export_writer) {} + + void writeFiles(const std::string& code_dir); + void serialize( + const Module& module, + const ExtraFilesMap& extra_files, + bool bytecode_format, + bool save_mobile_debug_info); + void serialize_unified_format(Module& module, uint64_t script_module_id); + SerializationStorageContext& storage_context(); + + ~ScriptModuleSerializer() = default; + + private: + void convertNamedType(const c10::NamedTypePtr& class_type); + void convertTypes(const at::NamedTypePtr& root_type); + void writeExtraFiles(const Module& module, const ExtraFilesMap& extra_files); + void writeByteCode(const Module& module, bool save_mobile_debug_info); + void writeArchive( + const IValue& value, + const std::string& archive_name, + const std::string& archive_dir, + const std::string& tensor_dir, + bool use_storage_context = false, + bool skip_tensor_data = false); + void updateSourceRangeTags(const SourceRangeRecords& ranges); + + caffe2::serialize::PyTorchStreamWriter& writer_; + std::vector constant_table_; + + std::unordered_set converted_types_; + PrintDepsTable class_deps_; + TypeNameUniquer type_name_uniquer_; + // qualifier, e.g. '__torch__.Bar' -> PythonPrint for the file that will be + // created + OrderedDict file_streams_; + // Used to keep references of storages around during serialization to solve + // for ABA memory reuse problem hit when storages are created/destroyed + // during serialization process. Also used to coordinate sharing of storages + // between Script and eager modules in torch.package. + SerializationStorageContext storage_context_; + + // Uniquely identifies a SourceRange in a model. + // SourceRanges are associated with Nodes of Graphs. + // However for mobile deployment we dont intend to ship + // full JIT with capabilities of reading code and constructing + // graphs. + // Instead we serialize the Code generated from graph of the methods. + // Code is serialized in bytecode format that contains instructions + // corresponding to the nodes of the graph. Since original graph is gone, the + // question is how do we identify where the ops, in serialized bytecode, come + // from in original model code. We do this in two parts. + // 1. Associate a unique tag to SourceRange. + // 2. Serialize this unique_tag. + // 2.1 Meaning save instead of + // + // 3. During serializing model for mobile, i.e. bytecode generation, + // save unique tag of SourceRange corresponding to the Node. + // 4. During deserialization, read all the debug_pkl, to construct a map + // of and use tag saved with OPs in bytecode + // to lookup the source range. + // Strictly speaking we will serialize InlinedCallStack directly, which + // contains SourceRange. This way we have access to entire callstack and not + // just source information about where the node is, since bytecode inlines the + // graph before saving it. + SourceRangeTagMap source_range_tags_; + int64_t current_source_range_tag_{0}; +}; + +// For testing purposes +TORCH_API std::string pretty_print_onnx( + const std::shared_ptr& graph, + const std::map& initializers, + int64_t onnx_opset_version, + bool defer_weight_export, + ::torch::onnx::OperatorExportTypes operator_export_type = + ::torch::onnx::OperatorExportTypes::ONNX, + bool google_printer = false, + bool keep_initializers_as_inputs = true, + const std::map& custom_opsets = {}, + bool add_node_names = true); + +TORCH_API void ExportModule( + const Module& module, + std::ostream& out, + const ExtraFilesMap& metadata = ExtraFilesMap(), + bool bytecode_format = false, + bool save_mobile_debug_info = false, + bool use_flatbuffer = false); + +TORCH_API void ExportModule( + const Module& module, + const std::string& filename, + const ExtraFilesMap& metadata = ExtraFilesMap(), + bool bytecode_format = false, + bool save_mobile_debug_info = false, + bool use_flatbuffer = false); + +TORCH_API void ExportModule( + const Module& module, + const std::function& writer_func, + const ExtraFilesMap& metadata = ExtraFilesMap(), + bool bytecode_format = false, + bool save_mobile_debug_info = false, + bool use_flatbuffer = false); + +// Write the bytes of a pickle archive and the tensors referenced inside that +// archive +TORCH_API void writeArchiveAndTensors( + const std::string& archive_name, + const char* pickle_bytes, + size_t size, + const std::vector& tensors, + caffe2::serialize::PyTorchStreamWriter& out); + +// Surrounding system can install an additional hook to produce extra files +// with metadata based on environment every time a module is serialized. +using ExportModuleExtraFilesHook = std::function; +TORCH_API void SetExportModuleExtraFilesHook(ExportModuleExtraFilesHook hook); + +/** + * Generates new bytecode for a Script module and returns what the op list + * would be for a LiteScriptModule based off the current code base. If you + * have a LiteScriptModule and want to get the currently present + * list of ops call _export_operator_list instead. + */ +TORCH_API std::vector export_opnames(const Module& m); + +struct TORCH_API BytecodeEmitMode { + static bool is_default_value_for_unspecified_arg_enabled(); + static void set_default_value_for_unspecified_arg_enabled(bool enabled); + + static bool is_default_args_before_out_args_enabled(); + static void set_default_args_before_out_args_enabled(bool enabled); + + static bool is_emit_promoted_ops_enabled(); + static void set_default_emit_promoted_ops_enabled(bool enabled); +}; + +// RAII guard to switch the way JIT emits the bytecode for inputs. +// default_value_for_unspecified_arg: +// true: instruction of default argument values (like LOADC) is emitted. +// false: instruction of default argument values are not emitted. Instead +// they are fetched from operator schema. +// default_args_before_out_args (to forward compatible support +// operators allowing out arguments and default arguments): +// true: the number of specified arguments will deserialized to (#all_args - +// #default_args). false: the number of specified arguments will deserialized to +// (#all_args). +struct TORCH_API BytecodeEmitModeGuard { + BytecodeEmitModeGuard( + bool enable_default_value_for_unspecified_arg, + bool enable_default_args_before_out_args, + bool enable_emit_promoted_ops) + : prev_default_value_for_unspecified_arg_mode( + BytecodeEmitMode::is_default_value_for_unspecified_arg_enabled()), + prev_default_args_before_out_args( + BytecodeEmitMode::is_default_args_before_out_args_enabled()), + prev_default_emit_promoted_ops( + BytecodeEmitMode::is_emit_promoted_ops_enabled()) { + BytecodeEmitMode::set_default_value_for_unspecified_arg_enabled( + enable_default_value_for_unspecified_arg); + BytecodeEmitMode::set_default_args_before_out_args_enabled( + enable_default_args_before_out_args); + BytecodeEmitMode::set_default_emit_promoted_ops_enabled( + enable_emit_promoted_ops); + } + ~BytecodeEmitModeGuard() { + BytecodeEmitMode::set_default_value_for_unspecified_arg_enabled( + prev_default_value_for_unspecified_arg_mode); + BytecodeEmitMode::set_default_args_before_out_args_enabled( + prev_default_args_before_out_args); + BytecodeEmitMode::set_default_emit_promoted_ops_enabled( + prev_default_emit_promoted_ops); + } + bool prev_default_value_for_unspecified_arg_mode; + bool prev_default_args_before_out_args; + bool prev_default_emit_promoted_ops; +}; + +TORCH_API IValue to_tuple(std::vector ivalues); +TORCH_API IValue +Table(const std::vector>& entries); + +// TODO remove these switches once interface call is rolled out. +TORCH_API void enableMobileInterfaceCallExport(); +bool getMobileInterfaceCallExport(); + +TORCH_API CompilationOptions getOptionsFromGlobal(); + +TORCH_API void save_jit_module( + const Module& module, + const std::string& filename, + const ExtraFilesMap& extra_files = ExtraFilesMap()); + +TORCH_API DetachedBuffer::UniqueDetachedBuffer save_jit_module_to_bytes( + const Module& module, + const ExtraFilesMap& extra_files = ExtraFilesMap()); + +TORCH_API void save_jit_module_to_write_func( + const Module& module, + const ExtraFilesMap& extra_files, + bool save_mobile_debug_info, + const std::function& writer_func); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export_bytecode.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export_bytecode.h new file mode 100644 index 0000000000000000000000000000000000000000..608e70c7b5f337bf0798888f1773018562cba00b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export_bytecode.h @@ -0,0 +1,46 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +struct TORCH_API CompilationOptions { + bool incl_interface_call = false; + bool enable_default_value_for_unspecified_arg = false; + bool enable_default_args_before_out_args = true; + bool enable_emit_promoted_ops = true; + int model_version = caffe2::serialize::kProducedBytecodeVersion; +}; + +TORCH_API mobile::Module jitModuleToMobile( + const Module& module, + const CompilationOptions& options); + +mobile::Code compileGraphToMobileCode( + const std::string& name, + const std::shared_ptr& graph, + const CompilationOptions& compilation_options, + BackendDebugInfoRecorder& debug_info_recorder); + +TORCH_API std::unique_ptr convertJitFunctionToMobileFunction( + const GraphFunction& function, + const CompilationOptions& options); + +TORCH_API IValue convertMobileFunctionToCodeTable( + const mobile::Function& func, + const CompilationOptions& compilation_options); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer.h new file mode 100644 index 0000000000000000000000000000000000000000..cfd7d513a0c578bc7dd102ec2c98db8c9a7e582c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer.h @@ -0,0 +1,97 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +/** + * Defines the public API for serializing mobile modules to flatbuffer. + * Note that this header must not include or depend on flatbuffer-defined + * types, to avoid leaking those details to PyTorch clients. + */ + +namespace torch::jit { + +/// Maps file names to file contents. +using ExtraFilesMap = std::unordered_map; + +/** + * Represents a span of data. Typically owned by a UniqueDetachedBuffer. + */ +class TORCH_API DetachedBuffer final { + public: + /// Creates a new DetachedBuffer with an optional data owner. This interface + /// is provided to let users create objects of this type for testing. + DetachedBuffer(void* data, size_t size, void* internal_data_owner = nullptr) + : data_(data), size_(size), data_owner_(internal_data_owner) {} + + /// Returns a pointer to the data. + [[nodiscard]] void* data() { + return data_; + } + /// Returns a pointer to the data. + [[nodiscard]] const void* data() const { + return data_; + } + /// Returns the size of the data, in bytes. + [[nodiscard]] size_t size() const { + return size_; + } + + /// Wrapper type that typically owns data_owner_. + using UniqueDetachedBuffer = + std::unique_ptr>; + + private: + /// Deletes the owner, if present, and the buf itself. + /// Note: we could have provided a movable type with a destructor that did + /// this work, but the unique wrapper was easier in practice. + static void destroy(DetachedBuffer* buf); + + /// Provides access to destroy() for implementation and testing. + friend struct DetachedBufferFriend; + friend struct DetachedBufferTestingFriend; + + /// Pointer to the data. Not owned by this class. + void* data_; + /// The size of `data_`, in bytes. + size_t size_; + /// Opaque pointer to the underlying owner of `data_`. This class + /// (DetachedBuffer) does not own the owner or the data. It will typically be + /// owned by a UniqueDetachedBuffer that knows how to delete the owner along + /// with this class. + void* data_owner_; +}; + +TORCH_API void save_mobile_module( + const mobile::Module& module, + const std::string& filename, + const ExtraFilesMap& extra_files = ExtraFilesMap(), + const ExtraFilesMap& jit_sources = ExtraFilesMap(), + const std::vector& jit_constants = {}); + +TORCH_API DetachedBuffer::UniqueDetachedBuffer save_mobile_module_to_bytes( + const mobile::Module& module, + const ExtraFilesMap& extra_files = ExtraFilesMap(), + const ExtraFilesMap& jit_sources = ExtraFilesMap(), + const std::vector& jit_constants = {}); + +TORCH_API void save_mobile_module_to_func( + const mobile::Module& module, + const std::function& writer_func); + +// TODO(qihan): delete +TORCH_API bool register_flatbuffer_serializer(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer_jit.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer_jit.h new file mode 100644 index 0000000000000000000000000000000000000000..fd11071344bc19fca9b1317d399d0c071928ac25 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer_jit.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API bool register_flatbuffer_all(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import.h new file mode 100644 index 0000000000000000000000000000000000000000..48c18b7905f4c70fb2f765e151dd2ce6cd449fc2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import.h @@ -0,0 +1,152 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace caffe2::serialize { +class ReadAdapterInterface; +} // namespace caffe2::serialize + +namespace torch::jit { + +class DeserializationStorageContext; + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + const std::string& filename, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::istream& in, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::unique_ptr rai, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + const std::string& filename, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true, + bool restore_shapes = false); + +// For reading unified serialization format from torch.Package +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::shared_ptr reader, + std::shared_ptr storage_context, + std::optional device, + const std::string& ts_id /* torchscript identifier inside package */); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::istream& in, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true, + bool restore_shapes = false); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::unique_ptr rai, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::shared_ptr rai, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given `istream`. +/// +/// The istream must contain a serialized `Module`, exported via +/// `torch::jit::ExportModule` in C++. +TORCH_API Module load( + std::istream& in, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + std::istream& in, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given `filename`. +/// +/// The file stored at the location given in `filename` must contain a +/// serialized `Module`, exported either via `ScriptModule.save()` in +/// Python or `torch::jit::ExportModule` in C++. +TORCH_API Module load( + const std::string& filename, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + const std::string& filename, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given shared_ptr `rai`. +/// +/// The reader adapter, which is for customized input stream, must contain a +/// serialized `Module`, exported either via `ScriptModule.save()` in +/// Python or `torch::jit::ExportModule` in C++. +TORCH_API Module load( + std::shared_ptr rai, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + std::shared_ptr rai, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +TORCH_API Module jitModuleFromSourceAndConstants( + const IValue& ivalue, + const ExtraFilesMap& source, + const std::vector& constants, + int32_t version); + +TORCH_API Module parse_and_initialize_jit_module( + const std::shared_ptr& data, + size_t size, + ExtraFilesMap& extra_files, + std::optional device = std::nullopt); + +TORCH_API Module load_jit_module_from_file( + const std::string& filename, + ExtraFilesMap& extra_files, + std::optional device = std::nullopt); + +TORCH_API Module load_jit_module_from_stream( + std::istream& in, + ExtraFilesMap& extra_files, + std::optional device = std::nullopt); + +TORCH_API c10::intrusive_ptr ObjLoaderFunc( + const at::StrongTypePtr& type, + IValue input); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_constants.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..2722a6533036cd74343c12898c9e268c17329856 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_constants.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::jit { +constexpr size_t BYTECODE_INDEX_INSTRUCTION = 0; +constexpr size_t BYTECODE_INDEX_OPERATOR = 1; +constexpr size_t BYTECODE_INDEX_CONSTANT = 2; +constexpr size_t BYTECODE_INDEX_TYPE = 3; +constexpr size_t BYTECODE_INDEX_REGISTER_SIZE = 4; + +constexpr size_t BYTECODE_INDEX_SCHEMA_ARGUMENTS = 0; +constexpr size_t BYTECODE_INDEX_SCHEMA_RETURNS = 1; + +constexpr size_t BYTECODE_INDEX_ARGUMENT_NAME = 0; +constexpr size_t BYTECODE_INDEX_ARGUMENT_TYPE = 1; +constexpr size_t BYTECODE_INDEX_ARGUMENT_DEFAULT_VALUE = 2; + +constexpr size_t BYTECODE_INDEX_MODULE_DEBUG_HANDLES = 0; +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..ea0af9d7782890380984ac33d376fffbb8540d78 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_functions.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +// Functions that are used in both import and export processes + +namespace torch::jit { +using c10::IValue; +IValue expect_field( + c10::ivalue::TupleElements& elements, + const std::string& expected_name, + size_t entry); +std::string operator_str( + const std::string& name, + const std::string& overloadname); +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_helpers.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..40a4f968c1ab3994a113b5e850f3c3bdb97c0e19 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_helpers.h @@ -0,0 +1,33 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace caffe2::serialize { +class PyTorchStreamReader; +} + +namespace torch::jit { + +struct Source; + +// Convert a class type's qualifier name to the corresponding path the source +// file it should be written to. +// +// Qualifier is like: foo.bar.baz +// Returns: libs/foo/bar/baz.py +std::string qualifierToArchivePath( + const std::string& qualifier, + const std::string& export_prefix); + +std::shared_ptr findSourceInArchiveFromQualifier( + caffe2::serialize::PyTorchStreamReader& reader, + const std::string& export_prefix, + const std::string& qualifier); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_read.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_read.h new file mode 100644 index 0000000000000000000000000000000000000000..431430271c69db92255ab8786686b0f51c390dff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_read.h @@ -0,0 +1,32 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace caffe2::serialize { +class PyTorchStreamReader; +} // namespace caffe2::serialize + +namespace torch::jit { + +TORCH_API IValue readArchiveAndTensors( + const std::string& archive_name, + const std::string& pickle_prefix, + const std::string& tensor_prefix, + std::optional type_resolver, + std::optional obj_loader, + std::optional device, + caffe2::serialize::PyTorchStreamReader& stream_reader, + c10::TypePtr (*type_parser)(const std::string&) = + Unpickler::defaultTypeParser, + std::shared_ptr storage_context = nullptr); + +bool check_zip_file( + const std::shared_ptr& rai); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_source.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_source.h new file mode 100644 index 0000000000000000000000000000000000000000..f279d6cb18e0f143076ce19c328c1ebbd19082be --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_source.h @@ -0,0 +1,105 @@ +#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 + +namespace torch::jit { + +using SourceLoader = std::function(const std::string&)>; + +struct SourceImporterImpl : public Resolver, + std::enable_shared_from_this { + SourceImporterImpl( + std::shared_ptr cu, + const std::vector* constant_table, + SourceLoader source_loader, + size_t version); + TypePtr findNamedType(const QualifiedName& name); + Function* findFunction(const QualifiedName& name); + void parseSourceIfNeeded(const std::string& qualifier); + void LEGACY_import_methods( + const Module& mod, + const std::shared_ptr& src); + + std::shared_ptr resolveValue( + const std::string& name, + GraphFunction& m, + const SourceRange& loc) override; + TypePtr resolveType(const std::string& name, const SourceRange& loc) override; + + private: + void importFunction(const std::string& qualifier, const Def& def); + void importNamedType(const std::string& qualifier, const ClassDef& class_def); + std::optional attributeAssignmentSpecialHandlingHack( + const QualifiedName& qualified_classname, + const Assign& assign); + void importClass( + const QualifiedName& qualified_classname, + const ClassDef& class_def, + bool is_module); + void importEnum( + const QualifiedName& qualified_name, + const ClassDef& enum_def); + void importNamedTuple( + const QualifiedName& qualified_name, + const ClassDef& named_tuple_def); + + void parsePossibleVersionNumber(Lexer& L); + + void parseImports(Lexer& L); + + std::shared_ptr cu_; + std::unordered_map> env_; + SourceLoader source_loader_; + std::optional version_ = std::nullopt; + std::unordered_set loaded_sources_; + // named types and functions loaded from a file but not yet defined because + // their type has not been requested yet. + std::unordered_map to_be_defined_; +}; + +// Given a directory of serialized TorchScript sources, +// This class allows the loading of individual named types in source. +// Resolves the dependencies between source files and parses +// the source files as necessary. + +struct TORCH_API SourceImporter { + SourceImporter( + // The compilation unit that will own the imported source + std::shared_ptr cu, + const std::vector* constant_table, + SourceLoader loader, + size_t version); + + TypePtr loadType(const QualifiedName& name) const; + + // Add the methods defined in `src` to the module `mod`, using SourceImporter + // to resolve any classes via loadType + void LEGACY_import_methods( + const Module& mod, + const std::shared_ptr& src); + ~SourceImporter(); + + private: + std::shared_ptr pImpl; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/mobile_bytecode_generated.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/mobile_bytecode_generated.h new file mode 100644 index 0000000000000000000000000000000000000000..5e5ad04400f6db8f5b880363162539c75253e01d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/mobile_bytecode_generated.h @@ -0,0 +1,2605 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MOBILEBYTECODE_TORCH_JIT_MOBILE_SERIALIZATION_H_ +#define FLATBUFFERS_GENERATED_MOBILEBYTECODE_TORCH_JIT_MOBILE_SERIALIZATION_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 12 && + FLATBUFFERS_VERSION_REVISION == 23, + "Non-compatible flatbuffers version included"); + +namespace torch { +namespace jit { +namespace mobile { +namespace serialization { + +struct Int; + +struct Bool; + +struct Double; + +struct PerTensorAffineSchema; + +struct QuantizedSchema; +struct QuantizedSchemaBuilder; + +struct TensorMetadata; +struct TensorMetadataBuilder; + +struct String; +struct StringBuilder; + +struct Device; +struct DeviceBuilder; + +struct List; +struct ListBuilder; + +struct IntList; +struct IntListBuilder; + +struct DoubleList; +struct DoubleListBuilder; + +struct BoolList; +struct BoolListBuilder; + +struct Tuple; +struct TupleBuilder; + +struct Dict; +struct DictBuilder; + +struct ObjectType; +struct ObjectTypeBuilder; + +struct Object; +struct ObjectBuilder; + +struct ComplexDouble; + +struct EnumValue; +struct EnumValueBuilder; + +struct Instruction; + +struct Operator; +struct OperatorBuilder; + +struct Arg; +struct ArgBuilder; + +struct Schema; +struct SchemaBuilder; + +struct DebugInfo; +struct DebugInfoBuilder; + +struct Function; +struct FunctionBuilder; + +struct StorageData; +struct StorageDataBuilder; + +struct IValue; +struct IValueBuilder; + +struct ExtraFile; +struct ExtraFileBuilder; + +struct Module; +struct ModuleBuilder; + +enum class TypeType : uint8_t { + UNSET = 0, + CLASS_WITH_FIELD = 1, + CUSTOM_CLASS = 2, + CLASS_WITH_SETSTATE = 3, + NON_OBJ = 4, + MIN = UNSET, + MAX = NON_OBJ +}; + +inline const TypeType (&EnumValuesTypeType())[5] { + static const TypeType values[] = { + TypeType::UNSET, + TypeType::CLASS_WITH_FIELD, + TypeType::CUSTOM_CLASS, + TypeType::CLASS_WITH_SETSTATE, + TypeType::NON_OBJ + }; + return values; +} + +inline const char * const *EnumNamesTypeType() { + static const char * const names[6] = { + "UNSET", + "CLASS_WITH_FIELD", + "CUSTOM_CLASS", + "CLASS_WITH_SETSTATE", + "NON_OBJ", + nullptr + }; + return names; +} + +inline const char *EnumNameTypeType(TypeType e) { + if (::flatbuffers::IsOutRange(e, TypeType::UNSET, TypeType::NON_OBJ)) return ""; + const size_t index = static_cast(e); + return EnumNamesTypeType()[index]; +} + +enum class IValueUnion : uint8_t { + NONE = 0, + Int = 1, + Bool = 2, + Double = 3, + ComplexDouble = 4, + TensorMetadata = 5, + String = 6, + List = 7, + Tuple = 8, + Dict = 9, + Object = 10, + IntList = 11, + DoubleList = 12, + BoolList = 13, + Device = 14, + EnumValue = 15, + Function = 16, + MIN = NONE, + MAX = Function +}; + +inline const IValueUnion (&EnumValuesIValueUnion())[17] { + static const IValueUnion values[] = { + IValueUnion::NONE, + IValueUnion::Int, + IValueUnion::Bool, + IValueUnion::Double, + IValueUnion::ComplexDouble, + IValueUnion::TensorMetadata, + IValueUnion::String, + IValueUnion::List, + IValueUnion::Tuple, + IValueUnion::Dict, + IValueUnion::Object, + IValueUnion::IntList, + IValueUnion::DoubleList, + IValueUnion::BoolList, + IValueUnion::Device, + IValueUnion::EnumValue, + IValueUnion::Function + }; + return values; +} + +inline const char * const *EnumNamesIValueUnion() { + static const char * const names[18] = { + "NONE", + "Int", + "Bool", + "Double", + "ComplexDouble", + "TensorMetadata", + "String", + "List", + "Tuple", + "Dict", + "Object", + "IntList", + "DoubleList", + "BoolList", + "Device", + "EnumValue", + "Function", + nullptr + }; + return names; +} + +inline const char *EnumNameIValueUnion(IValueUnion e) { + if (::flatbuffers::IsOutRange(e, IValueUnion::NONE, IValueUnion::Function)) return ""; + const size_t index = static_cast(e); + return EnumNamesIValueUnion()[index]; +} + +template struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::NONE; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Int; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Bool; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Double; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::ComplexDouble; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::TensorMetadata; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::String; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::List; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Tuple; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Dict; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Object; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::IntList; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::DoubleList; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::BoolList; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Device; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::EnumValue; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Function; +}; + +bool VerifyIValueUnion(::flatbuffers::Verifier &verifier, const void *obj, IValueUnion type); +bool VerifyIValueUnionVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Int FLATBUFFERS_FINAL_CLASS { + private: + int64_t int_val_; + + public: + Int() + : int_val_(0) { + } + Int(int64_t _int_val) + : int_val_(::flatbuffers::EndianScalar(_int_val)) { + } + int64_t int_val() const { + return ::flatbuffers::EndianScalar(int_val_); + } + void mutate_int_val(int64_t _int_val) { + ::flatbuffers::WriteScalar(&int_val_, _int_val); + } +}; +FLATBUFFERS_STRUCT_END(Int, 8); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(1) Bool FLATBUFFERS_FINAL_CLASS { + private: + uint8_t bool_val_; + + public: + Bool() + : bool_val_(0) { + } + Bool(bool _bool_val) + : bool_val_(::flatbuffers::EndianScalar(static_cast(_bool_val))) { + } + bool bool_val() const { + return ::flatbuffers::EndianScalar(bool_val_) != 0; + } + void mutate_bool_val(bool _bool_val) { + ::flatbuffers::WriteScalar(&bool_val_, static_cast(_bool_val)); + } +}; +FLATBUFFERS_STRUCT_END(Bool, 1); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Double FLATBUFFERS_FINAL_CLASS { + private: + double double_val_; + + public: + Double() + : double_val_(0) { + } + Double(double _double_val) + : double_val_(::flatbuffers::EndianScalar(_double_val)) { + } + double double_val() const { + return ::flatbuffers::EndianScalar(double_val_); + } + void mutate_double_val(double _double_val) { + ::flatbuffers::WriteScalar(&double_val_, _double_val); + } +}; +FLATBUFFERS_STRUCT_END(Double, 8); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) PerTensorAffineSchema FLATBUFFERS_FINAL_CLASS { + private: + double q_scale_; + int32_t q_zero_point_; + int32_t padding0__; + + public: + PerTensorAffineSchema() + : q_scale_(0), + q_zero_point_(0), + padding0__(0) { + (void)padding0__; + } + PerTensorAffineSchema(double _q_scale, int32_t _q_zero_point) + : q_scale_(::flatbuffers::EndianScalar(_q_scale)), + q_zero_point_(::flatbuffers::EndianScalar(_q_zero_point)), + padding0__(0) { + (void)padding0__; + } + double q_scale() const { + return ::flatbuffers::EndianScalar(q_scale_); + } + void mutate_q_scale(double _q_scale) { + ::flatbuffers::WriteScalar(&q_scale_, _q_scale); + } + int32_t q_zero_point() const { + return ::flatbuffers::EndianScalar(q_zero_point_); + } + void mutate_q_zero_point(int32_t _q_zero_point) { + ::flatbuffers::WriteScalar(&q_zero_point_, _q_zero_point); + } +}; +FLATBUFFERS_STRUCT_END(PerTensorAffineSchema, 16); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) ComplexDouble FLATBUFFERS_FINAL_CLASS { + private: + double real_; + double imag_; + + public: + ComplexDouble() + : real_(0), + imag_(0) { + } + ComplexDouble(double _real, double _imag) + : real_(::flatbuffers::EndianScalar(_real)), + imag_(::flatbuffers::EndianScalar(_imag)) { + } + double real() const { + return ::flatbuffers::EndianScalar(real_); + } + void mutate_real(double _real) { + ::flatbuffers::WriteScalar(&real_, _real); + } + double imag() const { + return ::flatbuffers::EndianScalar(imag_); + } + void mutate_imag(double _imag) { + ::flatbuffers::WriteScalar(&imag_, _imag); + } +}; +FLATBUFFERS_STRUCT_END(ComplexDouble, 16); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Instruction FLATBUFFERS_FINAL_CLASS { + private: + int8_t op_; + int8_t padding0__; + uint16_t n_; + int32_t x_; + + public: + Instruction() + : op_(0), + padding0__(0), + n_(0), + x_(0) { + (void)padding0__; + } + Instruction(int8_t _op, uint16_t _n, int32_t _x) + : op_(::flatbuffers::EndianScalar(_op)), + padding0__(0), + n_(::flatbuffers::EndianScalar(_n)), + x_(::flatbuffers::EndianScalar(_x)) { + (void)padding0__; + } + int8_t op() const { + return ::flatbuffers::EndianScalar(op_); + } + void mutate_op(int8_t _op) { + ::flatbuffers::WriteScalar(&op_, _op); + } + uint16_t n() const { + return ::flatbuffers::EndianScalar(n_); + } + void mutate_n(uint16_t _n) { + ::flatbuffers::WriteScalar(&n_, _n); + } + int32_t x() const { + return ::flatbuffers::EndianScalar(x_); + } + void mutate_x(int32_t _x) { + ::flatbuffers::WriteScalar(&x_, _x); + } +}; +FLATBUFFERS_STRUCT_END(Instruction, 8); + +struct QuantizedSchema FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef QuantizedSchemaBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_QSCHEME = 4, + VT_SCALE = 6, + VT_ZERO_POINT = 8, + VT_SCALES = 10, + VT_ZERO_POINTS = 12, + VT_AXIS = 14 + }; + int8_t qscheme() const { + return GetField(VT_QSCHEME, 0); + } + bool mutate_qscheme(int8_t _qscheme = 0) { + return SetField(VT_QSCHEME, _qscheme, 0); + } + double scale() const { + return GetField(VT_SCALE, 0.0); + } + bool mutate_scale(double _scale = 0.0) { + return SetField(VT_SCALE, _scale, 0.0); + } + int32_t zero_point() const { + return GetField(VT_ZERO_POINT, 0); + } + bool mutate_zero_point(int32_t _zero_point = 0) { + return SetField(VT_ZERO_POINT, _zero_point, 0); + } + const torch::jit::mobile::serialization::TensorMetadata *scales() const { + return GetPointer(VT_SCALES); + } + torch::jit::mobile::serialization::TensorMetadata *mutable_scales() { + return GetPointer(VT_SCALES); + } + const torch::jit::mobile::serialization::TensorMetadata *zero_points() const { + return GetPointer(VT_ZERO_POINTS); + } + torch::jit::mobile::serialization::TensorMetadata *mutable_zero_points() { + return GetPointer(VT_ZERO_POINTS); + } + int32_t axis() const { + return GetField(VT_AXIS, 0); + } + bool mutate_axis(int32_t _axis = 0) { + return SetField(VT_AXIS, _axis, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_QSCHEME, 1) && + VerifyField(verifier, VT_SCALE, 8) && + VerifyField(verifier, VT_ZERO_POINT, 4) && + VerifyOffset(verifier, VT_SCALES) && + verifier.VerifyTable(scales()) && + VerifyOffset(verifier, VT_ZERO_POINTS) && + verifier.VerifyTable(zero_points()) && + VerifyField(verifier, VT_AXIS, 4) && + verifier.EndTable(); + } +}; + +struct QuantizedSchemaBuilder { + typedef QuantizedSchema Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_qscheme(int8_t qscheme) { + fbb_.AddElement(QuantizedSchema::VT_QSCHEME, qscheme, 0); + } + void add_scale(double scale) { + fbb_.AddElement(QuantizedSchema::VT_SCALE, scale, 0.0); + } + void add_zero_point(int32_t zero_point) { + fbb_.AddElement(QuantizedSchema::VT_ZERO_POINT, zero_point, 0); + } + void add_scales(::flatbuffers::Offset scales) { + fbb_.AddOffset(QuantizedSchema::VT_SCALES, scales); + } + void add_zero_points(::flatbuffers::Offset zero_points) { + fbb_.AddOffset(QuantizedSchema::VT_ZERO_POINTS, zero_points); + } + void add_axis(int32_t axis) { + fbb_.AddElement(QuantizedSchema::VT_AXIS, axis, 0); + } + explicit QuantizedSchemaBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateQuantizedSchema( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t qscheme = 0, + double scale = 0.0, + int32_t zero_point = 0, + ::flatbuffers::Offset scales = 0, + ::flatbuffers::Offset zero_points = 0, + int32_t axis = 0) { + QuantizedSchemaBuilder builder_(_fbb); + builder_.add_scale(scale); + builder_.add_axis(axis); + builder_.add_zero_points(zero_points); + builder_.add_scales(scales); + builder_.add_zero_point(zero_point); + builder_.add_qscheme(qscheme); + return builder_.Finish(); +} + +struct TensorMetadata FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TensorMetadataBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_STORAGE_LOCATION_INDEX = 4, + VT_SCALAR_TYPE = 6, + VT_STORAGE_OFFSET = 8, + VT_SIZES = 10, + VT_STRIDES = 12, + VT_REQUIRES_GRAD = 14, + VT_QUANTIZED_SCHEMA = 16 + }; + uint32_t storage_location_index() const { + return GetField(VT_STORAGE_LOCATION_INDEX, 0); + } + bool mutate_storage_location_index(uint32_t _storage_location_index = 0) { + return SetField(VT_STORAGE_LOCATION_INDEX, _storage_location_index, 0); + } + int8_t scalar_type() const { + return GetField(VT_SCALAR_TYPE, 0); + } + bool mutate_scalar_type(int8_t _scalar_type = 0) { + return SetField(VT_SCALAR_TYPE, _scalar_type, 0); + } + int32_t storage_offset() const { + return GetField(VT_STORAGE_OFFSET, 0); + } + bool mutate_storage_offset(int32_t _storage_offset = 0) { + return SetField(VT_STORAGE_OFFSET, _storage_offset, 0); + } + const ::flatbuffers::Vector *sizes() const { + return GetPointer *>(VT_SIZES); + } + ::flatbuffers::Vector *mutable_sizes() { + return GetPointer<::flatbuffers::Vector *>(VT_SIZES); + } + const ::flatbuffers::Vector *strides() const { + return GetPointer *>(VT_STRIDES); + } + ::flatbuffers::Vector *mutable_strides() { + return GetPointer<::flatbuffers::Vector *>(VT_STRIDES); + } + bool requires_grad() const { + return GetField(VT_REQUIRES_GRAD, 0) != 0; + } + bool mutate_requires_grad(bool _requires_grad = 0) { + return SetField(VT_REQUIRES_GRAD, static_cast(_requires_grad), 0); + } + const torch::jit::mobile::serialization::QuantizedSchema *quantized_schema() const { + return GetPointer(VT_QUANTIZED_SCHEMA); + } + torch::jit::mobile::serialization::QuantizedSchema *mutable_quantized_schema() { + return GetPointer(VT_QUANTIZED_SCHEMA); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_STORAGE_LOCATION_INDEX, 4) && + VerifyField(verifier, VT_SCALAR_TYPE, 1) && + VerifyField(verifier, VT_STORAGE_OFFSET, 4) && + VerifyOffset(verifier, VT_SIZES) && + verifier.VerifyVector(sizes()) && + VerifyOffset(verifier, VT_STRIDES) && + verifier.VerifyVector(strides()) && + VerifyField(verifier, VT_REQUIRES_GRAD, 1) && + VerifyOffset(verifier, VT_QUANTIZED_SCHEMA) && + verifier.VerifyTable(quantized_schema()) && + verifier.EndTable(); + } +}; + +struct TensorMetadataBuilder { + typedef TensorMetadata Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_storage_location_index(uint32_t storage_location_index) { + fbb_.AddElement(TensorMetadata::VT_STORAGE_LOCATION_INDEX, storage_location_index, 0); + } + void add_scalar_type(int8_t scalar_type) { + fbb_.AddElement(TensorMetadata::VT_SCALAR_TYPE, scalar_type, 0); + } + void add_storage_offset(int32_t storage_offset) { + fbb_.AddElement(TensorMetadata::VT_STORAGE_OFFSET, storage_offset, 0); + } + void add_sizes(::flatbuffers::Offset<::flatbuffers::Vector> sizes) { + fbb_.AddOffset(TensorMetadata::VT_SIZES, sizes); + } + void add_strides(::flatbuffers::Offset<::flatbuffers::Vector> strides) { + fbb_.AddOffset(TensorMetadata::VT_STRIDES, strides); + } + void add_requires_grad(bool requires_grad) { + fbb_.AddElement(TensorMetadata::VT_REQUIRES_GRAD, static_cast(requires_grad), 0); + } + void add_quantized_schema(::flatbuffers::Offset quantized_schema) { + fbb_.AddOffset(TensorMetadata::VT_QUANTIZED_SCHEMA, quantized_schema); + } + explicit TensorMetadataBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTensorMetadata( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t storage_location_index = 0, + int8_t scalar_type = 0, + int32_t storage_offset = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> sizes = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> strides = 0, + bool requires_grad = false, + ::flatbuffers::Offset quantized_schema = 0) { + TensorMetadataBuilder builder_(_fbb); + builder_.add_quantized_schema(quantized_schema); + builder_.add_strides(strides); + builder_.add_sizes(sizes); + builder_.add_storage_offset(storage_offset); + builder_.add_storage_location_index(storage_location_index); + builder_.add_requires_grad(requires_grad); + builder_.add_scalar_type(scalar_type); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTensorMetadataDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t storage_location_index = 0, + int8_t scalar_type = 0, + int32_t storage_offset = 0, + const std::vector *sizes = nullptr, + const std::vector *strides = nullptr, + bool requires_grad = false, + ::flatbuffers::Offset quantized_schema = 0) { + auto sizes__ = sizes ? _fbb.CreateVector(*sizes) : 0; + auto strides__ = strides ? _fbb.CreateVector(*strides) : 0; + return torch::jit::mobile::serialization::CreateTensorMetadata( + _fbb, + storage_location_index, + scalar_type, + storage_offset, + sizes__, + strides__, + requires_grad, + quantized_schema); +} + +struct String FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StringBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DATA = 4 + }; + const ::flatbuffers::String *data() const { + return GetPointer(VT_DATA); + } + ::flatbuffers::String *mutable_data() { + return GetPointer<::flatbuffers::String *>(VT_DATA); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DATA) && + verifier.VerifyString(data()) && + verifier.EndTable(); + } +}; + +struct StringBuilder { + typedef String Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_data(::flatbuffers::Offset<::flatbuffers::String> data) { + fbb_.AddOffset(String::VT_DATA, data); + } + explicit StringBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateString( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> data = 0) { + StringBuilder builder_(_fbb); + builder_.add_data(data); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStringDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *data = nullptr) { + auto data__ = data ? _fbb.CreateString(data) : 0; + return torch::jit::mobile::serialization::CreateString( + _fbb, + data__); +} + +struct Device FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DeviceBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_STR = 4 + }; + const ::flatbuffers::String *str() const { + return GetPointer(VT_STR); + } + ::flatbuffers::String *mutable_str() { + return GetPointer<::flatbuffers::String *>(VT_STR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_STR) && + verifier.VerifyString(str()) && + verifier.EndTable(); + } +}; + +struct DeviceBuilder { + typedef Device Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_str(::flatbuffers::Offset<::flatbuffers::String> str) { + fbb_.AddOffset(Device::VT_STR, str); + } + explicit DeviceBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateDevice( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> str = 0) { + DeviceBuilder builder_(_fbb); + builder_.add_str(str); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDeviceDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *str = nullptr) { + auto str__ = str ? _fbb.CreateString(str) : 0; + return torch::jit::mobile::serialization::CreateDevice( + _fbb, + str__); +} + +struct List FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ListBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4, + VT_ANNOTATION_STR = 6 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + const ::flatbuffers::String *annotation_str() const { + return GetPointer(VT_ANNOTATION_STR); + } + ::flatbuffers::String *mutable_annotation_str() { + return GetPointer<::flatbuffers::String *>(VT_ANNOTATION_STR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + VerifyOffset(verifier, VT_ANNOTATION_STR) && + verifier.VerifyString(annotation_str()) && + verifier.EndTable(); + } +}; + +struct ListBuilder { + typedef List Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(List::VT_ITEMS, items); + } + void add_annotation_str(::flatbuffers::Offset<::flatbuffers::String> annotation_str) { + fbb_.AddOffset(List::VT_ANNOTATION_STR, annotation_str); + } + explicit ListBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateList( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0, + ::flatbuffers::Offset<::flatbuffers::String> annotation_str = 0) { + ListBuilder builder_(_fbb); + builder_.add_annotation_str(annotation_str); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateListDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr, + const char *annotation_str = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + auto annotation_str__ = annotation_str ? _fbb.CreateString(annotation_str) : 0; + return torch::jit::mobile::serialization::CreateList( + _fbb, + items__, + annotation_str__); +} + +struct IntList FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef IntListBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + verifier.EndTable(); + } +}; + +struct IntListBuilder { + typedef IntList Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(IntList::VT_ITEMS, items); + } + explicit IntListBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateIntList( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0) { + IntListBuilder builder_(_fbb); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateIntListDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + return torch::jit::mobile::serialization::CreateIntList( + _fbb, + items__); +} + +struct DoubleList FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DoubleListBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + verifier.EndTable(); + } +}; + +struct DoubleListBuilder { + typedef DoubleList Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(DoubleList::VT_ITEMS, items); + } + explicit DoubleListBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateDoubleList( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0) { + DoubleListBuilder builder_(_fbb); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDoubleListDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + return torch::jit::mobile::serialization::CreateDoubleList( + _fbb, + items__); +} + +struct BoolList FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef BoolListBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + verifier.EndTable(); + } +}; + +struct BoolListBuilder { + typedef BoolList Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(BoolList::VT_ITEMS, items); + } + explicit BoolListBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateBoolList( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0) { + BoolListBuilder builder_(_fbb); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateBoolListDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + return torch::jit::mobile::serialization::CreateBoolList( + _fbb, + items__); +} + +struct Tuple FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TupleBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + verifier.EndTable(); + } +}; + +struct TupleBuilder { + typedef Tuple Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(Tuple::VT_ITEMS, items); + } + explicit TupleBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTuple( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0) { + TupleBuilder builder_(_fbb); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTupleDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + return torch::jit::mobile::serialization::CreateTuple( + _fbb, + items__); +} + +struct Dict FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DictBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_KEYS = 4, + VT_VALUES = 6, + VT_ANNOTATION_STR = 8 + }; + const ::flatbuffers::Vector *keys() const { + return GetPointer *>(VT_KEYS); + } + ::flatbuffers::Vector *mutable_keys() { + return GetPointer<::flatbuffers::Vector *>(VT_KEYS); + } + const ::flatbuffers::Vector *values() const { + return GetPointer *>(VT_VALUES); + } + ::flatbuffers::Vector *mutable_values() { + return GetPointer<::flatbuffers::Vector *>(VT_VALUES); + } + const ::flatbuffers::String *annotation_str() const { + return GetPointer(VT_ANNOTATION_STR); + } + ::flatbuffers::String *mutable_annotation_str() { + return GetPointer<::flatbuffers::String *>(VT_ANNOTATION_STR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_KEYS) && + verifier.VerifyVector(keys()) && + VerifyOffset(verifier, VT_VALUES) && + verifier.VerifyVector(values()) && + VerifyOffset(verifier, VT_ANNOTATION_STR) && + verifier.VerifyString(annotation_str()) && + verifier.EndTable(); + } +}; + +struct DictBuilder { + typedef Dict Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_keys(::flatbuffers::Offset<::flatbuffers::Vector> keys) { + fbb_.AddOffset(Dict::VT_KEYS, keys); + } + void add_values(::flatbuffers::Offset<::flatbuffers::Vector> values) { + fbb_.AddOffset(Dict::VT_VALUES, values); + } + void add_annotation_str(::flatbuffers::Offset<::flatbuffers::String> annotation_str) { + fbb_.AddOffset(Dict::VT_ANNOTATION_STR, annotation_str); + } + explicit DictBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateDict( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> keys = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> values = 0, + ::flatbuffers::Offset<::flatbuffers::String> annotation_str = 0) { + DictBuilder builder_(_fbb); + builder_.add_annotation_str(annotation_str); + builder_.add_values(values); + builder_.add_keys(keys); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDictDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *keys = nullptr, + const std::vector *values = nullptr, + const char *annotation_str = nullptr) { + auto keys__ = keys ? _fbb.CreateVector(*keys) : 0; + auto values__ = values ? _fbb.CreateVector(*values) : 0; + auto annotation_str__ = annotation_str ? _fbb.CreateString(annotation_str) : 0; + return torch::jit::mobile::serialization::CreateDict( + _fbb, + keys__, + values__, + annotation_str__); +} + +struct ObjectType FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ObjectTypeBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_TYPE_NAME = 4, + VT_TYPE = 6, + VT_ATTR_NAMES = 8 + }; + const ::flatbuffers::String *type_name() const { + return GetPointer(VT_TYPE_NAME); + } + ::flatbuffers::String *mutable_type_name() { + return GetPointer<::flatbuffers::String *>(VT_TYPE_NAME); + } + torch::jit::mobile::serialization::TypeType type() const { + return static_cast(GetField(VT_TYPE, 0)); + } + bool mutate_type(torch::jit::mobile::serialization::TypeType _type = static_cast(0)) { + return SetField(VT_TYPE, static_cast(_type), 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *attr_names() const { + return GetPointer> *>(VT_ATTR_NAMES); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_attr_names() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_ATTR_NAMES); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_TYPE_NAME) && + verifier.VerifyString(type_name()) && + VerifyField(verifier, VT_TYPE, 1) && + VerifyOffset(verifier, VT_ATTR_NAMES) && + verifier.VerifyVector(attr_names()) && + verifier.VerifyVectorOfStrings(attr_names()) && + verifier.EndTable(); + } +}; + +struct ObjectTypeBuilder { + typedef ObjectType Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_type_name(::flatbuffers::Offset<::flatbuffers::String> type_name) { + fbb_.AddOffset(ObjectType::VT_TYPE_NAME, type_name); + } + void add_type(torch::jit::mobile::serialization::TypeType type) { + fbb_.AddElement(ObjectType::VT_TYPE, static_cast(type), 0); + } + void add_attr_names(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> attr_names) { + fbb_.AddOffset(ObjectType::VT_ATTR_NAMES, attr_names); + } + explicit ObjectTypeBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateObjectType( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> type_name = 0, + torch::jit::mobile::serialization::TypeType type = torch::jit::mobile::serialization::TypeType::UNSET, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> attr_names = 0) { + ObjectTypeBuilder builder_(_fbb); + builder_.add_attr_names(attr_names); + builder_.add_type_name(type_name); + builder_.add_type(type); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateObjectTypeDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *type_name = nullptr, + torch::jit::mobile::serialization::TypeType type = torch::jit::mobile::serialization::TypeType::UNSET, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *attr_names = nullptr) { + auto type_name__ = type_name ? _fbb.CreateString(type_name) : 0; + auto attr_names__ = attr_names ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*attr_names) : 0; + return torch::jit::mobile::serialization::CreateObjectType( + _fbb, + type_name__, + type, + attr_names__); +} + +struct Object FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ObjectBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_TYPE_INDEX = 4, + VT_STATE = 6, + VT_ATTRS = 8, + VT_SETSTATE_FUNC = 10 + }; + uint32_t type_index() const { + return GetField(VT_TYPE_INDEX, 0); + } + bool mutate_type_index(uint32_t _type_index = 0) { + return SetField(VT_TYPE_INDEX, _type_index, 0); + } + uint32_t state() const { + return GetField(VT_STATE, 0); + } + bool mutate_state(uint32_t _state = 0) { + return SetField(VT_STATE, _state, 0); + } + const ::flatbuffers::Vector *attrs() const { + return GetPointer *>(VT_ATTRS); + } + ::flatbuffers::Vector *mutable_attrs() { + return GetPointer<::flatbuffers::Vector *>(VT_ATTRS); + } + uint32_t setstate_func() const { + return GetField(VT_SETSTATE_FUNC, 0); + } + bool mutate_setstate_func(uint32_t _setstate_func = 0) { + return SetField(VT_SETSTATE_FUNC, _setstate_func, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_TYPE_INDEX, 4) && + VerifyField(verifier, VT_STATE, 4) && + VerifyOffset(verifier, VT_ATTRS) && + verifier.VerifyVector(attrs()) && + VerifyField(verifier, VT_SETSTATE_FUNC, 4) && + verifier.EndTable(); + } +}; + +struct ObjectBuilder { + typedef Object Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_type_index(uint32_t type_index) { + fbb_.AddElement(Object::VT_TYPE_INDEX, type_index, 0); + } + void add_state(uint32_t state) { + fbb_.AddElement(Object::VT_STATE, state, 0); + } + void add_attrs(::flatbuffers::Offset<::flatbuffers::Vector> attrs) { + fbb_.AddOffset(Object::VT_ATTRS, attrs); + } + void add_setstate_func(uint32_t setstate_func) { + fbb_.AddElement(Object::VT_SETSTATE_FUNC, setstate_func, 0); + } + explicit ObjectBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateObject( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t type_index = 0, + uint32_t state = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> attrs = 0, + uint32_t setstate_func = 0) { + ObjectBuilder builder_(_fbb); + builder_.add_setstate_func(setstate_func); + builder_.add_attrs(attrs); + builder_.add_state(state); + builder_.add_type_index(type_index); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateObjectDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t type_index = 0, + uint32_t state = 0, + const std::vector *attrs = nullptr, + uint32_t setstate_func = 0) { + auto attrs__ = attrs ? _fbb.CreateVector(*attrs) : 0; + return torch::jit::mobile::serialization::CreateObject( + _fbb, + type_index, + state, + attrs__, + setstate_func); +} + +struct EnumValue FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef EnumValueBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_TYPE_NAME = 4, + VT_VALUE = 6 + }; + const ::flatbuffers::String *type_name() const { + return GetPointer(VT_TYPE_NAME); + } + ::flatbuffers::String *mutable_type_name() { + return GetPointer<::flatbuffers::String *>(VT_TYPE_NAME); + } + uint32_t value() const { + return GetField(VT_VALUE, 0); + } + bool mutate_value(uint32_t _value = 0) { + return SetField(VT_VALUE, _value, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_TYPE_NAME) && + verifier.VerifyString(type_name()) && + VerifyField(verifier, VT_VALUE, 4) && + verifier.EndTable(); + } +}; + +struct EnumValueBuilder { + typedef EnumValue Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_type_name(::flatbuffers::Offset<::flatbuffers::String> type_name) { + fbb_.AddOffset(EnumValue::VT_TYPE_NAME, type_name); + } + void add_value(uint32_t value) { + fbb_.AddElement(EnumValue::VT_VALUE, value, 0); + } + explicit EnumValueBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateEnumValue( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> type_name = 0, + uint32_t value = 0) { + EnumValueBuilder builder_(_fbb); + builder_.add_value(value); + builder_.add_type_name(type_name); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateEnumValueDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *type_name = nullptr, + uint32_t value = 0) { + auto type_name__ = type_name ? _fbb.CreateString(type_name) : 0; + return torch::jit::mobile::serialization::CreateEnumValue( + _fbb, + type_name__, + value); +} + +struct Operator FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef OperatorBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_NAME = 4, + VT_OVERLOAD_NAME = 6, + VT_NUM_ARGS_SERIALIZED = 8 + }; + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + const ::flatbuffers::String *overload_name() const { + return GetPointer(VT_OVERLOAD_NAME); + } + ::flatbuffers::String *mutable_overload_name() { + return GetPointer<::flatbuffers::String *>(VT_OVERLOAD_NAME); + } + int32_t num_args_serialized() const { + return GetField(VT_NUM_ARGS_SERIALIZED, -1); + } + bool mutate_num_args_serialized(int32_t _num_args_serialized = -1) { + return SetField(VT_NUM_ARGS_SERIALIZED, _num_args_serialized, -1); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_OVERLOAD_NAME) && + verifier.VerifyString(overload_name()) && + VerifyField(verifier, VT_NUM_ARGS_SERIALIZED, 4) && + verifier.EndTable(); + } +}; + +struct OperatorBuilder { + typedef Operator Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Operator::VT_NAME, name); + } + void add_overload_name(::flatbuffers::Offset<::flatbuffers::String> overload_name) { + fbb_.AddOffset(Operator::VT_OVERLOAD_NAME, overload_name); + } + void add_num_args_serialized(int32_t num_args_serialized) { + fbb_.AddElement(Operator::VT_NUM_ARGS_SERIALIZED, num_args_serialized, -1); + } + explicit OperatorBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateOperator( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> overload_name = 0, + int32_t num_args_serialized = -1) { + OperatorBuilder builder_(_fbb); + builder_.add_num_args_serialized(num_args_serialized); + builder_.add_overload_name(overload_name); + builder_.add_name(name); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateOperatorDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *name = nullptr, + const char *overload_name = nullptr, + int32_t num_args_serialized = -1) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto overload_name__ = overload_name ? _fbb.CreateString(overload_name) : 0; + return torch::jit::mobile::serialization::CreateOperator( + _fbb, + name__, + overload_name__, + num_args_serialized); +} + +struct Arg FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ArgBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_NAME = 4, + VT_TYPE = 6, + VT_DEFAULT_VALUE = 8 + }; + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + const ::flatbuffers::String *type() const { + return GetPointer(VT_TYPE); + } + ::flatbuffers::String *mutable_type() { + return GetPointer<::flatbuffers::String *>(VT_TYPE); + } + uint32_t default_value() const { + return GetField(VT_DEFAULT_VALUE, 0); + } + bool mutate_default_value(uint32_t _default_value = 0) { + return SetField(VT_DEFAULT_VALUE, _default_value, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_TYPE) && + verifier.VerifyString(type()) && + VerifyField(verifier, VT_DEFAULT_VALUE, 4) && + verifier.EndTable(); + } +}; + +struct ArgBuilder { + typedef Arg Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Arg::VT_NAME, name); + } + void add_type(::flatbuffers::Offset<::flatbuffers::String> type) { + fbb_.AddOffset(Arg::VT_TYPE, type); + } + void add_default_value(uint32_t default_value) { + fbb_.AddElement(Arg::VT_DEFAULT_VALUE, default_value, 0); + } + explicit ArgBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateArg( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> type = 0, + uint32_t default_value = 0) { + ArgBuilder builder_(_fbb); + builder_.add_default_value(default_value); + builder_.add_type(type); + builder_.add_name(name); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateArgDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *name = nullptr, + const char *type = nullptr, + uint32_t default_value = 0) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto type__ = type ? _fbb.CreateString(type) : 0; + return torch::jit::mobile::serialization::CreateArg( + _fbb, + name__, + type__, + default_value); +} + +struct Schema FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef SchemaBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ARGUMENTS = 4, + VT_RETURNS = 6 + }; + const ::flatbuffers::Vector<::flatbuffers::Offset> *arguments() const { + return GetPointer> *>(VT_ARGUMENTS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_arguments() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_ARGUMENTS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *returns() const { + return GetPointer> *>(VT_RETURNS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_returns() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_RETURNS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ARGUMENTS) && + verifier.VerifyVector(arguments()) && + verifier.VerifyVectorOfTables(arguments()) && + VerifyOffset(verifier, VT_RETURNS) && + verifier.VerifyVector(returns()) && + verifier.VerifyVectorOfTables(returns()) && + verifier.EndTable(); + } +}; + +struct SchemaBuilder { + typedef Schema Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_arguments(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> arguments) { + fbb_.AddOffset(Schema::VT_ARGUMENTS, arguments); + } + void add_returns(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> returns) { + fbb_.AddOffset(Schema::VT_RETURNS, returns); + } + explicit SchemaBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateSchema( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> arguments = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> returns = 0) { + SchemaBuilder builder_(_fbb); + builder_.add_returns(returns); + builder_.add_arguments(arguments); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateSchemaDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector<::flatbuffers::Offset> *arguments = nullptr, + const std::vector<::flatbuffers::Offset> *returns = nullptr) { + auto arguments__ = arguments ? _fbb.CreateVector<::flatbuffers::Offset>(*arguments) : 0; + auto returns__ = returns ? _fbb.CreateVector<::flatbuffers::Offset>(*returns) : 0; + return torch::jit::mobile::serialization::CreateSchema( + _fbb, + arguments__, + returns__); +} + +struct DebugInfo FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DebugInfoBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DEBUG_HANDLE = 4 + }; + const ::flatbuffers::Vector *debug_handle() const { + return GetPointer *>(VT_DEBUG_HANDLE); + } + ::flatbuffers::Vector *mutable_debug_handle() { + return GetPointer<::flatbuffers::Vector *>(VT_DEBUG_HANDLE); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DEBUG_HANDLE) && + verifier.VerifyVector(debug_handle()) && + verifier.EndTable(); + } +}; + +struct DebugInfoBuilder { + typedef DebugInfo Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_debug_handle(::flatbuffers::Offset<::flatbuffers::Vector> debug_handle) { + fbb_.AddOffset(DebugInfo::VT_DEBUG_HANDLE, debug_handle); + } + explicit DebugInfoBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateDebugInfo( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> debug_handle = 0) { + DebugInfoBuilder builder_(_fbb); + builder_.add_debug_handle(debug_handle); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDebugInfoDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *debug_handle = nullptr) { + auto debug_handle__ = debug_handle ? _fbb.CreateVector(*debug_handle) : 0; + return torch::jit::mobile::serialization::CreateDebugInfo( + _fbb, + debug_handle__); +} + +struct Function FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef FunctionBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_QN = 4, + VT_INSTRUCTIONS = 6, + VT_OPERATORS = 8, + VT_CONSTANTS = 10, + VT_TYPE_ANNOTATIONS = 12, + VT_REGISTER_SIZE = 14, + VT_SCHEMA = 16, + VT_DEBUG_INFO = 18, + VT_CLASS_TYPE = 20 + }; + const ::flatbuffers::String *qn() const { + return GetPointer(VT_QN); + } + ::flatbuffers::String *mutable_qn() { + return GetPointer<::flatbuffers::String *>(VT_QN); + } + const ::flatbuffers::Vector *instructions() const { + return GetPointer *>(VT_INSTRUCTIONS); + } + ::flatbuffers::Vector *mutable_instructions() { + return GetPointer<::flatbuffers::Vector *>(VT_INSTRUCTIONS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *operators() const { + return GetPointer> *>(VT_OPERATORS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_operators() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_OPERATORS); + } + const ::flatbuffers::Vector *constants() const { + return GetPointer *>(VT_CONSTANTS); + } + ::flatbuffers::Vector *mutable_constants() { + return GetPointer<::flatbuffers::Vector *>(VT_CONSTANTS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *type_annotations() const { + return GetPointer> *>(VT_TYPE_ANNOTATIONS); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_type_annotations() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TYPE_ANNOTATIONS); + } + int32_t register_size() const { + return GetField(VT_REGISTER_SIZE, 0); + } + bool mutate_register_size(int32_t _register_size = 0) { + return SetField(VT_REGISTER_SIZE, _register_size, 0); + } + const torch::jit::mobile::serialization::Schema *schema() const { + return GetPointer(VT_SCHEMA); + } + torch::jit::mobile::serialization::Schema *mutable_schema() { + return GetPointer(VT_SCHEMA); + } + const torch::jit::mobile::serialization::DebugInfo *debug_info() const { + return GetPointer(VT_DEBUG_INFO); + } + torch::jit::mobile::serialization::DebugInfo *mutable_debug_info() { + return GetPointer(VT_DEBUG_INFO); + } + uint32_t class_type() const { + return GetField(VT_CLASS_TYPE, 0); + } + bool mutate_class_type(uint32_t _class_type = 0) { + return SetField(VT_CLASS_TYPE, _class_type, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_QN) && + verifier.VerifyString(qn()) && + VerifyOffset(verifier, VT_INSTRUCTIONS) && + verifier.VerifyVector(instructions()) && + VerifyOffset(verifier, VT_OPERATORS) && + verifier.VerifyVector(operators()) && + verifier.VerifyVectorOfTables(operators()) && + VerifyOffset(verifier, VT_CONSTANTS) && + verifier.VerifyVector(constants()) && + VerifyOffset(verifier, VT_TYPE_ANNOTATIONS) && + verifier.VerifyVector(type_annotations()) && + verifier.VerifyVectorOfStrings(type_annotations()) && + VerifyField(verifier, VT_REGISTER_SIZE, 4) && + VerifyOffset(verifier, VT_SCHEMA) && + verifier.VerifyTable(schema()) && + VerifyOffset(verifier, VT_DEBUG_INFO) && + verifier.VerifyTable(debug_info()) && + VerifyField(verifier, VT_CLASS_TYPE, 4) && + verifier.EndTable(); + } +}; + +struct FunctionBuilder { + typedef Function Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_qn(::flatbuffers::Offset<::flatbuffers::String> qn) { + fbb_.AddOffset(Function::VT_QN, qn); + } + void add_instructions(::flatbuffers::Offset<::flatbuffers::Vector> instructions) { + fbb_.AddOffset(Function::VT_INSTRUCTIONS, instructions); + } + void add_operators(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> operators) { + fbb_.AddOffset(Function::VT_OPERATORS, operators); + } + void add_constants(::flatbuffers::Offset<::flatbuffers::Vector> constants) { + fbb_.AddOffset(Function::VT_CONSTANTS, constants); + } + void add_type_annotations(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> type_annotations) { + fbb_.AddOffset(Function::VT_TYPE_ANNOTATIONS, type_annotations); + } + void add_register_size(int32_t register_size) { + fbb_.AddElement(Function::VT_REGISTER_SIZE, register_size, 0); + } + void add_schema(::flatbuffers::Offset schema) { + fbb_.AddOffset(Function::VT_SCHEMA, schema); + } + void add_debug_info(::flatbuffers::Offset debug_info) { + fbb_.AddOffset(Function::VT_DEBUG_INFO, debug_info); + } + void add_class_type(uint32_t class_type) { + fbb_.AddElement(Function::VT_CLASS_TYPE, class_type, 0); + } + explicit FunctionBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateFunction( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> qn = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> instructions = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> operators = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> constants = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> type_annotations = 0, + int32_t register_size = 0, + ::flatbuffers::Offset schema = 0, + ::flatbuffers::Offset debug_info = 0, + uint32_t class_type = 0) { + FunctionBuilder builder_(_fbb); + builder_.add_class_type(class_type); + builder_.add_debug_info(debug_info); + builder_.add_schema(schema); + builder_.add_register_size(register_size); + builder_.add_type_annotations(type_annotations); + builder_.add_constants(constants); + builder_.add_operators(operators); + builder_.add_instructions(instructions); + builder_.add_qn(qn); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateFunctionDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *qn = nullptr, + const std::vector *instructions = nullptr, + const std::vector<::flatbuffers::Offset> *operators = nullptr, + const std::vector *constants = nullptr, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *type_annotations = nullptr, + int32_t register_size = 0, + ::flatbuffers::Offset schema = 0, + ::flatbuffers::Offset debug_info = 0, + uint32_t class_type = 0) { + auto qn__ = qn ? _fbb.CreateString(qn) : 0; + auto instructions__ = instructions ? _fbb.CreateVectorOfStructs(*instructions) : 0; + auto operators__ = operators ? _fbb.CreateVector<::flatbuffers::Offset>(*operators) : 0; + auto constants__ = constants ? _fbb.CreateVector(*constants) : 0; + auto type_annotations__ = type_annotations ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*type_annotations) : 0; + return torch::jit::mobile::serialization::CreateFunction( + _fbb, + qn__, + instructions__, + operators__, + constants__, + type_annotations__, + register_size, + schema, + debug_info, + class_type); +} + +struct StorageData FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StorageDataBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DATA = 4 + }; + const ::flatbuffers::Vector *data() const { + return GetPointer *>(VT_DATA); + } + ::flatbuffers::Vector *mutable_data() { + return GetPointer<::flatbuffers::Vector *>(VT_DATA); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DATA) && + verifier.VerifyVector(data()) && + verifier.EndTable(); + } +}; + +struct StorageDataBuilder { + typedef StorageData Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_data(::flatbuffers::Offset<::flatbuffers::Vector> data) { + fbb_.AddOffset(StorageData::VT_DATA, data); + } + explicit StorageDataBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStorageData( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> data = 0) { + StorageDataBuilder builder_(_fbb); + builder_.add_data(data); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStorageDataDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *data = nullptr) { + if (data) { _fbb.ForceVectorAlignment(data->size(), sizeof(uint8_t), 16); } + auto data__ = data ? _fbb.CreateVector(*data) : 0; + return torch::jit::mobile::serialization::CreateStorageData( + _fbb, + data__); +} + +struct IValue FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef IValueBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_VAL_TYPE = 4, + VT_VAL = 6 + }; + torch::jit::mobile::serialization::IValueUnion val_type() const { + return static_cast(GetField(VT_VAL_TYPE, 0)); + } + const void *val() const { + return GetPointer(VT_VAL); + } + template const T *val_as() const; + const torch::jit::mobile::serialization::Int *val_as_Int() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Int ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Bool *val_as_Bool() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Bool ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Double *val_as_Double() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Double ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::ComplexDouble *val_as_ComplexDouble() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::ComplexDouble ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::TensorMetadata *val_as_TensorMetadata() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::TensorMetadata ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::String *val_as_String() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::String ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::List *val_as_List() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::List ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Tuple *val_as_Tuple() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Tuple ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Dict *val_as_Dict() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Dict ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Object *val_as_Object() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Object ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::IntList *val_as_IntList() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::IntList ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::DoubleList *val_as_DoubleList() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::DoubleList ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::BoolList *val_as_BoolList() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::BoolList ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Device *val_as_Device() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Device ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::EnumValue *val_as_EnumValue() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::EnumValue ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Function *val_as_Function() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Function ? static_cast(val()) : nullptr; + } + void *mutable_val() { + return GetPointer(VT_VAL); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_VAL_TYPE, 1) && + VerifyOffset(verifier, VT_VAL) && + VerifyIValueUnion(verifier, val(), val_type()) && + verifier.EndTable(); + } +}; + +template<> inline const torch::jit::mobile::serialization::Int *IValue::val_as() const { + return val_as_Int(); +} + +template<> inline const torch::jit::mobile::serialization::Bool *IValue::val_as() const { + return val_as_Bool(); +} + +template<> inline const torch::jit::mobile::serialization::Double *IValue::val_as() const { + return val_as_Double(); +} + +template<> inline const torch::jit::mobile::serialization::ComplexDouble *IValue::val_as() const { + return val_as_ComplexDouble(); +} + +template<> inline const torch::jit::mobile::serialization::TensorMetadata *IValue::val_as() const { + return val_as_TensorMetadata(); +} + +template<> inline const torch::jit::mobile::serialization::String *IValue::val_as() const { + return val_as_String(); +} + +template<> inline const torch::jit::mobile::serialization::List *IValue::val_as() const { + return val_as_List(); +} + +template<> inline const torch::jit::mobile::serialization::Tuple *IValue::val_as() const { + return val_as_Tuple(); +} + +template<> inline const torch::jit::mobile::serialization::Dict *IValue::val_as() const { + return val_as_Dict(); +} + +template<> inline const torch::jit::mobile::serialization::Object *IValue::val_as() const { + return val_as_Object(); +} + +template<> inline const torch::jit::mobile::serialization::IntList *IValue::val_as() const { + return val_as_IntList(); +} + +template<> inline const torch::jit::mobile::serialization::DoubleList *IValue::val_as() const { + return val_as_DoubleList(); +} + +template<> inline const torch::jit::mobile::serialization::BoolList *IValue::val_as() const { + return val_as_BoolList(); +} + +template<> inline const torch::jit::mobile::serialization::Device *IValue::val_as() const { + return val_as_Device(); +} + +template<> inline const torch::jit::mobile::serialization::EnumValue *IValue::val_as() const { + return val_as_EnumValue(); +} + +template<> inline const torch::jit::mobile::serialization::Function *IValue::val_as() const { + return val_as_Function(); +} + +struct IValueBuilder { + typedef IValue Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_val_type(torch::jit::mobile::serialization::IValueUnion val_type) { + fbb_.AddElement(IValue::VT_VAL_TYPE, static_cast(val_type), 0); + } + void add_val(::flatbuffers::Offset val) { + fbb_.AddOffset(IValue::VT_VAL, val); + } + explicit IValueBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateIValue( + ::flatbuffers::FlatBufferBuilder &_fbb, + torch::jit::mobile::serialization::IValueUnion val_type = torch::jit::mobile::serialization::IValueUnion::NONE, + ::flatbuffers::Offset val = 0) { + IValueBuilder builder_(_fbb); + builder_.add_val(val); + builder_.add_val_type(val_type); + return builder_.Finish(); +} + +struct ExtraFile FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ExtraFileBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_NAME = 4, + VT_CONTENT = 6 + }; + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + const ::flatbuffers::String *content() const { + return GetPointer(VT_CONTENT); + } + ::flatbuffers::String *mutable_content() { + return GetPointer<::flatbuffers::String *>(VT_CONTENT); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_CONTENT) && + verifier.VerifyString(content()) && + verifier.EndTable(); + } +}; + +struct ExtraFileBuilder { + typedef ExtraFile Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(ExtraFile::VT_NAME, name); + } + void add_content(::flatbuffers::Offset<::flatbuffers::String> content) { + fbb_.AddOffset(ExtraFile::VT_CONTENT, content); + } + explicit ExtraFileBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateExtraFile( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> content = 0) { + ExtraFileBuilder builder_(_fbb); + builder_.add_content(content); + builder_.add_name(name); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateExtraFileDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *name = nullptr, + const char *content = nullptr) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto content__ = content ? _fbb.CreateString(content) : 0; + return torch::jit::mobile::serialization::CreateExtraFile( + _fbb, + name__, + content__); +} + +struct Module FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ModuleBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_BYTECODE_VERSION = 4, + VT_EXTRA_FILES = 6, + VT_METHODS = 8, + VT_STATE_OBJ = 10, + VT_IVALUES = 12, + VT_STORAGE_DATA_SIZE = 14, + VT_STORAGE_DATA = 16, + VT_OBJECT_TYPES = 18, + VT_JIT_SOURCES = 20, + VT_JIT_CONSTANTS = 22, + VT_OPERATOR_VERSION = 24, + VT_MOBILE_IVALUE_SIZE = 26 + }; + uint32_t bytecode_version() const { + return GetField(VT_BYTECODE_VERSION, 0); + } + bool mutate_bytecode_version(uint32_t _bytecode_version = 0) { + return SetField(VT_BYTECODE_VERSION, _bytecode_version, 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *extra_files() const { + return GetPointer> *>(VT_EXTRA_FILES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_extra_files() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_EXTRA_FILES); + } + const ::flatbuffers::Vector *methods() const { + return GetPointer *>(VT_METHODS); + } + ::flatbuffers::Vector *mutable_methods() { + return GetPointer<::flatbuffers::Vector *>(VT_METHODS); + } + uint32_t state_obj() const { + return GetField(VT_STATE_OBJ, 0); + } + bool mutate_state_obj(uint32_t _state_obj = 0) { + return SetField(VT_STATE_OBJ, _state_obj, 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *ivalues() const { + return GetPointer> *>(VT_IVALUES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_ivalues() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_IVALUES); + } + int32_t storage_data_size() const { + return GetField(VT_STORAGE_DATA_SIZE, 0); + } + bool mutate_storage_data_size(int32_t _storage_data_size = 0) { + return SetField(VT_STORAGE_DATA_SIZE, _storage_data_size, 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *storage_data() const { + return GetPointer> *>(VT_STORAGE_DATA); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_storage_data() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_STORAGE_DATA); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *object_types() const { + return GetPointer> *>(VT_OBJECT_TYPES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_object_types() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_OBJECT_TYPES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *jit_sources() const { + return GetPointer> *>(VT_JIT_SOURCES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_jit_sources() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_JIT_SOURCES); + } + const ::flatbuffers::Vector *jit_constants() const { + return GetPointer *>(VT_JIT_CONSTANTS); + } + ::flatbuffers::Vector *mutable_jit_constants() { + return GetPointer<::flatbuffers::Vector *>(VT_JIT_CONSTANTS); + } + uint32_t operator_version() const { + return GetField(VT_OPERATOR_VERSION, 0); + } + bool mutate_operator_version(uint32_t _operator_version = 0) { + return SetField(VT_OPERATOR_VERSION, _operator_version, 0); + } + uint32_t mobile_ivalue_size() const { + return GetField(VT_MOBILE_IVALUE_SIZE, 0); + } + bool mutate_mobile_ivalue_size(uint32_t _mobile_ivalue_size = 0) { + return SetField(VT_MOBILE_IVALUE_SIZE, _mobile_ivalue_size, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_BYTECODE_VERSION, 4) && + VerifyOffset(verifier, VT_EXTRA_FILES) && + verifier.VerifyVector(extra_files()) && + verifier.VerifyVectorOfTables(extra_files()) && + VerifyOffset(verifier, VT_METHODS) && + verifier.VerifyVector(methods()) && + VerifyField(verifier, VT_STATE_OBJ, 4) && + VerifyOffset(verifier, VT_IVALUES) && + verifier.VerifyVector(ivalues()) && + verifier.VerifyVectorOfTables(ivalues()) && + VerifyField(verifier, VT_STORAGE_DATA_SIZE, 4) && + VerifyOffset(verifier, VT_STORAGE_DATA) && + verifier.VerifyVector(storage_data()) && + verifier.VerifyVectorOfTables(storage_data()) && + VerifyOffset(verifier, VT_OBJECT_TYPES) && + verifier.VerifyVector(object_types()) && + verifier.VerifyVectorOfTables(object_types()) && + VerifyOffset(verifier, VT_JIT_SOURCES) && + verifier.VerifyVector(jit_sources()) && + verifier.VerifyVectorOfTables(jit_sources()) && + VerifyOffset(verifier, VT_JIT_CONSTANTS) && + verifier.VerifyVector(jit_constants()) && + VerifyField(verifier, VT_OPERATOR_VERSION, 4) && + VerifyField(verifier, VT_MOBILE_IVALUE_SIZE, 4) && + verifier.EndTable(); + } +}; + +struct ModuleBuilder { + typedef Module Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_bytecode_version(uint32_t bytecode_version) { + fbb_.AddElement(Module::VT_BYTECODE_VERSION, bytecode_version, 0); + } + void add_extra_files(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> extra_files) { + fbb_.AddOffset(Module::VT_EXTRA_FILES, extra_files); + } + void add_methods(::flatbuffers::Offset<::flatbuffers::Vector> methods) { + fbb_.AddOffset(Module::VT_METHODS, methods); + } + void add_state_obj(uint32_t state_obj) { + fbb_.AddElement(Module::VT_STATE_OBJ, state_obj, 0); + } + void add_ivalues(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> ivalues) { + fbb_.AddOffset(Module::VT_IVALUES, ivalues); + } + void add_storage_data_size(int32_t storage_data_size) { + fbb_.AddElement(Module::VT_STORAGE_DATA_SIZE, storage_data_size, 0); + } + void add_storage_data(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> storage_data) { + fbb_.AddOffset(Module::VT_STORAGE_DATA, storage_data); + } + void add_object_types(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> object_types) { + fbb_.AddOffset(Module::VT_OBJECT_TYPES, object_types); + } + void add_jit_sources(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> jit_sources) { + fbb_.AddOffset(Module::VT_JIT_SOURCES, jit_sources); + } + void add_jit_constants(::flatbuffers::Offset<::flatbuffers::Vector> jit_constants) { + fbb_.AddOffset(Module::VT_JIT_CONSTANTS, jit_constants); + } + void add_operator_version(uint32_t operator_version) { + fbb_.AddElement(Module::VT_OPERATOR_VERSION, operator_version, 0); + } + void add_mobile_ivalue_size(uint32_t mobile_ivalue_size) { + fbb_.AddElement(Module::VT_MOBILE_IVALUE_SIZE, mobile_ivalue_size, 0); + } + explicit ModuleBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateModule( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t bytecode_version = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> extra_files = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> methods = 0, + uint32_t state_obj = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> ivalues = 0, + int32_t storage_data_size = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> storage_data = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> object_types = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> jit_sources = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> jit_constants = 0, + uint32_t operator_version = 0, + uint32_t mobile_ivalue_size = 0) { + ModuleBuilder builder_(_fbb); + builder_.add_mobile_ivalue_size(mobile_ivalue_size); + builder_.add_operator_version(operator_version); + builder_.add_jit_constants(jit_constants); + builder_.add_jit_sources(jit_sources); + builder_.add_object_types(object_types); + builder_.add_storage_data(storage_data); + builder_.add_storage_data_size(storage_data_size); + builder_.add_ivalues(ivalues); + builder_.add_state_obj(state_obj); + builder_.add_methods(methods); + builder_.add_extra_files(extra_files); + builder_.add_bytecode_version(bytecode_version); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateModuleDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t bytecode_version = 0, + const std::vector<::flatbuffers::Offset> *extra_files = nullptr, + const std::vector *methods = nullptr, + uint32_t state_obj = 0, + const std::vector<::flatbuffers::Offset> *ivalues = nullptr, + int32_t storage_data_size = 0, + const std::vector<::flatbuffers::Offset> *storage_data = nullptr, + const std::vector<::flatbuffers::Offset> *object_types = nullptr, + const std::vector<::flatbuffers::Offset> *jit_sources = nullptr, + const std::vector *jit_constants = nullptr, + uint32_t operator_version = 0, + uint32_t mobile_ivalue_size = 0) { + auto extra_files__ = extra_files ? _fbb.CreateVector<::flatbuffers::Offset>(*extra_files) : 0; + auto methods__ = methods ? _fbb.CreateVector(*methods) : 0; + auto ivalues__ = ivalues ? _fbb.CreateVector<::flatbuffers::Offset>(*ivalues) : 0; + auto storage_data__ = storage_data ? _fbb.CreateVector<::flatbuffers::Offset>(*storage_data) : 0; + auto object_types__ = object_types ? _fbb.CreateVector<::flatbuffers::Offset>(*object_types) : 0; + auto jit_sources__ = jit_sources ? _fbb.CreateVector<::flatbuffers::Offset>(*jit_sources) : 0; + auto jit_constants__ = jit_constants ? _fbb.CreateVector(*jit_constants) : 0; + return torch::jit::mobile::serialization::CreateModule( + _fbb, + bytecode_version, + extra_files__, + methods__, + state_obj, + ivalues__, + storage_data_size, + storage_data__, + object_types__, + jit_sources__, + jit_constants__, + operator_version, + mobile_ivalue_size); +} + +inline bool VerifyIValueUnion(::flatbuffers::Verifier &verifier, const void *obj, IValueUnion type) { + switch (type) { + case IValueUnion::NONE: { + return true; + } + case IValueUnion::Int: { + return verifier.VerifyField(static_cast(obj), 0, 8); + } + case IValueUnion::Bool: { + return verifier.VerifyField(static_cast(obj), 0, 1); + } + case IValueUnion::Double: { + return verifier.VerifyField(static_cast(obj), 0, 8); + } + case IValueUnion::ComplexDouble: { + return verifier.VerifyField(static_cast(obj), 0, 8); + } + case IValueUnion::TensorMetadata: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::String: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::List: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Tuple: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Dict: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Object: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::IntList: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::DoubleList: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::BoolList: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Device: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::EnumValue: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Function: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyIValueUnionVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyIValueUnion( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline const torch::jit::mobile::serialization::Module *GetModule(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const torch::jit::mobile::serialization::Module *GetSizePrefixedModule(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Module *GetMutableModule(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline torch::jit::mobile::serialization::Module *GetMutableSizePrefixedModule(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *ModuleIdentifier() { + return "PTMF"; +} + +inline bool ModuleBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, ModuleIdentifier()); +} + +inline bool SizePrefixedModuleBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, ModuleIdentifier(), true); +} + +inline bool VerifyModuleBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(ModuleIdentifier()); +} + +inline bool VerifySizePrefixedModuleBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(ModuleIdentifier()); +} + +inline void FinishModuleBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, ModuleIdentifier()); +} + +inline void FinishSizePrefixedModuleBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, ModuleIdentifier()); +} + +} // namespace serialization +} // namespace mobile +} // namespace jit +} // namespace torch + +#endif // FLATBUFFERS_GENERATED_MOBILEBYTECODE_TORCH_JIT_MOBILE_SERIALIZATION_H_ +// @generated + +#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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/onnx.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..45d67dc480dddf573c951d42be5fc187175d8eaf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/onnx.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED( + "-Winconsistent-missing-destructor-override") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wsuggest-override") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED( + "-Wdeprecated-dynamic-exception-spec") +#include +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() +#include + +namespace torch::jit { + +TORCH_API std::string prettyPrint(const ::ONNX_NAMESPACE::ModelProto& model); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickle.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickle.h new file mode 100644 index 0000000000000000000000000000000000000000..0cdf6cded25e7574958df43ea4bf338dc5bc6ba2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickle.h @@ -0,0 +1,145 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +/// Pickle an IValue by calling a function to handle writing the data. +/// +/// `writer` is a function that takes in a pointer to a chunk of memory and its +/// size and consumes it. +/// +/// See `jit::pickle` for more details. +TORCH_API void pickle( + std::function writer, + const IValue& ivalue, + std::vector* tensor_table = nullptr); + +/// Save a `torch::IValue` in a format compatible with Python's `pickle` module +/// +/// If present, `tensor_table` is a pointer to a table in which tensors that +/// are contained within `ivalue` are stored, and the bytes returned by the +/// pickler will only include references to these tensors in the table. This can +/// be used to keep the binary blob size small. +/// If not provided, tensors are stored in the same byte stream as the pickle +/// data, similar to `torch.save()` in eager Python. +/// +/// Pickled values can be loaded in Python and C++: +/// \rst +/// .. code-block:: cpp +/// +/// torch::IValue float_value(2.3); +/// +/// // TODO: when tensors are stored in the pickle, delete this +/// std::vector tensor_table; +/// auto data = torch::jit::pickle(float_value, &tensor_table); +/// +/// std::vector ivalues = +/// torch::jit::unpickle(data.data(), data.size()); +/// +/// .. code-block:: python +/// +/// values = torch.load('data.pkl') +/// print(values) +/// +/// \endrst +TORCH_API std::vector pickle( + const IValue& ivalue, + std::vector* tensor_table = nullptr); + +/// Save a `torch::IValue` in a format that can be loaded by both +/// `torch::pickle_load` in C++ and `torch.load` in Python. +TORCH_API std::vector pickle_save(const IValue& ivalue); + +/// Deserialize a `torch::IValue` from bytes produced by either +/// `torch::pickle_save` in C++ or `torch.save` in Python +TORCH_API IValue pickle_load(const std::vector& data); + +/// Deserialize a `torch::IValue` from bytes produced by either +/// `torch::pickle_save` in C++ or `torch.save` in Python with custom object. +TORCH_API IValue pickle_load_obj(std::string_view data); + +/// `reader` is a function that takes in a size to read from some pickled +/// binary. `reader` should remember where it last read, and return +/// the number of bytes read. +/// See `torch::pickle` for details. +/// type_resolver is used to resolve any JIT type based on type str +TORCH_API IValue unpickle( + std::function reader, + TypeResolver type_resolver, + c10::ArrayRef tensor_table, + c10::TypePtr (*type_parser)(const std::string&) = + Unpickler::defaultTypeParser, + ObjLoader obj_loader = nullptr); + +/// Decode a chunk of memory containing pickled data into its `torch::IValue`s. +/// +/// If any `torch::IValue`s in the pickled data are `Object`s, then a +/// `class_resolver` function must be provided. +/// +/// See `torch::pickle` for details. +TORCH_API IValue unpickle( + const char* data, + size_t size, + TypeResolver type_resolver = nullptr, + c10::ArrayRef tensor_table = {}, + c10::TypePtr (*type_parser)(const std::string&) = + Unpickler::defaultTypeParser); + +/// Decode a chunk of memory containing pickled data into its `torch::IValue`s. +/// +/// If any `torch::IValue`s in the pickled data are `Object`s, then a +/// `class_resolver` function must be provided. +/// +/// See `torch::pickle` for details. +TORCH_API IValue unpickle( + const char* data, + size_t size, + ObjLoader obj_loader, + TypeResolver type_resolver = nullptr, + c10::ArrayRef tensor_table = {}, + c10::TypePtr (*type_parser)(const std::string&) = + Unpickler::defaultTypeParser); + +#ifndef C10_MOBILE +class VectorReader : public caffe2::serialize::ReadAdapterInterface { + public: + VectorReader(std::vector data) : data_(std::move(data)) {} + + size_t size() const override { + return data_.size(); + } + + size_t read(uint64_t pos, void* buf, size_t n, const char* what) + const override; + + private: + std::vector data_; +}; + +class StringViewReader : public caffe2::serialize::ReadAdapterInterface { + public: + StringViewReader(std::string_view data) : data_(data) {} + + size_t size() const override { + return data_.size(); + } + + size_t read(uint64_t pos, void* buf, size_t n, const char* what) + const override; + + private: + std::string_view data_; +}; +#endif +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler.h new file mode 100644 index 0000000000000000000000000000000000000000..6361fed7b397d707816fbde1dedfebf39b0f2422 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler.h @@ -0,0 +1,190 @@ +#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 { + +using ::c10::IValue; + +class TORCH_API Pickler { + AT_DISALLOW_COPY_AND_ASSIGN(Pickler); + + public: + Pickler(std::function writer) + : Pickler(std::move(writer), nullptr, nullptr, nullptr) {} + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + Pickler( + std::function writer, + std::vector* tensor_table, + std::function type_renamer, + std::vector* memoized_class_types, + std::function get_tensor_id = nullptr, + bool tag_aggregates = true) + : writer_(std::move(writer)), + tensor_table_(tensor_table), + type_renamer_(std::move(type_renamer)), + memoized_class_types_(memoized_class_types), + get_tensor_id_(std::move(get_tensor_id)), + tag_aggregates_(tag_aggregates) {} + ~Pickler(); + + // Push protocol onto the stack + void protocol(); + + // Push STOP PickleOpCode onto the stack + void stop(); + + void pushIValue(const IValue& ivalue); + + void startTuple(); + void endTuple(); + + const std::vector& tensorData() { + return tensor_data_; + } + + void pushEmptyDict(); + void pushDict(const IValue& ivalue); + void pushInt(int64_t value); + void pushLong(const std::string& data); + + private: + void pushIValueImpl(const IValue& ivalue); + void startTypeTag(); + void endTypeTag(const IValue& value); + void pushBool(bool value); + void pushDouble(double value); + void pushComplexDouble(const IValue& value); + void pushGenericList(const IValue& ivalue); + void pushIntList(const IValue& ivalue); + void pushList(const IValue& ivalue); + void pushTensor(const IValue& ivalue); + void pushTensorReference(const IValue& ivalue); + void pushLiteralTensor(const IValue& ivalue); + void pushLiteralSparseTensor(const at::Tensor& tensor); + void pushTuple(const IValue& ivalue); + void pushString(const std::string& string); + void pushDevice(const IValue& ivalue); +#ifdef USE_DISTRIBUTED + void pushRRef(const IValue& ivalue); +#endif + // unmemoized version + void pushStringImpl(const std::string& string); + void pushStorageOfTensor(const at::Tensor& tensor); + + void pushBinGet(uint32_t memo_id); + void pushSpecializedList( + const IValue& ivalue, + const char* list_name, + const std::function& item_pusher); + void pushGlobal(std::string_view module_name, std::string_view class_name); + // raw string data is appended directly to the byte stream + void pushBytes(const std::string& string); + void pushTensorData(const at::Tensor& tensor); + + // Add a BINPUT op and return the memoization id used + size_t pushNextBinPut(); + + const void* getPointer(const IValue& ivalue); + + // Caller checks that bufferPos_ > 0 + void flushNonEmpty() { + writer_(buffer_.data(), bufferPos_); + bufferPos_ = 0; + } + + void flush() { + if (bufferPos_ != 0) { + flushNonEmpty(); + } + } + + // These convert values to bytes and add them to the stack (NB: since T is to + // the left of a '::', its type cannot be deduced by the compiler so one must + // explicitly instantiate the template, i.e. push(int) works, push(int) + // does not) + static constexpr size_t kBufferSize = 256; + template + void push(std::common_type_t value) { + const char* begin = reinterpret_cast(&value); + if (bufferPos_ + sizeof(T) > buffer_.size()) { + flushNonEmpty(); + } + static_assert(sizeof(T) <= kBufferSize, "Buffer size assumption"); + memcpy(buffer_.data() + bufferPos_, begin, sizeof(T)); + bufferPos_ += sizeof(T); + } + + // Stream to write binary data to + // Code shouldn't call writer_ directly without first flushing. + std::function writer_; + + // Buffer to avoid calling a writer_ on a per-byte basis. + std::array buffer_; + size_t bufferPos_{0}; + + // Stack of opcodes/data + std::vector stack_; + + // External table of tensors to serialize. If this is missing, then tensors + // are serialized directly into the pickle + std::vector* tensor_table_; + + // TODO: only use this if necessary (add a pass to find all shared ivalues, + // and only memoize those) + uint32_t memo_id_ = 0; + + // Memoization of IValues that have been written (index in table is used for + // BINPUT opcodes) to enable shared references + c10::FastMap memoized_ivalue_map_; + + // because we de-dup ivalues based on their raw pointer address in the above + // map we need to keep all the memoized values alive during the pickle. + // Otherwise, it is possible that a raw address gets reused for another + // object, and we will alias it to the old object at that address. + std::vector memoized_ivalues_; + + std::function type_renamer_; + + // List of all the types that it wrote, inspect from the IValues it wrote. + std::vector* memoized_class_types_; + + // Function to grab next id_name for tensor storage, function is responsible + // for returning unique ids + std::function get_tensor_id_; + + // List of tensor storages to serialize in the same binary as the pickle data + // similar to ivalues, they are memoized using BINPUT + std::vector tensor_data_; + c10::FastMap memoized_storage_map_; + + c10::FastMap memoized_globals_map_; + c10::FastMap memoized_strings_map_; + c10::FastMap memoized_devices_map_; + // when true, List and Dict objects will be wrapped in a + // torch.jit._pickle.restore_type_tag call to correctly set the dynamic + // TorchScript type for the object. When true the thing unpickling must have + // torch installed. + bool tag_aggregates_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler_helper.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..523e912a392aab0104f6279d32b90c12c6d3bd74 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler_helper.h @@ -0,0 +1,239 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +namespace torch::jit { + +// See Python's pickletools.py for a detailed description of each of these codes +enum class PickleOpCode : char { + MARK = '(', + STOP = '.', + POP = '0', + POP_MARK = '1', + DUP = '2', + FLOAT = 'F', + INT = 'I', + BININT = 'J', + BININT1 = 'K', + LONG = 'L', + BININT2 = 'M', + NONE = 'N', + PERSID = 'P', + BINPERSID = 'Q', + REDUCE = 'R', + STRING = 'S', + BINSTRING = 'T', + SHORT_BINSTRING = 'U', + // NB: Avoid using UNICODE as it is a macro in the Windows API + UNICODE_ = 'V', + BINUNICODE = 'X', + APPEND = 'a', + BUILD = 'b', + GLOBAL = 'c', + DICT = 'd', + EMPTY_DICT = '}', + APPENDS = 'e', + GET = 'g', + BINGET = 'h', + INST = 'i', + LONG_BINGET = 'j', + LIST = 'l', + EMPTY_LIST = ']', + OBJ = 'o', + PUT = 'p', + BINPUT = 'q', + LONG_BINPUT = 'r', + SETITEM = 's', + TUPLE = 't', + EMPTY_TUPLE = ')', + SETITEMS = 'u', + BINFLOAT = 'G', + + // Protocol 2 + // NOLINTNEXTLINE(readability-redundant-inline-specifier) + PROTO = char('\x80'), + NEWOBJ = '\x81', + EXT1 = '\x82', + EXT2 = '\x83', + EXT4 = '\x84', + TUPLE1 = '\x85', + TUPLE2 = '\x86', + TUPLE3 = '\x87', + NEWTRUE = '\x88', + NEWFALSE = '\x89', + LONG1 = '\x8a', + LONG4 = '\x8b', + + // Protocol 3 (Python 3.x) + BINBYTES = 'B', + SHORT_BINBYTES = 'C', + + // Protocol 4 + // NOLINTNEXTLINE(readability-redundant-inline-specifier) + SHORT_BINUNICODE = char('\x8c'), + BINUNICODE8 = '\x8d', + BINBYTES8 = '\x8e', + EMPTY_SET = '\x8f', + ADDITEMS = '\x90', + FROZENSET = '\x91', + NEWOBJ_EX = '\x92', + STACK_GLOBAL = '\x93', + MEMOIZE = '\x94', + FRAME = '\x95' +}; + +struct WriteableTensorData { + const char* data() const { + return static_cast(tensor_.storage().data()); + } + size_t sizeInBytes() const { + return size_; + } + size_t nbytes() const { + return tensor_.storage().nbytes(); + } + bool storageHasDeleter() const { + return tensor_.storage().data_ptr().get_context() != nullptr; + } + + private: + friend TORCH_API WriteableTensorData + getWriteableTensorData(const at::Tensor& tensor, bool to_cpu); + at::Tensor tensor_; + uint64_t size_; +}; + +// returns a (tensor, record_size) for a tensor, converting it to a CPU tensor +// if it was CUDA and to_cpu is True. +TORCH_API WriteableTensorData +getWriteableTensorData(const at::Tensor& tensor, bool to_cpu = true); + +// if the cls has __getstate__/__setstate__ +// assert they have the right schema and return true, +// otherwise return false +bool checkHasValidSetGetState(const c10::ClassType& cls); + +// Declare BackendMeta serialization and deserialization function pointer types. +using BackendMetaPtr = std::function< + void(const at::Tensor&, std::unordered_map&)>; + +// A allowlist of device type, currently available is PrivateUse1 +TORCH_API std::unordered_set& GetBackendMetaAllowlist(); + +// Dynamically obtain serialization function pairs +// that require the corresponding backend. +TORCH_API std::array< + std::optional>, + at::COMPILE_TIME_MAX_DEVICE_TYPES>& +GetBackendMetaSerialization(); + +// Return a map of Tensor Metadata which including BackendMetaData for +// serialization. For now, it only takes care of `conj` and `neg` bit. +inline std::unordered_map getTensorMetadata( + const at::Tensor& t) { + // We don't support serializing `ZeroTensor` as it is not public + // facing yet. + TORCH_CHECK( + !t._is_zerotensor(), + "ZeroTensor is not serializable,", + " please file an issue if required."); + std::unordered_map metadata{}; + + // Only add meta-data if the value is not default. + if (t.is_conj()) { + metadata["conj"] = true; + } + if (t.is_neg()) { + metadata["neg"] = true; + } + // Only add BackendMetaData for custom backend if the function pointer is + // registered. + int device_type = static_cast(t.device().type()); + const auto& BackendMetaSerialization = GetBackendMetaSerialization(); + if (BackendMetaSerialization[device_type].has_value()) { + // Pass the tensor and metadata map references as parameters to the custom + // serialization function. + BackendMetaPtr fptr = BackendMetaSerialization[device_type].value().first; + fptr(t, metadata); + } + return metadata; +} + +// set Tensor Metadata based on the map. +// Refer: getTensorMetadata +inline void setTensorMetadata( + const at::Tensor& t, + std::unordered_map metadata) { + auto iter_end = metadata.end(); + auto iter_temp = metadata.find("conj"); + if (iter_temp != iter_end) { + t._set_conj(true); + metadata.erase(iter_temp); + } + iter_temp = metadata.find("neg"); + if (iter_temp != iter_end) { + t._set_neg(true); + metadata.erase(iter_temp); + } + // Only set BackendMetaData for custom backend if the function pointer is + // registered. + int device_type = static_cast(t.device().type()); + const auto& BackendMetaSerialization = GetBackendMetaSerialization(); + if (BackendMetaSerialization[device_type].has_value()) { + // Pass the tensor and metadata map references as parameters to the custom + // deserialization function. + BackendMetaPtr fptr = BackendMetaSerialization[device_type].value().second; + fptr(t, metadata); + } +} + +// set Tensor metadata based on the map. +// NOTE: This overload is required by unpickler.cpp +inline void setTensorMetadata( + const at::Tensor& t, + const c10::Dict& metadata_idict) { + std::unordered_map metadata; + for (auto& pair : metadata_idict) { + auto key = *pair.key().toString(); + metadata[key] = pair.value().toBool(); + } + setTensorMetadata(t, std::move(metadata)); +} + +// Register function pointer of Tensor BackendMetadata for serialization. +inline void TensorBackendMetaRegistry( + c10::DeviceType t, + const BackendMetaPtr& get_fptr, + const BackendMetaPtr& set_fptr) { + // allowlist verification + // Only if the devicetype is in the allowlist, + // we allow the serialization extension to be registered for backendmeta data. + const auto& DeviceTypeAllowlist = GetBackendMetaAllowlist(); + TORCH_CHECK( + DeviceTypeAllowlist.find(t) != DeviceTypeAllowlist.end(), + "It is not allowed to register the serialization method ", + "of backendMeta data for PrivateUse1. ", + "If you have related serialization requirements, ", + "please expand the allowlist"); + // Register function pointer + int device_type = static_cast(t); + auto& BackendMetaSerialization = GetBackendMetaSerialization(); + TORCH_CHECK( + !BackendMetaSerialization[device_type].has_value(), + "The tensor BackendMeta serialization function pointer for ", + t, + " has been registered."); + BackendMetaSerialization[device_type] = + std::optional>( + std::make_pair(get_fptr, set_fptr)); +} + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/python_print.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/python_print.h new file mode 100644 index 0000000000000000000000000000000000000000..7cefbe091fa581766880dcde6a7ae49a4a56705d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/python_print.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::jit { + +struct Method; +struct Module; +struct PythonPrintImpl; + +struct PrintDepsTable { + void add(const c10::NamedTypePtr& type); + + size_t size() const { + return table_.size(); + } + + const c10::NamedTypePtr& operator[](size_t index) const { + return table_[index]; + } + + private: + std::vector table_; + std::unordered_set non_unique_; +}; + +struct TORCH_API PythonPrint { + PythonPrint( + std::vector& constant_table, + PrintDepsTable& deps_table, + c10::TypePrinter type_printer = nullptr, + bool enforce_importable = false); + + void printNamedType(const c10::NamedTypePtr& classType); + void printFunction(const Function& callee); + void printMethod(const Function& callee); + + std::string str() const; + const SourceRangeRecords& ranges() const; + uint64_t minVersion() const; + + private: + std::shared_ptr pImpl; +}; + +TORCH_API bool printerHasSpecialCaseFor(c10::Symbol sym); + +TORCH_API void jitModuleToPythonCodeAndConstants( + const Module& module, + ExtraFilesMap* jit_sources, // output + std::vector* constants // output +); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization.h new file mode 100644 index 0000000000000000000000000000000000000000..3ff838cc62409bd0a5b9f14c9a60ea1e744c223f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization.h @@ -0,0 +1,71 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +#include +#include + +namespace c10 { +struct IValue; +} + +namespace torch::jit { + +class Pickler; +class SourceRangeSerializer; +static constexpr size_t kByteOffsetIndex = 0; +static constexpr size_t kSourceRangeIndex = 1; +static constexpr size_t kSourceRangeTagIndex = 2; +constexpr std::string_view kFormatWithStringTable = "FORMAT_WITH_STRING_TABLE"; + +class SourceRangePickler { + public: + SourceRangePickler(); + + std::vector pickle( + const SourceRangeRecords& ranges, + const SourceRangeTagMap& source_range_tags); + + private: + std::shared_ptr srs; +}; + +class SourceRangeDeserializer { + public: + SourceRangeDeserializer() = default; + explicit SourceRangeDeserializer(const c10::IValue& text_table) { + for (const auto& x : text_table.toTuple()->elements()) { + text_table_.emplace_back(std::make_shared(x.toStringRef())); + } + } + SourceRange deserialize(const c10::IValue& iv); + + private: + std::shared_ptr deserialize_source(const c10::IValue& iv); + std::unordered_map< + c10::intrusive_ptr, + std::shared_ptr> + cached_sources; + std::vector> text_table_; +}; + +class SourceRangeUnpickler { + public: + virtual std::optional findSourceRangeThatGenerated( + const SourceRange& range) = 0; + + virtual ~SourceRangeUnpickler() = default; +}; + +TORCH_API void setShouldUseFormatWithStringTable( + bool should_use_format_with_string_table); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..35161796290f4cd756de6f789d8bd645828da80f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h @@ -0,0 +1,33 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Do this clownyness with virtual functions because of the split +// between ATen core and torch + +class ConcreteSourceRangeUnpickler : public SourceRangeUnpickler { + public: + ConcreteSourceRangeUnpickler(at::DataPtr&& data, size_t size); + + std::optional findSourceRangeThatGenerated( + const SourceRange& range) override; + + private: + at::DataPtr data; + size_t size; + + void unpickle(); + + std::mutex mutex; + std::shared_ptr deserializer; + std::shared_ptr unpickled_records; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/storage_context.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/storage_context.h new file mode 100644 index 0000000000000000000000000000000000000000..fac2b53c200ebeba2daf2affbafc3a6b15fe6fd6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/storage_context.h @@ -0,0 +1,88 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Used in torch.package and TorchScript serialization to coordinate +// sharing of storages between models. Also used to create deterministic +// naming for storages. +class TORCH_API SerializationStorageContext { + public: + explicit SerializationStorageContext() = default; + SerializationStorageContext operator=(const SerializationStorageContext&) = + delete; + SerializationStorageContext(const SerializationStorageContext&) = delete; + + uint64_t getOrAddStorage(const c10::Storage& storage) { + if (!hasStorage(storage)) { + uint64_t size = storage_id_map_.size(); + storage_id_map_[storage] = size; + } + return storage_id_map_[storage]; + } + + bool hasStorage(const c10::Storage& storage) { + return storage_id_map_.find(storage) != storage_id_map_.end(); + } + + ~SerializationStorageContext() = default; + + private: + class StorageSerializationHash { + public: + size_t operator()(const c10::Storage& storage) const { + return std::hash()( + reinterpret_cast(storage.unsafeGetStorageImpl())); + } + }; + + class StorageSerializationEqual { + public: + bool operator()(const c10::Storage& lhs, const c10::Storage& rhs) const { + return lhs.unsafeGetStorageImpl() == rhs.unsafeGetStorageImpl(); + } + }; + + std::unordered_map< + c10::Storage, + uint64_t, + StorageSerializationHash, + StorageSerializationEqual> + storage_id_map_; +}; + +// Used in torch.package and TorchScript deserialization to coordinate +// sharing of storages between models. +class TORCH_API DeserializationStorageContext { + public: + explicit DeserializationStorageContext() = default; + DeserializationStorageContext operator=( + const DeserializationStorageContext&) = delete; + DeserializationStorageContext(const DeserializationStorageContext&) = delete; + + void addStorage(std::string name, c10::Storage storage) { + TORCH_INTERNAL_ASSERT(!hasStorage(name)); + name_storage_map_.emplace(std::move(name), std::move(storage)); + } + + bool hasStorage(const std::string& name) { + return name_storage_map_.find(name) != name_storage_map_.end(); + } + + c10::Storage getStorage(const std::string& name) { + TORCH_INTERNAL_ASSERT(hasStorage(name)); + return name_storage_map_.find(name)->second; + } + ~DeserializationStorageContext() = default; + + private: + std::unordered_map name_storage_map_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/type_name_uniquer.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/type_name_uniquer.h new file mode 100644 index 0000000000000000000000000000000000000000..62747c3514fa4fba667368b2830b78c3f8355dc3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/type_name_uniquer.h @@ -0,0 +1,36 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +/** + * class TypeNameUniquer + * + * Generates a unique name for every type `t` passed in. Types that compare + * equal with EqualType will receive the same unique name. + * + * This is used during Module::save(), to resolve type name collisions during + * serialization. + */ +class TORCH_API TypeNameUniquer { + public: + c10::QualifiedName getUniqueName(c10::ConstNamedTypePtr t); + + private: + NameMangler mangler_; + std::unordered_set used_names_; + std::unordered_map< + c10::ConstNamedTypePtr, + c10::QualifiedName, + HashType, + EqualType> + name_map_; +}; +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/unpickler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/unpickler.h new file mode 100644 index 0000000000000000000000000000000000000000..02fc9ba8d543c72132359bb1ccc846402c498574 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/unpickler.h @@ -0,0 +1,211 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace torch::jit { + +using TypeResolver = + std::function; + +using ObjLoader = std::function< + c10::intrusive_ptr(const at::StrongTypePtr&, IValue)>; + +class DeserializationStorageContext; + +// [unpickler refactor] there is some cruft around PickleOpCode::BUILD, +// PickleOpCode::NEWOBJ, and the last_opcode_ member below that should be +// deleted at some point, the Pickler doesn't produce it and it's only around to +// support models saved before 1.1 +class TORCH_API Unpickler { + AT_DISALLOW_COPY_AND_ASSIGN(Unpickler); + + using TypeParserT = c10::TypePtr (*)(const std::string&); + + public: + // tensors inside the pickle are references to the tensor_table. + // class_resolver is to resolve strong class type, type_resolver_ is + // to resolve any JIT type. class_resolver and type_resolver are not merged + // here because some use cases need to get strong class type that + // type_resolver_ can not return. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + Unpickler( + std::function reader, + TypeResolver type_resolver, + c10::ArrayRef tensor_table, + TypeParserT type_parser = defaultTypeParser) + : reader_(std::move(reader)), + tensor_table_(tensor_table), + type_resolver_(std::move(type_resolver)), + use_storage_device_(false), + type_parser_(type_parser), + version_(caffe2::serialize::kProducedFileFormatVersion) {} + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + Unpickler( + std::function reader, + TypeResolver type_resolver, + c10::ArrayRef tensor_table, + ObjLoader obj_loader, + TypeParserT type_parser = defaultTypeParser) + : reader_(std::move(reader)), + tensor_table_(tensor_table), + type_resolver_(std::move(type_resolver)), + obj_loader_(std::move(obj_loader)), + use_storage_device_(false), + type_parser_(type_parser), + version_(caffe2::serialize::kProducedFileFormatVersion) {} + + // tensors inside the pickle contain meta-data, the raw tensor + // dead is retrieved by calling `read_record`. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + Unpickler( + std::function reader, + TypeResolver type_resolver, + ObjLoader obj_loader, + std::function read_record, + std::optional device, + bool use_storage_device = false, + TypeParserT type_parser = defaultTypeParser, + std::shared_ptr storage_context = nullptr) + : reader_(std::move(reader)), + type_resolver_(std::move(type_resolver)), + obj_loader_(std::move(obj_loader)), + read_record_(std::move(read_record)), + device_(device), + use_storage_device_(use_storage_device), + type_parser_(type_parser), + storage_context_(std::move(storage_context)), + version_(caffe2::serialize::kProducedFileFormatVersion) {} + + Unpickler(Unpickler&&) = delete; + Unpickler& operator=(Unpickler&&) = delete; + ~Unpickler() = default; + + // consume the pickle stream, producing an IValue from the contents. + // Type Tags: the pickler will restore the type tags on + // List and Dict objects when possible IValue is an Object. + // Otherwise, Dict and List objects will end up with Any as their tag. + // If you know the type of the ivalue, tags can be restored with + // restoreAccurateTypeTags + IValue parse_ivalue(); + + // [type tag serialization] + // This is used to determine whether to restore type tags be recursively + // descending into the returned stack object (if version_number <= 2), or + // if version_number >= 3, to use the type strings included in the pickle + // archive for container types. By default this is set to + // `kProducedFileFormatVersion` so unless you're loading a pickle file + // from alongside a corresponding `version` file, you don't need to set + // the version manually. + void set_version(uint64_t version_number) { + version_ = version_number; + } + + static c10::TypePtr defaultTypeParser(const std::string& str) { + ScriptTypeParser parser; + return parser.parseType(str); + } + + private: + // No arguments ensures that a template argument must be specified + // so that the number of bytes read / type read is explicit + template + T read() { + T item; + if (sizeof(T) <= buffer_remaining_) { + // Fast path: entirely from buffer. + memcpy(&item, buffer_.data() + buffer_pos_, sizeof(T)); + buffer_remaining_ -= sizeof(T); + buffer_pos_ += sizeof(T); + } else { + // Don't over-template the slow path, to avoid code size bloat. + readSlowWithBuffer(reinterpret_cast(&item), sizeof(T)); + } + return item; + } + void readSlowWithBuffer(char* dest, size_t sz); + std::string readBytes(size_t num_bytes); + + double readFloat(); + void readGlobal( + const std::string& module_name, + const std::string& class_name); + void rebuildTensor(bool quantized); + void rebuildParameter(); + void rebuildTensorFromTypeV2(); + void rebuildSparseTensor(); +#ifdef USE_DISTRIBUTED + void rebuildRRef(); +#endif + PickleOpCode readInstruction(); + PickleOpCode readOpCode() { + return static_cast(read()); + } + std::string readString(); + void readList(IValue list_ivalue); + void readListElements(IValue list_ivalue, size_t start); + void setInput(size_t memo_id); + void run(); + + // Returns the number of bytes read. This should statefully + // remember the position. Don't call reader_ directly. + std::function reader_; + // Small buffer to avoid calling reader_ on a per-byte basis. + std::array buffer_; + size_t buffer_pos_{0}; + size_t buffer_remaining_{0}; + + std::vector stack_; + + // globals are represented on the stack as IValue integer indices + // into this list + std::vector> globals_; + std::vector memo_table_; + std::vector marks_; + c10::ArrayRef tensor_table_; + + // When deserializing types on lists and dicts, cache the type here + // so we don't have to parse the same type multiple times. Strings + // are already de-duplicated and replaced with BINGETs in the + // pickler, so we can just use the actual data pointer of each string. + std::unordered_map type_cache_; + + // optionally nullptr, needs to be present for creating classes + TypeResolver type_resolver_; + ObjLoader obj_loader_; + IValue empty_tuple_; + + std::function read_record_; + std::optional device_; + // When set to true, Unpickler will ignore the pickled device and use the + // device of the DataPtr returned by the read_record_ function. The default + // value of this flag is false. + const bool use_storage_device_; + + TypeParserT type_parser_{defaultTypeParser}; + + // Used for torch.package to enable sharing of storages across + // ScriptModules and eager modules + std::shared_ptr storage_context_; + + // See [type tag serialization] + uint64_t version_; + + // See [NOTE] skip_next_read_global + uint8_t skip_next_read_global = 0; +}; + +void restoreAccurateTypeTags(const IValue& root, const c10::TypePtr& type_tag); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/analysis.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..d0b79418577b6a7bbabd2acbb418175ac5542924 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/analysis.h @@ -0,0 +1,403 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { +class HasRand : public IRVisitor { + public: + HasRand(StmtPtr stmt) : stmt_(std::move(stmt)) { + stmt_->accept(this); + } + + bool has_rand() const { + return has_rand_; + } + + private: + void visit(const IntrinsicsPtr& v) override { + if (v->op_type() == IntrinsicsOp::kRand) { + has_rand_ = true; + } else { + IRVisitor::visit(v); + } + } + StmtPtr stmt_; + bool has_rand_ = false; +}; + +template +class NodeFinder : public IRVisitor { + public: + void visit(const NodePtr& v) override { + nodes.push_back((NodePtr)v); + IRVisitor::visit(v); + } + + static std::vector> find(const StmtPtr& s) { + NodeFinder nf; + s->accept(&nf); + return nf.nodes; + } + + static std::vector> find(const ExprPtr& e) { + NodeFinder nf; + e->accept(&nf); + return nf.nodes; + } + + std::vector> nodes; +}; + +class VarFinder : public IRVisitor { + public: + void visit(const VarPtr& v) override { + vars_.insert(v); + IRVisitor::visit(v); + } + + static std::unordered_set find(const StmtPtr& s) { + VarFinder nf; + s->accept(&nf); + return nf.vars(); + } + + static std::unordered_set find(const ExprPtr& e) { + VarFinder nf; + e->accept(&nf); + return nf.vars(); + } + + const std::unordered_set& vars() { + return vars_; + } + + private: + std::unordered_set vars_; +}; + +class BufFinder : public IRVisitor { + public: + void visit(const BufPtr& v) override { + bufs_.insert(v); + IRVisitor::visit(v); + } + + static std::unordered_set find(const StmtPtr& s) { + BufFinder nf; + s->accept(&nf); + return nf.bufs(); + } + + static std::unordered_set find(const ExprPtr& e) { + BufFinder nf; + e->accept(&nf); + return nf.bufs(); + } + + const std::unordered_set& bufs() { + return bufs_; + } + + private: + std::unordered_set bufs_; +}; + +// Finds all kinds of write operations to the provided Buf. +class WritesToBuf : public IRVisitor { + public: + WritesToBuf(BufPtr target) : target_(std::move(target)) {} + + std::vector writes() { + return writes_; + } + + static std::vector find(const StmtPtr& s, BufPtr b) { + WritesToBuf finder(std::move(b)); + s->accept(&finder); + return finder.writes(); + } + + private: + void visit(const StorePtr& v) override { + if (v->buf() == target_) { + writes_.push_back(v); + } + } + + void visit(const AtomicAddPtr& v) override { + if (v->buf() == target_) { + writes_.push_back(v); + } + } + + BufPtr target_; + std::vector writes_; +}; + +class StmtsReadingBuf : public IRVisitor { + public: + StmtsReadingBuf(BufPtr target) : target_(std::move(target)) {} + + std::vector reads() { + return reads_; + } + + static std::vector find(const StmtPtr& s, BufPtr b) { + StmtsReadingBuf finder(std::move(b)); + s->accept(&finder); + return finder.reads(); + } + + private: + bool readsBuffer(const StmtPtr& s) { + auto loads = NodeFinder::find(s); + for (const auto& l : loads) { + if (l->buf() == target_) { + return true; + } + } + return false; + } + + void visit(const StorePtr& v) override { + if (readsBuffer(v)) { + reads_.push_back(v); + } + } + + void visit(const LetPtr& v) override { + if (readsBuffer(v)) { + reads_.push_back(v); + } + } + + void visit(const CondPtr& v) override { + if (readsBuffer(v)) { + reads_.push_back(v); + } + } + + void visit(const AtomicAddPtr& v) override { + if (readsBuffer(v)) { + reads_.push_back(v); + } + } + + BufPtr target_; + std::vector reads_; +}; + +class ExternalAllocBufFinder : public IRVisitor { + public: + void visit(const ExternalCallWithAllocPtr& v) override { + const auto& bufs_out = v->buf_out_args(); + bufs_.insert(bufs_out.begin(), bufs_out.end()); + IRVisitor::visit(v); + } + + static std::unordered_set find(const StmtPtr& s) { + ExternalAllocBufFinder f; + s->accept(&f); + return f.bufs(); + } + + static std::unordered_set find(const ExprPtr& e) { + ExternalAllocBufFinder f; + e->accept(&f); + return f.bufs(); + } + + const std::unordered_set& bufs() { + return bufs_; + } + + private: + std::unordered_set bufs_; +}; + +// Traverses the IR to determine if a particular Var is modified within it. +class ModifiesVarChecker : public IRVisitor { + public: + ModifiesVarChecker(VarPtr v) : var_(std::move(v)) {} + + static bool check(const StmtPtr& s, VarPtr v) { + ModifiesVarChecker checker(std::move(v)); + s->accept(&checker); + return checker.found(); + } + + bool found() { + return found_; + } + + private: + void visit(const StorePtr& v) override { + if (v->buf()->base_handle() == var_) { + found_ = true; + return; + } + IRVisitor::visit(v); + } + + void visit(const AtomicAddPtr& v) override { + if (v->buf()->base_handle() == var_) { + found_ = true; + return; + } + IRVisitor::visit(v); + } + + void visit(const LetPtr& v) override { + if (v->var() == var_) { + found_ = true; + return; + } + IRVisitor::visit(v); + } + + void visit(const ForPtr& v) override { + if (v->var() == var_) { + found_ = true; + return; + } + IRVisitor::visit(v); + } + + VarPtr var_; + bool found_{false}; +}; + +// Traverse the Block stmt to identify the live range of the specified buf. The +// live range, indicated by a pair of integers, specifies the first and last +// stmt in block stmts that access to the buf. +class BufLiveRange : public IRVisitor { + public: + BufLiveRange(BufPtr b) : buf_(std::move(b)) {} + + static std::tuple liveRange(const StmtPtr& s, BufPtr b) { + BlockPtr block = to(s); + // We Only analyze buffer live ranges for block stmts. + if (!block) { + return std::make_tuple(0, 0); + } + + BufLiveRange analyzer(std::move(b)); + block->accept(&analyzer); + return analyzer.getLiveRange(); + } + + private: + std::tuple getLiveRange() { + return std::make_tuple(begin_, end_); + } + + bool hasBufReads(const StmtPtr& s) { + auto loads1 = NodeFinder::find(s); + for (const auto& l : loads1) { + if (l->buf() == buf_) { + return true; + } + } + auto loads2 = NodeFinder::find(s); + for (const auto& l : loads2) { + for (const auto& lb : l->buf_args()) { + if (lb == buf_) { + return true; + } + } + } + auto loads3 = NodeFinder::find(s); + for (const auto& l : loads3) { + for (const auto& lb : l->buf_args()) { + if (lb == buf_) { + return true; + } + } + } + return false; + } + + bool hasBufWrites(const StmtPtr& s) { + auto writes1 = NodeFinder::find(s); + for (const auto& w : writes1) { + if (w->buf() == buf_) { + return true; + } + } + auto writes2 = NodeFinder::find(s); + for (const auto& w : writes2) { + if (w->buf() == buf_) { + return true; + } + } + auto writes3 = NodeFinder::find(s); + for (const auto& w : writes3) { + for (const auto& wb : w->buf_out_args()) { + if (wb == buf_) { + return true; + } + } + } + return false; + } + + void findAccAndUpdateLiveRange(const StmtPtr& s) { + bool has_reads = hasBufReads(s), has_writes = hasBufWrites(s); + if (has_reads || has_writes) { + if (begin_ == -1) { + begin_ = curr_index_; + }; + end_ = curr_index_; + } + } + + void visit(const BlockPtr& v) override { + for (const StmtPtr& s : *v) { + curr_index_ += 1; + findAccAndUpdateLiveRange(s); + } + } + + BufPtr buf_; + int32_t begin_ = -1; + int32_t end_ = -1; + int32_t curr_index_ = -1; +}; + +// A class that analyzes the given program relevant for Block backend +// It creates a map of multi dim buffers and their flat versions +class CreateBufferMap : public IRVisitor { + public: + const std::unordered_map& getBufferMap() const { + return map_input_to_tensor_bufs_; + } + + private: + void visit(const StorePtr& v) override { + auto load_node = to(v->value()); + if (load_node) { + auto t_buf = load_node->buf(); + map_input_to_tensor_bufs_.emplace(t_buf->name_hint(), v->buf()); + } else { + auto add_node = to(v->value()); + auto mul_node = to(v->value()); + // This means for now, v->value() can be Add or Mul + TORCH_INTERNAL_ASSERT(add_node || mul_node, buildErrorMessage()); + map_input_to_tensor_bufs_.emplace(v->buf()->name_hint(), v->buf()); + } + v->value()->accept(this); + } + std::unordered_map map_input_to_tensor_bufs_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/block_codegen.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/block_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..3dabc4cef5692cd72a0bdc2d79c454d8afa320fb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/block_codegen.h @@ -0,0 +1,151 @@ +#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::jit::tensorexpr { + +// A class that analyzes the given program relevant for Block backend. +class BlockAnalysis : public IRVisitor { + public: + bool is_buf_store_target(const BufPtr& buf) const { + return store_targets_.count(buf) > 0; + } + + const std::unordered_set& loads() const { + return loads_; + } + + const std::unordered_set& stores() const { + return store_targets_; + } + + int64_t block_size() const { + return block_size_; + } + + bool areBufsInMap(const std::unordered_set& bufs) const; + + BufPtr getMultiDimBuf(const BufPtr& buf) const; + + std::string getInputName(const BufPtr& buf) const; + + std::string getFlatInputName(const BufPtr& buf) const { + return getInputName(buf) + "_flat"; + } + + std::unordered_map getBufferMap() const { + return map_input_to_tensor_bufs_; + } + + private: + void visit(const StorePtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const ForPtr& v) override; + + std::unordered_map map_input_to_tensor_bufs_; + std::unordered_set store_targets_; + std::unordered_set loads_; + int64_t block_size_ = 32; +}; + +// A class that overrides the underlying IRPrinter to produce Block. +class BlockPrinter : public IRPrinter { + public: + BlockPrinter(std::ostream* os, BlockAnalysis* block_analysis) + : IRPrinter(*os), block_analysis_(block_analysis) {} + + using IRPrinter::name_manager; + using IRPrinter::visit; + + private: + BlockAnalysis* block_analysis_; + std::unordered_map dim_values_map; + std::vector dim_names = {"N", "H", "W", "C"}; + std::vector flat_dim_names = {"N", "NH", "NHW", "NHWC"}; + void PrintTensorInfo(const std::unordered_set& bufs); + void PrintArguments(const std::unordered_set& bufs); + void PrintBufferInfo(const std::unordered_set& bufs); + void PrintDistribution(const std::unordered_set& bufs); + void PrintLoop(const std::unordered_set& bufs, bool block_idx = true); + void PrintReshapeInfo( + const std::unordered_set& bufs, + bool reverse = false); + void PrintDMAs(const std::unordered_set& bufs); + void PrintAdjustBuffers(const std::unordered_set& bufs); + + void visit(const ForPtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const AddPtr& v) override; + void visit(const MulPtr& v) override; +}; + +class TORCH_API BlockCodeGen : public CodeGen { + public: + template + /* implicit */ + BlockCodeGen(StmtPtr stmt, Ts... ts) + : CodeGen( + stmt, + std::vector({BufferArg(ts)...}), + at::Device(at::kCPU)) { + Initialize(); + } + + BlockCodeGen( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::Device(at::kCPU), + const std::string& kernel_func_name = "func") + : CodeGen(std::move(stmt), buffer_args, device, kernel_func_name) { + Initialize(); + } + + ~BlockCodeGen() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + + void Initialize(); + + std::string getCodeText(const std::string& attr = "") override { + return oss_.str(); + } + + private: + 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 block_analysis_; + + 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_inference.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..7d8ca6785aeeae1e886d2e46319bfca72cd3d564 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_inference.h @@ -0,0 +1,80 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { + +class Expr; +class Buf; +class Stmt; + +enum C10_API_ENUM TensorAccessKind { kLoad, kStore, kMutate }; + +struct TORCH_API TensorAccessBoundsInfo { + TensorAccessKind kind; + std::vector start; + std::vector stop; +}; + +using BoundsInfo = + std::unordered_map>; + +TORCH_API BoundsInfo +inferBounds(const StmtPtr& s, bool distinctAccessKinds = true); + +// Bounds inference caching the analysis. The MemDependencyChecker must already +// have been run. +TORCH_API BoundsInfo getInferredBounds( + analysis::MemDependencyChecker& analyzer, + const StmtPtr& s, + bool distinctAccessKinds = true); +TORCH_API BoundsInfo getInferredBounds( + analysis::MemDependencyChecker& analyzer, + const ExprPtr& e, + bool distinctAccessKinds = true); + +TORCH_API void printBoundsInfo(const BoundsInfo& v); + +TORCH_API std::vector getBoundExtents( + const std::vector& infos); + +// The kind of dependency found, in increasing order of exclusivity. +enum class HazardKind { + ReadAfterWrite, + WriteAfterRead, + WriteAfterWrite, + NoDependency, +}; +TORCH_API HazardKind getPotentialHazards( + analysis::MemDependencyChecker& analyzer, + const StmtPtr& A, + const StmtPtr& B); + +// Returns true if there is a conflicting overlap between accesses in +// statements A and B. A conflicting overlap is an overlap in buffer accesses +// where at least one of the accesses is a Store. +TORCH_API bool hasConflictingOverlap( + analysis::MemDependencyChecker& analyzer, + const StmtPtr& A, + const StmtPtr& B); +// Same as above, between accesses in stores S1 and S2. +TORCH_API bool isOverlapping( + analysis::MemDependencyChecker& analyzer, + const StorePtr& S1, + const StorePtr& S2); +// Same as above, between accesses in store S and load L. +TORCH_API bool isOverlapping( + analysis::MemDependencyChecker& analyzer, + const StorePtr& S, + const LoadPtr& 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_overlap.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_overlap.h new file mode 100644 index 0000000000000000000000000000000000000000..e19bc7b4752d5f13bac53fb3e56d229daf3e42d8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_overlap.h @@ -0,0 +1,126 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr::analysis { + +// A simple class containing the start and end of a range in a single dimension. +struct TORCH_API Bound { + ExprPtr start{nullptr}; + ExprPtr end{nullptr}; + + // This stores whether or not the start and end of this Bound have previously + // been swapped. This occurs when the bound is in a loop with a negative + // stride. + bool swapped{false}; + + Bound() = default; + Bound(ExprPtr s, ExprPtr e) : start(std::move(s)), end(std::move(e)) {} + + void print() const; + bool equals(const Bound& other) const; + + // The comparison operators are conservative. If the compare operator returns + // true, it means that all the elements satisfy the logical expression. But + // the false does not mean the opposite comparison is satisfied. It could be + // but not always. + bool operator==(const Bound& other) const; + bool operator!=(const Bound& other) const; + bool operator<(const Bound& other) const; + bool operator<=(const Bound& other) const; + bool operator>(const Bound& other) const; + bool operator>=(const Bound& other) const; + + void swap() noexcept { + std::swap(start, end); + swapped = !swapped; + } +}; + +struct BoundHash { + size_t operator()(const Bound& b) const { + return std::hash()(b.start) ^ std::hash()(b.end); + } +}; + +// The type of overlap found. Each condition is true only if none of the +// previous conditions hold. +// ContainedOrEqual: All elements in the Bound A are in the Bound B (this +// includes the case where the bounds are equal). +// Contains: All elements in the Bound B are in the Bound B. +// PartialOverlap: Any elements in the Bound B are in the Bound A. +// NoOverlap: No elements in the Bound A are in the bound B. +enum class OverlapKind { + ContainedOrEqual, + Contains, + PartialOverlap, + NoOverlap +}; + +// The Bound comparison result. +// True: Every Bound element always satisfies the given comparison operator +// False: Every Bound element always does NOT satisfy the given comparison +// operator +// NotDetermined: Some elements satisfy the given comparison operator and +// some elements not +enum class CmpEvalResult { True, False, NotDetermined }; + +// Returns the kind of overlap between Bound A and Bound A in a single +// dimension. +OverlapKind TORCH_API boundOverlap(const Bound& A, const Bound& B); + +// The comparison is conservative and the compare result is deterministic. +// It means that every element of the Bound to be compared needs to satisfy +// the given comparison operator. +CmpEvalResult TORCH_API compareBound( + const Bound& a, + const Bound& b, + const CompareSelectOperation& cmp_op); + +// A multi dimensional bound representing the bound of a set of indices. +using IndexBounds = std::vector; + +// Returns true if two IndexBounds are equivalent. +bool TORCH_API indexBoundsEquals(const IndexBounds& A, const IndexBounds& B); + +// Flattens a multi dimensional bound to a single dimension. The IndexBounds "a" +// *must* encapsulate the entire range of the buffer. +Bound TORCH_API flattenBounds(const IndexBounds& a); + +// Determines the kind of overlap in X dimensions. +OverlapKind TORCH_API overlaps(const IndexBounds& a, const IndexBounds& b); + +// Returns the Bound slices created by subtracing bound B from bound A. +// Multiple Bounds can be returned in the case where B slices A into two +// distinct regions with no overlap. +// +// For example: +// subtractBound((0, 10), (2, 4)) => [(0, 1), (5, 10)] +// bound A: (0, 10) +// bound B: (2, 4) +// If we remove slice (2, 4) from the slice (0, 10), we will be left +// with 2 slices, one at the start (0, 1), and one at the end (5, 10). +// So, the result of this subtraction is [(0, 1), (5, 10)]. +// +// Note: this doesn't use IndexBounds because the Bounds returned do not +// represent multiple different dimensions. +std::vector TORCH_API subtractBound(const Bound& a, const Bound& b); + +// Returns the bound slices created by subtracting the IndexBounds B from A. +std::vector TORCH_API subtractIndicesBounds( + const IndexBounds& A, + const IndexBounds& B, + OverlapKind overlap); +std::vector TORCH_API +subtractIndicesBounds(const IndexBounds& A, const IndexBounds& B); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/codegen.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_cloner.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_printer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_visitor.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/kernel.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/stmt.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/types.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/catch_utils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_data.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_device.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/backend_interface.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/cache.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/config.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/debug_util.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/dynamic_ir.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/hash.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/helpers.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/internal_ops/ltc_ops.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_builder.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_dump_util.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_metadata.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ir_util.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/lazy_graph_executor.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/metrics.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/multi_wait.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ops/arithmetic_ir_ops.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/ops/utils.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/permutation_util.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/shape.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/shape_inference.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor_impl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/tensor_util.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/thread_pool.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/trie.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/unique.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/core/util.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyIr.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyNativeFunctions.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/generated/LazyNonNativeIr.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/python/init.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/python/python_util.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/config.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/dynamic_ir.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/device_data.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/generic.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ops/to_copy.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/tensor_aten_ops.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_autograd_functions.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_backend_impl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_eager_fallback.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_lowering_context.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node_lowering.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/counters.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/counters.h new file mode 100644 index 0000000000000000000000000000000000000000..137c149ed6737e3484f6536a6dba0462c47f33ee --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/events.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/events.h new file mode 100644 index 0000000000000000000000000000000000000000..320d63457f91c46c501bfc9c62d1e3aeb8624676 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/monitor/python_init.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/mps/Module.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/mps/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..f636e580b673f35d4e0fbbc7308c79f020d72bc5 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/Module.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..84259c7651ebceace7f29d7429e5e3217eba57a4 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/mtia/profiler/MTIAMemoryProfiler.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/multiprocessing/init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/multiprocessing/init.h new file mode 100644 index 0000000000000000000000000000000000000000..1800ffa2ce1dd605a0daae7e707516920537060f --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/back_compat.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/init.h new file mode 100644 index 0000000000000000000000000000000000000000..4c451df8c9e5f9af3b5ece63f82e9c93cdd785ee --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/onnx.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/onnx/onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..6a5eb189134d0eaac3e056b939ef8cf539edb8d9 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/api.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/api.h new file mode 100644 index 0000000000000000000000000000000000000000..02514ee197c4cacafa6b324da402be8ed4504787 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/collection.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/collection.h new file mode 100644 index 0000000000000000000000000000000000000000..9156463cd066b05c998e5f9261aa889d85a0244f --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/combined_traceback.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/containers.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/containers.h new file mode 100644 index 0000000000000000000000000000000000000000..49c872babfc71e7edd119d15c359877962304717 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/data_flow.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/events.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/events.h new file mode 100644 index 0000000000000000000000000000000000000000..83cc186e15f19dc61fb6d0123593631c5d5961d0 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/kineto_client_interface.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/kineto_shim.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/observer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/python_tracer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/orchestration/vulkan.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf-inl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/perf.h new file mode 100644 index 0000000000000000000000000000000000000000..70ea26a46330fdeb556b76a511add5253b0b2314 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/combined_traceback.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/init.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/python/pybind.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/execution_trace_observer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/itt_observer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/nvtx_observer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/standalone/privateuse1_observer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/stubs/base.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/action.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/communicate.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/debug_info.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_enums.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_symbolize_enums.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/eh_frame_hdr.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/fast_symbolizer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/fde.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/lexer.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/line_number_program.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/mem_file.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/range_table.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/sections.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwind.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwind_error.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/unwind/unwinder.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/util.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/profiler/util.h new file mode 100644 index 0000000000000000000000000000000000000000..b1e64e56da5e31ff01d02f236c98b0f5a6919a7d --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/accelerator.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/accelerator.h new file mode 100644 index 0000000000000000000000000000000000000000..b73b27936ea716715940c841fd245412b4eced14 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/c/shim.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device.h new file mode 100644 index 0000000000000000000000000000000000000000..223e3320a4fd341ba0b388b1dfe08ff38f2d94df --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device_inl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/device_struct.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/library.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/library.h new file mode 100644 index 0000000000000000000000000000000000000000..9c8424ac16b6ce167acaa07d727732c19a2c4791 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/macros.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..c06e9f0f541c85dd2445814e6f320b986d19c05b --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/ops.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/ops.h new file mode 100644 index 0000000000000000000000000000000000000000..246df3cfd8c7eb10bb67343875254259a5511252 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/stableivalue_conversions.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..8762372a415cf30f429808980e0e2f2af7942b1d --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor_inl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/tensor_struct.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/version.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/stable/version.h new file mode 100644 index 0000000000000000000000000000000000000000..22c9076a3a1b3b325c20ebd2f21be8b1df367747 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/tensor/python_tensor.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/byte_order.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cpp_stacktraces.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cuda_enabled.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/device_lazy_init.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/disable_torch_function.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/generated_serialization_types.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/init.h new file mode 100644 index 0000000000000000000000000000000000000000..0496865beeb547590c24aa992f4484333fe02230 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/invalid_arguments.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/nested.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/nested.h new file mode 100644 index 0000000000000000000000000000000000000000..0d06a65acbe2b076b72dd01d6ceed3f10cc51dc6 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/numpy_stub.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/object_ptr.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/out_types.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pybind.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..4c399988a8d8a05859c9b71917e9e94c8b4147f6 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pycfunction_helpers.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pyobject_preservation.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_arg_parser.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_compat.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_dispatch.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_numbers.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_raii.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_scalars.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_strings.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_stub.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_symnode.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_torch_function_mode.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/python_tuples.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pythoncapi_compat.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/schema_info.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/six.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/six.h new file mode 100644 index 0000000000000000000000000000000000000000..85cceb07dcc70d7cce1fe1d67631a64ca3fe2bf8 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/structseq.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/structseq.h new file mode 100644 index 0000000000000000000000000000000000000000..8d40d6bf4adc54ded2638bf0c67062a733ce9f5e --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_apply.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_dtypes.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_flatten.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_layouts.h b/miniconda3/envs/ladir/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/ladir/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)