diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h new file mode 100644 index 0000000000000000000000000000000000000000..4fd21079677db142e5848bc31ef97a6428629d02 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h @@ -0,0 +1,307 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#include + +namespace torch::autograd { + +#define CHECK_RESULT(RESULT, VAR) \ + if (!(RESULT.is_sparse() || VAR.is_sparse() || RESULT.is_sparse_csr() || \ + VAR.is_sparse_csr())) { \ + if (!utils::obeys_layout_contract(RESULT, VAR)) { \ + TORCH_WARN_ONCE( \ + "grad and param do not obey the gradient layout contract. " \ + "This is not an error, but may impair performance.\n" \ + "grad.sizes() = ", \ + RESULT.sizes(), \ + ", strides() = ", \ + RESULT.strides(), \ + "\n", \ + "param.sizes() = ", \ + VAR.sizes(), \ + ", strides() = ", \ + VAR.strides()); \ + } \ + } + +struct TORCH_API AccumulateGrad : public Node { + explicit AccumulateGrad(Variable variable_); + + variable_list apply(variable_list&& grads) override; + + std::vector>& tensor_pre_hooks() noexcept + override { + // NB: Since the AccumulateGrad Node is only a weak ref from the Tensor, + // it can be destroyed even though the Tensor is still alive (contrary + // to all other Nodes). So we must lazily read the Tensor hooks here. + return impl::hooks(variable); + } + + std::unique_ptr& tensor_post_acc_grad_hooks() + const noexcept override { + // NB: Since the AccumulateGrad Node is only a weak ref from the Tensor, + // it can be destroyed even though the Tensor is still alive (contrary + // to all other Nodes). So we must lazily read the Tensor hooks here. + return impl::post_acc_grad_hooks(variable); + } + + // Note: Gradient Layout Contract + // + // AccumulateGrad tries to stash strided (non-sparse) grads with memory layout + // (strides) such that variables and grads interact efficiently in later + // optimizer kernels, and grads interact efficiently with c10d::Reducer.cpp. + // + // Specifically, AccumulateGrad tries to ensure the following + // (cf torch/csrc/autograd/utils/grad_layout_contract.h): + // (1) if variable.is_non_overlapping_and_dense(), the stashed grad's + // strides match variable. + // (2) else, stashed grad is rowmajor contiguous. + // If variable's grad does not exist (!variable_grad.defined()) + // AccumulateGrad steals new_grad if it's stealable and obeys the contract + // already, otherwise it deep copies new_grad into an obedient clone. + // + // If variable's grad already exists (variable_grad.defined()), new_grad must + // be added to variable_grad. If we aren't setting up for double backward + // (!GradMode::is_enabled()), AccumulateGrad performs "variable_grad += + // new_grad" in-place, which keeps variable_grad's layout. We assume (hope) + // variable_grad was created obeying (1) or (2) at some point in the past. + // + // If we are setting up for double backward, AccumulateGrad updates the grad + // out-of-place via "variable_grad + new_grad." TensorIterator operator+ + // decides result's layout. Typically TensorIterator matches strides of the + // first arg, so we once again assume (hope) variable_grad was originally + // created obeying (1) or (2). + // + // AccumulateGrad does not enforce the contract with 100% certainty. Examples: + // - If a user manually permutes a param or its grad, then runs a fwd+bwd, + // variable_grad += new_grad keeps variable_grad's layout without + // rechecking the contract. + // - If TensorIterator changes its corner cases about operator+'s result + // (for example, giving more or less priority to channels_last inputs, see + // https://github.com/pytorch/pytorch/pull/37968) the result may not obey. + // + // Fortunately, if a given grad doesn't satisfy (1) or (2), the penalty is + // degraded performance in Reducer.cpp or optimizer kernels, not death by + // assert or silently bad numerics. + + // Gradient Accumulation + // Given a variable with its current grad as variable_grad, accumulates + // new_grad into variable_grad if in place accumulation is possible. + // Otherwise, uses 'update_grad' to update the grad for the variable. + // + // Branch breakdown: + // - Case 1: Param has no existing grad + // - Case 1.1: Stealable dense new_grad + // . We aren't setting up for double-backward. + // . No other user-visible tensor references new_grad. + // . new_grad obeys the "Gradient Layout Contract", there has a special + // case, For MKLDNN tensor, which is a opaque tensor, assuming it obeys + // layout_contract. + // - Case 1.2: Stealable sparse new_grad + // . Can't detach sparse tensor (since metadata changes are not allowed + // after detach), so just create a new one for the grad which is a + // shallow copy. We need a shallow copy so that modifying the original + // grad tensor doesn't modify the grad we accumulate. + // . We only skip clone if indices and values themselves are contiguous + // for backward compatibility reasons. Since without this optimization, + // earlier we would clone the entire SparseTensor which cloned indices + // and values. For details see + // https://github.com/pytorch/pytorch/issues/34375. + // - Case 1.3: Cloning sparse/nested new_grad + // - Case 1.4: Cloning MKLDNN new_grad + // - Case 1.5: Deep copies new_grad according to the Gradient Layout + // Contract. + // - Case 2: Param has existing grad and grad mode is not enabled + // - This case is not strictly necessary, but it makes the first-order only + // case slightly more efficient. + // - Case 2.1: Sparse variable_grad + Dense new_grad + // . If `variable_grad` is sparse and `new_grad` is not sparse, their + // sum is not sparse, and we must change the TensorImpl type of + // `variable_grad` for it to store the result. However, changing the + // TensorImpl type of a tensor requires changing the tensor itself, and + // thus in this case we have to change the grad tensor. + // - Case 2.2: Vmap-incompatible + // . Ideally we'd perform an in-place operation to avoid changing + // the grad tensor. However, if that's impossible because the grads + // are vmap-incompatible (See NOTE: [vmap-incompatible in-place + // operations]), then we just add them out-of-place. + // - Case 2.3: In-place addition + // . In this case we can avoid changing the grad tensor. There are three + // scenarios when we'll hit this case: + // . `variable_grad` is sparse, and `new_grad` is sparse. + // . `variable_grad` is dense, and `new_grad` is sparse. + // . `variable_grad` is dense, and `new_grad` is dense. + // . `variable_grad` is mkldnn, and `new_grad` is mkldnn. + // + // In all of these four cases, `variable_grad += new_grad` is a + // valid operation which adds `new_grad` to `variable_grad` in + // place. `variable_grad` is thus still referring to the same tensor + // after the operation. + // . DistributedDataParallel(DDP) package relies on grad being + // mutated in place for saving peak memory usage. DDP will still + // work correctly if it is mutated out of place here, but DDP will + // maintain one extra copy of grad tensors in buffer and thus + // increase peak memory usage. + // - Case 3: Param has existing grad and grad mode is enabled + // - Case 3.1: Sparse variable_grad + Dense new_grad + // - Case 3.2: Not Sparse variable_grad + Dense new_grad + // + // variable: the variable whose grad we're accumulating. + // variable_grad: the current grad for the variable. + // new_grad: new grad we want to accumulate for the variable. + // num_expected_refs: the number of refs we expect to hold internally + // such that it is safe to avoid cloning the grad + // if use_count() of the grad is less than or equal + // to this value (in addition to post_hooks). + // update_grad: Function that is used to update grad for the variable. + // The argument to the function is a Tensor which + // is used to set a new value for the grad. + template + static void accumulateGrad( + const Variable& variable, + at::Tensor& variable_grad, + const at::Tensor& new_grad, + size_t num_expected_refs, + const T& update_grad) { + if (!variable_grad.defined()) { + if (!GradMode::is_enabled() && !new_grad.is_sparse() && + !new_grad.is_sparse_csr() && + !(variable.is_sparse_csr() && new_grad.layout() == at::kStrided) && + impl::is_tensor_stealable( + new_grad, + num_expected_refs + at::caching::is_cached_tensor(new_grad)) && + (new_grad.is_mkldnn() || + utils::obeys_layout_contract(new_grad, variable))) { + // See Case 1.1: Stealable dense new_grad + update_grad(new_grad.detach()); + } else if ( + !GradMode::is_enabled() && new_grad.is_sparse() && + new_grad._indices().is_contiguous() && + new_grad._values().is_contiguous() && + // Use count for indices and values should always be <=1 since the + // SparseTensor should be the only one holding a reference to these. + new_grad._indices().use_count() <= 1 && + new_grad._values().use_count() <= 1 && + impl::is_tensor_stealable(new_grad, num_expected_refs)) { + // Case 1.2: Stealable sparse new_grad + // No scenario where we expect this to be true currently + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + !at::caching::is_cached_tensor(new_grad._indices()) && + !at::caching::is_cached_tensor(new_grad._values()) && + !at::caching::is_cached_tensor(new_grad)); + + update_grad(at::_sparse_coo_tensor_unsafe( + new_grad._indices(), + new_grad._values(), + new_grad.sizes(), + new_grad.options())); + } else { + if (new_grad.is_sparse() || new_grad.is_sparse_csr() || + new_grad.is_nested()) { + // Case 1.3: Cloning sparse/nested new_grad + update_grad(new_grad.clone()); + } else { + if (new_grad.is_mkldnn()) { + // Case 1.4: Cloning MKLDNN new_grad + update_grad(new_grad.clone()); + } else { + // Case 1.5: Deep copies new_grad according to the "Gradient + // Layout Contract." + update_grad(utils::clone_obey_contract(new_grad, variable)); + } + } + } + } else if (!GradMode::is_enabled()) { + // Case 2: Param has existing grad and grad mode is not enabled + if (variable_grad.is_sparse() && !new_grad.is_sparse()) { + // Case 2.1: Sparse variable_grad + Dense new_grad + auto result = new_grad + variable_grad; + CHECK_RESULT(result, variable); + update_grad(std::move(result)); + } else if (!at::inplaceIsVmapCompatible(variable_grad, new_grad)) { + // Case 2.2: Vmap-incompatible + auto result = variable_grad + new_grad; + CHECK_RESULT(result, variable); + update_grad(std::move(result)); + } else { + // Case 2.3: In-place addition + variable_grad += new_grad; + CHECK_RESULT(variable_grad, variable); + // ^ We could enforce the contract more aggressively here by writing: + // if (variable_grad.is_sparse() || new_grad.is_sparse()) { + // variable_grad += new_grad; + // } else if (obeys_layout_contract(variable_grad, variable)) { + // variable_grad += new_grad; + // } else { + // result = at::empty_strided(variable.sizes(), variable.strides(), + // variable.options().memory_format(std::nullopt)); + // update_grad(at::native::add_out(result, variable_grad, + // new_grad, 1.0); + // } + // However, that accumulation is sometimes in place and sometimes not, + // which may break user code. + } + } else { + // Case 3: Param has existing grad and grad mode is enabled + at::Tensor result; + if (variable_grad.is_sparse() && !new_grad.is_sparse()) { + // Case 3.1: Sparse variable_grad + Dense new_grad + // CPU backend throws an error on sparse + dense, so + // prefer dense + sparse here. + result = new_grad + variable_grad; + } else { + // Case 3.2: Not Sparse variable_grad + Dense new_grad + // Assumes operator+ result typically matches strides of first arg, + // and hopes variable_grad was originally created obeying layout + // contract. + result = variable_grad + new_grad; + } + CHECK_RESULT(result, variable); + update_grad(std::move(result)); + // ^ We could enforce the contract more aggressively here by saying + // if (obeys_layout_contract(new_grad, variable)) { + // update_grad(new_grad + variable_grad); + // } else { + // update_grad(variable_grad + new_grad); + // } + // such that the stashed grad is likely to have the right strides if + // either variable_grad or new_grad already has the right strides. + // We could enforce the contract with certainty by saying + // auto result = variable_grad + new_grad (or vice versa), checking + // result's layout, and copying to an obedient clone if necessary before + // update_grad. The copy would require another gmem pass. We can't create + // empty result with the right layout then add_out into it with a single + // kernel, because GradMode is enabled in this branch, and add_out isn't + // differentiable. Maybe more trouble than it's worth. + } + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) override; + + Variable variable; +}; + +#undef CHECK_RESULT + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..921e8cd820f52bd8d04f5f8d83ab75a713174bc6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h @@ -0,0 +1,117 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::autograd { + +struct TORCH_API Error : public Node { + Error(std::string msg, edge_list&& next_edges) + : Node(std::move(next_edges)), msg(std::move(msg)) {} + + Error(std::string msg) : msg(std::move(msg)) {} + + variable_list apply(variable_list&& inputs) override; + variable_list apply(variable_list&& inputs) const; + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) override; + + std::string msg; +}; + +// We print grad_fn names in tensor printing. For functions with backward +// NYI, grad_fn= will be printed if we use Error, which is confusing. So +// special case with a new NotImplemented function here. +struct TORCH_API NotImplemented : public Error { + NotImplemented(const std::string& forward_fn, edge_list&& next_edges) + : Error( + "derivative for " + forward_fn + " is not implemented", + std::move(next_edges)) {} + + NotImplemented(const std::string& forward_fn) + : Error("derivative for " + forward_fn + " is not implemented") {} +}; + +// Identity in forward, Error in backward. Used to implement +// @once_differentiable +struct TORCH_API DelayedError : public Node { + DelayedError(std::string msg, int64_t num_inputs) : msg(std::move(msg)) { + for ([[maybe_unused]] const auto _ [[maybe_unused]] : + c10::irange(num_inputs)) { + add_input_metadata(Node::undefined_input()); + } + } + + variable_list apply(variable_list&& inputs) override; + variable_list apply(variable_list&& inputs) const; + + std::string msg; +}; + +struct TORCH_API UndefinedGrad : public Node { + UndefinedGrad() { + add_input_metadata(Node::undefined_input()); + } + + variable_list apply(variable_list&& inputs) override; + variable_list apply(variable_list&& inputs) const; +}; + +struct TORCH_API UndefinedGradBackward : public Node { + UndefinedGradBackward(edge_list&& next_edges) : Node(std::move(next_edges)) {} + + UndefinedGradBackward() = default; + + variable_list apply(variable_list&& inputs) override; + variable_list apply(variable_list&& inputs) const; + + void compiled_args(CompiledNodeArgs& args) const override {} + variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) override { + return apply(variable_list(inputs)); + } +}; + +struct TORCH_API GraphRoot : public Node { + GraphRoot(edge_list functions, variable_list inputs) + : Node(std::move(functions)), outputs(std::move(inputs)) { + // Ensures calls to stream() on a GraphRoot instance reflect current + // stream(s) on devices of root grad tensors at the time the instance is + // constructed. + for (const auto& t : outputs) { + add_input_metadata(t); + } + } + + variable_list apply(variable_list&& inputs) override { + return outputs; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) override; + + variable_list outputs; +}; + +struct TORCH_API Identity : public Node { + variable_list apply(variable_list&& inputs) override; +}; + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/comm.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/comm.h new file mode 100644 index 0000000000000000000000000000000000000000..f5b6f2bac67215a67adc92e73c22b673604b323d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/comm.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include +#include + +namespace torch::autograd { + +struct TORCH_CUDA_CU_API Scatter : public Node { + explicit Scatter( + std::vector devices, + std::optional> chunk_sizes = std::nullopt, + int64_t dim = 0, + std::optional>> streams = + std::nullopt, + bool unsqueeze_scalars = false); + ~Scatter() override; + + variable_list apply(variable_list&& inputs) override; + + std::vector devices_; + std::optional> chunk_sizes_; + int64_t dim_; + std::optional>> streams_; + bool unsqueeze_scalars_; +}; + +struct TORCH_CUDA_CU_API Gather : public Node { + explicit Gather(const at::Device& destination_device, int64_t dim = 0); + ~Gather() override; + + variable_list apply(variable_list&& inputs) override; + + at::Device destination_device_; + int64_t dim_; +}; + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..b0bd95b8a41bf4e825758242b2f6752b95e860df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +// NOLINTNEXTLINE(misc-unused-alias-decls) +namespace py = pybind11; + +namespace pybind11::detail {} // namespace pybind11::detail + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..592d8ff39d4aae3c0e4f863308555b7c81e2168a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h @@ -0,0 +1,190 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include +#include + +namespace torch::autograd { + +struct TORCH_API CopyBackwards : public Node { + variable_list apply(variable_list&& grads) override; + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) override; + + at::TensorOptions src_options; +}; + +// Note [View + Inplace update for base tensor] +// +// This note covers a few important topics related to view + inplace handling. +// - It explains what is the CopySlices Node and why we need it. +// - It explains the considerations on what is saved for backward in +// CopySlices. +// - It explains why we need to sometimes change the exec_info of the current +// backward +// +// What is CopySlices? +// ~~~~~~~~~~~~~~~~~~~ +// +// We support autograd with inplace mutation; e.g., if you write x.mul_(2) +// the autograd will work as if you now had multiple Tensors under the hood and +// you did +// x = t.clone() +// x0 = x +// x1 = x0 * 2 +// x = x1 +// As you can see here, after this operation, x.grad_fn now points to x1.grad_fn +// (the MulBackward node) and this node points to x's original grad_fn (which is +// also x0.grad_fn). It is important to keep in mind that after the inplace, +// there is no Tensor object that represents the x0 state anymore. But the graph +// for it is still around in autograd (in case x was used before being modified +// inplace). See Example 1 in +// https://docs.google.com/drawings/d/1-T5DyYfChMX1ONQkY-zU-hj_ayQ2zmA5CBOKDWqvEhE +// We call this rebasing the history of the Tensor. +// +// Now, a difficult situation is what happens if x is a differentiable view +// of a base b. +// b = t.clone() +// x = b.select(0, 0) +// x *= 2 +// With the same approach as above, this will become +// b = t.clone() +// x = b.select(0, 0) +// b0 = b +// x0 = x +// x1 = x0 * 2 +// b1 = b0.select_scatter(x1, 0, 0) +// x2 = b1.select(0, 0) +// x = x2 +// b = b1 +// As you can see here, not only we need to modify x's grad_fn, we also need to +// modify the one from b. We also need to ensure that the new grad_fn on x is +// linked to b's new grad_fn. The chain the select_scatter, multiplication and +// select is what CopySlices does, all wrapped into a single Node. +// +// See Example 1 in +// https://docs.google.com/drawings/d/1-T5DyYfChMX1ONQkY-zU-hj_ayQ2zmA5CBOKDWqvEhE +// +// What do we need to save in CopySlices to run backward? +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// We need to perform grad_view = fn(grad_view), but out-of-place. +// view_fn_ is an optional function saved in DifferentiableViewMeta +// from forward pass, so that we can recover we when as_strided is not +// supported. It preserves the invariants: +// view = view_fn_(base) +// grad_view = view_fn_(grad_base) +// +// When as_strided is supported (e.g. strided CPU/CUDA Tensors), view_fn_ +// is empty and we save TensorGeometry(view) instead. +// With the TensorGeometry information we can use `as_strided` call which +// is more efficient to recover views in backward. +// +// For example: +// view_1 = view_op_1(base) +// view_2 = view_op_2(view_1) +// ... +// view_n = view_op_n(view_n-1) +// view_n = inplace_op(view_n) +// +// In CPU/CUDA case where we support efficient as_strided implementation, +// grad_view_n can be calculated through 1 step. +// +// grad_view_n = grad_base.as_strided(view_sizes, view_strides, view_offset); +// +// But in XLA backend where we don't have full support of as_strided, +// it has to save a chained lambda function view_fn_, to exactly +// replay how the view was done in forward. +// +// view_fn_ = view_op_n(...(view_op_2(view_op_1()))) +// grad_view_n = view_fn_(grad_base) +// +// This chain view_fn_ works as long as forward view ops are implemented, +// e.g XLA simulates view without a real Storage behind Tensor, but it's less +// efficient than the as_strided one so we should be careful to only use it when +// necessary. +// +// - For CPU/CUDA we save TensorGeometry of both base and view tensors, +// That's all we need to pass into as_strided. +// E.g. int[] sizes, int[] strides, and int storage_offset. +// - For XLA we use view_fn_, which captures all forward view op arguments +// by **value**. +// E.g for at::narrow, int dim, int start, in length are saved. +// +// Theoretically we could also save Tensor `view` in CopySlices Node, but +// it's far more expensive than what we currently save. +// 1. We cannot afford keeping large tensors alive to recover views only. +// 2. There are inplace checks when Tensors are loaded back to make sure +// they haven't been changed (including size metadata). +// So saving metadata like TensorGeometry/view arguments is much better +// because it is minimal information needed to recover views, as well as it +// allows the user to modify the original Tensor without preventing the +// backward pass from running. +// +// Why do we manually change exec_info in the apply? +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Using the same example as before, +// b = t.clone() +// x = b.select(0, 0) +// x *= y +// +// You can see the visualization at +// https://docs.google.com/drawings/d/1Bx-Hcz-zlIv7PabQqnPhUIVIs9F8WWi48svqMsAUMFs +// which contains the wrapped MulBackward Node and show what it links to. +// Since a backward can happen between any subset of the inputs (t and y) and +// outputs (o, x, b). It is possible to get into a state where CopySlices's 0th +// next function (CloneBackward) needs gradient but MulBackward's 0th next +// function (SelectBackward) is not. This happens if you do autograd.grad +// between x and t for example. +// In such a case, we do need to mark SelectBackward as requiring gradient such +// that, during the execution of MulBackward, we will actually compute gradient +// for the 0th input. +// +// All the other next functions are always shared (this is asserted in the apply +// code) and so nothing needs to be done for them. + +// See Note [View + Inplace update for view tensor] for what we do to view +// tensor when an in-place operation happens. +struct TORCH_API CopySlices : public Node { + CopySlices( + const Variable& base_var, + at::TensorGeometry view_, + std::unique_ptr view_fn_, + std::shared_ptr fn_); + + // common code between apply/apply_with_saved + template + variable_list apply_impl(variable_list&& inputs, const T& call_fn); + + variable_list apply(variable_list&& inputs) override; + void release_variables() override; + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) override; + void update_exec_info(); + + at::TensorGeometry base; + // view and view_fn are redundant and view_fn will be used if available. + // See Note [View + Inplace update for base tensor] for details. + at::TensorGeometry view; + std::unique_ptr view_fn; + std::shared_ptr fn; +}; + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..7531a8eb132c90b58b3855e646ac8d2bf7d90e25 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/utils.h @@ -0,0 +1,120 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace torch::autograd { + +using function_constructor = std::function(edge_list&&)>; + +/** + * Wraps the tensor outputs in variables and creates the grad_fn and sets the + * grad_fn if necessary. + */ +TORCH_API variable_list wrap_outputs( + const variable_list& inputs, + tensor_list&& outputs, + const function_constructor& ctr); + +/// Checks that inputs contains exactly `args` items and that the first +/// `required_args` +/// items are not nullptr. If not specified, `required_args` defaults to `args`. +TORCH_API void check_input_variables( + const char* name, + const variable_list& inputs, + int args, + int required_args = -1, + bool allow_undefined = false); + +struct ComputeRequiresGrad : IterArgs { + bool out = false; + using IterArgs::operator(); + void operator()(const at::Tensor& tensor) { + const auto& var = static_cast(tensor); + if (var.defined() && var.requires_grad()) { + out = true; + } + } + void operator()(const std::optional& tensor) { + if (tensor.has_value()) { + (*this)(*tensor); + } + } + bool short_circuit() { + return out; + } +}; + +template +inline bool compute_requires_grad(Args&&... args) { + if (!GradMode::is_enabled()) { + return false; + } + return ComputeRequiresGrad().apply(std::forward(args)...).out; +} + +inline void set_history( + const at::Tensor& variable, + const std::shared_ptr& grad_fn) { + TORCH_CHECK(grad_fn != nullptr); + if (variable.defined()) { + // If the codegen triggers this, you most likely want to add your newly + // added function to the DONT_REQUIRE_DERIVATIVE list in + // tools/autograd/gen_variable_type.py + TORCH_CHECK( + isDifferentiableType(variable.scalar_type()), + "Autograd not support dtype: ", + variable.scalar_type()); + auto output_nr = grad_fn->add_input_metadata(variable); + impl::set_gradient_edge(variable, {grad_fn, output_nr}); + } else { + grad_fn->add_input_metadata(Node::undefined_input()); + } +} + +inline void set_history( + const std::vector& variables, + const std::shared_ptr& grad_fn) { + for (auto& variable : variables) { + set_history(variable, grad_fn); + } +} + +inline bool isFwGradDefined(const std::optional& t) { + return t.has_value() && t->defined() && t->_fw_grad(/*level */ 0).defined(); +} + +inline bool isFwGradDefinedTensorList(const at::ITensorListRef& variables) { + bool ret = false; + for (auto& variable : variables) { + ret |= isFwGradDefined(variable); + } + return ret; +} + +inline bool isFwGradDefinedTensorList( + const c10::List>& li) { + bool ret = false; + for (auto i : c10::irange(li.size())) { + auto t = li.get(i); + ret |= isFwGradDefined(t); + } + return ret; +} + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h new file mode 100644 index 0000000000000000000000000000000000000000..261b8abae0f2b0fbcc00012bd67301a7e69d46c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h @@ -0,0 +1,15399 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// @generated from ../tools/autograd/templates/Functions.h + +#include +#include +#include + +#include "torch/csrc/autograd/function.h" +#include "torch/csrc/autograd/variable.h" +#include "torch/csrc/autograd/saved_variable.h" +#include + +#include + +namespace torch { namespace autograd { namespace generated { + +using at::Scalar; +using at::Tensor; +using at::IntArrayRef; +using at::ArrayRef; +using at::Type; +using at::TensorGeometry; +using at::ScalarType; +using std::optional; +using c10::fmap; + +inline std::vector unpack_list(at::ArrayRef xs, std::shared_ptr saved_for = nullptr) { + // NB: we must explicitly do the conversion in the lambda, otherwise template + // deduction will give a Tensor of Variable which is not convertible + return fmap(xs, [&saved_for](const SavedVariable& x) { + // TODO(crcrpar): Use `std::move(saved_for)` to avoid incrementing refcount, which would need refactoring. + return static_cast(x.unpack(saved_for)); + }); +} + +inline c10::List> unpack_opt_list(at::ArrayRef xs, std::shared_ptr saved_for = nullptr) { + torch::List> result; + result.reserve(xs.size()); + for (const SavedVariable& v : xs) { + auto var = v.unpack(saved_for); + result.push_back(var.defined() ? std::optional(var) : ::std::nullopt); + } + return result; +} + +using torch::autograd::TypeAndSize; + +#ifdef _WIN32 +struct AbsBackward0 : public TraceableFunction { + TORCH_API AbsBackward0() = default; +#else +struct TORCH_API AbsBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AbsBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AcosBackward0 : public TraceableFunction { + TORCH_API AcosBackward0() = default; +#else +struct TORCH_API AcosBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AcosBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AddBackward0 : public TraceableFunction { + TORCH_API AddBackward0() = default; +#else +struct TORCH_API AddBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AddBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::ScalarType other_scalar_type; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct AddBackward1 : public TraceableFunction { + TORCH_API AddBackward1() = default; +#else +struct TORCH_API AddBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AddBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct AddbmmBackward0 : public TraceableFunction { + TORCH_API AddbmmBackward0() = default; +#else +struct TORCH_API AddbmmBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AddbmmBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + batch1_.reset_data(); + batch2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + SavedVariable batch1_; + c10::SymInt batch1_sym_argsize_0; + c10::SymInt batch1_sym_argsize_1; + SavedVariable batch2_; + c10::SymInt batch2_sym_argsize_2; + at::Scalar beta; + +}; +#ifdef _WIN32 +struct AddcdivBackward0 : public TraceableFunction { + TORCH_API AddcdivBackward0() = default; +#else +struct TORCH_API AddcdivBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AddcdivBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + tensor1_.reset_data(); + tensor2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::ScalarType self_scalar_type; + SavedVariable tensor1_; + at::ScalarType tensor1_scalar_type; + SavedVariable tensor2_; + at::ScalarType tensor2_scalar_type; + at::Scalar value; + +}; +#ifdef _WIN32 +struct AddcmulBackward0 : public TraceableFunction { + TORCH_API AddcmulBackward0() = default; +#else +struct TORCH_API AddcmulBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AddcmulBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + tensor1_.reset_data(); + tensor2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::ScalarType self_scalar_type; + SavedVariable tensor1_; + at::ScalarType tensor1_scalar_type; + SavedVariable tensor2_; + at::ScalarType tensor2_scalar_type; + at::Scalar value; + +}; +#ifdef _WIN32 +struct AddmmBackward0 : public TraceableFunction { + TORCH_API AddmmBackward0() = default; +#else +struct TORCH_API AddmmBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AddmmBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mat1_.reset_data(); + mat2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::Scalar beta; + SavedVariable mat1_; + at::Layout mat1_layout; + std::vector mat1_sym_sizes; + std::vector mat1_sym_strides; + SavedVariable mat2_; + at::Layout mat2_layout; + std::vector mat2_sym_sizes; + std::vector mat2_sym_strides; + +}; +#ifdef _WIN32 +struct SparseAddmmBackward0 : public TraceableFunction { + TORCH_API SparseAddmmBackward0() = default; +#else +struct TORCH_API SparseAddmmBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseAddmmBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mat1_.reset_data(); + mat2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::Scalar beta; + SavedVariable mat1_; + SavedVariable mat2_; + at::Layout mat2_layout; + std::vector mat2_sym_sizes; + std::vector mat2_sym_strides; + +}; +#ifdef _WIN32 +struct AddmvBackward0 : public TraceableFunction { + TORCH_API AddmvBackward0() = default; +#else +struct TORCH_API AddmvBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AddmvBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mat_.reset_data(); + vec_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::Scalar beta; + SavedVariable mat_; + SavedVariable vec_; + +}; +#ifdef _WIN32 +struct AddrBackward0 : public TraceableFunction { + TORCH_API AddrBackward0() = default; +#else +struct TORCH_API AddrBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AddrBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + vec1_.reset_data(); + vec2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::Scalar beta; + SavedVariable vec1_; + SavedVariable vec2_; + +}; +#ifdef _WIN32 +struct AffineGridGeneratorBackward0 : public TraceableFunction { + TORCH_API AffineGridGeneratorBackward0() = default; +#else +struct TORCH_API AffineGridGeneratorBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AffineGridGeneratorBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector size; + +}; +#ifdef _WIN32 +struct AliasBackward0 : public Node { + TORCH_API AliasBackward0() = default; +#else +struct TORCH_API AliasBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AliasBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct AngleBackward0 : public TraceableFunction { + TORCH_API AngleBackward0() = default; +#else +struct TORCH_API AngleBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AngleBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AcoshBackward0 : public TraceableFunction { + TORCH_API AcoshBackward0() = default; +#else +struct TORCH_API AcoshBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AcoshBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AcoshBackward1 : public TraceableFunction { + TORCH_API AcoshBackward1() = default; +#else +struct TORCH_API AcoshBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AcoshBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct AsinhBackward0 : public TraceableFunction { + TORCH_API AsinhBackward0() = default; +#else +struct TORCH_API AsinhBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AsinhBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AsinhBackward1 : public TraceableFunction { + TORCH_API AsinhBackward1() = default; +#else +struct TORCH_API AsinhBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AsinhBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct AtanhBackward0 : public TraceableFunction { + TORCH_API AtanhBackward0() = default; +#else +struct TORCH_API AtanhBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AtanhBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AtanhBackward1 : public TraceableFunction { + TORCH_API AtanhBackward1() = default; +#else +struct TORCH_API AtanhBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AtanhBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct AsStridedBackward0 : public Node { + TORCH_API AsStridedBackward0() = default; +#else +struct TORCH_API AsStridedBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AsStridedBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::TensorGeometry self_geometry; + std::vector size; + ::std::optional storage_offset; + std::vector stride; + +}; +#ifdef _WIN32 +struct AsStridedBackward1 : public TraceableFunction { + TORCH_API AsStridedBackward1() = default; +#else +struct TORCH_API AsStridedBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AsStridedBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::TensorGeometry self_geometry; + std::vector size; + ::std::optional storage_offset; + std::vector stride; + +}; +#ifdef _WIN32 +struct AsinBackward0 : public TraceableFunction { + TORCH_API AsinBackward0() = default; +#else +struct TORCH_API AsinBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AsinBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AtanBackward0 : public TraceableFunction { + TORCH_API AtanBackward0() = default; +#else +struct TORCH_API AtanBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AtanBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct Atan2Backward0 : public TraceableFunction { + TORCH_API Atan2Backward0() = default; +#else +struct TORCH_API Atan2Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Atan2Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct BaddbmmBackward0 : public TraceableFunction { + TORCH_API BaddbmmBackward0() = default; +#else +struct TORCH_API BaddbmmBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BaddbmmBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + batch1_.reset_data(); + batch2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + SavedVariable batch1_; + SavedVariable batch2_; + at::Scalar beta; + +}; +#ifdef _WIN32 +struct BernoulliBackward0 : public TraceableFunction { + TORCH_API BernoulliBackward0() = default; +#else +struct TORCH_API BernoulliBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BernoulliBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct BernoulliBackward1 : public TraceableFunction { + TORCH_API BernoulliBackward1() = default; +#else +struct TORCH_API BernoulliBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BernoulliBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize p_info; + +}; +#ifdef _WIN32 +struct BernoulliBackward2 : public TraceableFunction { + TORCH_API BernoulliBackward2() = default; +#else +struct TORCH_API BernoulliBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BernoulliBackward2"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct BmmBackward0 : public TraceableFunction { + TORCH_API BmmBackward0() = default; +#else +struct TORCH_API BmmBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BmmBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mat2_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mat2_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct MatmulBackward0 : public TraceableFunction { + TORCH_API MatmulBackward0() = default; +#else +struct TORCH_API MatmulBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MatmulBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct CatBackward0 : public TraceableFunction { + TORCH_API CatBackward0() = default; +#else +struct TORCH_API CatBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CatBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + ::std::vector tensors_args_scalartypes; + ::std::vector<::std::vector> tensors_args_sizes_symint; + size_t tensors_size_; +}; +#ifdef _WIN32 +struct CauchyBackward0 : public TraceableFunction { + TORCH_API CauchyBackward0() = default; +#else +struct TORCH_API CauchyBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CauchyBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct CeilBackward0 : public TraceableFunction { + TORCH_API CeilBackward0() = default; +#else +struct TORCH_API CeilBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CeilBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct CholeskyBackward0 : public TraceableFunction { + TORCH_API CholeskyBackward0() = default; +#else +struct TORCH_API CholeskyBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CholeskyBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool upper; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ChunkBackward0 : public TraceableFunction { + TORCH_API ChunkBackward0() = default; +#else +struct TORCH_API ChunkBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ChunkBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ChunkBackwardAutogradNestedTensor0 : public TraceableFunction { + TORCH_API ChunkBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API ChunkBackwardAutogradNestedTensor0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ChunkBackwardAutogradNestedTensor0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t chunks = 0; + int64_t dim = 0; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LinalgCholeskyExBackward0 : public TraceableFunction { + TORCH_API LinalgCholeskyExBackward0() = default; +#else +struct TORCH_API LinalgCholeskyExBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgCholeskyExBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + L_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool upper; + SavedVariable L_; + +}; +#ifdef _WIN32 +struct CholeskySolveBackward0 : public TraceableFunction { + TORCH_API CholeskySolveBackward0() = default; +#else +struct TORCH_API CholeskySolveBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CholeskySolveBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input2_.reset_data(); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable input2_; + SavedVariable self_; + bool upper; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct CholeskyInverseBackward0 : public TraceableFunction { + TORCH_API CholeskyInverseBackward0() = default; +#else +struct TORCH_API CholeskyInverseBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CholeskyInverseBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + bool upper; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ClampBackward0 : public TraceableFunction { + TORCH_API ClampBackward0() = default; +#else +struct TORCH_API ClampBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ClampBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + max_.reset_data(); + min_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable max_; + SavedVariable min_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ClampBackward1 : public TraceableFunction { + TORCH_API ClampBackward1() = default; +#else +struct TORCH_API ClampBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ClampBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional max; + ::std::optional min; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ClampMinBackward0 : public TraceableFunction { + TORCH_API ClampMinBackward0() = default; +#else +struct TORCH_API ClampMinBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ClampMinBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar min; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ClampMinBackward1 : public TraceableFunction { + TORCH_API ClampMinBackward1() = default; +#else +struct TORCH_API ClampMinBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ClampMinBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + min_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable min_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ClampMaxBackward0 : public TraceableFunction { + TORCH_API ClampMaxBackward0() = default; +#else +struct TORCH_API ClampMaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ClampMaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar max; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ClampMaxBackward1 : public TraceableFunction { + TORCH_API ClampMaxBackward1() = default; +#else +struct TORCH_API ClampMaxBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ClampMaxBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + max_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable max_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct CloneBackward0 : public TraceableFunction { + TORCH_API CloneBackward0() = default; +#else +struct TORCH_API CloneBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CloneBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct LazyCloneBackward0 : public TraceableFunction { + TORCH_API LazyCloneBackward0() = default; +#else +struct TORCH_API LazyCloneBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LazyCloneBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ToCopyBackward0 : public TraceableFunction { + TORCH_API ToCopyBackward0() = default; +#else +struct TORCH_API ToCopyBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToCopyBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::TensorOptions self_options; + +}; +#ifdef _WIN32 +struct CoalesceBackward0 : public TraceableFunction { + TORCH_API CoalesceBackward0() = default; +#else +struct TORCH_API CoalesceBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CoalesceBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ComplexBackward0 : public TraceableFunction { + TORCH_API ComplexBackward0() = default; +#else +struct TORCH_API ComplexBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ComplexBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + imag_.reset_data(); + real_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable imag_; + SavedVariable real_; + +}; +#ifdef _WIN32 +struct PolarBackward0 : public TraceableFunction { + TORCH_API PolarBackward0() = default; +#else +struct TORCH_API PolarBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PolarBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ConjBackward0 : public Node { + TORCH_API ConjBackward0() = default; +#else +struct TORCH_API ConjBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConjBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NegViewBackward0 : public Node { + TORCH_API NegViewBackward0() = default; +#else +struct TORCH_API NegViewBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NegViewBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ConjPhysicalBackward0 : public TraceableFunction { + TORCH_API ConjPhysicalBackward0() = default; +#else +struct TORCH_API ConjPhysicalBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConjPhysicalBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ConjPhysicalBackward1 : public TraceableFunction { + TORCH_API ConjPhysicalBackward1() = default; +#else +struct TORCH_API ConjPhysicalBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConjPhysicalBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct CopysignBackward0 : public TraceableFunction { + TORCH_API CopysignBackward0() = default; +#else +struct TORCH_API CopysignBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CopysignBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize other_info; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct CopysignBackward1 : public TraceableFunction { + TORCH_API CopysignBackward1() = default; +#else +struct TORCH_API CopysignBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CopysignBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct CosBackward0 : public TraceableFunction { + TORCH_API CosBackward0() = default; +#else +struct TORCH_API CosBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CosBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct CoshBackward0 : public TraceableFunction { + TORCH_API CoshBackward0() = default; +#else +struct TORCH_API CoshBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CoshBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LinalgCrossBackward0 : public TraceableFunction { + TORCH_API LinalgCrossBackward0() = default; +#else +struct TORCH_API LinalgCrossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgCrossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LogcumsumexpBackward0 : public TraceableFunction { + TORCH_API LogcumsumexpBackward0() = default; +#else +struct TORCH_API LogcumsumexpBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogcumsumexpBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct CumprodBackward0 : public TraceableFunction { + TORCH_API CumprodBackward0() = default; +#else +struct TORCH_API CumprodBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CumprodBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + at::ScalarType self_scalar_type; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct CumsumBackward0 : public TraceableFunction { + TORCH_API CumsumBackward0() = default; +#else +struct TORCH_API CumsumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CumsumBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct CummaxBackward0 : public TraceableFunction { + TORCH_API CummaxBackward0() = default; +#else +struct TORCH_API CummaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CummaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct CumminBackward0 : public TraceableFunction { + TORCH_API CumminBackward0() = default; +#else +struct TORCH_API CumminBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CumminBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct ConvTbcBackward0 : public TraceableFunction { + TORCH_API ConvTbcBackward0() = default; +#else +struct TORCH_API ConvTbcBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConvTbcBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + bias_.reset_data(); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable bias_; + int64_t pad = 0; + SavedVariable self_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct CtcLossBackward0 : public TraceableFunction { + TORCH_API CtcLossBackward0() = default; +#else +struct TORCH_API CtcLossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CtcLossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + log_probs_.reset_data(); + targets_.reset_data(); + result0_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t blank = 0; + std::vector input_lengths; + SavedVariable log_probs_; + std::vector target_lengths; + SavedVariable targets_; + bool zero_infinity; + SavedVariable result0_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct CtcLossBackward1 : public TraceableFunction { + TORCH_API CtcLossBackward1() = default; +#else +struct TORCH_API CtcLossBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CtcLossBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_lengths_.reset_data(); + log_probs_.reset_data(); + target_lengths_.reset_data(); + targets_.reset_data(); + result0_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t blank = 0; + SavedVariable input_lengths_; + SavedVariable log_probs_; + SavedVariable target_lengths_; + SavedVariable targets_; + bool zero_infinity; + SavedVariable result0_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct Deg2RadBackward0 : public TraceableFunction { + TORCH_API Deg2RadBackward0() = default; +#else +struct TORCH_API Deg2RadBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Deg2RadBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct LinalgDetBackward0 : public TraceableFunction { + TORCH_API LinalgDetBackward0() = default; +#else +struct TORCH_API LinalgDetBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgDetBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + A_.reset_data(); + LU_.reset_data(); + pivots_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable A_; + SavedVariable LU_; + SavedVariable pivots_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct LinalgSlogdetBackward0 : public TraceableFunction { + TORCH_API LinalgSlogdetBackward0() = default; +#else +struct TORCH_API LinalgSlogdetBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgSlogdetBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + A_.reset_data(); + LU_.reset_data(); + pivots_.reset_data(); + sign_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable A_; + SavedVariable LU_; + SavedVariable pivots_; + SavedVariable sign_; + +}; +#ifdef _WIN32 +struct BlockDiagBackward0 : public TraceableFunction { + TORCH_API BlockDiagBackward0() = default; +#else +struct TORCH_API BlockDiagBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BlockDiagBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::vector tensors_args_scalartypes; + ::std::vector<::std::vector> tensors_args_sizes; + size_t tensors_size_; +}; +#ifdef _WIN32 +struct DiagEmbedBackward0 : public TraceableFunction { + TORCH_API DiagEmbedBackward0() = default; +#else +struct TORCH_API DiagEmbedBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DiagEmbedBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim1 = 0; + int64_t dim2 = 0; + int64_t offset = 0; + +}; +#ifdef _WIN32 +struct DiagonalBackward0 : public Node { + TORCH_API DiagonalBackward0() = default; +#else +struct TORCH_API DiagonalBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DiagonalBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim1 = 0; + int64_t dim2 = 0; + int64_t offset = 0; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct DiagonalBackwardBackward0 : public TraceableFunction { + TORCH_API DiagonalBackwardBackward0() = default; +#else +struct TORCH_API DiagonalBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DiagonalBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim1 = 0; + int64_t dim2 = 0; + int64_t offset = 0; + +}; +#ifdef _WIN32 +struct DistBackward0 : public TraceableFunction { + TORCH_API DistBackward0() = default; +#else +struct TORCH_API DistBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DistBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + at::Scalar p; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct DivBackward0 : public TraceableFunction { + TORCH_API DivBackward0() = default; +#else +struct TORCH_API DivBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DivBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct DivBackward1 : public TraceableFunction { + TORCH_API DivBackward1() = default; +#else +struct TORCH_API DivBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DivBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar other; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct DivBackward2 : public TraceableFunction { + TORCH_API DivBackward2() = default; +#else +struct TORCH_API DivBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DivBackward2"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + std::optional rounding_mode; + SavedVariable self_; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct DivBackward3 : public TraceableFunction { + TORCH_API DivBackward3() = default; +#else +struct TORCH_API DivBackward3 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DivBackward3"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar other; + std::optional rounding_mode; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct DotBackward0 : public TraceableFunction { + TORCH_API DotBackward0() = default; +#else +struct TORCH_API DotBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DotBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + tensor_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable tensor_; + +}; +#ifdef _WIN32 +struct VdotBackward0 : public TraceableFunction { + TORCH_API VdotBackward0() = default; +#else +struct TORCH_API VdotBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "VdotBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct FusedDropoutBackward0 : public TraceableFunction { + TORCH_API FusedDropoutBackward0() = default; +#else +struct TORCH_API FusedDropoutBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FusedDropoutBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double p; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct NativeDropoutBackward0 : public TraceableFunction { + TORCH_API NativeDropoutBackward0() = default; +#else +struct TORCH_API NativeDropoutBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeDropoutBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double p; + ::std::optional train; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct NativeDropoutBackwardBackward0 : public TraceableFunction { + TORCH_API NativeDropoutBackwardBackward0() = default; +#else +struct TORCH_API NativeDropoutBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeDropoutBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + SavedVariable mask_; + double scale; + +}; +#ifdef _WIN32 +struct EqBackward0 : public TraceableFunction { + TORCH_API EqBackward0() = default; +#else +struct TORCH_API EqBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EqBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct EqBackward1 : public TraceableFunction { + TORCH_API EqBackward1() = default; +#else +struct TORCH_API EqBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EqBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize other_info; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct ErfBackward0 : public TraceableFunction { + TORCH_API ErfBackward0() = default; +#else +struct TORCH_API ErfBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ErfBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ErfcBackward0 : public TraceableFunction { + TORCH_API ErfcBackward0() = default; +#else +struct TORCH_API ErfcBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ErfcBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SpecialErfcxBackward0 : public TraceableFunction { + TORCH_API SpecialErfcxBackward0() = default; +#else +struct TORCH_API SpecialErfcxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialErfcxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ErfinvBackward0 : public TraceableFunction { + TORCH_API ErfinvBackward0() = default; +#else +struct TORCH_API ErfinvBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ErfinvBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ExpBackward0 : public TraceableFunction { + TORCH_API ExpBackward0() = default; +#else +struct TORCH_API ExpBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ExpBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct Exp2Backward0 : public TraceableFunction { + TORCH_API Exp2Backward0() = default; +#else +struct TORCH_API Exp2Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Exp2Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct Expm1Backward0 : public TraceableFunction { + TORCH_API Expm1Backward0() = default; +#else +struct TORCH_API Expm1Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Expm1Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ExpandBackward0 : public Node { + TORCH_API ExpandBackward0() = default; +#else +struct TORCH_API ExpandBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ExpandBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct ExponentialBackward0 : public TraceableFunction { + TORCH_API ExponentialBackward0() = default; +#else +struct TORCH_API ExponentialBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ExponentialBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FakeQuantizePerTensorAffineCachemaskBackward0 : public TraceableFunction { + TORCH_API FakeQuantizePerTensorAffineCachemaskBackward0() = default; +#else +struct TORCH_API FakeQuantizePerTensorAffineCachemaskBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FakeQuantizePerTensorAffineCachemaskBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + +}; +#ifdef _WIN32 +struct FakeQuantizePerTensorAffineCachemaskTensorQparamsBackward0 : public TraceableFunction { + TORCH_API FakeQuantizePerTensorAffineCachemaskTensorQparamsBackward0() = default; +#else +struct TORCH_API FakeQuantizePerTensorAffineCachemaskTensorQparamsBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FakeQuantizePerTensorAffineCachemaskTensorQparamsBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + +}; +#ifdef _WIN32 +struct FakeQuantizeLearnablePerTensorAffineBackward0 : public TraceableFunction { + TORCH_API FakeQuantizeLearnablePerTensorAffineBackward0() = default; +#else +struct TORCH_API FakeQuantizeLearnablePerTensorAffineBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FakeQuantizeLearnablePerTensorAffineBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scale_.reset_data(); + self_.reset_data(); + zero_point_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double grad_factor; + int64_t quant_max = 0; + int64_t quant_min = 0; + SavedVariable scale_; + SavedVariable self_; + SavedVariable zero_point_; + +}; +#ifdef _WIN32 +struct FakeQuantizePerChannelAffineCachemaskBackward0 : public TraceableFunction { + TORCH_API FakeQuantizePerChannelAffineCachemaskBackward0() = default; +#else +struct TORCH_API FakeQuantizePerChannelAffineCachemaskBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FakeQuantizePerChannelAffineCachemaskBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + +}; +#ifdef _WIN32 +struct FakeQuantizeLearnablePerChannelAffineBackward0 : public TraceableFunction { + TORCH_API FakeQuantizeLearnablePerChannelAffineBackward0() = default; +#else +struct TORCH_API FakeQuantizeLearnablePerChannelAffineBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FakeQuantizeLearnablePerChannelAffineBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scale_.reset_data(); + self_.reset_data(); + zero_point_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t axis = 0; + double grad_factor; + int64_t quant_max = 0; + int64_t quant_min = 0; + SavedVariable scale_; + SavedVariable self_; + SavedVariable zero_point_; + +}; +#ifdef _WIN32 +struct FusedMovingAvgObsFqHelperBackward0 : public TraceableFunction { + TORCH_API FusedMovingAvgObsFqHelperBackward0() = default; +#else +struct TORCH_API FusedMovingAvgObsFqHelperBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FusedMovingAvgObsFqHelperBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + +}; +#ifdef _WIN32 +struct FillBackward0 : public TraceableFunction { + TORCH_API FillBackward0() = default; +#else +struct TORCH_API FillBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FillBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FillBackward1 : public TraceableFunction { + TORCH_API FillBackward1() = default; +#else +struct TORCH_API FillBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FillBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FillBackward2 : public TraceableFunction { + TORCH_API FillBackward2() = default; +#else +struct TORCH_API FillBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FillBackward2"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FillBackward3 : public TraceableFunction { + TORCH_API FillBackward3() = default; +#else +struct TORCH_API FillBackward3 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FillBackward3"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FloorBackward0 : public TraceableFunction { + TORCH_API FloorBackward0() = default; +#else +struct TORCH_API FloorBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FloorBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FmodBackward0 : public TraceableFunction { + TORCH_API FmodBackward0() = default; +#else +struct TORCH_API FmodBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FmodBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FmodBackward1 : public TraceableFunction { + TORCH_API FmodBackward1() = default; +#else +struct TORCH_API FmodBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FmodBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct FracBackward0 : public TraceableFunction { + TORCH_API FracBackward0() = default; +#else +struct TORCH_API FracBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FracBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FrexpBackward0 : public TraceableFunction { + TORCH_API FrexpBackward0() = default; +#else +struct TORCH_API FrexpBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FrexpBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + exponent_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable exponent_; + +}; +#ifdef _WIN32 +struct GatherBackward0 : public TraceableFunction { + TORCH_API GatherBackward0() = default; +#else +struct TORCH_API GatherBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GatherBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable index_; + SavedVariable self_; + bool sparse_grad; + +}; +#ifdef _WIN32 +struct GeBackward0 : public TraceableFunction { + TORCH_API GeBackward0() = default; +#else +struct TORCH_API GeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GeBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct GeBackward1 : public TraceableFunction { + TORCH_API GeBackward1() = default; +#else +struct TORCH_API GeBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GeBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize other_info; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct GeometricBackward0 : public TraceableFunction { + TORCH_API GeometricBackward0() = default; +#else +struct TORCH_API GeometricBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GeometricBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct GeqrfBackward0 : public TraceableFunction { + TORCH_API GeqrfBackward0() = default; +#else +struct TORCH_API GeqrfBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GeqrfBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct GridSampler2DBackward0 : public TraceableFunction { + TORCH_API GridSampler2DBackward0() = default; +#else +struct TORCH_API GridSampler2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GridSampler2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grid_.reset_data(); + input_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + SavedVariable grid_; + SavedVariable input_; + int64_t interpolation_mode = 0; + int64_t padding_mode = 0; + +}; +#ifdef _WIN32 +struct GridSampler3DBackward0 : public TraceableFunction { + TORCH_API GridSampler3DBackward0() = default; +#else +struct TORCH_API GridSampler3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GridSampler3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grid_.reset_data(); + input_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + SavedVariable grid_; + SavedVariable input_; + int64_t interpolation_mode = 0; + int64_t padding_mode = 0; + +}; +#ifdef _WIN32 +struct GridSampler2DCpuFallbackBackward0 : public TraceableFunction { + TORCH_API GridSampler2DCpuFallbackBackward0() = default; +#else +struct TORCH_API GridSampler2DCpuFallbackBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GridSampler2DCpuFallbackBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grid_.reset_data(); + input_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + SavedVariable grid_; + SavedVariable input_; + int64_t interpolation_mode = 0; + int64_t padding_mode = 0; + +}; +#ifdef _WIN32 +struct GtBackward0 : public TraceableFunction { + TORCH_API GtBackward0() = default; +#else +struct TORCH_API GtBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GtBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct GtBackward1 : public TraceableFunction { + TORCH_API GtBackward1() = default; +#else +struct TORCH_API GtBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GtBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize other_info; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct HardsigmoidBackward0 : public TraceableFunction { + TORCH_API HardsigmoidBackward0() = default; +#else +struct TORCH_API HardsigmoidBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HardsigmoidBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct HardswishBackward0 : public TraceableFunction { + TORCH_API HardswishBackward0() = default; +#else +struct TORCH_API HardswishBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HardswishBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct HardswishBackwardBackward0 : public TraceableFunction { + TORCH_API HardswishBackwardBackward0() = default; +#else +struct TORCH_API HardswishBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HardswishBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + SavedVariable self_; + at::TensorOptions self_options; + +}; +#ifdef _WIN32 +struct HypotBackward0 : public TraceableFunction { + TORCH_API HypotBackward0() = default; +#else +struct TORCH_API HypotBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HypotBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct I0Backward0 : public TraceableFunction { + TORCH_API I0Backward0() = default; +#else +struct TORCH_API I0Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "I0Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SpecialI0EBackward0 : public TraceableFunction { + TORCH_API SpecialI0EBackward0() = default; +#else +struct TORCH_API SpecialI0EBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialI0EBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SpecialI1Backward0 : public TraceableFunction { + TORCH_API SpecialI1Backward0() = default; +#else +struct TORCH_API SpecialI1Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialI1Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SpecialI1EBackward0 : public TraceableFunction { + TORCH_API SpecialI1EBackward0() = default; +#else +struct TORCH_API SpecialI1EBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialI1EBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct IgammaBackward0 : public TraceableFunction { + TORCH_API IgammaBackward0() = default; +#else +struct TORCH_API IgammaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IgammaBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct IgammacBackward0 : public TraceableFunction { + TORCH_API IgammacBackward0() = default; +#else +struct TORCH_API IgammacBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IgammacBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct IndexBackward0 : public TraceableFunction { + TORCH_API IndexBackward0() = default; +#else +struct TORCH_API IndexBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.clear(); + indices_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector indices_; + bool indices_released_ = false; + at::TensorOptions self_options; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UnsafeIndexBackward0 : public TraceableFunction { + TORCH_API UnsafeIndexBackward0() = default; +#else +struct TORCH_API UnsafeIndexBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsafeIndexBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.clear(); + indices_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector indices_; + bool indices_released_ = false; + at::TensorOptions self_options; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UnsafeMaskedIndexBackward0 : public TraceableFunction { + TORCH_API UnsafeMaskedIndexBackward0() = default; +#else +struct TORCH_API UnsafeMaskedIndexBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsafeMaskedIndexBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.clear(); + indices_released_ = true; + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector indices_; + bool indices_released_ = false; + SavedVariable mask_; + at::TensorOptions self_options; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UnsafeMaskedIndexPutAccumulateBackward0 : public TraceableFunction { + TORCH_API UnsafeMaskedIndexPutAccumulateBackward0() = default; +#else +struct TORCH_API UnsafeMaskedIndexPutAccumulateBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsafeMaskedIndexPutAccumulateBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.clear(); + indices_released_ = true; + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector indices_; + bool indices_released_ = false; + SavedVariable mask_; + +}; +#ifdef _WIN32 +struct IndexAddBackward0 : public TraceableFunction { + TORCH_API IndexAddBackward0() = default; +#else +struct TORCH_API IndexAddBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexAddBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + source_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + int64_t dim = 0; + SavedVariable index_; + SavedVariable source_; + int64_t source_dim = 0; + +}; +#ifdef _WIN32 +struct IndexReduceBackward0 : public TraceableFunction { + TORCH_API IndexReduceBackward0() = default; +#else +struct TORCH_API IndexReduceBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexReduceBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + self_.reset_data(); + source_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool include_self; + SavedVariable index_; + std::string reduce; + SavedVariable self_; + SavedVariable source_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct IndexCopyBackward0 : public TraceableFunction { + TORCH_API IndexCopyBackward0() = default; +#else +struct TORCH_API IndexCopyBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexCopyBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + source_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable index_; + SavedVariable source_; + int64_t source_dim = 0; + +}; +#ifdef _WIN32 +struct IndexFillBackward0 : public TraceableFunction { + TORCH_API IndexFillBackward0() = default; +#else +struct TORCH_API IndexFillBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexFillBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable index_; + +}; +#ifdef _WIN32 +struct IndexFillBackward1 : public TraceableFunction { + TORCH_API IndexFillBackward1() = default; +#else +struct TORCH_API IndexFillBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexFillBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable index_; + +}; +#ifdef _WIN32 +struct IndexPutBackward0 : public TraceableFunction { + TORCH_API IndexPutBackward0() = default; +#else +struct TORCH_API IndexPutBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexPutBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.clear(); + indices_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool accumulate; + std::vector indices_; + bool indices_released_ = false; + torch::autograd::generated::TypeAndSize values_info; + +}; +#ifdef _WIN32 +struct UnsafeIndexPutBackward0 : public TraceableFunction { + TORCH_API UnsafeIndexPutBackward0() = default; +#else +struct TORCH_API UnsafeIndexPutBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsafeIndexPutBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.clear(); + indices_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool accumulate; + std::vector indices_; + bool indices_released_ = false; + torch::autograd::generated::TypeAndSize values_info; + +}; +#ifdef _WIN32 +struct IndexPutImplBackward0 : public TraceableFunction { + TORCH_API IndexPutImplBackward0() = default; +#else +struct TORCH_API IndexPutImplBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexPutImplBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.clear(); + indices_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool accumulate; + std::vector indices_; + bool indices_released_ = false; + torch::autograd::generated::TypeAndSize values_info; + +}; +#ifdef _WIN32 +struct IndexSelectBackward0 : public TraceableFunction { + TORCH_API IndexSelectBackward0() = default; +#else +struct TORCH_API IndexSelectBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "IndexSelectBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable index_; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct LinalgInvExBackward0 : public TraceableFunction { + TORCH_API LinalgInvExBackward0() = default; +#else +struct TORCH_API LinalgInvExBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgInvExBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + inverse_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable inverse_; + +}; +#ifdef _WIN32 +struct LinalgPinvBackward0 : public TraceableFunction { + TORCH_API LinalgPinvBackward0() = default; +#else +struct TORCH_API LinalgPinvBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgPinvBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct KthvalueBackward0 : public TraceableFunction { + TORCH_API KthvalueBackward0() = default; +#else +struct TORCH_API KthvalueBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "KthvalueBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool keepdim; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct LeBackward0 : public TraceableFunction { + TORCH_API LeBackward0() = default; +#else +struct TORCH_API LeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LeBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct LeBackward1 : public TraceableFunction { + TORCH_API LeBackward1() = default; +#else +struct TORCH_API LeBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LeBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize other_info; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct LerpBackward0 : public TraceableFunction { + TORCH_API LerpBackward0() = default; +#else +struct TORCH_API LerpBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LerpBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar weight; + +}; +#ifdef _WIN32 +struct LerpBackward1 : public TraceableFunction { + TORCH_API LerpBackward1() = default; +#else +struct TORCH_API LerpBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LerpBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + end_.reset_data(); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable end_; + SavedVariable self_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct LgammaBackward0 : public TraceableFunction { + TORCH_API LgammaBackward0() = default; +#else +struct TORCH_API LgammaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LgammaBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct DigammaBackward0 : public TraceableFunction { + TORCH_API DigammaBackward0() = default; +#else +struct TORCH_API DigammaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DigammaBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct PolygammaBackward0 : public TraceableFunction { + TORCH_API PolygammaBackward0() = default; +#else +struct TORCH_API PolygammaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PolygammaBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t n = 0; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct PolygammaBackward1 : public TraceableFunction { + TORCH_API PolygammaBackward1() = default; +#else +struct TORCH_API PolygammaBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PolygammaBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t n = 0; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LogBackward0 : public TraceableFunction { + TORCH_API LogBackward0() = default; +#else +struct TORCH_API LogBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct Log10Backward0 : public TraceableFunction { + TORCH_API Log10Backward0() = default; +#else +struct TORCH_API Log10Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Log10Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct Log1PBackward0 : public TraceableFunction { + TORCH_API Log1PBackward0() = default; +#else +struct TORCH_API Log1PBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Log1PBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct Log2Backward0 : public TraceableFunction { + TORCH_API Log2Backward0() = default; +#else +struct TORCH_API Log2Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Log2Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LogaddexpBackward0 : public TraceableFunction { + TORCH_API LogaddexpBackward0() = default; +#else +struct TORCH_API LogaddexpBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogaddexpBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct Logaddexp2Backward0 : public TraceableFunction { + TORCH_API Logaddexp2Backward0() = default; +#else +struct TORCH_API Logaddexp2Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Logaddexp2Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct XlogyBackward0 : public TraceableFunction { + TORCH_API XlogyBackward0() = default; +#else +struct TORCH_API XlogyBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "XlogyBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct XlogyBackward1 : public TraceableFunction { + TORCH_API XlogyBackward1() = default; +#else +struct TORCH_API XlogyBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "XlogyBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + at::Scalar self; + +}; +#ifdef _WIN32 +struct XlogyBackward2 : public TraceableFunction { + TORCH_API XlogyBackward2() = default; +#else +struct TORCH_API XlogyBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "XlogyBackward2"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar other; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SpecialXlog1PyBackward0 : public TraceableFunction { + TORCH_API SpecialXlog1PyBackward0() = default; +#else +struct TORCH_API SpecialXlog1PyBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialXlog1PyBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SpecialXlog1PyBackward1 : public TraceableFunction { + TORCH_API SpecialXlog1PyBackward1() = default; +#else +struct TORCH_API SpecialXlog1PyBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialXlog1PyBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + at::Scalar self; + +}; +#ifdef _WIN32 +struct SpecialXlog1PyBackward2 : public TraceableFunction { + TORCH_API SpecialXlog1PyBackward2() = default; +#else +struct TORCH_API SpecialXlog1PyBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialXlog1PyBackward2"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar other; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SpecialZetaBackward0 : public TraceableFunction { + TORCH_API SpecialZetaBackward0() = default; +#else +struct TORCH_API SpecialZetaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialZetaBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SpecialZetaBackward1 : public TraceableFunction { + TORCH_API SpecialZetaBackward1() = default; +#else +struct TORCH_API SpecialZetaBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialZetaBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + at::Scalar self; + +}; +#ifdef _WIN32 +struct SpecialZetaBackward2 : public TraceableFunction { + TORCH_API SpecialZetaBackward2() = default; +#else +struct TORCH_API SpecialZetaBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialZetaBackward2"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct LogNormalBackward0 : public TraceableFunction { + TORCH_API LogNormalBackward0() = default; +#else +struct TORCH_API LogNormalBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogNormalBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct LogsumexpBackward0 : public TraceableFunction { + TORCH_API LogsumexpBackward0() = default; +#else +struct TORCH_API LogsumexpBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogsumexpBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + bool keepdim; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct LinalgLstsqBackward0 : public TraceableFunction { + TORCH_API LinalgLstsqBackward0() = default; +#else +struct TORCH_API LinalgLstsqBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgLstsqBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + b_.reset_data(); + self_.reset_data(); + solution_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable b_; + SavedVariable self_; + SavedVariable solution_; + +}; +#ifdef _WIN32 +struct LtBackward0 : public TraceableFunction { + TORCH_API LtBackward0() = default; +#else +struct TORCH_API LtBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LtBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct LtBackward1 : public TraceableFunction { + TORCH_API LtBackward1() = default; +#else +struct TORCH_API LtBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LtBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize other_info; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct LinalgLuFactorExBackward0 : public TraceableFunction { + TORCH_API LinalgLuFactorExBackward0() = default; +#else +struct TORCH_API LinalgLuFactorExBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgLuFactorExBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + LU_.reset_data(); + pivots_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool pivot; + SavedVariable LU_; + SavedVariable pivots_; + +}; +#ifdef _WIN32 +struct LinalgLuBackward0 : public TraceableFunction { + TORCH_API LinalgLuBackward0() = default; +#else +struct TORCH_API LinalgLuBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgLuBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + L_.reset_data(); + P_.reset_data(); + U_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool pivot; + SavedVariable L_; + SavedVariable P_; + SavedVariable U_; + +}; +#ifdef _WIN32 +struct LinalgLuSolveBackward0 : public TraceableFunction { + TORCH_API LinalgLuSolveBackward0() = default; +#else +struct TORCH_API LinalgLuSolveBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgLuSolveBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + LU_.reset_data(); + pivots_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable LU_; + bool adjoint; + bool left; + SavedVariable pivots_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct LuUnpackBackward0 : public TraceableFunction { + TORCH_API LuUnpackBackward0() = default; +#else +struct TORCH_API LuUnpackBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LuUnpackBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt LU_data_sym_argsize_minus_1; + c10::SymInt LU_data_sym_argsize_minus_2; + +}; +#ifdef _WIN32 +struct MaskedFillBackward0 : public TraceableFunction { + TORCH_API MaskedFillBackward0() = default; +#else +struct TORCH_API MaskedFillBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaskedFillBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + +}; +#ifdef _WIN32 +struct MaskedFillBackward1 : public TraceableFunction { + TORCH_API MaskedFillBackward1() = default; +#else +struct TORCH_API MaskedFillBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaskedFillBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + +}; +#ifdef _WIN32 +struct MaskedScatterBackward0 : public TraceableFunction { + TORCH_API MaskedScatterBackward0() = default; +#else +struct TORCH_API MaskedScatterBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaskedScatterBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + std::vector source_sym_sizes; + +}; +#ifdef _WIN32 +struct MaskedScatterBackwardBackward0 : public TraceableFunction { + TORCH_API MaskedScatterBackwardBackward0() = default; +#else +struct TORCH_API MaskedScatterBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaskedScatterBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize grad_output_info; + SavedVariable mask_; + +}; +#ifdef _WIN32 +struct MaskedSelectBackward0 : public TraceableFunction { + TORCH_API MaskedSelectBackward0() = default; +#else +struct TORCH_API MaskedSelectBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaskedSelectBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LinalgMatrixExpBackward0 : public TraceableFunction { + TORCH_API LinalgMatrixExpBackward0() = default; +#else +struct TORCH_API LinalgMatrixExpBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgMatrixExpBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct MaxBackward0 : public TraceableFunction { + TORCH_API MaxBackward0() = default; +#else +struct TORCH_API MaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool keepdim; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct MaxBackward1 : public TraceableFunction { + TORCH_API MaxBackward1() = default; +#else +struct TORCH_API MaxBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct MaximumBackward0 : public TraceableFunction { + TORCH_API MaximumBackward0() = default; +#else +struct TORCH_API MaximumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaximumBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct FmaxBackward0 : public TraceableFunction { + TORCH_API FmaxBackward0() = default; +#else +struct TORCH_API FmaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FmaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct MeanBackward0 : public TraceableFunction { + TORCH_API MeanBackward0() = default; +#else +struct TORCH_API MeanBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MeanBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt self_sym_numel; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct MeanBackwardAutogradNestedTensor0 : public TraceableFunction { + TORCH_API MeanBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API MeanBackwardAutogradNestedTensor0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MeanBackwardAutogradNestedTensor0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + c10::SymInt self_sym_numel; + +}; +#ifdef _WIN32 +struct MeanBackward1 : public TraceableFunction { + TORCH_API MeanBackward1() = default; +#else +struct TORCH_API MeanBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MeanBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray dim; + bool keepdim; + c10::SymInt self_sym_numel; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct MedianBackward0 : public TraceableFunction { + TORCH_API MedianBackward0() = default; +#else +struct TORCH_API MedianBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MedianBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct NanmedianBackward0 : public TraceableFunction { + TORCH_API NanmedianBackward0() = default; +#else +struct TORCH_API NanmedianBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NanmedianBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct MedianBackward1 : public TraceableFunction { + TORCH_API MedianBackward1() = default; +#else +struct TORCH_API MedianBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MedianBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool keepdim; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct NanmedianBackward1 : public TraceableFunction { + TORCH_API NanmedianBackward1() = default; +#else +struct TORCH_API NanmedianBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NanmedianBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool keepdim; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct MinBackward0 : public TraceableFunction { + TORCH_API MinBackward0() = default; +#else +struct TORCH_API MinBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MinBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool keepdim; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct MinBackward1 : public TraceableFunction { + TORCH_API MinBackward1() = default; +#else +struct TORCH_API MinBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MinBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct MinimumBackward0 : public TraceableFunction { + TORCH_API MinimumBackward0() = default; +#else +struct TORCH_API MinimumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MinimumBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct FminBackward0 : public TraceableFunction { + TORCH_API FminBackward0() = default; +#else +struct TORCH_API FminBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FminBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AmaxBackward0 : public TraceableFunction { + TORCH_API AmaxBackward0() = default; +#else +struct TORCH_API AmaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AmaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + bool keepdim; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct AminBackward0 : public TraceableFunction { + TORCH_API AminBackward0() = default; +#else +struct TORCH_API AminBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AminBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + bool keepdim; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct MmBackward0 : public TraceableFunction { + TORCH_API MmBackward0() = default; +#else +struct TORCH_API MmBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MmBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mat2_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mat2_; + at::Layout mat2_layout; + std::vector mat2_sym_sizes; + std::vector mat2_sym_strides; + SavedVariable self_; + at::Layout self_layout; + std::vector self_sym_sizes; + std::vector self_sym_strides; + +}; +#ifdef _WIN32 +struct GroupedMmBackward0 : public TraceableFunction { + TORCH_API GroupedMmBackward0() = default; +#else +struct TORCH_API GroupedMmBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GroupedMmBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mat2_.reset_data(); + offs_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mat2_; + at::Layout mat2_layout; + std::vector mat2_sym_sizes; + std::vector mat2_sym_strides; + SavedVariable offs_; + SavedVariable self_; + at::Layout self_layout; + std::vector self_sym_sizes; + std::vector self_sym_strides; + +}; +#ifdef _WIN32 +struct ModeBackward0 : public TraceableFunction { + TORCH_API ModeBackward0() = default; +#else +struct TORCH_API ModeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ModeBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool keepdim; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct MulBackward0 : public TraceableFunction { + TORCH_API MulBackward0() = default; +#else +struct TORCH_API MulBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MulBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + at::ScalarType other_scalar_type; + SavedVariable self_; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct MulBackward1 : public TraceableFunction { + TORCH_API MulBackward1() = default; +#else +struct TORCH_API MulBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MulBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar other; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct MvBackward0 : public TraceableFunction { + TORCH_API MvBackward0() = default; +#else +struct TORCH_API MvBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MvBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + vec_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable vec_; + +}; +#ifdef _WIN32 +struct MvlgammaBackward0 : public TraceableFunction { + TORCH_API MvlgammaBackward0() = default; +#else +struct TORCH_API MvlgammaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MvlgammaBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t p = 0; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct NanToNumBackward0 : public TraceableFunction { + TORCH_API NanToNumBackward0() = default; +#else +struct TORCH_API NanToNumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NanToNumBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct NativeBatchNormBackward0 : public TraceableFunction { + TORCH_API NativeBatchNormBackward0() = default; +#else +struct TORCH_API NativeBatchNormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeBatchNormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double eps; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + bool training; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + +}; +#ifdef _WIN32 +struct NativeBatchNormLegitBackward0 : public TraceableFunction { + TORCH_API NativeBatchNormLegitBackward0() = default; +#else +struct TORCH_API NativeBatchNormLegitBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeBatchNormLegitBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double eps; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + bool training; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + +}; +#ifdef _WIN32 +struct NativeBatchNormLegitNoTrainingBackward0 : public TraceableFunction { + TORCH_API NativeBatchNormLegitNoTrainingBackward0() = default; +#else +struct TORCH_API NativeBatchNormLegitNoTrainingBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeBatchNormLegitNoTrainingBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double eps; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + +}; +#ifdef _WIN32 +struct NativeBatchNormLegitBackward1 : public TraceableFunction { + TORCH_API NativeBatchNormLegitBackward1() = default; +#else +struct TORCH_API NativeBatchNormLegitBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeBatchNormLegitBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double eps; + SavedVariable input_; + bool training; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + +}; +#ifdef _WIN32 +struct NativeBatchNormBackwardBackward0 : public TraceableFunction { + TORCH_API NativeBatchNormBackwardBackward0() = default; +#else +struct TORCH_API NativeBatchNormBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeBatchNormBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_out_.reset_data(); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + save_invstd_.reset_data(); + save_mean_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double eps; + SavedVariable grad_out_; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + SavedVariable save_invstd_; + SavedVariable save_mean_; + bool train; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct NativeLayerNormBackward0 : public TraceableFunction { + TORCH_API NativeLayerNormBackward0() = default; +#else +struct TORCH_API NativeLayerNormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeLayerNormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + bias_.reset_data(); + input_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable bias_; + SavedVariable input_; + std::vector normalized_shape; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + +}; +#ifdef _WIN32 +struct NativeLayerNormBackwardBackward0 : public TraceableFunction { + TORCH_API NativeLayerNormBackwardBackward0() = default; +#else +struct TORCH_API NativeLayerNormBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeLayerNormBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_out_.reset_data(); + input_.reset_data(); + mean_.reset_data(); + rstd_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_out_; + SavedVariable input_; + SavedVariable mean_; + std::vector normalized_shape; + SavedVariable rstd_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct FusedRmsNormBackward0 : public TraceableFunction { + TORCH_API FusedRmsNormBackward0() = default; +#else +struct TORCH_API FusedRmsNormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FusedRmsNormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable input_; + std::vector normalized_shape; + SavedVariable weight_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct NativeGroupNormBackward0 : public TraceableFunction { + TORCH_API NativeGroupNormBackward0() = default; +#else +struct TORCH_API NativeGroupNormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NativeGroupNormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt C; + c10::SymInt HxW; + c10::SymInt N; + double eps; + int64_t group = 0; + SavedVariable input_; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + +}; +#ifdef _WIN32 +struct NeBackward0 : public TraceableFunction { + TORCH_API NeBackward0() = default; +#else +struct TORCH_API NeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NeBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct NeBackward1 : public TraceableFunction { + TORCH_API NeBackward1() = default; +#else +struct TORCH_API NeBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NeBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize other_info; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct NegBackward0 : public TraceableFunction { + TORCH_API NegBackward0() = default; +#else +struct TORCH_API NegBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NegBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct BatchNormWithUpdateBackward0 : public TraceableFunction { + TORCH_API BatchNormWithUpdateBackward0() = default; +#else +struct TORCH_API BatchNormWithUpdateBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BatchNormWithUpdateBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + result3_.reset_data(); + } + bool retain_variables = true; + void will_release_variables() override { + retain_variables = false; + } + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double eps; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + SavedVariable result3_; + +}; +#ifdef _WIN32 +struct BatchNormNoUpdateBackward0 : public TraceableFunction { + TORCH_API BatchNormNoUpdateBackward0() = default; +#else +struct TORCH_API BatchNormNoUpdateBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BatchNormNoUpdateBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + result3_.reset_data(); + } + bool retain_variables = true; + void will_release_variables() override { + retain_variables = false; + } + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double eps; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + SavedVariable result3_; + +}; +#ifdef _WIN32 +struct BatchNormBackwardBackward0 : public TraceableFunction { + TORCH_API BatchNormBackwardBackward0() = default; +#else +struct TORCH_API BatchNormBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BatchNormBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_out_.reset_data(); + input_.reset_data(); + reserve_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + save_mean_.reset_data(); + save_var_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double eps; + SavedVariable grad_out_; + SavedVariable input_; + SavedVariable reserve_; + SavedVariable running_mean_; + SavedVariable running_var_; + SavedVariable save_mean_; + SavedVariable save_var_; + bool update; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct NextafterBackward0 : public TraceableFunction { + TORCH_API NextafterBackward0() = default; +#else +struct TORCH_API NextafterBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NextafterBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NormBackward0 : public TraceableFunction { + TORCH_API NormBackward0() = default; +#else +struct TORCH_API NormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar p; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct NormBackward1 : public TraceableFunction { + TORCH_API NormBackward1() = default; +#else +struct TORCH_API NormBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NormBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + bool keepdim; + ::std::optional p; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct NormBackward2 : public TraceableFunction { + TORCH_API NormBackward2() = default; +#else +struct TORCH_API NormBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NormBackward2"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional p; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct NormBackward3 : public TraceableFunction { + TORCH_API NormBackward3() = default; +#else +struct TORCH_API NormBackward3 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NormBackward3"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + bool keepdim; + ::std::optional p; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct LinalgVectorNormBackward0 : public TraceableFunction { + TORCH_API LinalgVectorNormBackward0() = default; +#else +struct TORCH_API LinalgVectorNormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgVectorNormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray dim; + bool keepdim; + at::Scalar ord; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct PdistBackward0 : public TraceableFunction { + TORCH_API PdistBackward0() = default; +#else +struct TORCH_API PdistBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PdistBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double p; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct PdistBackwardBackward0 : public TraceableFunction { + TORCH_API PdistBackwardBackward0() = default; +#else +struct TORCH_API PdistBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PdistBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct EuclideanDistBackward0 : public TraceableFunction { + TORCH_API EuclideanDistBackward0() = default; +#else +struct TORCH_API EuclideanDistBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EuclideanDistBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + x1_.reset_data(); + x2_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable x1_; + SavedVariable x2_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct CdistBackward0 : public TraceableFunction { + TORCH_API CdistBackward0() = default; +#else +struct TORCH_API CdistBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CdistBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + x1_.reset_data(); + x2_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double p; + SavedVariable x1_; + SavedVariable x2_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct CdistBackwardBackward0 : public TraceableFunction { + TORCH_API CdistBackwardBackward0() = default; +#else +struct TORCH_API CdistBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CdistBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NormalBackward0 : public TraceableFunction { + TORCH_API NormalBackward0() = default; +#else +struct TORCH_API NormalBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NormalBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NormalBackward1 : public TraceableFunction { + TORCH_API NormalBackward1() = default; +#else +struct TORCH_API NormalBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NormalBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector mean_sym_sizes; + +}; +#ifdef _WIN32 +struct NormalBackward2 : public TraceableFunction { + TORCH_API NormalBackward2() = default; +#else +struct TORCH_API NormalBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NormalBackward2"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector std_sym_sizes; + +}; +#ifdef _WIN32 +struct NormalBackward3 : public TraceableFunction { + TORCH_API NormalBackward3() = default; +#else +struct TORCH_API NormalBackward3 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NormalBackward3"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector mean_sym_sizes; + std::vector std_sym_sizes; + +}; +#ifdef _WIN32 +struct LinalgHouseholderProductBackward0 : public TraceableFunction { + TORCH_API LinalgHouseholderProductBackward0() = default; +#else +struct TORCH_API LinalgHouseholderProductBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgHouseholderProductBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + tau_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable input_; + SavedVariable tau_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct OrmqrBackward0 : public TraceableFunction { + TORCH_API OrmqrBackward0() = default; +#else +struct TORCH_API OrmqrBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "OrmqrBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input2_.reset_data(); + input3_.reset_data(); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable input2_; + SavedVariable input3_; + bool left; + SavedVariable self_; + bool transpose; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct PermuteBackward0 : public Node { + TORCH_API PermuteBackward0() = default; +#else +struct TORCH_API PermuteBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PermuteBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dims; + +}; +#ifdef _WIN32 +struct PoissonBackward0 : public TraceableFunction { + TORCH_API PoissonBackward0() = default; +#else +struct TORCH_API PoissonBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PoissonBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct PowBackward0 : public TraceableFunction { + TORCH_API PowBackward0() = default; +#else +struct TORCH_API PowBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PowBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar exponent; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct PowBackward1 : public TraceableFunction { + TORCH_API PowBackward1() = default; +#else +struct TORCH_API PowBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PowBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + exponent_.reset_data(); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable exponent_; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct PowBackward2 : public TraceableFunction { + TORCH_API PowBackward2() = default; +#else +struct TORCH_API PowBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PowBackward2"; } + void release_variables() override { + std::lock_guard lock(mutex_); + exponent_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable exponent_; + at::Scalar self; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ProdBackward0 : public TraceableFunction { + TORCH_API ProdBackward0() = default; +#else +struct TORCH_API ProdBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ProdBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ProdBackward1 : public TraceableFunction { + TORCH_API ProdBackward1() = default; +#else +struct TORCH_API ProdBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ProdBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool keepdim; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct PutBackward0 : public TraceableFunction { + TORCH_API PutBackward0() = default; +#else +struct TORCH_API PutBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PutBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + source_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool accumulate; + SavedVariable index_; + SavedVariable source_; + torch::autograd::generated::TypeAndSize source_info; + +}; +#ifdef _WIN32 +struct LinalgQrBackward0 : public TraceableFunction { + TORCH_API LinalgQrBackward0() = default; +#else +struct TORCH_API LinalgQrBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgQrBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + Q_.reset_data(); + R_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::string mode; + SavedVariable Q_; + SavedVariable R_; + +}; +#ifdef _WIN32 +struct Rad2DegBackward0 : public TraceableFunction { + TORCH_API Rad2DegBackward0() = default; +#else +struct TORCH_API Rad2DegBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Rad2DegBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct RandomBackward0 : public TraceableFunction { + TORCH_API RandomBackward0() = default; +#else +struct TORCH_API RandomBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RandomBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct RandomBackward1 : public TraceableFunction { + TORCH_API RandomBackward1() = default; +#else +struct TORCH_API RandomBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RandomBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct RandomBackward2 : public TraceableFunction { + TORCH_API RandomBackward2() = default; +#else +struct TORCH_API RandomBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RandomBackward2"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ReciprocalBackward0 : public TraceableFunction { + TORCH_API ReciprocalBackward0() = default; +#else +struct TORCH_API ReciprocalBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReciprocalBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct RemainderBackward0 : public TraceableFunction { + TORCH_API RemainderBackward0() = default; +#else +struct TORCH_API RemainderBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RemainderBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct RemainderBackward1 : public TraceableFunction { + TORCH_API RemainderBackward1() = default; +#else +struct TORCH_API RemainderBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RemainderBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct RenormBackward0 : public TraceableFunction { + TORCH_API RenormBackward0() = default; +#else +struct TORCH_API RenormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RenormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::Scalar maxnorm; + at::Scalar p; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct RepeatBackward0 : public TraceableFunction { + TORCH_API RepeatBackward0() = default; +#else +struct TORCH_API RepeatBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RepeatBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector repeats; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SpecialEntrBackward0 : public TraceableFunction { + TORCH_API SpecialEntrBackward0() = default; +#else +struct TORCH_API SpecialEntrBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialEntrBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SpecialNdtriBackward0 : public TraceableFunction { + TORCH_API SpecialNdtriBackward0() = default; +#else +struct TORCH_API SpecialNdtriBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialNdtriBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SpecialLogNdtrBackward0 : public TraceableFunction { + TORCH_API SpecialLogNdtrBackward0() = default; +#else +struct TORCH_API SpecialLogNdtrBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SpecialLogNdtrBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ReshapeAliasBackward0 : public Node { + TORCH_API ReshapeAliasBackward0() = default; +#else +struct TORCH_API ReshapeAliasBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReshapeAliasBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct RoundBackward0 : public TraceableFunction { + TORCH_API RoundBackward0() = default; +#else +struct TORCH_API RoundBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RoundBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct RoundBackward1 : public TraceableFunction { + TORCH_API RoundBackward1() = default; +#else +struct TORCH_API RoundBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RoundBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct RsqrtBackward0 : public TraceableFunction { + TORCH_API RsqrtBackward0() = default; +#else +struct TORCH_API RsqrtBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RsqrtBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ScatterBackward0 : public TraceableFunction { + TORCH_API ScatterBackward0() = default; +#else +struct TORCH_API ScatterBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScatterBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable index_; + +}; +#ifdef _WIN32 +struct ScatterBackward1 : public TraceableFunction { + TORCH_API ScatterBackward1() = default; +#else +struct TORCH_API ScatterBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScatterBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable index_; + +}; +#ifdef _WIN32 +struct ScatterAddBackward0 : public TraceableFunction { + TORCH_API ScatterAddBackward0() = default; +#else +struct TORCH_API ScatterAddBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScatterAddBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable index_; + +}; +#ifdef _WIN32 +struct SelectBackward0 : public Node { + TORCH_API SelectBackward0() = default; +#else +struct TORCH_API SelectBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SelectBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + c10::SymInt index; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SelectBackwardAutogradNestedTensor0 : public Node { + TORCH_API SelectBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API SelectBackwardAutogradNestedTensor0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SelectBackwardAutogradNestedTensor0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + c10::SymInt index; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SelectBackwardBackward0 : public TraceableFunction { + TORCH_API SelectBackwardBackward0() = default; +#else +struct TORCH_API SelectBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SelectBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + c10::SymInt index; + +}; +#ifdef _WIN32 +struct SigmoidBackward0 : public TraceableFunction { + TORCH_API SigmoidBackward0() = default; +#else +struct TORCH_API SigmoidBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SigmoidBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct LogitBackward0 : public TraceableFunction { + TORCH_API LogitBackward0() = default; +#else +struct TORCH_API LogitBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogitBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional eps; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SignBackward0 : public TraceableFunction { + TORCH_API SignBackward0() = default; +#else +struct TORCH_API SignBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SignBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct SgnBackward0 : public TraceableFunction { + TORCH_API SgnBackward0() = default; +#else +struct TORCH_API SgnBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SgnBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SinBackward0 : public TraceableFunction { + TORCH_API SinBackward0() = default; +#else +struct TORCH_API SinBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SinBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SincBackward0 : public TraceableFunction { + TORCH_API SincBackward0() = default; +#else +struct TORCH_API SincBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SincBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SinhBackward0 : public TraceableFunction { + TORCH_API SinhBackward0() = default; +#else +struct TORCH_API SinhBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SinhBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SliceBackward0 : public Node { + TORCH_API SliceBackward0() = default; +#else +struct TORCH_API SliceBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SliceBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + ::std::optional end; + std::vector self_sym_sizes; + ::std::optional start; + c10::SymInt step; + +}; +#ifdef _WIN32 +struct SliceBackwardBackward0 : public TraceableFunction { + TORCH_API SliceBackwardBackward0() = default; +#else +struct TORCH_API SliceBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SliceBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + c10::SymInt end; + c10::SymInt start; + c10::SymInt step; + +}; +#ifdef _WIN32 +struct SliceInverseBackward0 : public Node { + TORCH_API SliceInverseBackward0() = default; +#else +struct TORCH_API SliceInverseBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SliceInverseBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + ::std::optional end; + torch::autograd::generated::TypeAndSize self_info; + ::std::optional start; + c10::SymInt step; + +}; +#ifdef _WIN32 +struct SliceScatterBackward0 : public TraceableFunction { + TORCH_API SliceScatterBackward0() = default; +#else +struct TORCH_API SliceScatterBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SliceScatterBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + ::std::optional end; + torch::autograd::generated::TypeAndSize src_info; + ::std::optional start; + c10::SymInt step; + +}; +#ifdef _WIN32 +struct SelectScatterBackward0 : public TraceableFunction { + TORCH_API SelectScatterBackward0() = default; +#else +struct TORCH_API SelectScatterBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SelectScatterBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + c10::SymInt index; + torch::autograd::generated::TypeAndSize src_info; + +}; +#ifdef _WIN32 +struct DiagonalScatterBackward0 : public TraceableFunction { + TORCH_API DiagonalScatterBackward0() = default; +#else +struct TORCH_API DiagonalScatterBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DiagonalScatterBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim1 = 0; + int64_t dim2 = 0; + int64_t offset = 0; + torch::autograd::generated::TypeAndSize src_info; + +}; +#ifdef _WIN32 +struct AsStridedScatterBackward0 : public TraceableFunction { + TORCH_API AsStridedScatterBackward0() = default; +#else +struct TORCH_API AsStridedScatterBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AsStridedScatterBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::TensorGeometry self_geometry; + std::vector size; + at::TensorGeometry src_geometry; + ::std::optional storage_offset; + std::vector stride; + +}; +#ifdef _WIN32 +struct LinalgSolveExBackward0 : public TraceableFunction { + TORCH_API LinalgSolveExBackward0() = default; +#else +struct TORCH_API LinalgSolveExBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgSolveExBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + A_.reset_data(); + LU_.reset_data(); + pivots_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable A_; + bool left; + SavedVariable LU_; + SavedVariable pivots_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SortBackward0 : public TraceableFunction { + TORCH_API SortBackward0() = default; +#else +struct TORCH_API SortBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SortBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct SortBackward1 : public TraceableFunction { + TORCH_API SortBackward1() = default; +#else +struct TORCH_API SortBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SortBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct SplitBackward0 : public Node { + TORCH_API SplitBackward0() = default; +#else +struct TORCH_API SplitBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SplitBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::TensorOptions self_options; + std::vector self_sym_sizes; + c10::SymInt split_size; + +}; +#ifdef _WIN32 +struct UnsafeSplitBackward0 : public TraceableFunction { + TORCH_API UnsafeSplitBackward0() = default; +#else +struct TORCH_API UnsafeSplitBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsafeSplitBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::TensorOptions self_options; + std::vector self_sym_sizes; + c10::SymInt split_size; + +}; +#ifdef _WIN32 +struct SplitWithSizesBackward0 : public Node { + TORCH_API SplitWithSizesBackward0() = default; +#else +struct TORCH_API SplitWithSizesBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SplitWithSizesBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::TensorOptions self_options; + std::vector self_sym_sizes; + std::vector split_sizes; + +}; +#ifdef _WIN32 +struct SplitWithSizesBackwardAutogradNestedTensor0 : public Node { + TORCH_API SplitWithSizesBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API SplitWithSizesBackwardAutogradNestedTensor0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SplitWithSizesBackwardAutogradNestedTensor0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + at::TensorOptions self_options; + std::vector split_sizes; + +}; +#ifdef _WIN32 +struct UnsafeSplitWithSizesBackward0 : public TraceableFunction { + TORCH_API UnsafeSplitWithSizesBackward0() = default; +#else +struct TORCH_API UnsafeSplitWithSizesBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsafeSplitWithSizesBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::TensorOptions self_options; + std::vector self_sym_sizes; + std::vector split_sizes; + +}; +#ifdef _WIN32 +struct SqrtBackward0 : public TraceableFunction { + TORCH_API SqrtBackward0() = default; +#else +struct TORCH_API SqrtBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqrtBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SqueezeBackward0 : public Node { + TORCH_API SqueezeBackward0() = default; +#else +struct TORCH_API SqueezeBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackward1 : public Node { + TORCH_API SqueezeBackward1() = default; +#else +struct TORCH_API SqueezeBackward1 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackwardAutogradNestedTensor0 : public Node { + TORCH_API SqueezeBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API SqueezeBackwardAutogradNestedTensor0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackwardAutogradNestedTensor0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + +}; +#ifdef _WIN32 +struct SqueezeBackward2 : public Node { + TORCH_API SqueezeBackward2() = default; +#else +struct TORCH_API SqueezeBackward2 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward2"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackwardAutogradNestedTensor1 : public Node { + TORCH_API SqueezeBackwardAutogradNestedTensor1() = default; +#else +struct TORCH_API SqueezeBackwardAutogradNestedTensor1 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackwardAutogradNestedTensor1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + int64_t self_dim = 0; + +}; +#ifdef _WIN32 +struct SqueezeBackward3 : public TraceableFunction { + TORCH_API SqueezeBackward3() = default; +#else +struct TORCH_API SqueezeBackward3 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward3"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackward4 : public TraceableFunction { + TORCH_API SqueezeBackward4() = default; +#else +struct TORCH_API SqueezeBackward4 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward4"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackward5 : public TraceableFunction { + TORCH_API SqueezeBackward5() = default; +#else +struct TORCH_API SqueezeBackward5 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward5"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct StdBackward0 : public TraceableFunction { + TORCH_API StdBackward0() = default; +#else +struct TORCH_API StdBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "StdBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional correction; + c10::OptionalArray dim; + bool keepdim; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct StdMeanBackward0 : public TraceableFunction { + TORCH_API StdMeanBackward0() = default; +#else +struct TORCH_API StdMeanBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "StdMeanBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result0_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional correction; + c10::OptionalArray dim; + bool keepdim; + SavedVariable self_; + SavedVariable result0_; + +}; +#ifdef _WIN32 +struct SubBackward0 : public TraceableFunction { + TORCH_API SubBackward0() = default; +#else +struct TORCH_API SubBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SubBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::ScalarType other_scalar_type; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct SubBackward1 : public TraceableFunction { + TORCH_API SubBackward1() = default; +#else +struct TORCH_API SubBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SubBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct RsubBackward0 : public TraceableFunction { + TORCH_API RsubBackward0() = default; +#else +struct TORCH_API RsubBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RsubBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::ScalarType other_scalar_type; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct RsubBackward1 : public TraceableFunction { + TORCH_API RsubBackward1() = default; +#else +struct TORCH_API RsubBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RsubBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct SumBackward0 : public TraceableFunction { + TORCH_API SumBackward0() = default; +#else +struct TORCH_API SumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SumBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SumBackwardAutogradNestedTensor0 : public TraceableFunction { + TORCH_API SumBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API SumBackwardAutogradNestedTensor0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SumBackwardAutogradNestedTensor0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SumBackward1 : public TraceableFunction { + TORCH_API SumBackward1() = default; +#else +struct TORCH_API SumBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SumBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray dim; + bool keepdim; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SumBackwardAutogradNestedTensor1 : public TraceableFunction { + TORCH_API SumBackwardAutogradNestedTensor1() = default; +#else +struct TORCH_API SumBackwardAutogradNestedTensor1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SumBackwardAutogradNestedTensor1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray dim; + bool keepdim; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct NansumBackward0 : public TraceableFunction { + TORCH_API NansumBackward0() = default; +#else +struct TORCH_API NansumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NansumBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray dim; + bool keepdim; + SavedVariable self_; + at::ScalarType self_scalar_type; + +}; +#ifdef _WIN32 +struct LinalgSvdBackward0 : public TraceableFunction { + TORCH_API LinalgSvdBackward0() = default; +#else +struct TORCH_API LinalgSvdBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgSvdBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + S_.reset_data(); + U_.reset_data(); + Vh_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool full_matrices; + SavedVariable S_; + c10::SymInt S_sym_argsize_minus_1; + SavedVariable U_; + SavedVariable Vh_; + +}; +#ifdef _WIN32 +struct LinalgEighBackward0 : public TraceableFunction { + TORCH_API LinalgEighBackward0() = default; +#else +struct TORCH_API LinalgEighBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgEighBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + eigenvalues_.reset_data(); + eigenvectors_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable eigenvalues_; + SavedVariable eigenvectors_; + +}; +#ifdef _WIN32 +struct LinalgEigBackward0 : public TraceableFunction { + TORCH_API LinalgEigBackward0() = default; +#else +struct TORCH_API LinalgEigBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgEigBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + eigenvalues_.reset_data(); + eigenvectors_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::ScalarType self_scalar_type; + SavedVariable eigenvalues_; + SavedVariable eigenvectors_; + +}; +#ifdef _WIN32 +struct TBackward0 : public Node { + TORCH_API TBackward0() = default; +#else +struct TORCH_API TBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct TBackward1 : public TraceableFunction { + TORCH_API TBackward1() = default; +#else +struct TORCH_API TBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct FlipBackward0 : public TraceableFunction { + TORCH_API FlipBackward0() = default; +#else +struct TORCH_API FlipBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FlipBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dims; + +}; +#ifdef _WIN32 +struct RollBackward0 : public TraceableFunction { + TORCH_API RollBackward0() = default; +#else +struct TORCH_API RollBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RollBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dims; + std::vector shifts; + +}; +#ifdef _WIN32 +struct Rot90Backward0 : public TraceableFunction { + TORCH_API Rot90Backward0() = default; +#else +struct TORCH_API Rot90Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Rot90Backward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dims; + int64_t k = 0; + +}; +#ifdef _WIN32 +struct TakeBackward0 : public TraceableFunction { + TORCH_API TakeBackward0() = default; +#else +struct TORCH_API TakeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TakeBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable index_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct TanBackward0 : public TraceableFunction { + TORCH_API TanBackward0() = default; +#else +struct TORCH_API TanBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TanBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct TanhBackward0 : public TraceableFunction { + TORCH_API TanhBackward0() = default; +#else +struct TORCH_API TanhBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TanhBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct TopkBackward0 : public TraceableFunction { + TORCH_API TopkBackward0() = default; +#else +struct TORCH_API TopkBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TopkBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + std::vector self_sym_sizes; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct TraceBackward0 : public TraceableFunction { + TORCH_API TraceBackward0() = default; +#else +struct TORCH_API TraceBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TraceBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct TransposeBackward0 : public Node { + TORCH_API TransposeBackward0() = default; +#else +struct TORCH_API TransposeBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TransposeBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim0 = 0; + int64_t dim1 = 0; + +}; +#ifdef _WIN32 +struct TransposeBackward1 : public TraceableFunction { + TORCH_API TransposeBackward1() = default; +#else +struct TORCH_API TransposeBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TransposeBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim0 = 0; + int64_t dim1 = 0; + +}; +#ifdef _WIN32 +struct TriangularSolveBackward0 : public TraceableFunction { + TORCH_API TriangularSolveBackward0() = default; +#else +struct TORCH_API TriangularSolveBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TriangularSolveBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + A_.reset_data(); + self_.reset_data(); + solution_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable A_; + SavedVariable self_; + bool transpose; + bool unitriangular; + bool upper; + SavedVariable solution_; + +}; +#ifdef _WIN32 +struct LinalgSolveTriangularBackward0 : public TraceableFunction { + TORCH_API LinalgSolveTriangularBackward0() = default; +#else +struct TORCH_API LinalgSolveTriangularBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinalgSolveTriangularBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool left; + SavedVariable self_; + bool unitriangular; + bool upper; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct TrilBackward0 : public TraceableFunction { + TORCH_API TrilBackward0() = default; +#else +struct TORCH_API TrilBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TrilBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt diagonal; + +}; +#ifdef _WIN32 +struct TriuBackward0 : public TraceableFunction { + TORCH_API TriuBackward0() = default; +#else +struct TORCH_API TriuBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TriuBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt diagonal; + +}; +#ifdef _WIN32 +struct TruncBackward0 : public TraceableFunction { + TORCH_API TruncBackward0() = default; +#else +struct TORCH_API TruncBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TruncBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ToDenseBackward0 : public TraceableFunction { + TORCH_API ToDenseBackward0() = default; +#else +struct TORCH_API ToDenseBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToDenseBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional masked_grad; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ToSparseBackward0 : public TraceableFunction { + TORCH_API ToSparseBackward0() = default; +#else +struct TORCH_API ToSparseBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToSparseBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Layout self_layout; + c10::OptionalArray self_self_sym_blocksize_opt; + +}; +#ifdef _WIN32 +struct ToSparseBackward1 : public TraceableFunction { + TORCH_API ToSparseBackward1() = default; +#else +struct TORCH_API ToSparseBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToSparseBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Layout self_layout; + c10::OptionalArray self_self_sym_blocksize_opt; + +}; +#ifdef _WIN32 +struct ToSparseCsrBackward0 : public TraceableFunction { + TORCH_API ToSparseCsrBackward0() = default; +#else +struct TORCH_API ToSparseCsrBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToSparseCsrBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Layout self_layout; + c10::OptionalArray self_self_sym_blocksize_opt; + +}; +#ifdef _WIN32 +struct ToSparseCscBackward0 : public TraceableFunction { + TORCH_API ToSparseCscBackward0() = default; +#else +struct TORCH_API ToSparseCscBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToSparseCscBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Layout self_layout; + c10::OptionalArray self_self_sym_blocksize_opt; + +}; +#ifdef _WIN32 +struct ToSparseBsrBackward0 : public TraceableFunction { + TORCH_API ToSparseBsrBackward0() = default; +#else +struct TORCH_API ToSparseBsrBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToSparseBsrBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Layout self_layout; + c10::OptionalArray self_self_sym_blocksize_opt; + +}; +#ifdef _WIN32 +struct ToSparseBscBackward0 : public TraceableFunction { + TORCH_API ToSparseBscBackward0() = default; +#else +struct TORCH_API ToSparseBscBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToSparseBscBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Layout self_layout; + c10::OptionalArray self_self_sym_blocksize_opt; + +}; +#ifdef _WIN32 +struct ToMkldnnBackward0 : public TraceableFunction { + TORCH_API ToMkldnnBackward0() = default; +#else +struct TORCH_API ToMkldnnBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToMkldnnBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct UnfoldBackward0 : public Node { + TORCH_API UnfoldBackward0() = default; +#else +struct TORCH_API UnfoldBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnfoldBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dimension = 0; + std::vector self_sym_sizes; + int64_t size = 0; + int64_t step = 0; + +}; +#ifdef _WIN32 +struct UnfoldBackwardBackward0 : public TraceableFunction { + TORCH_API UnfoldBackwardBackward0() = default; +#else +struct TORCH_API UnfoldBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnfoldBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + int64_t size = 0; + int64_t step = 0; + +}; +#ifdef _WIN32 +struct UniformBackward0 : public TraceableFunction { + TORCH_API UniformBackward0() = default; +#else +struct TORCH_API UniformBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UniformBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct UniqueBackward0 : public TraceableFunction { + TORCH_API UniqueBackward0() = default; +#else +struct TORCH_API UniqueBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UniqueBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct UniqueDimBackward0 : public TraceableFunction { + TORCH_API UniqueDimBackward0() = default; +#else +struct TORCH_API UniqueDimBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UniqueDimBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct UniqueConsecutiveBackward0 : public TraceableFunction { + TORCH_API UniqueConsecutiveBackward0() = default; +#else +struct TORCH_API UniqueConsecutiveBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UniqueConsecutiveBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct UniqueDimConsecutiveBackward0 : public TraceableFunction { + TORCH_API UniqueDimConsecutiveBackward0() = default; +#else +struct TORCH_API UniqueDimConsecutiveBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UniqueDimConsecutiveBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct Unique2Backward0 : public TraceableFunction { + TORCH_API Unique2Backward0() = default; +#else +struct TORCH_API Unique2Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Unique2Backward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct UnsafeViewBackward0 : public TraceableFunction { + TORCH_API UnsafeViewBackward0() = default; +#else +struct TORCH_API UnsafeViewBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsafeViewBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct LiftBackward0 : public TraceableFunction { + TORCH_API LiftBackward0() = default; +#else +struct TORCH_API LiftBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LiftBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct LiftFreshBackward0 : public TraceableFunction { + TORCH_API LiftFreshBackward0() = default; +#else +struct TORCH_API LiftFreshBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LiftFreshBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct UnsqueezeBackward0 : public Node { + TORCH_API UnsqueezeBackward0() = default; +#else +struct TORCH_API UnsqueezeBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsqueezeBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + +}; +#ifdef _WIN32 +struct UnsqueezeBackward1 : public TraceableFunction { + TORCH_API UnsqueezeBackward1() = default; +#else +struct TORCH_API UnsqueezeBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsqueezeBackward1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + +}; +#ifdef _WIN32 +struct VarBackward0 : public TraceableFunction { + TORCH_API VarBackward0() = default; +#else +struct TORCH_API VarBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "VarBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional correction; + c10::OptionalArray dim; + bool keepdim; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct VarMeanBackward0 : public TraceableFunction { + TORCH_API VarMeanBackward0() = default; +#else +struct TORCH_API VarMeanBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "VarMeanBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional correction; + c10::OptionalArray dim; + bool keepdim; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ViewBackward0 : public Node { + TORCH_API ViewBackward0() = default; +#else +struct TORCH_API ViewBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ViewBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct ViewBackwardAutogradNestedTensor0 : public Node { + TORCH_API ViewBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API ViewBackwardAutogradNestedTensor0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ViewBackwardAutogradNestedTensor0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ViewAsRealBackward0 : public Node { + TORCH_API ViewAsRealBackward0() = default; +#else +struct TORCH_API ViewAsRealBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ViewAsRealBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ViewAsComplexBackward0 : public Node { + TORCH_API ViewAsComplexBackward0() = default; +#else +struct TORCH_API ViewAsComplexBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ViewAsComplexBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct WhereBackward0 : public TraceableFunction { + TORCH_API WhereBackward0() = default; +#else +struct TORCH_API WhereBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "WhereBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + condition_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable condition_; + +}; +#ifdef _WIN32 +struct WeightNormInterfaceBackward0 : public TraceableFunction { + TORCH_API WeightNormInterfaceBackward0() = default; +#else +struct TORCH_API WeightNormInterfaceBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "WeightNormInterfaceBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + g_.reset_data(); + v_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable g_; + SavedVariable v_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct ZeroBackward0 : public TraceableFunction { + TORCH_API ZeroBackward0() = default; +#else +struct TORCH_API ZeroBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ZeroBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct SparseMaskBackward0 : public TraceableFunction { + TORCH_API SparseMaskBackward0() = default; +#else +struct TORCH_API SparseMaskBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseMaskBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable mask_; + at::Layout self_layout; + +}; +#ifdef _WIN32 +struct SparseCooTensorWithDimsAndTensorsBackward0 : public TraceableFunction { + TORCH_API SparseCooTensorWithDimsAndTensorsBackward0() = default; +#else +struct TORCH_API SparseCooTensorWithDimsAndTensorsBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseCooTensorWithDimsAndTensorsBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SparseCompressedTensorBackward0 : public TraceableFunction { + TORCH_API SparseCompressedTensorBackward0() = default; +#else +struct TORCH_API SparseCompressedTensorBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseCompressedTensorBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + values_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable values_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SparseSumBackward0 : public TraceableFunction { + TORCH_API SparseSumBackward0() = default; +#else +struct TORCH_API SparseSumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseSumBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct StandardGammaBackward0 : public TraceableFunction { + TORCH_API StandardGammaBackward0() = default; +#else +struct TORCH_API StandardGammaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "StandardGammaBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct StandardGammaGradBackward0 : public TraceableFunction { + TORCH_API StandardGammaGradBackward0() = default; +#else +struct TORCH_API StandardGammaGradBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "StandardGammaGradBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ValuesBackward0 : public Node { + TORCH_API ValuesBackward0() = default; +#else +struct TORCH_API ValuesBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ValuesBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ValuesBackwardAutogradNestedTensor0 : public Node { + TORCH_API ValuesBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API ValuesBackwardAutogradNestedTensor0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ValuesBackwardAutogradNestedTensor0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct TrilinearBackward0 : public TraceableFunction { + TORCH_API TrilinearBackward0() = default; +#else +struct TORCH_API TrilinearBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TrilinearBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + i1_.reset_data(); + i2_.reset_data(); + i3_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector expand1; + std::vector expand2; + std::vector expand3; + SavedVariable i1_; + SavedVariable i2_; + SavedVariable i3_; + std::vector sumdim; + +}; +#ifdef _WIN32 +struct ConstantPadNdBackward0 : public TraceableFunction { + TORCH_API ConstantPadNdBackward0() = default; +#else +struct TORCH_API ConstantPadNdBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConstantPadNdBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector pad; + +}; +#ifdef _WIN32 +struct BinaryCrossEntropyBackward0 : public TraceableFunction { + TORCH_API BinaryCrossEntropyBackward0() = default; +#else +struct TORCH_API BinaryCrossEntropyBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BinaryCrossEntropyBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct BinaryCrossEntropyBackwardBackward0 : public TraceableFunction { + TORCH_API BinaryCrossEntropyBackwardBackward0() = default; +#else +struct TORCH_API BinaryCrossEntropyBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BinaryCrossEntropyBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + target_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct BinaryCrossEntropyWithLogitsBackward0 : public TraceableFunction { + TORCH_API BinaryCrossEntropyWithLogitsBackward0() = default; +#else +struct TORCH_API BinaryCrossEntropyWithLogitsBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "BinaryCrossEntropyWithLogitsBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + pos_weight_.reset_data(); + self_.reset_data(); + target_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable pos_weight_; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct EmbeddingBackward0 : public TraceableFunction { + TORCH_API EmbeddingBackward0() = default; +#else +struct TORCH_API EmbeddingBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EmbeddingBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + c10::SymInt padding_idx; + bool scale_grad_by_freq; + bool sparse; + c10::SymInt weight_sym_argsize_0; + +}; +#ifdef _WIN32 +struct EmbeddingDenseBackwardBackward0 : public TraceableFunction { + TORCH_API EmbeddingDenseBackwardBackward0() = default; +#else +struct TORCH_API EmbeddingDenseBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EmbeddingDenseBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + c10::SymInt padding_idx; + +}; +#ifdef _WIN32 +struct EmbeddingBagBackward0 : public TraceableFunction { + TORCH_API EmbeddingBagBackward0() = default; +#else +struct TORCH_API EmbeddingBagBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EmbeddingBagBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + offsets_.reset_data(); + per_sample_weights_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + result3_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + int64_t mode = 0; + SavedVariable offsets_; + int64_t padding_idx = 0; + SavedVariable per_sample_weights_; + bool scale_grad_by_freq; + bool sparse; + SavedVariable weight_; + c10::SymInt weight_sym_argsize_0; + SavedVariable result1_; + SavedVariable result2_; + SavedVariable result3_; + +}; +#ifdef _WIN32 +struct EmbeddingBagBackwardBackward0 : public TraceableFunction { + TORCH_API EmbeddingBagBackwardBackward0() = default; +#else +struct TORCH_API EmbeddingBagBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EmbeddingBagBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct EmbeddingBagDenseBackwardBackward0 : public TraceableFunction { + TORCH_API EmbeddingBagDenseBackwardBackward0() = default; +#else +struct TORCH_API EmbeddingBagDenseBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EmbeddingBagDenseBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct EmbeddingRenormBackward0 : public TraceableFunction { + TORCH_API EmbeddingRenormBackward0() = default; +#else +struct TORCH_API EmbeddingRenormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EmbeddingRenormBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct MseLossBackward0 : public TraceableFunction { + TORCH_API MseLossBackward0() = default; +#else +struct TORCH_API MseLossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MseLossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + +}; +#ifdef _WIN32 +struct MultiMarginLossBackward0 : public TraceableFunction { + TORCH_API MultiMarginLossBackward0() = default; +#else +struct TORCH_API MultiMarginLossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MultiMarginLossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar margin; + at::Scalar p; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MultilabelMarginLossBackward0 : public TraceableFunction { + TORCH_API MultilabelMarginLossBackward0() = default; +#else +struct TORCH_API MultilabelMarginLossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MultilabelMarginLossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + is_target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + SavedVariable is_target_; + +}; +#ifdef _WIN32 +struct NllLossBackward0 : public TraceableFunction { + TORCH_API NllLossBackward0() = default; +#else +struct TORCH_API NllLossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NllLossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + weight_.reset_data(); + total_weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt ignore_index; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + SavedVariable weight_; + SavedVariable total_weight_; + +}; +#ifdef _WIN32 +struct NllLoss2DBackward0 : public TraceableFunction { + TORCH_API NllLoss2DBackward0() = default; +#else +struct TORCH_API NllLoss2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NllLoss2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + weight_.reset_data(); + total_weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt ignore_index; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + SavedVariable weight_; + SavedVariable total_weight_; + +}; +#ifdef _WIN32 +struct SmoothL1LossBackward0 : public TraceableFunction { + TORCH_API SmoothL1LossBackward0() = default; +#else +struct TORCH_API SmoothL1LossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SmoothL1LossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double beta; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + +}; +#ifdef _WIN32 +struct HuberLossBackward0 : public TraceableFunction { + TORCH_API HuberLossBackward0() = default; +#else +struct TORCH_API HuberLossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HuberLossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double delta; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + +}; +#ifdef _WIN32 +struct SoftMarginLossBackward0 : public TraceableFunction { + TORCH_API SoftMarginLossBackward0() = default; +#else +struct TORCH_API SoftMarginLossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SoftMarginLossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + +}; +#ifdef _WIN32 +struct ReluBackward0 : public TraceableFunction { + TORCH_API ReluBackward0() = default; +#else +struct TORCH_API ReluBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReluBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SiluBackward0 : public TraceableFunction { + TORCH_API SiluBackward0() = default; +#else +struct TORCH_API SiluBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SiluBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct MishBackward0 : public TraceableFunction { + TORCH_API MishBackward0() = default; +#else +struct TORCH_API MishBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MishBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct EluBackward0 : public TraceableFunction { + TORCH_API EluBackward0() = default; +#else +struct TORCH_API EluBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EluBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::Scalar input_scale; + at::Scalar scale; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct EluBackward1 : public TraceableFunction { + TORCH_API EluBackward1() = default; +#else +struct TORCH_API EluBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EluBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::Scalar input_scale; + at::Scalar scale; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct CeluBackward0 : public TraceableFunction { + TORCH_API CeluBackward0() = default; +#else +struct TORCH_API CeluBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CeluBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct CeluBackward1 : public TraceableFunction { + TORCH_API CeluBackward1() = default; +#else +struct TORCH_API CeluBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CeluBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct GeluBackward0 : public TraceableFunction { + TORCH_API GeluBackward0() = default; +#else +struct TORCH_API GeluBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GeluBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::string approximate; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct GeluBackwardBackward0 : public TraceableFunction { + TORCH_API GeluBackwardBackward0() = default; +#else +struct TORCH_API GeluBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GeluBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::string approximate; + SavedVariable grad_output_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct GluBackward0 : public TraceableFunction { + TORCH_API GluBackward0() = default; +#else +struct TORCH_API GluBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GluBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct HardshrinkBackward0 : public TraceableFunction { + TORCH_API HardshrinkBackward0() = default; +#else +struct TORCH_API HardshrinkBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HardshrinkBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar lambd; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct HardshrinkBackwardBackward0 : public TraceableFunction { + TORCH_API HardshrinkBackwardBackward0() = default; +#else +struct TORCH_API HardshrinkBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HardshrinkBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar lambd; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct HardtanhBackward0 : public TraceableFunction { + TORCH_API HardtanhBackward0() = default; +#else +struct TORCH_API HardtanhBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HardtanhBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar max_val; + at::Scalar min_val; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LeakyReluBackward0 : public TraceableFunction { + TORCH_API LeakyReluBackward0() = default; +#else +struct TORCH_API LeakyReluBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LeakyReluBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar negative_slope; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LeakyReluBackward1 : public TraceableFunction { + TORCH_API LeakyReluBackward1() = default; +#else +struct TORCH_API LeakyReluBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LeakyReluBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar negative_slope; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct LogSigmoidBackward0 : public TraceableFunction { + TORCH_API LogSigmoidBackward0() = default; +#else +struct TORCH_API LogSigmoidBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogSigmoidBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + buffer_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable buffer_; + +}; +#ifdef _WIN32 +struct LogSoftmaxBackward0 : public TraceableFunction { + TORCH_API LogSoftmaxBackward0() = default; +#else +struct TORCH_API LogSoftmaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogSoftmaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::ScalarType self_scalar_type; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SparseLogSoftmaxBackward0 : public TraceableFunction { + TORCH_API SparseLogSoftmaxBackward0() = default; +#else +struct TORCH_API SparseLogSoftmaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseLogSoftmaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct MaskedSoftmaxBackward0 : public TraceableFunction { + TORCH_API MaskedSoftmaxBackward0() = default; +#else +struct TORCH_API MaskedSoftmaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaskedSoftmaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mask_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ::std::optional dim; + SavedVariable mask_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct PreluKernelBackward0 : public TraceableFunction { + TORCH_API PreluKernelBackward0() = default; +#else +struct TORCH_API PreluKernelBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PreluKernelBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct PreluKernelBackwardBackward0 : public TraceableFunction { + TORCH_API PreluKernelBackwardBackward0() = default; +#else +struct TORCH_API PreluKernelBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PreluKernelBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + at::TensorOptions grad_output_options; + SavedVariable self_; + torch::autograd::generated::TypeAndSize self_info; + at::TensorOptions self_options; + SavedVariable weight_; + at::TensorOptions weight_options; + +}; +#ifdef _WIN32 +struct RreluWithNoiseBackward0 : public TraceableFunction { + TORCH_API RreluWithNoiseBackward0() = default; +#else +struct TORCH_API RreluWithNoiseBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RreluWithNoiseBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + noise_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar lower; + SavedVariable noise_; + SavedVariable self_; + bool training; + at::Scalar upper; + +}; +#ifdef _WIN32 +struct RreluWithNoiseBackward1 : public TraceableFunction { + TORCH_API RreluWithNoiseBackward1() = default; +#else +struct TORCH_API RreluWithNoiseBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RreluWithNoiseBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + noise_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar lower; + SavedVariable noise_; + bool training; + at::Scalar upper; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct RreluWithNoiseFunctionalBackward0 : public TraceableFunction { + TORCH_API RreluWithNoiseFunctionalBackward0() = default; +#else +struct TORCH_API RreluWithNoiseFunctionalBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RreluWithNoiseFunctionalBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + noise_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar lower; + SavedVariable noise_; + SavedVariable self_; + bool training; + at::Scalar upper; + +}; +#ifdef _WIN32 +struct SoftmaxBackward0 : public TraceableFunction { + TORCH_API SoftmaxBackward0() = default; +#else +struct TORCH_API SoftmaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SoftmaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::ScalarType self_scalar_type; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SparseSoftmaxBackward0 : public TraceableFunction { + TORCH_API SparseSoftmaxBackward0() = default; +#else +struct TORCH_API SparseSoftmaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseSoftmaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct SparseSparseMatmulBackward0 : public TraceableFunction { + TORCH_API SparseSparseMatmulBackward0() = default; +#else +struct TORCH_API SparseSparseMatmulBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseSparseMatmulBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SoftplusBackward0 : public TraceableFunction { + TORCH_API SoftplusBackward0() = default; +#else +struct TORCH_API SoftplusBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SoftplusBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar beta; + SavedVariable self_; + at::Scalar threshold; + +}; +#ifdef _WIN32 +struct SoftshrinkBackward0 : public TraceableFunction { + TORCH_API SoftshrinkBackward0() = default; +#else +struct TORCH_API SoftshrinkBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SoftshrinkBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar lambd; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ThresholdBackward0 : public TraceableFunction { + TORCH_API ThresholdBackward0() = default; +#else +struct TORCH_API ThresholdBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ThresholdBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + at::Scalar threshold; + +}; +#ifdef _WIN32 +struct ThresholdBackward1 : public TraceableFunction { + TORCH_API ThresholdBackward1() = default; +#else +struct TORCH_API ThresholdBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ThresholdBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + at::Scalar threshold; + +}; +#ifdef _WIN32 +struct ReflectionPad1DBackward0 : public TraceableFunction { + TORCH_API ReflectionPad1DBackward0() = default; +#else +struct TORCH_API ReflectionPad1DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReflectionPad1DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ReflectionPad2DBackward0 : public TraceableFunction { + TORCH_API ReflectionPad2DBackward0() = default; +#else +struct TORCH_API ReflectionPad2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReflectionPad2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ReflectionPad3DBackward0 : public TraceableFunction { + TORCH_API ReflectionPad3DBackward0() = default; +#else +struct TORCH_API ReflectionPad3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReflectionPad3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ReplicationPad1DBackward0 : public TraceableFunction { + TORCH_API ReplicationPad1DBackward0() = default; +#else +struct TORCH_API ReplicationPad1DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReplicationPad1DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ReplicationPad2DBackward0 : public TraceableFunction { + TORCH_API ReplicationPad2DBackward0() = default; +#else +struct TORCH_API ReplicationPad2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReplicationPad2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ReplicationPad3DBackward0 : public TraceableFunction { + TORCH_API ReplicationPad3DBackward0() = default; +#else +struct TORCH_API ReplicationPad3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReplicationPad3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct UpsampleLinear1DBackward0 : public TraceableFunction { + TORCH_API UpsampleLinear1DBackward0() = default; +#else +struct TORCH_API UpsampleLinear1DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleLinear1DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleBilinear2DBackward0 : public TraceableFunction { + TORCH_API UpsampleBilinear2DBackward0() = default; +#else +struct TORCH_API UpsampleBilinear2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleBilinear2DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleBilinear2DAaBackward0 : public TraceableFunction { + TORCH_API UpsampleBilinear2DAaBackward0() = default; +#else +struct TORCH_API UpsampleBilinear2DAaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleBilinear2DAaBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleBicubic2DBackward0 : public TraceableFunction { + TORCH_API UpsampleBicubic2DBackward0() = default; +#else +struct TORCH_API UpsampleBicubic2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleBicubic2DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleBicubic2DAaBackward0 : public TraceableFunction { + TORCH_API UpsampleBicubic2DAaBackward0() = default; +#else +struct TORCH_API UpsampleBicubic2DAaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleBicubic2DAaBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleTrilinear3DBackward0 : public TraceableFunction { + TORCH_API UpsampleTrilinear3DBackward0() = default; +#else +struct TORCH_API UpsampleTrilinear3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleTrilinear3DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_d; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleNearest1DBackward0 : public TraceableFunction { + TORCH_API UpsampleNearest1DBackward0() = default; +#else +struct TORCH_API UpsampleNearest1DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearest1DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleNearestExact1DBackward0 : public TraceableFunction { + TORCH_API UpsampleNearestExact1DBackward0() = default; +#else +struct TORCH_API UpsampleNearestExact1DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearestExact1DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleNearest2DBackward0 : public TraceableFunction { + TORCH_API UpsampleNearest2DBackward0() = default; +#else +struct TORCH_API UpsampleNearest2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearest2DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleNearestExact2DBackward0 : public TraceableFunction { + TORCH_API UpsampleNearestExact2DBackward0() = default; +#else +struct TORCH_API UpsampleNearestExact2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearestExact2DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleNearest3DBackward0 : public TraceableFunction { + TORCH_API UpsampleNearest3DBackward0() = default; +#else +struct TORCH_API UpsampleNearest3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearest3DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales_d; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct UpsampleNearestExact3DBackward0 : public TraceableFunction { + TORCH_API UpsampleNearestExact3DBackward0() = default; +#else +struct TORCH_API UpsampleNearestExact3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearestExact3DBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales_d; + ::std::optional scales_h; + ::std::optional scales_w; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct PixelShuffleBackward0 : public TraceableFunction { + TORCH_API PixelShuffleBackward0() = default; +#else +struct TORCH_API PixelShuffleBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PixelShuffleBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t upscale_factor = 0; + +}; +#ifdef _WIN32 +struct PixelUnshuffleBackward0 : public TraceableFunction { + TORCH_API PixelUnshuffleBackward0() = default; +#else +struct TORCH_API PixelUnshuffleBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PixelUnshuffleBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t downscale_factor = 0; + +}; +#ifdef _WIN32 +struct ChannelShuffleBackward0 : public TraceableFunction { + TORCH_API ChannelShuffleBackward0() = default; +#else +struct TORCH_API ChannelShuffleBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ChannelShuffleBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt groups; + +}; +#ifdef _WIN32 +struct AdaptiveAvgPool2DBackward0 : public TraceableFunction { + TORCH_API AdaptiveAvgPool2DBackward0() = default; +#else +struct TORCH_API AdaptiveAvgPool2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AdaptiveAvgPool2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AdaptiveAvgPool3DBackward0 : public TraceableFunction { + TORCH_API AdaptiveAvgPool3DBackward0() = default; +#else +struct TORCH_API AdaptiveAvgPool3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AdaptiveAvgPool3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct AdaptiveMaxPool2DBackward0 : public TraceableFunction { + TORCH_API AdaptiveMaxPool2DBackward0() = default; +#else +struct TORCH_API AdaptiveMaxPool2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AdaptiveMaxPool2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct AdaptiveMaxPool3DBackward0 : public TraceableFunction { + TORCH_API AdaptiveMaxPool3DBackward0() = default; +#else +struct TORCH_API AdaptiveMaxPool3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AdaptiveMaxPool3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct AvgPool2DBackward0 : public TraceableFunction { + TORCH_API AvgPool2DBackward0() = default; +#else +struct TORCH_API AvgPool2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AvgPool2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + bool count_include_pad; + ::std::optional divisor_override; + std::vector kernel_size; + std::vector padding; + SavedVariable self_; + std::vector stride; + +}; +#ifdef _WIN32 +struct AvgPool3DBackward0 : public TraceableFunction { + TORCH_API AvgPool3DBackward0() = default; +#else +struct TORCH_API AvgPool3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AvgPool3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + bool count_include_pad; + ::std::optional divisor_override; + std::vector kernel_size; + std::vector padding; + SavedVariable self_; + std::vector stride; + +}; +#ifdef _WIN32 +struct FractionalMaxPool2DBackward0 : public TraceableFunction { + TORCH_API FractionalMaxPool2DBackward0() = default; +#else +struct TORCH_API FractionalMaxPool2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FractionalMaxPool2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector kernel_size; + std::vector output_size; + SavedVariable self_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct FractionalMaxPool3DBackward0 : public TraceableFunction { + TORCH_API FractionalMaxPool3DBackward0() = default; +#else +struct TORCH_API FractionalMaxPool3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FractionalMaxPool3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector kernel_size; + std::vector output_size; + SavedVariable self_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct LinearBackward0 : public TraceableFunction { + TORCH_API LinearBackward0() = default; +#else +struct TORCH_API LinearBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinearBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable input_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct LinearBackwardBackward0 : public TraceableFunction { + TORCH_API LinearBackwardBackward0() = default; +#else +struct TORCH_API LinearBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LinearBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + SavedVariable self_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MaxPool2DBackward0 : public TraceableFunction { + TORCH_API MaxPool2DBackward0() = default; +#else +struct TORCH_API MaxPool2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxPool2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + std::vector dilation; + std::vector kernel_size; + std::vector padding; + SavedVariable self_; + std::vector stride; + +}; +#ifdef _WIN32 +struct MpsConvolutionBackward0 : public TraceableFunction { + TORCH_API MpsConvolutionBackward0() = default; +#else +struct TORCH_API MpsConvolutionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MpsConvolutionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + c10::SymInt groups; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MpsConvolutionBackwardBackward0 : public TraceableFunction { + TORCH_API MpsConvolutionBackwardBackward0() = default; +#else +struct TORCH_API MpsConvolutionBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MpsConvolutionBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + SavedVariable grad_output_; + c10::SymInt groups; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MaxPool2DWithIndicesBackward0 : public TraceableFunction { + TORCH_API MaxPool2DWithIndicesBackward0() = default; +#else +struct TORCH_API MaxPool2DWithIndicesBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxPool2DWithIndicesBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + std::vector dilation; + std::vector kernel_size; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct MaxPool3DWithIndicesBackward0 : public TraceableFunction { + TORCH_API MaxPool3DWithIndicesBackward0() = default; +#else +struct TORCH_API MaxPool3DWithIndicesBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxPool3DWithIndicesBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + std::vector dilation; + std::vector kernel_size; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct MaxUnpool2DBackward0 : public TraceableFunction { + TORCH_API MaxUnpool2DBackward0() = default; +#else +struct TORCH_API MaxUnpool2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxUnpool2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct MaxUnpool3DBackward0 : public TraceableFunction { + TORCH_API MaxUnpool3DBackward0() = default; +#else +struct TORCH_API MaxUnpool3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxUnpool3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + +}; +#ifdef _WIN32 +struct ConvolutionBackward0 : public TraceableFunction { + TORCH_API ConvolutionBackward0() = default; +#else +struct TORCH_API ConvolutionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConvolutionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + c10::SymInt groups; + SavedVariable input_; + std::vector output_padding; + std::vector padding; + std::vector stride; + bool transposed; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct ConvolutionBackward1 : public TraceableFunction { + TORCH_API ConvolutionBackward1() = default; +#else +struct TORCH_API ConvolutionBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConvolutionBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + c10::SymInt groups; + SavedVariable input_; + std::vector output_padding; + std::vector padding; + std::vector stride; + bool transposed; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct ConvolutionBackwardBackward0 : public TraceableFunction { + TORCH_API ConvolutionBackwardBackward0() = default; +#else +struct TORCH_API ConvolutionBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConvolutionBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + input_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + SavedVariable grad_output_; + c10::SymInt groups; + SavedVariable input_; + std::vector output_padding; + std::vector padding; + std::vector stride; + bool transposed; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct ConvolutionOverrideableBackward0 : public TraceableFunction { + TORCH_API ConvolutionOverrideableBackward0() = default; +#else +struct TORCH_API ConvolutionOverrideableBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConvolutionOverrideableBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + c10::SymInt groups; + SavedVariable input_; + std::vector output_padding; + std::vector padding; + std::vector stride; + bool transposed; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct ConvolutionBackwardOverrideableBackward0 : public TraceableFunction { + TORCH_API ConvolutionBackwardOverrideableBackward0() = default; +#else +struct TORCH_API ConvolutionBackwardOverrideableBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConvolutionBackwardOverrideableBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + input_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + SavedVariable grad_output_; + c10::SymInt groups; + SavedVariable input_; + std::vector output_padding; + std::vector padding; + std::vector stride; + bool transposed; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct SlowConvTranspose2DBackward0 : public TraceableFunction { + TORCH_API SlowConvTranspose2DBackward0() = default; +#else +struct TORCH_API SlowConvTranspose2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SlowConvTranspose2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + std::vector output_padding; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct SlowConvTranspose3DBackward0 : public TraceableFunction { + TORCH_API SlowConvTranspose3DBackward0() = default; +#else +struct TORCH_API SlowConvTranspose3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SlowConvTranspose3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + std::vector output_padding; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct SlowConv2DBackward0 : public TraceableFunction { + TORCH_API SlowConv2DBackward0() = default; +#else +struct TORCH_API SlowConv2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SlowConv2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector kernel_size; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct SlowConv2DBackwardBackward0 : public TraceableFunction { + TORCH_API SlowConv2DBackwardBackward0() = default; +#else +struct TORCH_API SlowConv2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SlowConv2DBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct ConvDepthwise2DBackward0 : public TraceableFunction { + TORCH_API ConvDepthwise2DBackward0() = default; +#else +struct TORCH_API ConvDepthwise2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConvDepthwise2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct ConvDepthwise3DBackward0 : public TraceableFunction { + TORCH_API ConvDepthwise3DBackward0() = default; +#else +struct TORCH_API ConvDepthwise3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConvDepthwise3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct SlowConv3DBackward0 : public TraceableFunction { + TORCH_API SlowConv3DBackward0() = default; +#else +struct TORCH_API SlowConv3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SlowConv3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct SlowConvDilated2DBackward0 : public TraceableFunction { + TORCH_API SlowConvDilated2DBackward0() = default; +#else +struct TORCH_API SlowConvDilated2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SlowConvDilated2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct SlowConvDilated3DBackward0 : public TraceableFunction { + TORCH_API SlowConvDilated3DBackward0() = default; +#else +struct TORCH_API SlowConvDilated3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SlowConvDilated3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct Col2ImBackward0 : public TraceableFunction { + TORCH_API Col2ImBackward0() = default; +#else +struct TORCH_API Col2ImBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Col2ImBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + std::vector kernel_size; + std::vector padding; + std::vector stride; + +}; +#ifdef _WIN32 +struct Im2ColBackward0 : public TraceableFunction { + TORCH_API Im2ColBackward0() = default; +#else +struct TORCH_API Im2ColBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "Im2ColBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + std::vector kernel_size; + std::vector padding; + c10::SymInt self_sym_argsize_minus_1; + c10::SymInt self_sym_argsize_minus_2; + std::vector stride; + +}; +#ifdef _WIN32 +struct AdaptiveAvgPool2DBackwardBackward0 : public TraceableFunction { + TORCH_API AdaptiveAvgPool2DBackwardBackward0() = default; +#else +struct TORCH_API AdaptiveAvgPool2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AdaptiveAvgPool2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt grad_output_sym_argsize_minus_1; + c10::SymInt grad_output_sym_argsize_minus_2; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct AdaptiveAvgPool3DBackwardBackward0 : public TraceableFunction { + TORCH_API AdaptiveAvgPool3DBackwardBackward0() = default; +#else +struct TORCH_API AdaptiveAvgPool3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AdaptiveAvgPool3DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt grad_output_sym_argsize_minus_1; + c10::SymInt grad_output_sym_argsize_minus_2; + c10::SymInt grad_output_sym_argsize_minus_3; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct AdaptiveMaxPool2DBackwardBackward0 : public TraceableFunction { + TORCH_API AdaptiveMaxPool2DBackwardBackward0() = default; +#else +struct TORCH_API AdaptiveMaxPool2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AdaptiveMaxPool2DBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct AdaptiveMaxPool3DBackwardBackward0 : public TraceableFunction { + TORCH_API AdaptiveMaxPool3DBackwardBackward0() = default; +#else +struct TORCH_API AdaptiveMaxPool3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AdaptiveMaxPool3DBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct AvgPool2DBackwardBackward0 : public TraceableFunction { + TORCH_API AvgPool2DBackwardBackward0() = default; +#else +struct TORCH_API AvgPool2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AvgPool2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + bool count_include_pad; + ::std::optional divisor_override; + std::vector kernel_size; + std::vector padding; + torch::autograd::generated::TypeAndSize self_info; + std::vector stride; + +}; +#ifdef _WIN32 +struct AvgPool3DBackwardBackward0 : public TraceableFunction { + TORCH_API AvgPool3DBackwardBackward0() = default; +#else +struct TORCH_API AvgPool3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AvgPool3DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + bool count_include_pad; + ::std::optional divisor_override; + std::vector kernel_size; + std::vector padding; + torch::autograd::generated::TypeAndSize self_info; + std::vector stride; + +}; +#ifdef _WIN32 +struct EluBackwardBackward0 : public TraceableFunction { + TORCH_API EluBackwardBackward0() = default; +#else +struct TORCH_API EluBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EluBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_or_result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + SavedVariable grad_output_; + at::Scalar input_scale; + bool is_result; + at::Scalar scale; + SavedVariable self_or_result_; + +}; +#ifdef _WIN32 +struct FractionalMaxPool2DBackwardBackward0 : public TraceableFunction { + TORCH_API FractionalMaxPool2DBackwardBackward0() = default; +#else +struct TORCH_API FractionalMaxPool2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FractionalMaxPool2DBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct FractionalMaxPool3DBackwardBackward0 : public TraceableFunction { + TORCH_API FractionalMaxPool3DBackwardBackward0() = default; +#else +struct TORCH_API FractionalMaxPool3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FractionalMaxPool3DBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct GluBackwardBackward0 : public TraceableFunction { + TORCH_API GluBackwardBackward0() = default; +#else +struct TORCH_API GluBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "GluBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable grad_output_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct HardtanhBackwardBackward0 : public TraceableFunction { + TORCH_API HardtanhBackwardBackward0() = default; +#else +struct TORCH_API HardtanhBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HardtanhBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar max_val; + at::Scalar min_val; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LogSigmoidBackwardBackward0 : public TraceableFunction { + TORCH_API LogSigmoidBackwardBackward0() = default; +#else +struct TORCH_API LogSigmoidBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogSigmoidBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + buffer_.reset_data(); + grad_output_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable buffer_; + SavedVariable grad_output_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct LogSoftmaxBackwardDataBackward0 : public TraceableFunction { + TORCH_API LogSoftmaxBackwardDataBackward0() = default; +#else +struct TORCH_API LogSoftmaxBackwardDataBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LogSoftmaxBackwardDataBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + output_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable grad_output_; + SavedVariable output_; + +}; +#ifdef _WIN32 +struct LeakyReluBackwardBackward0 : public TraceableFunction { + TORCH_API LeakyReluBackwardBackward0() = default; +#else +struct TORCH_API LeakyReluBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LeakyReluBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar negative_slope; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct MaxPool2DBackwardBackward0 : public TraceableFunction { + TORCH_API MaxPool2DBackwardBackward0() = default; +#else +struct TORCH_API MaxPool2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxPool2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct MaxPool2DWithIndicesBackwardBackward0 : public TraceableFunction { + TORCH_API MaxPool2DWithIndicesBackwardBackward0() = default; +#else +struct TORCH_API MaxPool2DWithIndicesBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxPool2DWithIndicesBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct MaxPool3DWithIndicesBackwardBackward0 : public TraceableFunction { + TORCH_API MaxPool3DWithIndicesBackwardBackward0() = default; +#else +struct TORCH_API MaxPool3DWithIndicesBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MaxPool3DWithIndicesBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + indices_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable indices_; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct MseLossBackwardBackward0 : public TraceableFunction { + TORCH_API MseLossBackwardBackward0() = default; +#else +struct TORCH_API MseLossBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MseLossBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + +}; +#ifdef _WIN32 +struct NllLossBackwardBackward0 : public TraceableFunction { + TORCH_API NllLossBackwardBackward0() = default; +#else +struct TORCH_API NllLossBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NllLossBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + target_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt ignore_index; + int64_t reduction = 0; + SavedVariable target_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct NllLoss2DBackwardBackward0 : public TraceableFunction { + TORCH_API NllLoss2DBackwardBackward0() = default; +#else +struct TORCH_API NllLoss2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NllLoss2DBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + target_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::SymInt ignore_index; + int64_t reduction = 0; + SavedVariable target_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct RreluWithNoiseBackwardBackward0 : public TraceableFunction { + TORCH_API RreluWithNoiseBackwardBackward0() = default; +#else +struct TORCH_API RreluWithNoiseBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "RreluWithNoiseBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + noise_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar lower; + SavedVariable noise_; + SavedVariable self_; + bool training; + at::Scalar upper; + +}; +#ifdef _WIN32 +struct ReflectionPad1DBackwardBackward0 : public TraceableFunction { + TORCH_API ReflectionPad1DBackwardBackward0() = default; +#else +struct TORCH_API ReflectionPad1DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReflectionPad1DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct ReflectionPad2DBackwardBackward0 : public TraceableFunction { + TORCH_API ReflectionPad2DBackwardBackward0() = default; +#else +struct TORCH_API ReflectionPad2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReflectionPad2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct ReflectionPad3DBackwardBackward0 : public TraceableFunction { + TORCH_API ReflectionPad3DBackwardBackward0() = default; +#else +struct TORCH_API ReflectionPad3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReflectionPad3DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct ReplicationPad1DBackwardBackward0 : public TraceableFunction { + TORCH_API ReplicationPad1DBackwardBackward0() = default; +#else +struct TORCH_API ReplicationPad1DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReplicationPad1DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct ReplicationPad2DBackwardBackward0 : public TraceableFunction { + TORCH_API ReplicationPad2DBackwardBackward0() = default; +#else +struct TORCH_API ReplicationPad2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReplicationPad2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct ReplicationPad3DBackwardBackward0 : public TraceableFunction { + TORCH_API ReplicationPad3DBackwardBackward0() = default; +#else +struct TORCH_API ReplicationPad3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReplicationPad3DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padding; + torch::autograd::generated::TypeAndSize self_info; + +}; +#ifdef _WIN32 +struct SparseSampledAddmmBackward0 : public TraceableFunction { + TORCH_API SparseSampledAddmmBackward0() = default; +#else +struct TORCH_API SparseSampledAddmmBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseSampledAddmmBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + mat1_.reset_data(); + mat2_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + at::Scalar beta; + SavedVariable mat1_; + SavedVariable mat2_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SparseMmReduceImplBackward0 : public TraceableFunction { + TORCH_API SparseMmReduceImplBackward0() = default; +#else +struct TORCH_API SparseMmReduceImplBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SparseMmReduceImplBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + std::string reduce; + SavedVariable self_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct SmoothL1LossBackwardBackward0 : public TraceableFunction { + TORCH_API SmoothL1LossBackwardBackward0() = default; +#else +struct TORCH_API SmoothL1LossBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SmoothL1LossBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double beta; + SavedVariable grad_output_; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + +}; +#ifdef _WIN32 +struct HuberLossBackwardBackward0 : public TraceableFunction { + TORCH_API HuberLossBackwardBackward0() = default; +#else +struct TORCH_API HuberLossBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "HuberLossBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double delta; + SavedVariable grad_output_; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + +}; +#ifdef _WIN32 +struct SoftplusBackwardBackward0 : public TraceableFunction { + TORCH_API SoftplusBackwardBackward0() = default; +#else +struct TORCH_API SoftplusBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SoftplusBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar beta; + SavedVariable grad_output_; + SavedVariable self_; + at::Scalar threshold; + +}; +#ifdef _WIN32 +struct SoftmaxBackwardDataBackward0 : public TraceableFunction { + TORCH_API SoftmaxBackwardDataBackward0() = default; +#else +struct TORCH_API SoftmaxBackwardDataBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SoftmaxBackwardDataBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + output_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable grad_output_; + at::ScalarType input_dtype; + SavedVariable output_; + +}; +#ifdef _WIN32 +struct SoftMarginLossBackwardBackward0 : public TraceableFunction { + TORCH_API SoftMarginLossBackwardBackward0() = default; +#else +struct TORCH_API SoftMarginLossBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SoftMarginLossBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + self_.reset_data(); + target_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + int64_t reduction = 0; + SavedVariable self_; + SavedVariable target_; + +}; +#ifdef _WIN32 +struct SoftshrinkBackwardBackward0 : public TraceableFunction { + TORCH_API SoftshrinkBackwardBackward0() = default; +#else +struct TORCH_API SoftshrinkBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SoftshrinkBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar lambd; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ThresholdBackwardBackward0 : public TraceableFunction { + TORCH_API ThresholdBackwardBackward0() = default; +#else +struct TORCH_API ThresholdBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ThresholdBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + at::Scalar threshold; + +}; +#ifdef _WIN32 +struct UpsampleLinear1DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleLinear1DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleLinear1DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleLinear1DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales; + +}; +#ifdef _WIN32 +struct UpsampleBilinear2DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleBilinear2DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleBilinear2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleBilinear2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct UpsampleBilinear2DAaBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleBilinear2DAaBackwardBackward0() = default; +#else +struct TORCH_API UpsampleBilinear2DAaBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleBilinear2DAaBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct UpsampleBicubic2DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleBicubic2DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleBicubic2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleBicubic2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct UpsampleBicubic2DAaBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleBicubic2DAaBackwardBackward0() = default; +#else +struct TORCH_API UpsampleBicubic2DAaBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleBicubic2DAaBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct UpsampleTrilinear3DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleTrilinear3DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleTrilinear3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleTrilinear3DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool align_corners; + std::vector output_size; + ::std::optional scales_d; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct UpsampleNearest1DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleNearest1DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleNearest1DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearest1DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales; + +}; +#ifdef _WIN32 +struct UpsampleNearestExact1DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleNearestExact1DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleNearestExact1DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearestExact1DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales; + +}; +#ifdef _WIN32 +struct UpsampleNearest2DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleNearest2DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleNearest2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearest2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct UpsampleNearestExact2DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleNearestExact2DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleNearestExact2DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearestExact2DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct UpsampleNearest3DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleNearest3DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleNearest3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearest3DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales_d; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct UpsampleNearestExact3DBackwardBackward0 : public TraceableFunction { + TORCH_API UpsampleNearestExact3DBackwardBackward0() = default; +#else +struct TORCH_API UpsampleNearestExact3DBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UpsampleNearestExact3DBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector output_size; + ::std::optional scales_d; + ::std::optional scales_h; + ::std::optional scales_w; + +}; +#ifdef _WIN32 +struct SigmoidBackwardBackward0 : public TraceableFunction { + TORCH_API SigmoidBackwardBackward0() = default; +#else +struct TORCH_API SigmoidBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SigmoidBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + output_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + SavedVariable output_; + +}; +#ifdef _WIN32 +struct TanhBackwardBackward0 : public TraceableFunction { + TORCH_API TanhBackwardBackward0() = default; +#else +struct TORCH_API TanhBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TanhBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + output_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grad_output_; + SavedVariable output_; + +}; +#ifdef _WIN32 +struct CudnnCtcLossBackward0 : public TraceableFunction { + TORCH_API CudnnCtcLossBackward0() = default; +#else +struct TORCH_API CudnnCtcLossBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnCtcLossBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result0_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool zero_infinity; + SavedVariable result0_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct CudnnCtcLossBackward1 : public TraceableFunction { + TORCH_API CudnnCtcLossBackward1() = default; +#else +struct TORCH_API CudnnCtcLossBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnCtcLossBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result0_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool zero_infinity; + SavedVariable result0_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct CudnnConvolutionTransposeBackward0 : public TraceableFunction { + TORCH_API CudnnConvolutionTransposeBackward0() = default; +#else +struct TORCH_API CudnnConvolutionTransposeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnConvolutionTransposeBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + c10::SymInt groups; + std::vector output_padding; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MpsConvolutionTransposeBackward0 : public TraceableFunction { + TORCH_API MpsConvolutionTransposeBackward0() = default; +#else +struct TORCH_API MpsConvolutionTransposeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MpsConvolutionTransposeBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + c10::SymInt groups; + std::vector output_padding; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct CudnnConvolutionBackward0 : public TraceableFunction { + TORCH_API CudnnConvolutionBackward0() = default; +#else +struct TORCH_API CudnnConvolutionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnConvolutionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dilation; + c10::SymInt groups; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct CudnnGridSamplerBackward0 : public TraceableFunction { + TORCH_API CudnnGridSamplerBackward0() = default; +#else +struct TORCH_API CudnnGridSamplerBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnGridSamplerBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grid_.reset_data(); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable grid_; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct CudnnAffineGridGeneratorBackward0 : public TraceableFunction { + TORCH_API CudnnAffineGridGeneratorBackward0() = default; +#else +struct TORCH_API CudnnAffineGridGeneratorBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnAffineGridGeneratorBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t C = 0; + int64_t H = 0; + int64_t N = 0; + int64_t W = 0; + +}; +#ifdef _WIN32 +struct CudnnBatchNormBackward0 : public TraceableFunction { + TORCH_API CudnnBatchNormBackward0() = default; +#else +struct TORCH_API CudnnBatchNormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnBatchNormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + result3_.reset_data(); + } + bool retain_variables = true; + void will_release_variables() override { + retain_variables = false; + } + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double epsilon; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + bool training; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + SavedVariable result3_; + +}; +#ifdef _WIN32 +struct CudnnBatchNormBackwardBackward0 : public TraceableFunction { + TORCH_API CudnnBatchNormBackwardBackward0() = default; +#else +struct TORCH_API CudnnBatchNormBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnBatchNormBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + input_.reset_data(); + reserveSpace_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + save_mean_.reset_data(); + save_var_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double epsilon; + SavedVariable grad_output_; + SavedVariable input_; + SavedVariable reserveSpace_; + SavedVariable running_mean_; + SavedVariable running_var_; + SavedVariable save_mean_; + SavedVariable save_var_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct NnpackSpatialConvolutionBackward0 : public TraceableFunction { + TORCH_API NnpackSpatialConvolutionBackward0() = default; +#else +struct TORCH_API NnpackSpatialConvolutionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NnpackSpatialConvolutionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + SavedVariable input_; + std::vector padding; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct LstmMpsBackward0 : public TraceableFunction { + TORCH_API LstmMpsBackward0() = default; +#else +struct TORCH_API LstmMpsBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LstmMpsBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + hx_.clear(); + hx_released_ = true; + input_.reset_data(); + params_.clear(); + params_released_ = true; + result3_.reset_data(); + result4_.reset_data(); + result5_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool batch_first; + bool bidirectional; + double dropout; + bool has_biases; + std::vector hx_; + bool hx_released_ = false; + SavedVariable input_; + int64_t num_layers = 0; + std::vector params_; + bool params_released_ = false; + bool train; + SavedVariable result3_; + SavedVariable result4_; + SavedVariable result5_; + size_t hx_size_; + size_t params_size_; +}; +#ifdef _WIN32 +struct CudnnRnnBackward0 : public TraceableFunction { + TORCH_API CudnnRnnBackward0() = default; +#else +struct TORCH_API CudnnRnnBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnRnnBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + cx_.reset_data(); + dropout_state_.reset_data(); + hx_.reset_data(); + input_.reset_data(); + weight_.clear(); + weight_released_ = true; + result0_.reset_data(); + result3_.reset_data(); + result4_.reset_data(); + } + bool retain_variables = true; + void will_release_variables() override { + retain_variables = false; + } + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool batch_first; + std::vector batch_sizes; + bool bidirectional; + SavedVariable cx_; + double dropout; + SavedVariable dropout_state_; + c10::SymInt hidden_size; + SavedVariable hx_; + SavedVariable input_; + int64_t mode = 0; + int64_t num_layers = 0; + c10::SymInt proj_size; + bool train; + std::vector weight_; + bool weight_released_ = false; + int64_t weight_stride0 = 0; + SavedVariable result0_; + SavedVariable result3_; + SavedVariable result4_; + size_t weight_size_; +}; +#ifdef _WIN32 +struct CudnnRnnBackwardBackward0 : public TraceableFunction { + TORCH_API CudnnRnnBackwardBackward0() = default; +#else +struct TORCH_API CudnnRnnBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnRnnBackwardBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + size_t weight_size_; +}; +#ifdef _WIN32 +struct MiopenConvolutionTransposeBackward0 : public TraceableFunction { + TORCH_API MiopenConvolutionTransposeBackward0() = default; +#else +struct TORCH_API MiopenConvolutionTransposeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MiopenConvolutionTransposeBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + c10::SymInt groups; + std::vector output_padding; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MiopenConvolutionBackward0 : public TraceableFunction { + TORCH_API MiopenConvolutionBackward0() = default; +#else +struct TORCH_API MiopenConvolutionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MiopenConvolutionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + c10::SymInt groups; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MiopenDepthwiseConvolutionBackward0 : public TraceableFunction { + TORCH_API MiopenDepthwiseConvolutionBackward0() = default; +#else +struct TORCH_API MiopenDepthwiseConvolutionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MiopenDepthwiseConvolutionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + c10::SymInt groups; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MiopenBatchNormBackward0 : public TraceableFunction { + TORCH_API MiopenBatchNormBackward0() = default; +#else +struct TORCH_API MiopenBatchNormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MiopenBatchNormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + weight_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double epsilon; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + bool training; + SavedVariable weight_; + SavedVariable result1_; + SavedVariable result2_; + +}; +#ifdef _WIN32 +struct MiopenBatchNormBackwardBackward0 : public TraceableFunction { + TORCH_API MiopenBatchNormBackwardBackward0() = default; +#else +struct TORCH_API MiopenBatchNormBackwardBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MiopenBatchNormBackwardBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + grad_output_.reset_data(); + input_.reset_data(); + running_mean_.reset_data(); + running_var_.reset_data(); + save_mean_.reset_data(); + save_var_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double epsilon; + SavedVariable grad_output_; + SavedVariable input_; + SavedVariable running_mean_; + SavedVariable running_var_; + SavedVariable save_mean_; + SavedVariable save_var_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MiopenRnnBackward0 : public TraceableFunction { + TORCH_API MiopenRnnBackward0() = default; +#else +struct TORCH_API MiopenRnnBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MiopenRnnBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + cx_.reset_data(); + dropout_state_.reset_data(); + hx_.reset_data(); + input_.reset_data(); + weight_.clear(); + weight_released_ = true; + result0_.reset_data(); + result3_.reset_data(); + result4_.reset_data(); + } + bool retain_variables = true; + void will_release_variables() override { + retain_variables = false; + } + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool batch_first; + std::vector batch_sizes; + bool bidirectional; + SavedVariable cx_; + double dropout; + SavedVariable dropout_state_; + int64_t hidden_size = 0; + SavedVariable hx_; + SavedVariable input_; + int64_t mode = 0; + int64_t num_layers = 0; + bool train; + std::vector weight_; + bool weight_released_ = false; + int64_t weight_stride0 = 0; + SavedVariable result0_; + SavedVariable result3_; + SavedVariable result4_; + size_t weight_size_; +}; +#ifdef _WIN32 +struct MkldnnRnnLayerBackward0 : public TraceableFunction { + TORCH_API MkldnnRnnLayerBackward0() = default; +#else +struct TORCH_API MkldnnRnnLayerBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MkldnnRnnLayerBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + cx__.reset_data(); + hx__.reset_data(); + input_.reset_data(); + weight0_.reset_data(); + weight1_.reset_data(); + weight2_.reset_data(); + weight3_.reset_data(); + result0_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + result3_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool batch_first; + std::vector batch_sizes; + bool bidirectional; + SavedVariable cx__; + bool has_biases; + int64_t hidden_size = 0; + SavedVariable hx__; + SavedVariable input_; + int64_t mode = 0; + int64_t num_layers = 0; + bool reverse; + bool train; + SavedVariable weight0_; + SavedVariable weight1_; + SavedVariable weight2_; + SavedVariable weight3_; + SavedVariable result0_; + SavedVariable result1_; + SavedVariable result2_; + SavedVariable result3_; + +}; +#ifdef _WIN32 +struct MkldnnConvolutionBackward0 : public TraceableFunction { + TORCH_API MkldnnConvolutionBackward0() = default; +#else +struct TORCH_API MkldnnConvolutionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MkldnnConvolutionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + c10::OptionalArray bias_sym_sizes_opt; + std::vector dilation; + c10::SymInt groups; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MkldnnLinearBackward0 : public TraceableFunction { + TORCH_API MkldnnLinearBackward0() = default; +#else +struct TORCH_API MkldnnLinearBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MkldnnLinearBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + weight_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + SavedVariable weight_; + +}; +#ifdef _WIN32 +struct MkldnnMaxPool2DBackward0 : public TraceableFunction { + TORCH_API MkldnnMaxPool2DBackward0() = default; +#else +struct TORCH_API MkldnnMaxPool2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MkldnnMaxPool2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + std::vector dilation; + std::vector kernel_size; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct MkldnnMaxPool3DBackward0 : public TraceableFunction { + TORCH_API MkldnnMaxPool3DBackward0() = default; +#else +struct TORCH_API MkldnnMaxPool3DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MkldnnMaxPool3DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool ceil_mode; + std::vector dilation; + std::vector kernel_size; + std::vector padding; + SavedVariable self_; + std::vector stride; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct MkldnnAdaptiveAvgPool2DBackward0 : public TraceableFunction { + TORCH_API MkldnnAdaptiveAvgPool2DBackward0() = default; +#else +struct TORCH_API MkldnnAdaptiveAvgPool2DBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MkldnnAdaptiveAvgPool2DBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct MkldnnReshapeBackward0 : public TraceableFunction { + TORCH_API MkldnnReshapeBackward0() = default; +#else +struct TORCH_API MkldnnReshapeBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "MkldnnReshapeBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct NestedTensorFromTensorListBackward0 : public TraceableFunction { + TORCH_API NestedTensorFromTensorListBackward0() = default; +#else +struct TORCH_API NestedTensorFromTensorListBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedTensorFromTensorListBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + list_.clear(); + list_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector list_; + bool list_released_ = false; + size_t list_size_; +}; +#ifdef _WIN32 +struct NestedTensorFromMaskBackward0 : public TraceableFunction { + TORCH_API NestedTensorFromMaskBackward0() = default; +#else +struct TORCH_API NestedTensorFromMaskBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedTensorFromMaskBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector t_sym_sizes; + +}; +#ifdef _WIN32 +struct NestedFromPaddedBackward0 : public TraceableFunction { + TORCH_API NestedFromPaddedBackward0() = default; +#else +struct TORCH_API NestedFromPaddedBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedFromPaddedBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + padded_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool fuse_transform_0213; + SavedVariable padded_; + +}; +#ifdef _WIN32 +struct ToPaddedTensorBackward0 : public TraceableFunction { + TORCH_API ToPaddedTensorBackward0() = default; +#else +struct TORCH_API ToPaddedTensorBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ToPaddedTensorBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + at::Layout self_layout; + +}; +#ifdef _WIN32 +struct NestedFromPaddedTensorBackward0 : public TraceableFunction { + TORCH_API NestedFromPaddedTensorBackward0() = default; +#else +struct TORCH_API NestedFromPaddedTensorBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedFromPaddedTensorBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector padded_sym_sizes; + +}; +#ifdef _WIN32 +struct NestedViewFromBufferBackward0 : public Node { + TORCH_API NestedViewFromBufferBackward0() = default; +#else +struct TORCH_API NestedViewFromBufferBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedViewFromBufferBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NestedViewFromJaggedBackward0 : public Node { + TORCH_API NestedViewFromJaggedBackward0() = default; +#else +struct TORCH_API NestedViewFromJaggedBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedViewFromJaggedBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NestedGetValuesBackward0 : public Node { + TORCH_API NestedGetValuesBackward0() = default; +#else +struct TORCH_API NestedGetValuesBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedGetValuesBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SafeSoftmaxBackward0 : public TraceableFunction { + TORCH_API SafeSoftmaxBackward0() = default; +#else +struct TORCH_API SafeSoftmaxBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SafeSoftmaxBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::ScalarType self_scalar_type; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ScaledDotProductEfficientAttentionBackward0 : public TraceableFunction { + TORCH_API ScaledDotProductEfficientAttentionBackward0() = default; +#else +struct TORCH_API ScaledDotProductEfficientAttentionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScaledDotProductEfficientAttentionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + attn_bias_.reset_data(); + key_.reset_data(); + query_.reset_data(); + value_.reset_data(); + log_sumexp_.reset_data(); + output_.reset_data(); + philox_offset_.reset_data(); + philox_seed_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable attn_bias_; + double dropout_p; + bool is_causal; + SavedVariable key_; + SavedVariable query_; + ::std::optional scale; + SavedVariable value_; + SavedVariable log_sumexp_; + SavedVariable output_; + SavedVariable philox_offset_; + SavedVariable philox_seed_; + +}; +#ifdef _WIN32 +struct ScaledDotProductFlashAttentionBackward0 : public TraceableFunction { + TORCH_API ScaledDotProductFlashAttentionBackward0() = default; +#else +struct TORCH_API ScaledDotProductFlashAttentionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScaledDotProductFlashAttentionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + key_.reset_data(); + query_.reset_data(); + value_.reset_data(); + cum_seq_k_.reset_data(); + cum_seq_q_.reset_data(); + logsumexp_.reset_data(); + output_.reset_data(); + rng_state_.reset_data(); + unused_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + double dropout_p; + bool is_causal; + SavedVariable key_; + SavedVariable query_; + ::std::optional scale; + SavedVariable value_; + SavedVariable cum_seq_k_; + SavedVariable cum_seq_q_; + SavedVariable logsumexp_; + c10::SymInt max_k; + c10::SymInt max_q; + SavedVariable output_; + SavedVariable rng_state_; + SavedVariable unused_; + +}; +#ifdef _WIN32 +struct ScaledDotProductFlashAttentionForCpuBackward0 : public TraceableFunction { + TORCH_API ScaledDotProductFlashAttentionForCpuBackward0() = default; +#else +struct TORCH_API ScaledDotProductFlashAttentionForCpuBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScaledDotProductFlashAttentionForCpuBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + attn_mask_.reset_data(); + key_.reset_data(); + query_.reset_data(); + value_.reset_data(); + logsumexp_.reset_data(); + output_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable attn_mask_; + double dropout_p; + bool is_causal; + SavedVariable key_; + SavedVariable query_; + ::std::optional scale; + SavedVariable value_; + SavedVariable logsumexp_; + SavedVariable output_; + +}; +#ifdef _WIN32 +struct FlashAttentionBackward0 : public TraceableFunction { + TORCH_API FlashAttentionBackward0() = default; +#else +struct TORCH_API FlashAttentionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FlashAttentionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + cum_seq_k_.reset_data(); + cum_seq_q_.reset_data(); + key_.reset_data(); + query_.reset_data(); + value_.reset_data(); + output_.reset_data(); + rng_state_.reset_data(); + softmax_logsumexp_.reset_data(); + unused_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable cum_seq_k_; + SavedVariable cum_seq_q_; + double dropout_p; + bool is_causal; + SavedVariable key_; + c10::SymInt max_k; + c10::SymInt max_q; + SavedVariable query_; + ::std::optional scale; + SavedVariable value_; + ::std::optional window_size_left; + ::std::optional window_size_right; + SavedVariable output_; + SavedVariable rng_state_; + SavedVariable softmax_logsumexp_; + SavedVariable unused_; + +}; +#ifdef _WIN32 +struct EfficientAttentionBackward0 : public TraceableFunction { + TORCH_API EfficientAttentionBackward0() = default; +#else +struct TORCH_API EfficientAttentionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "EfficientAttentionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + bias_.reset_data(); + cu_seqlens_k_.reset_data(); + cu_seqlens_q_.reset_data(); + key_.reset_data(); + query_.reset_data(); + value_.reset_data(); + logsumexp_.reset_data(); + output_.reset_data(); + philox_offset_.reset_data(); + philox_seed_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable bias_; + SavedVariable cu_seqlens_k_; + SavedVariable cu_seqlens_q_; + int64_t custom_mask_type = 0; + double dropout_p; + SavedVariable key_; + SavedVariable query_; + ::std::optional scale; + SavedVariable value_; + SavedVariable logsumexp_; + c10::SymInt max_seqlen_batch_k; + c10::SymInt max_seqlen_batch_q; + SavedVariable output_; + SavedVariable philox_offset_; + SavedVariable philox_seed_; + +}; +#ifdef _WIN32 +struct CudnnAttentionBackward0 : public TraceableFunction { + TORCH_API CudnnAttentionBackward0() = default; +#else +struct TORCH_API CudnnAttentionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "CudnnAttentionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + attn_bias_.reset_data(); + cum_seq_k_.reset_data(); + cum_seq_q_.reset_data(); + key_.reset_data(); + query_.reset_data(); + value_.reset_data(); + logsumexp_.reset_data(); + output_.reset_data(); + philox_offset_.reset_data(); + philox_seed_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable attn_bias_; + SavedVariable cum_seq_k_; + SavedVariable cum_seq_q_; + double dropout_p; + bool is_causal; + SavedVariable key_; + c10::SymInt max_k; + c10::SymInt max_q; + SavedVariable query_; + ::std::optional scale; + SavedVariable value_; + SavedVariable logsumexp_; + SavedVariable output_; + SavedVariable philox_offset_; + SavedVariable philox_seed_; + +}; +#ifdef _WIN32 +struct ScaledDotProductCudnnAttentionBackward0 : public TraceableFunction { + TORCH_API ScaledDotProductCudnnAttentionBackward0() = default; +#else +struct TORCH_API ScaledDotProductCudnnAttentionBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScaledDotProductCudnnAttentionBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + attn_bias_.reset_data(); + key_.reset_data(); + query_.reset_data(); + value_.reset_data(); + cum_seq_k_.reset_data(); + cum_seq_q_.reset_data(); + logsumexp_.reset_data(); + output_.reset_data(); + philox_offset_.reset_data(); + philox_seed_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable attn_bias_; + double dropout_p; + bool is_causal; + SavedVariable key_; + SavedVariable query_; + ::std::optional scale; + SavedVariable value_; + SavedVariable cum_seq_k_; + SavedVariable cum_seq_q_; + SavedVariable logsumexp_; + c10::SymInt max_k; + c10::SymInt max_q; + SavedVariable output_; + SavedVariable philox_offset_; + SavedVariable philox_seed_; + +}; +#ifdef _WIN32 +struct ScaledDotProductFusedAttentionOverrideableBackward0 : public TraceableFunction { + TORCH_API ScaledDotProductFusedAttentionOverrideableBackward0() = default; +#else +struct TORCH_API ScaledDotProductFusedAttentionOverrideableBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScaledDotProductFusedAttentionOverrideableBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + attn_bias_.reset_data(); + key_.reset_data(); + query_.reset_data(); + value_.reset_data(); + cum_seq_k_.reset_data(); + cum_seq_q_.reset_data(); + logsumexp_.reset_data(); + output_.reset_data(); + philox_offset_.reset_data(); + philox_seed_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable attn_bias_; + double dropout_p; + bool is_causal; + SavedVariable key_; + SavedVariable query_; + ::std::optional scale; + SavedVariable value_; + SavedVariable cum_seq_k_; + SavedVariable cum_seq_q_; + SavedVariable logsumexp_; + c10::SymInt max_k; + c10::SymInt max_q; + SavedVariable output_; + SavedVariable philox_offset_; + SavedVariable philox_seed_; + +}; +#ifdef _WIN32 +struct FftR2CBackward0 : public TraceableFunction { + TORCH_API FftR2CBackward0() = default; +#else +struct TORCH_API FftR2CBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FftR2CBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + int64_t normalization = 0; + bool onesided; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct FftC2RBackward0 : public TraceableFunction { + TORCH_API FftC2RBackward0() = default; +#else +struct TORCH_API FftC2RBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FftC2RBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + int64_t normalization = 0; + +}; +#ifdef _WIN32 +struct FftC2CBackward0 : public TraceableFunction { + TORCH_API FftC2CBackward0() = default; +#else +struct TORCH_API FftC2CBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "FftC2CBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + bool forward; + int64_t normalization = 0; + +}; +#ifdef _WIN32 +struct UnbindBackward0 : public Node { + TORCH_API UnbindBackward0() = default; +#else +struct TORCH_API UnbindBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnbindBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + +}; +#ifdef _WIN32 +struct UnbindBackwardAutogradNestedTensor0 : public Node { + TORCH_API UnbindBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API UnbindBackwardAutogradNestedTensor0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnbindBackwardAutogradNestedTensor0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + at::Layout self_layout; + at::TensorOptions self_options; + +}; +#ifdef _WIN32 +struct StackBackward0 : public TraceableFunction { + TORCH_API StackBackward0() = default; +#else +struct TORCH_API StackBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "StackBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + ::std::vector tensors_args_scalartypes; + size_t tensors_size_; +}; +#ifdef _WIN32 +struct ThnnFusedLstmCellBackward0 : public TraceableFunction { + TORCH_API ThnnFusedLstmCellBackward0() = default; +#else +struct TORCH_API ThnnFusedLstmCellBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ThnnFusedLstmCellBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + cx_.reset_data(); + hidden_bias_.reset_data(); + hidden_gates_.reset_data(); + input_bias_.reset_data(); + input_gates_.reset_data(); + result1_.reset_data(); + result2_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable cx_; + SavedVariable hidden_bias_; + SavedVariable hidden_gates_; + SavedVariable input_bias_; + SavedVariable input_gates_; + SavedVariable result1_; + SavedVariable result2_; + +}; +#ifdef _WIN32 +struct ThnnFusedGruCellBackward0 : public TraceableFunction { + TORCH_API ThnnFusedGruCellBackward0() = default; +#else +struct TORCH_API ThnnFusedGruCellBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ThnnFusedGruCellBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + hidden_bias_.reset_data(); + hidden_gates_.reset_data(); + hx_.reset_data(); + input_bias_.reset_data(); + input_gates_.reset_data(); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable hidden_bias_; + SavedVariable hidden_gates_; + SavedVariable hx_; + SavedVariable input_bias_; + SavedVariable input_gates_; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct PackPaddedSequenceBackward0 : public TraceableFunction { + TORCH_API PackPaddedSequenceBackward0() = default; +#else +struct TORCH_API PackPaddedSequenceBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PackPaddedSequenceBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result1_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + bool batch_first; + std::vector input_sym_sizes; + SavedVariable result1_; + +}; +#ifdef _WIN32 +struct SegmentReduceBackward0 : public TraceableFunction { + TORCH_API SegmentReduceBackward0() = default; +#else +struct TORCH_API SegmentReduceBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SegmentReduceBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + data_.reset_data(); + lengths_.reset_data(); + offsets_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t axis = 0; + SavedVariable data_; + ::std::optional initial; + SavedVariable lengths_; + SavedVariable offsets_; + std::string reduce; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct PinMemoryBackward0 : public TraceableFunction { + TORCH_API PinMemoryBackward0() = default; +#else +struct TORCH_API PinMemoryBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PinMemoryBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct TestWarnInAutogradBackward0 : public TraceableFunction { + TORCH_API TestWarnInAutogradBackward0() = default; +#else +struct TORCH_API TestWarnInAutogradBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestWarnInAutogradBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct TestAutogradMultipleDispatchBackward0 : public TraceableFunction { + TORCH_API TestAutogradMultipleDispatchBackward0() = default; +#else +struct TORCH_API TestAutogradMultipleDispatchBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestAutogradMultipleDispatchBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct TestAutogradMultipleDispatchBackwardAutogradNestedTensor0 : public TraceableFunction { + TORCH_API TestAutogradMultipleDispatchBackwardAutogradNestedTensor0() = default; +#else +struct TORCH_API TestAutogradMultipleDispatchBackwardAutogradNestedTensor0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestAutogradMultipleDispatchBackwardAutogradNestedTensor0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct TestAutogradMultipleDispatchBackwardAutogradCUDA0 : public TraceableFunction { + TORCH_API TestAutogradMultipleDispatchBackwardAutogradCUDA0() = default; +#else +struct TORCH_API TestAutogradMultipleDispatchBackwardAutogradCUDA0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestAutogradMultipleDispatchBackwardAutogradCUDA0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct TestAutogradMultipleDispatchBackwardAutogradNestedTensor1 : public TraceableFunction { + TORCH_API TestAutogradMultipleDispatchBackwardAutogradNestedTensor1() = default; +#else +struct TORCH_API TestAutogradMultipleDispatchBackwardAutogradNestedTensor1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestAutogradMultipleDispatchBackwardAutogradNestedTensor1"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct TestAutogradMultipleDispatchViewBackward0 : public Node { + TORCH_API TestAutogradMultipleDispatchViewBackward0() = default; +#else +struct TORCH_API TestAutogradMultipleDispatchViewBackward0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestAutogradMultipleDispatchViewBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct TestAutogradMultipleDispatchViewBackwardAutogradCUDA0 : public Node { + TORCH_API TestAutogradMultipleDispatchViewBackwardAutogradCUDA0() = default; +#else +struct TORCH_API TestAutogradMultipleDispatchViewBackwardAutogradCUDA0 : public Node { +#endif + using Node::Node; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestAutogradMultipleDispatchViewBackwardAutogradCUDA0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ScatterReduceBackward0 : public TraceableFunction { + TORCH_API ScatterReduceBackward0() = default; +#else +struct TORCH_API ScatterReduceBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ScatterReduceBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + index_.reset_data(); + self_.reset_data(); + src_.reset_data(); + result_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + bool include_self; + SavedVariable index_; + std::string reduce; + SavedVariable self_; + SavedVariable src_; + SavedVariable result_; + +}; +#ifdef _WIN32 +struct ReshapeCopyBackward0 : public TraceableFunction { + TORCH_API ReshapeCopyBackward0() = default; +#else +struct TORCH_API ReshapeCopyBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReshapeCopyBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct ForeachDivBackward0 : public TraceableFunction { + TORCH_API ForeachDivBackward0() = default; +#else +struct TORCH_API ForeachDivBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachDivBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.clear(); + other_released_ = true; + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector other_; + bool other_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; + size_t other_size_; +}; +#ifdef _WIN32 +struct ForeachPowBackward0 : public TraceableFunction { + TORCH_API ForeachPowBackward0() = default; +#else +struct TORCH_API ForeachPowBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachPowBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + exponent_.clear(); + exponent_released_ = true; + self_.clear(); + self_released_ = true; + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector exponent_; + bool exponent_released_ = false; + std::vector self_; + bool self_released_ = false; + std::vector result_; + bool result_released_ = false; + size_t self_size_; + size_t exponent_size_; +}; +#ifdef _WIN32 +struct ForeachPowBackward1 : public TraceableFunction { + TORCH_API ForeachPowBackward1() = default; +#else +struct TORCH_API ForeachPowBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachPowBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + exponent.clear(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector exponent; + bool exponent_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachPowBackward2 : public TraceableFunction { + TORCH_API ForeachPowBackward2() = default; +#else +struct TORCH_API ForeachPowBackward2 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachPowBackward2"; } + void release_variables() override { + std::lock_guard lock(mutex_); + exponent_.clear(); + exponent_released_ = true; + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector exponent_; + bool exponent_released_ = false; + at::Scalar self; + std::vector result_; + bool result_released_ = false; + size_t exponent_size_; +}; +#ifdef _WIN32 +struct ForeachMinimumBackward0 : public TraceableFunction { + TORCH_API ForeachMinimumBackward0() = default; +#else +struct TORCH_API ForeachMinimumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMinimumBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar scalar; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachMinimumBackward1 : public TraceableFunction { + TORCH_API ForeachMinimumBackward1() = default; +#else +struct TORCH_API ForeachMinimumBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMinimumBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scalars.clear(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector scalars; + bool scalars_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachMaximumBackward0 : public TraceableFunction { + TORCH_API ForeachMaximumBackward0() = default; +#else +struct TORCH_API ForeachMaximumBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMaximumBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar scalar; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachMaximumBackward1 : public TraceableFunction { + TORCH_API ForeachMaximumBackward1() = default; +#else +struct TORCH_API ForeachMaximumBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMaximumBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scalars.clear(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector scalars; + bool scalars_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachNormBackward0 : public TraceableFunction { + TORCH_API ForeachNormBackward0() = default; +#else +struct TORCH_API ForeachNormBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachNormBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar ord; + std::vector self_; + bool self_released_ = false; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct AliasBackward0_copy : public TraceableFunction { + TORCH_API AliasBackward0_copy() = default; +#else +struct TORCH_API AliasBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AliasBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct AsStridedBackward0_copy : public TraceableFunction { + TORCH_API AsStridedBackward0_copy() = default; +#else +struct TORCH_API AsStridedBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "AsStridedBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::TensorGeometry self_geometry; + std::vector size; + ::std::optional storage_offset; + std::vector stride; + +}; +#ifdef _WIN32 +struct ConjBackward0_copy : public TraceableFunction { + TORCH_API ConjBackward0_copy() = default; +#else +struct TORCH_API ConjBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ConjBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NegViewBackward0_copy : public TraceableFunction { + TORCH_API NegViewBackward0_copy() = default; +#else +struct TORCH_API NegViewBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NegViewBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct DiagonalBackward0_copy : public TraceableFunction { + TORCH_API DiagonalBackward0_copy() = default; +#else +struct TORCH_API DiagonalBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "DiagonalBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim1 = 0; + int64_t dim2 = 0; + int64_t offset = 0; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct ExpandBackward0_copy : public TraceableFunction { + TORCH_API ExpandBackward0_copy() = default; +#else +struct TORCH_API ExpandBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ExpandBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct PermuteBackward0_copy : public TraceableFunction { + TORCH_API PermuteBackward0_copy() = default; +#else +struct TORCH_API PermuteBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "PermuteBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dims; + +}; +#ifdef _WIN32 +struct ReshapeAliasBackward0_copy : public TraceableFunction { + TORCH_API ReshapeAliasBackward0_copy() = default; +#else +struct TORCH_API ReshapeAliasBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ReshapeAliasBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SelectBackward0_copy : public TraceableFunction { + TORCH_API SelectBackward0_copy() = default; +#else +struct TORCH_API SelectBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SelectBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + c10::SymInt index; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SelectBackwardAutogradNestedTensor0_copy : public TraceableFunction { + TORCH_API SelectBackwardAutogradNestedTensor0_copy() = default; +#else +struct TORCH_API SelectBackwardAutogradNestedTensor0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SelectBackwardAutogradNestedTensor0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + c10::SymInt index; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct SliceBackward0_copy : public TraceableFunction { + TORCH_API SliceBackward0_copy() = default; +#else +struct TORCH_API SliceBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SliceBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + ::std::optional end; + std::vector self_sym_sizes; + ::std::optional start; + c10::SymInt step; + +}; +#ifdef _WIN32 +struct SplitBackward0_copy : public TraceableFunction { + TORCH_API SplitBackward0_copy() = default; +#else +struct TORCH_API SplitBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SplitBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::TensorOptions self_options; + std::vector self_sym_sizes; + c10::SymInt split_size; + +}; +#ifdef _WIN32 +struct SplitWithSizesBackward0_copy : public TraceableFunction { + TORCH_API SplitWithSizesBackward0_copy() = default; +#else +struct TORCH_API SplitWithSizesBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SplitWithSizesBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + at::TensorOptions self_options; + std::vector self_sym_sizes; + std::vector split_sizes; + +}; +#ifdef _WIN32 +struct SplitWithSizesBackwardAutogradNestedTensor0_copy : public TraceableFunction { + TORCH_API SplitWithSizesBackwardAutogradNestedTensor0_copy() = default; +#else +struct TORCH_API SplitWithSizesBackwardAutogradNestedTensor0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SplitWithSizesBackwardAutogradNestedTensor0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + at::TensorOptions self_options; + std::vector split_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackward0_copy : public TraceableFunction { + TORCH_API SqueezeBackward0_copy() = default; +#else +struct TORCH_API SqueezeBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackward1_copy : public TraceableFunction { + TORCH_API SqueezeBackward1_copy() = default; +#else +struct TORCH_API SqueezeBackward1_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward1_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackwardAutogradNestedTensor0_copy : public TraceableFunction { + TORCH_API SqueezeBackwardAutogradNestedTensor0_copy() = default; +#else +struct TORCH_API SqueezeBackwardAutogradNestedTensor0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackwardAutogradNestedTensor0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + +}; +#ifdef _WIN32 +struct SqueezeBackward2_copy : public TraceableFunction { + TORCH_API SqueezeBackward2_copy() = default; +#else +struct TORCH_API SqueezeBackward2_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackward2_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct SqueezeBackwardAutogradNestedTensor1_copy : public TraceableFunction { + TORCH_API SqueezeBackwardAutogradNestedTensor1_copy() = default; +#else +struct TORCH_API SqueezeBackwardAutogradNestedTensor1_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "SqueezeBackwardAutogradNestedTensor1_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector dim; + int64_t self_dim = 0; + +}; +#ifdef _WIN32 +struct TBackward0_copy : public TraceableFunction { + TORCH_API TBackward0_copy() = default; +#else +struct TORCH_API TBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct TransposeBackward0_copy : public TraceableFunction { + TORCH_API TransposeBackward0_copy() = default; +#else +struct TORCH_API TransposeBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TransposeBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim0 = 0; + int64_t dim1 = 0; + +}; +#ifdef _WIN32 +struct UnfoldBackward0_copy : public TraceableFunction { + TORCH_API UnfoldBackward0_copy() = default; +#else +struct TORCH_API UnfoldBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnfoldBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dimension = 0; + std::vector self_sym_sizes; + int64_t size = 0; + int64_t step = 0; + +}; +#ifdef _WIN32 +struct LiftFreshBackward0_copy : public TraceableFunction { + TORCH_API LiftFreshBackward0_copy() = default; +#else +struct TORCH_API LiftFreshBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "LiftFreshBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct UnsqueezeBackward0_copy : public TraceableFunction { + TORCH_API UnsqueezeBackward0_copy() = default; +#else +struct TORCH_API UnsqueezeBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnsqueezeBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + +}; +#ifdef _WIN32 +struct ViewBackward0_copy : public TraceableFunction { + TORCH_API ViewBackward0_copy() = default; +#else +struct TORCH_API ViewBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ViewBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_sym_sizes; + +}; +#ifdef _WIN32 +struct ViewBackwardAutogradNestedTensor0_copy : public TraceableFunction { + TORCH_API ViewBackwardAutogradNestedTensor0_copy() = default; +#else +struct TORCH_API ViewBackwardAutogradNestedTensor0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ViewBackwardAutogradNestedTensor0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ViewAsRealBackward0_copy : public TraceableFunction { + TORCH_API ViewAsRealBackward0_copy() = default; +#else +struct TORCH_API ViewAsRealBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ViewAsRealBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ViewAsComplexBackward0_copy : public TraceableFunction { + TORCH_API ViewAsComplexBackward0_copy() = default; +#else +struct TORCH_API ViewAsComplexBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ViewAsComplexBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct ValuesBackward0_copy : public TraceableFunction { + TORCH_API ValuesBackward0_copy() = default; +#else +struct TORCH_API ValuesBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ValuesBackward0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ValuesBackwardAutogradNestedTensor0_copy : public TraceableFunction { + TORCH_API ValuesBackwardAutogradNestedTensor0_copy() = default; +#else +struct TORCH_API ValuesBackwardAutogradNestedTensor0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ValuesBackwardAutogradNestedTensor0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct NestedViewFromBufferBackward0_copy : public TraceableFunction { + TORCH_API NestedViewFromBufferBackward0_copy() = default; +#else +struct TORCH_API NestedViewFromBufferBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedViewFromBufferBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NestedViewFromJaggedBackward0_copy : public TraceableFunction { + TORCH_API NestedViewFromJaggedBackward0_copy() = default; +#else +struct TORCH_API NestedViewFromJaggedBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedViewFromJaggedBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + +}; +#ifdef _WIN32 +struct NestedGetValuesBackward0_copy : public TraceableFunction { + TORCH_API NestedGetValuesBackward0_copy() = default; +#else +struct TORCH_API NestedGetValuesBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "NestedGetValuesBackward0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct UnbindBackward0_copy : public TraceableFunction { + TORCH_API UnbindBackward0_copy() = default; +#else +struct TORCH_API UnbindBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnbindBackward0_copy"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + +}; +#ifdef _WIN32 +struct UnbindBackwardAutogradNestedTensor0_copy : public TraceableFunction { + TORCH_API UnbindBackwardAutogradNestedTensor0_copy() = default; +#else +struct TORCH_API UnbindBackwardAutogradNestedTensor0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "UnbindBackwardAutogradNestedTensor0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + int64_t dim = 0; + SavedVariable self_; + at::Layout self_layout; + at::TensorOptions self_options; + +}; +#ifdef _WIN32 +struct TestAutogradMultipleDispatchViewBackward0_copy : public TraceableFunction { + TORCH_API TestAutogradMultipleDispatchViewBackward0_copy() = default; +#else +struct TORCH_API TestAutogradMultipleDispatchViewBackward0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestAutogradMultipleDispatchViewBackward0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct TestAutogradMultipleDispatchViewBackwardAutogradCUDA0_copy : public TraceableFunction { + TORCH_API TestAutogradMultipleDispatchViewBackwardAutogradCUDA0_copy() = default; +#else +struct TORCH_API TestAutogradMultipleDispatchViewBackwardAutogradCUDA0_copy : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "TestAutogradMultipleDispatchViewBackwardAutogradCUDA0_copy"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.reset_data(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable self_; + +}; +#ifdef _WIN32 +struct ForeachAbsBackward0 : public TraceableFunction { + TORCH_API ForeachAbsBackward0() = default; +#else +struct TORCH_API ForeachAbsBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAbsBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachAcosBackward0 : public TraceableFunction { + TORCH_API ForeachAcosBackward0() = default; +#else +struct TORCH_API ForeachAcosBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAcosBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachAddBackward1Scalar : public TraceableFunction { + TORCH_API ForeachAddBackward1Scalar() = default; +#else +struct TORCH_API ForeachAddBackward1Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAddBackward1Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachAddBackward0List : public TraceableFunction { + TORCH_API ForeachAddBackward0List() = default; +#else +struct TORCH_API ForeachAddBackward0List : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAddBackward0List"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.clear(); + other_released_ = true; + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + std::vector other_; + bool other_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; + size_t other_size_; +}; +#ifdef _WIN32 +struct ForeachAddBackward1ScalarList : public TraceableFunction { + TORCH_API ForeachAddBackward1ScalarList() = default; +#else +struct TORCH_API ForeachAddBackward1ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAddBackward1ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachAddBackward0Tensor : public TraceableFunction { + TORCH_API ForeachAddBackward0Tensor() = default; +#else +struct TORCH_API ForeachAddBackward0Tensor : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAddBackward0Tensor"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + SavedVariable other_; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachAddcdivBackward0Scalar : public TraceableFunction { + TORCH_API ForeachAddcdivBackward0Scalar() = default; +#else +struct TORCH_API ForeachAddcdivBackward0Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAddcdivBackward0Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + tensor1_.clear(); + tensor1_released_ = true; + tensor2_.clear(); + tensor2_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + std::vector tensor1_; + bool tensor1_released_ = false; + std::vector tensor2_; + bool tensor2_released_ = false; + at::Scalar value; + size_t self_size_; + size_t tensor1_size_; + size_t tensor2_size_; +}; +#ifdef _WIN32 +struct ForeachAddcdivBackward0ScalarList : public TraceableFunction { + TORCH_API ForeachAddcdivBackward0ScalarList() = default; +#else +struct TORCH_API ForeachAddcdivBackward0ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAddcdivBackward0ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scalars.clear(); + self_.clear(); + self_released_ = true; + tensor1_.clear(); + tensor1_released_ = true; + tensor2_.clear(); + tensor2_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector scalars; + bool scalars_released_ = false; + std::vector self_; + bool self_released_ = false; + std::vector tensor1_; + bool tensor1_released_ = false; + std::vector tensor2_; + bool tensor2_released_ = false; + size_t self_size_; + size_t tensor1_size_; + size_t tensor2_size_; +}; +#ifdef _WIN32 +struct ForeachAddcmulBackward0Scalar : public TraceableFunction { + TORCH_API ForeachAddcmulBackward0Scalar() = default; +#else +struct TORCH_API ForeachAddcmulBackward0Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAddcmulBackward0Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + tensor1_.clear(); + tensor1_released_ = true; + tensor2_.clear(); + tensor2_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + std::vector tensor1_; + bool tensor1_released_ = false; + std::vector tensor2_; + bool tensor2_released_ = false; + at::Scalar value; + size_t self_size_; + size_t tensor1_size_; + size_t tensor2_size_; +}; +#ifdef _WIN32 +struct ForeachAddcmulBackward0ScalarList : public TraceableFunction { + TORCH_API ForeachAddcmulBackward0ScalarList() = default; +#else +struct TORCH_API ForeachAddcmulBackward0ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAddcmulBackward0ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scalars.clear(); + self_.clear(); + self_released_ = true; + tensor1_.clear(); + tensor1_released_ = true; + tensor2_.clear(); + tensor2_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector scalars; + bool scalars_released_ = false; + std::vector self_; + bool self_released_ = false; + std::vector tensor1_; + bool tensor1_released_ = false; + std::vector tensor2_; + bool tensor2_released_ = false; + size_t self_size_; + size_t tensor1_size_; + size_t tensor2_size_; +}; +#ifdef _WIN32 +struct ForeachAsinBackward0 : public TraceableFunction { + TORCH_API ForeachAsinBackward0() = default; +#else +struct TORCH_API ForeachAsinBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAsinBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachAtanBackward0 : public TraceableFunction { + TORCH_API ForeachAtanBackward0() = default; +#else +struct TORCH_API ForeachAtanBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachAtanBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachCeilBackward0 : public TraceableFunction { + TORCH_API ForeachCeilBackward0() = default; +#else +struct TORCH_API ForeachCeilBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachCeilBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachClampMaxBackward0Scalar : public TraceableFunction { + TORCH_API ForeachClampMaxBackward0Scalar() = default; +#else +struct TORCH_API ForeachClampMaxBackward0Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachClampMaxBackward0Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar scalar; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachClampMaxBackward1List : public TraceableFunction { + TORCH_API ForeachClampMaxBackward1List() = default; +#else +struct TORCH_API ForeachClampMaxBackward1List : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachClampMaxBackward1List"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.clear(); + other_released_ = true; + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector other_; + bool other_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; + size_t other_size_; +}; +#ifdef _WIN32 +struct ForeachClampMaxBackward0ScalarList : public TraceableFunction { + TORCH_API ForeachClampMaxBackward0ScalarList() = default; +#else +struct TORCH_API ForeachClampMaxBackward0ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachClampMaxBackward0ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scalars.clear(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector scalars; + bool scalars_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachClampMinBackward0Scalar : public TraceableFunction { + TORCH_API ForeachClampMinBackward0Scalar() = default; +#else +struct TORCH_API ForeachClampMinBackward0Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachClampMinBackward0Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar scalar; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachClampMinBackward1List : public TraceableFunction { + TORCH_API ForeachClampMinBackward1List() = default; +#else +struct TORCH_API ForeachClampMinBackward1List : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachClampMinBackward1List"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.clear(); + other_released_ = true; + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector other_; + bool other_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; + size_t other_size_; +}; +#ifdef _WIN32 +struct ForeachClampMinBackward0ScalarList : public TraceableFunction { + TORCH_API ForeachClampMinBackward0ScalarList() = default; +#else +struct TORCH_API ForeachClampMinBackward0ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachClampMinBackward0ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scalars.clear(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector scalars; + bool scalars_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachCosBackward0 : public TraceableFunction { + TORCH_API ForeachCosBackward0() = default; +#else +struct TORCH_API ForeachCosBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachCosBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachCoshBackward0 : public TraceableFunction { + TORCH_API ForeachCoshBackward0() = default; +#else +struct TORCH_API ForeachCoshBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachCoshBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachDivBackward1Scalar : public TraceableFunction { + TORCH_API ForeachDivBackward1Scalar() = default; +#else +struct TORCH_API ForeachDivBackward1Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachDivBackward1Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar scalar; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachDivBackward1ScalarList : public TraceableFunction { + TORCH_API ForeachDivBackward1ScalarList() = default; +#else +struct TORCH_API ForeachDivBackward1ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachDivBackward1ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scalars.clear(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector scalars; + bool scalars_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachDivBackward0Tensor : public TraceableFunction { + TORCH_API ForeachDivBackward0Tensor() = default; +#else +struct TORCH_API ForeachDivBackward0Tensor : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachDivBackward0Tensor"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachErfBackward0 : public TraceableFunction { + TORCH_API ForeachErfBackward0() = default; +#else +struct TORCH_API ForeachErfBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachErfBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachErfcBackward0 : public TraceableFunction { + TORCH_API ForeachErfcBackward0() = default; +#else +struct TORCH_API ForeachErfcBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachErfcBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachExpBackward0 : public TraceableFunction { + TORCH_API ForeachExpBackward0() = default; +#else +struct TORCH_API ForeachExpBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachExpBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachExpm1Backward0 : public TraceableFunction { + TORCH_API ForeachExpm1Backward0() = default; +#else +struct TORCH_API ForeachExpm1Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachExpm1Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachFloorBackward0 : public TraceableFunction { + TORCH_API ForeachFloorBackward0() = default; +#else +struct TORCH_API ForeachFloorBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachFloorBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachFracBackward0 : public TraceableFunction { + TORCH_API ForeachFracBackward0() = default; +#else +struct TORCH_API ForeachFracBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachFracBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachLerpBackward1List : public TraceableFunction { + TORCH_API ForeachLerpBackward1List() = default; +#else +struct TORCH_API ForeachLerpBackward1List : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachLerpBackward1List"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + tensors1_.clear(); + tensors1_released_ = true; + weights_.clear(); + weights_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + std::vector tensors1_; + bool tensors1_released_ = false; + std::vector weights_; + bool weights_released_ = false; + size_t self_size_; + size_t tensors1_size_; + size_t weights_size_; +}; +#ifdef _WIN32 +struct ForeachLerpBackward0Scalar : public TraceableFunction { + TORCH_API ForeachLerpBackward0Scalar() = default; +#else +struct TORCH_API ForeachLerpBackward0Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachLerpBackward0Scalar"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar weight; + size_t self_size_; + size_t tensors1_size_; +}; +#ifdef _WIN32 +struct ForeachLerpBackward0ScalarList : public TraceableFunction { + TORCH_API ForeachLerpBackward0ScalarList() = default; +#else +struct TORCH_API ForeachLerpBackward0ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachLerpBackward0ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + weight.clear(); + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector weight; + bool weight_released_ = false; + size_t self_size_; + size_t tensors1_size_; +}; +#ifdef _WIN32 +struct ForeachLgammaBackward0 : public TraceableFunction { + TORCH_API ForeachLgammaBackward0() = default; +#else +struct TORCH_API ForeachLgammaBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachLgammaBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachLogBackward0 : public TraceableFunction { + TORCH_API ForeachLogBackward0() = default; +#else +struct TORCH_API ForeachLogBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachLogBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachLog10Backward0 : public TraceableFunction { + TORCH_API ForeachLog10Backward0() = default; +#else +struct TORCH_API ForeachLog10Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachLog10Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachLog1PBackward0 : public TraceableFunction { + TORCH_API ForeachLog1PBackward0() = default; +#else +struct TORCH_API ForeachLog1PBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachLog1PBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachLog2Backward0 : public TraceableFunction { + TORCH_API ForeachLog2Backward0() = default; +#else +struct TORCH_API ForeachLog2Backward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachLog2Backward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachMaxBackward1 : public TraceableFunction { + TORCH_API ForeachMaxBackward1() = default; +#else +struct TORCH_API ForeachMaxBackward1 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMaxBackward1"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachMaximumBackward0List : public TraceableFunction { + TORCH_API ForeachMaximumBackward0List() = default; +#else +struct TORCH_API ForeachMaximumBackward0List : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMaximumBackward0List"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.clear(); + other_released_ = true; + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector other_; + bool other_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; + size_t other_size_; +}; +#ifdef _WIN32 +struct ForeachMinimumBackward0List : public TraceableFunction { + TORCH_API ForeachMinimumBackward0List() = default; +#else +struct TORCH_API ForeachMinimumBackward0List : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMinimumBackward0List"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.clear(); + other_released_ = true; + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector other_; + bool other_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; + size_t other_size_; +}; +#ifdef _WIN32 +struct ForeachMulBackward1Scalar : public TraceableFunction { + TORCH_API ForeachMulBackward1Scalar() = default; +#else +struct TORCH_API ForeachMulBackward1Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMulBackward1Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar scalar; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachMulBackward0List : public TraceableFunction { + TORCH_API ForeachMulBackward0List() = default; +#else +struct TORCH_API ForeachMulBackward0List : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMulBackward0List"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.clear(); + other_released_ = true; + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector other_; + bool other_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; + size_t other_size_; +}; +#ifdef _WIN32 +struct ForeachMulBackward1ScalarList : public TraceableFunction { + TORCH_API ForeachMulBackward1ScalarList() = default; +#else +struct TORCH_API ForeachMulBackward1ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMulBackward1ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + scalars.clear(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector scalars; + bool scalars_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachMulBackward0Tensor : public TraceableFunction { + TORCH_API ForeachMulBackward0Tensor() = default; +#else +struct TORCH_API ForeachMulBackward0Tensor : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachMulBackward0Tensor"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.reset_data(); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + SavedVariable other_; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachNegBackward0 : public TraceableFunction { + TORCH_API ForeachNegBackward0() = default; +#else +struct TORCH_API ForeachNegBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachNegBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachPowBackward0Scalar : public TraceableFunction { + TORCH_API ForeachPowBackward0Scalar() = default; +#else +struct TORCH_API ForeachPowBackward0Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachPowBackward0Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar exponent; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachReciprocalBackward0 : public TraceableFunction { + TORCH_API ForeachReciprocalBackward0() = default; +#else +struct TORCH_API ForeachReciprocalBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachReciprocalBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachRoundBackward0 : public TraceableFunction { + TORCH_API ForeachRoundBackward0() = default; +#else +struct TORCH_API ForeachRoundBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachRoundBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachRsqrtBackward0 : public TraceableFunction { + TORCH_API ForeachRsqrtBackward0() = default; +#else +struct TORCH_API ForeachRsqrtBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachRsqrtBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachSigmoidBackward0 : public TraceableFunction { + TORCH_API ForeachSigmoidBackward0() = default; +#else +struct TORCH_API ForeachSigmoidBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachSigmoidBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachSignBackward0 : public TraceableFunction { + TORCH_API ForeachSignBackward0() = default; +#else +struct TORCH_API ForeachSignBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachSignBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachSinBackward0 : public TraceableFunction { + TORCH_API ForeachSinBackward0() = default; +#else +struct TORCH_API ForeachSinBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachSinBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachSinhBackward0 : public TraceableFunction { + TORCH_API ForeachSinhBackward0() = default; +#else +struct TORCH_API ForeachSinhBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachSinhBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachSqrtBackward0 : public TraceableFunction { + TORCH_API ForeachSqrtBackward0() = default; +#else +struct TORCH_API ForeachSqrtBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachSqrtBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachSubBackward1Scalar : public TraceableFunction { + TORCH_API ForeachSubBackward1Scalar() = default; +#else +struct TORCH_API ForeachSubBackward1Scalar : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachSubBackward1Scalar"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachSubBackward0List : public TraceableFunction { + TORCH_API ForeachSubBackward0List() = default; +#else +struct TORCH_API ForeachSubBackward0List : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachSubBackward0List"; } + void release_variables() override { + std::lock_guard lock(mutex_); + other_.clear(); + other_released_ = true; + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + at::Scalar alpha; + std::vector other_; + bool other_released_ = false; + std::vector self_; + bool self_released_ = false; + size_t self_size_; + size_t other_size_; +}; +#ifdef _WIN32 +struct ForeachSubBackward1ScalarList : public TraceableFunction { + TORCH_API ForeachSubBackward1ScalarList() = default; +#else +struct TORCH_API ForeachSubBackward1ScalarList : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachSubBackward1ScalarList"; } + void release_variables() override { + std::lock_guard lock(mutex_); + self_.clear(); + self_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector self_; + bool self_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachTanBackward0 : public TraceableFunction { + TORCH_API ForeachTanBackward0() = default; +#else +struct TORCH_API ForeachTanBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachTanBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachTanhBackward0 : public TraceableFunction { + TORCH_API ForeachTanhBackward0() = default; +#else +struct TORCH_API ForeachTanhBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachTanhBackward0"; } + void release_variables() override { + std::lock_guard lock(mutex_); + result_.clear(); + result_released_ = true; + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + std::vector result_; + bool result_released_ = false; + size_t self_size_; +}; +#ifdef _WIN32 +struct ForeachTruncBackward0 : public TraceableFunction { + TORCH_API ForeachTruncBackward0() = default; +#else +struct TORCH_API ForeachTruncBackward0 : public TraceableFunction { +#endif + using TraceableFunction::TraceableFunction; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "ForeachTruncBackward0"; } + void release_variables() override { + + + } + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + + size_t self_size_; +}; + +}}} // namespace torch::autograd::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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h new file mode 100644 index 0000000000000000000000000000000000000000..a45a50e0d56cf428749161878437844bba2ea0cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h @@ -0,0 +1,60 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// @generated from ../tools/autograd/templates/VariableType.h + +#include +#include + +#include + +#include +#include + +#include // for size_t +#include // for function +#include // for unique_ptr +#include +#include + +namespace at { + struct Quantizer; +} + +namespace torch { namespace autograd { + +using Variable = at::Tensor; +using at::Context; +using at::Device; +using at::Dimname; +using at::DimnameList; +using at::Generator; +using at::IntArrayRef; +using at::MemoryFormat; +using at::QScheme; +using at::Scalar; +using at::ScalarType; +using at::Storage; +using at::Tensor; +using at::TensorList; +using at::TensorOptions; +using at::Quantizer; +using std::optional; + +namespace VariableType { + TORCH_API std::vector allCUDATypes(); + TORCH_API std::vector allXPUTypes(); + TORCH_API std::vector allCPUTypes(); + TORCH_API std::vector allPrivateUser1Types(); + + at::Tensor & unpack(Tensor & t, const char * name, int pos); + const at::Tensor & unpack(const Tensor & t, const char * name, int pos); + at::Tensor unpack_opt(const Tensor & t, const char * name, int pos); + std::vector unpack(const at::ITensorListRef& tl, const char *name, int pos); +} + +}} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h new file mode 100644 index 0000000000000000000000000000000000000000..5a1ea210425a19969792213e7f74d988adcc60e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h @@ -0,0 +1,960 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// @generated from ../tools/autograd/templates/ViewFuncs.h + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#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 +#include +#endif + +namespace torch::autograd::generated { + +using at::Scalar; +using at::Tensor; +using at::IntArrayRef; +using at::ArrayRef; +using at::Type; +using at::ScalarType; +using std::optional; +using c10::fmap; + +#define _CONJ_VIEW_FUNC_AVAILABLE +struct _ConjViewFunc : public torch::autograd::ViewFunc { + _ConjViewFunc() + {} + virtual ~_ConjViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define _INDICES_VIEW_FUNC_AVAILABLE +struct _IndicesViewFunc : public torch::autograd::ViewFunc { + _IndicesViewFunc() + {} + virtual ~_IndicesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define _NEG_VIEW_VIEW_FUNC_AVAILABLE +struct _NegViewViewFunc : public torch::autograd::ViewFunc { + _NegViewViewFunc() + {} + virtual ~_NegViewViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define _NESTED_GET_VALUES_VIEW_FUNC_AVAILABLE +struct _NestedGetValuesViewFunc : public torch::autograd::ViewFunc { + _NestedGetValuesViewFunc() + {} + virtual ~_NestedGetValuesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define _NESTED_VIEW_FROM_BUFFER_VIEW_FUNC_AVAILABLE +struct _NestedViewFromBufferViewFunc : public torch::autograd::ViewFunc { + _NestedViewFromBufferViewFunc(const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets) : nested_size(nested_size), nested_strides(nested_strides), offsets(offsets) + {} + virtual ~_NestedViewFromBufferViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + at::Tensor nested_size; + at::Tensor nested_strides; + at::Tensor offsets; +}; + +#define _NESTED_VIEW_FROM_JAGGED_VIEW_FUNC_AVAILABLE +struct _NestedViewFromJaggedViewFunc : public torch::autograd::ViewFunc { + _NestedViewFromJaggedViewFunc(const at::Tensor & offsets, const at::Tensor & dummy, const ::std::optional & lengths, int64_t ragged_idx, const ::std::optional & min_seqlen, const ::std::optional & max_seqlen) : offsets(offsets), dummy(dummy), lengths(lengths), ragged_idx(ragged_idx), min_seqlen(min_seqlen), max_seqlen(max_seqlen) + {} + virtual ~_NestedViewFromJaggedViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + at::Tensor offsets; + at::Tensor dummy; + ::std::optional lengths; + int64_t ragged_idx; + ::std::optional min_seqlen; + ::std::optional max_seqlen; +}; + +#define _RESHAPE_ALIAS_VIEW_FUNC_AVAILABLE +struct _ReshapeAliasViewFunc : public torch::autograd::ViewFunc { + _ReshapeAliasViewFunc(c10::SymIntArrayRef size, c10::SymIntArrayRef stride) : size(size.vec()), stride(stride.vec()) + {} + virtual ~_ReshapeAliasViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + ::std::vector size; + ::std::vector stride; +}; + +#define _TEST_AUTOGRAD_MULTIPLE_DISPATCH_VIEW_VIEW_FUNC_AVAILABLE +struct _TestAutogradMultipleDispatchViewViewFunc : public torch::autograd::ViewFunc { + _TestAutogradMultipleDispatchViewViewFunc() + {} + virtual ~_TestAutogradMultipleDispatchViewViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define _VALUES_VIEW_FUNC_AVAILABLE +struct _ValuesViewFunc : public torch::autograd::ViewFunc { + _ValuesViewFunc() + {} + virtual ~_ValuesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define ALIAS_VIEW_FUNC_AVAILABLE +struct AliasViewFunc : public torch::autograd::ViewFunc { + AliasViewFunc() + {} + virtual ~AliasViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define AS_STRIDED_VIEW_FUNC_AVAILABLE +struct AsStridedViewFunc : public torch::autograd::ViewFunc { + AsStridedViewFunc(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset) : size(size.vec()), stride(stride.vec()), storage_offset(storage_offset) + {} + virtual ~AsStridedViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + ::std::vector size; + ::std::vector stride; + ::std::optional storage_offset; +}; + +#define CCOL_INDICES_VIEW_FUNC_AVAILABLE +struct CcolIndicesViewFunc : public torch::autograd::ViewFunc { + CcolIndicesViewFunc() + {} + virtual ~CcolIndicesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define CHUNK_VIEW_FUNC_AVAILABLE +struct ChunkViewFunc : public torch::autograd::ViewFunc { + ChunkViewFunc(int64_t chunks, int64_t dim, int64_t view_idx) : chunks(chunks), dim(dim), view_idx(view_idx) + {} + virtual ~ChunkViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t chunks; + int64_t dim; + int64_t view_idx; +}; + +#define COL_INDICES_VIEW_FUNC_AVAILABLE +struct ColIndicesViewFunc : public torch::autograd::ViewFunc { + ColIndicesViewFunc() + {} + virtual ~ColIndicesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define CROW_INDICES_VIEW_FUNC_AVAILABLE +struct CrowIndicesViewFunc : public torch::autograd::ViewFunc { + CrowIndicesViewFunc() + {} + virtual ~CrowIndicesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define DIAGONAL_VIEW_FUNC_AVAILABLE +struct DiagonalViewFunc : public torch::autograd::ViewFunc { + DiagonalViewFunc(int64_t offset, int64_t dim1, int64_t dim2) : offset(offset), dim1(dim1), dim2(dim2) + {} + virtual ~DiagonalViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t offset; + int64_t dim1; + int64_t dim2; +}; + +#define EXPAND_VIEW_FUNC_AVAILABLE +struct ExpandViewFunc : public torch::autograd::ViewFunc { + ExpandViewFunc(c10::SymIntArrayRef size, bool implicit) : size(size.vec()), implicit(implicit) + {} + virtual ~ExpandViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + ::std::vector size; + bool implicit; +}; + +#define INDICES_VIEW_FUNC_AVAILABLE +struct IndicesViewFunc : public torch::autograd::ViewFunc { + IndicesViewFunc() + {} + virtual ~IndicesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define NARROW_VIEW_FUNC_AVAILABLE +struct NarrowViewFunc : public torch::autograd::ViewFunc { + NarrowViewFunc(int64_t dim, c10::SymInt start, c10::SymInt length) : dim(dim), start(start), length(length) + {} + virtual ~NarrowViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t dim; + c10::SymInt start; + c10::SymInt length; +}; + +#define PERMUTE_VIEW_FUNC_AVAILABLE +struct PermuteViewFunc : public torch::autograd::ViewFunc { + PermuteViewFunc(at::IntArrayRef dims) : dims(dims.vec()) + {} + virtual ~PermuteViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + ::std::vector dims; +}; + +#define ROW_INDICES_VIEW_FUNC_AVAILABLE +struct RowIndicesViewFunc : public torch::autograd::ViewFunc { + RowIndicesViewFunc() + {} + virtual ~RowIndicesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define SELECT_INT_VIEW_FUNC_AVAILABLE +struct SelectIntViewFunc : public torch::autograd::ViewFunc { + SelectIntViewFunc(int64_t dim, c10::SymInt index) : dim(dim), index(index) + {} + virtual ~SelectIntViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t dim; + c10::SymInt index; +}; + +#define SLICE_TENSOR_VIEW_FUNC_AVAILABLE +struct SliceTensorViewFunc : public torch::autograd::ViewFunc { + SliceTensorViewFunc(int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step) : dim(dim), start(start), end(end), step(step) + {} + virtual ~SliceTensorViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t dim; + ::std::optional start; + ::std::optional end; + c10::SymInt step; +}; + +#define SLICE_INVERSE_VIEW_FUNC_AVAILABLE +struct SliceInverseViewFunc : public torch::autograd::ViewFunc { + SliceInverseViewFunc(const at::Tensor & src, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step) : src(src), dim(dim), start(start), end(end), step(step) + {} + virtual ~SliceInverseViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + at::Tensor src; + int64_t dim; + ::std::optional start; + ::std::optional end; + c10::SymInt step; +}; + +#define SPLIT_TENSOR_VIEW_FUNC_AVAILABLE +struct SplitTensorViewFunc : public torch::autograd::ViewFunc { + SplitTensorViewFunc(c10::SymInt split_size, int64_t dim, int64_t view_idx) : split_size(split_size), dim(dim), view_idx(view_idx) + {} + virtual ~SplitTensorViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + c10::SymInt split_size; + int64_t dim; + int64_t view_idx; +}; + +#define SPLIT_WITH_SIZES_VIEW_FUNC_AVAILABLE +struct SplitWithSizesViewFunc : public torch::autograd::ViewFunc { + SplitWithSizesViewFunc(c10::SymIntArrayRef split_sizes, int64_t dim, int64_t view_idx) : split_sizes(split_sizes.vec()), dim(dim), view_idx(view_idx) + {} + virtual ~SplitWithSizesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + ::std::vector split_sizes; + int64_t dim; + int64_t view_idx; +}; + +#define SQUEEZE_VIEW_FUNC_AVAILABLE +struct SqueezeViewFunc : public torch::autograd::ViewFunc { + SqueezeViewFunc() + {} + virtual ~SqueezeViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define SQUEEZE_DIM_VIEW_FUNC_AVAILABLE +struct SqueezeDimViewFunc : public torch::autograd::ViewFunc { + SqueezeDimViewFunc(int64_t dim) : dim(dim) + {} + virtual ~SqueezeDimViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t dim; +}; + +#define SQUEEZE_DIMS_VIEW_FUNC_AVAILABLE +struct SqueezeDimsViewFunc : public torch::autograd::ViewFunc { + SqueezeDimsViewFunc(at::IntArrayRef dim) : dim(dim.vec()) + {} + virtual ~SqueezeDimsViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + ::std::vector dim; +}; + +#define T_VIEW_FUNC_AVAILABLE +struct TViewFunc : public torch::autograd::ViewFunc { + TViewFunc() + {} + virtual ~TViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define TRANSPOSE_INT_VIEW_FUNC_AVAILABLE +struct TransposeIntViewFunc : public torch::autograd::ViewFunc { + TransposeIntViewFunc(int64_t dim0, int64_t dim1) : dim0(dim0), dim1(dim1) + {} + virtual ~TransposeIntViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t dim0; + int64_t dim1; +}; + +#define UNBIND_INT_VIEW_FUNC_AVAILABLE +struct UnbindIntViewFunc : public torch::autograd::ViewFunc { + UnbindIntViewFunc(int64_t dim, int64_t view_idx) : dim(dim), view_idx(view_idx) + {} + virtual ~UnbindIntViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t dim; + int64_t view_idx; +}; + +#define UNFOLD_VIEW_FUNC_AVAILABLE +struct UnfoldViewFunc : public torch::autograd::ViewFunc { + UnfoldViewFunc(int64_t dimension, int64_t size, int64_t step) : dimension(dimension), size(size), step(step) + {} + virtual ~UnfoldViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t dimension; + int64_t size; + int64_t step; +}; + +#define UNSQUEEZE_VIEW_FUNC_AVAILABLE +struct UnsqueezeViewFunc : public torch::autograd::ViewFunc { + UnsqueezeViewFunc(int64_t dim) : dim(dim) + {} + virtual ~UnsqueezeViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + int64_t dim; +}; + +#define VALUES_VIEW_FUNC_AVAILABLE +struct ValuesViewFunc : public torch::autograd::ViewFunc { + ValuesViewFunc() + {} + virtual ~ValuesViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define VIEW_VIEW_FUNC_AVAILABLE +struct ViewViewFunc : public torch::autograd::ViewFunc { + ViewViewFunc(c10::SymIntArrayRef size) : size(size.vec()) + {} + virtual ~ViewViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + ::std::vector size; +}; + +#define VIEW_DTYPE_VIEW_FUNC_AVAILABLE +struct ViewDtypeViewFunc : public torch::autograd::ViewFunc { + ViewDtypeViewFunc(at::ScalarType dtype) : dtype(dtype) + {} + virtual ~ViewDtypeViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + at::ScalarType dtype; +}; + +#define VIEW_AS_COMPLEX_VIEW_FUNC_AVAILABLE +struct ViewAsComplexViewFunc : public torch::autograd::ViewFunc { + ViewAsComplexViewFunc() + {} + virtual ~ViewAsComplexViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +#define VIEW_AS_REAL_VIEW_FUNC_AVAILABLE +struct ViewAsRealViewFunc : public torch::autograd::ViewFunc { + ViewAsRealViewFunc() + {} + virtual ~ViewAsRealViewFunc() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + +}; + +} // namespace torch::autograd::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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..b5920c11ab730d0c4d2c973044983b7b630322b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// @generated from ../tools/autograd/templates/python_functions.h + +// Python bindings for automatically generated autograd functions + +namespace torch { namespace autograd { namespace generated { + +void initialize_autogenerated_functions_0(PyObject* module); +void initialize_autogenerated_functions_1(PyObject* module); +void initialize_autogenerated_functions_2(PyObject* module); +void initialize_autogenerated_functions_3(PyObject* module); +void initialize_autogenerated_functions_4(PyObject* module); + +inline void initialize_autogenerated_functions(PyObject* module) { + initialize_autogenerated_functions_0(module); + initialize_autogenerated_functions_1(module); + initialize_autogenerated_functions_2(module); + initialize_autogenerated_functions_3(module); + initialize_autogenerated_functions_4(module); +} + +}}} // namespace torch::autograd::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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h new file mode 100644 index 0000000000000000000000000000000000000000..e792fa8b41c689be5cf136ec7c763d488503f605 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch { +namespace autograd { +namespace generated { + +PyTypeObject* get__fake_quantize_per_tensor_affine_cachemask_tensor_qparams_structseq(); +PyTypeObject* get__fused_moving_avg_obs_fq_helper_structseq(); +PyTypeObject* get__linalg_det_structseq(); +PyTypeObject* get__linalg_det_out_structseq(); +PyTypeObject* get__linalg_eigh_structseq(); +PyTypeObject* get__linalg_eigh_out_structseq(); +PyTypeObject* get__linalg_slogdet_structseq(); +PyTypeObject* get__linalg_slogdet_out_structseq(); +PyTypeObject* get__linalg_solve_ex_structseq(); +PyTypeObject* get__linalg_solve_ex_out_structseq(); +PyTypeObject* get__linalg_svd_structseq(); +PyTypeObject* get__linalg_svd_out_structseq(); +PyTypeObject* get__lu_with_info_structseq(); +PyTypeObject* get__scaled_dot_product_cudnn_attention_structseq(); +PyTypeObject* get__scaled_dot_product_efficient_attention_structseq(); +PyTypeObject* get__scaled_dot_product_flash_attention_structseq(); +PyTypeObject* get__scaled_dot_product_flash_attention_for_cpu_structseq(); +PyTypeObject* get__unpack_dual_structseq(); +PyTypeObject* get_aminmax_structseq(); +PyTypeObject* get_aminmax_out_structseq(); +PyTypeObject* get_cummax_structseq(); +PyTypeObject* get_cummax_out_structseq(); +PyTypeObject* get_cummin_structseq(); +PyTypeObject* get_cummin_out_structseq(); +PyTypeObject* get_frexp_structseq(); +PyTypeObject* get_frexp_out_structseq(); +PyTypeObject* get_geqrf_out_structseq(); +PyTypeObject* get_geqrf_structseq(); +PyTypeObject* get_histogram_out_structseq(); +PyTypeObject* get_histogram_structseq(); +PyTypeObject* get_histogramdd_structseq(); +PyTypeObject* get_kthvalue_structseq(); +PyTypeObject* get_kthvalue_out_structseq(); +PyTypeObject* get_linalg_cholesky_ex_structseq(); +PyTypeObject* get_linalg_cholesky_ex_out_structseq(); +PyTypeObject* get_linalg_eig_structseq(); +PyTypeObject* get_linalg_eig_out_structseq(); +PyTypeObject* get_linalg_eigh_structseq(); +PyTypeObject* get_linalg_eigh_out_structseq(); +PyTypeObject* get_linalg_inv_ex_structseq(); +PyTypeObject* get_linalg_inv_ex_out_structseq(); +PyTypeObject* get_linalg_ldl_factor_structseq(); +PyTypeObject* get_linalg_ldl_factor_out_structseq(); +PyTypeObject* get_linalg_ldl_factor_ex_structseq(); +PyTypeObject* get_linalg_ldl_factor_ex_out_structseq(); +PyTypeObject* get_linalg_lstsq_structseq(); +PyTypeObject* get_linalg_lstsq_out_structseq(); +PyTypeObject* get_linalg_lu_structseq(); +PyTypeObject* get_linalg_lu_out_structseq(); +PyTypeObject* get_linalg_lu_factor_structseq(); +PyTypeObject* get_linalg_lu_factor_out_structseq(); +PyTypeObject* get_linalg_lu_factor_ex_structseq(); +PyTypeObject* get_linalg_lu_factor_ex_out_structseq(); +PyTypeObject* get_linalg_qr_structseq(); +PyTypeObject* get_linalg_qr_out_structseq(); +PyTypeObject* get_linalg_slogdet_structseq(); +PyTypeObject* get_linalg_slogdet_out_structseq(); +PyTypeObject* get_linalg_solve_ex_structseq(); +PyTypeObject* get_linalg_solve_ex_out_structseq(); +PyTypeObject* get_linalg_svd_structseq(); +PyTypeObject* get_linalg_svd_out_structseq(); +PyTypeObject* get_lu_unpack_structseq(); +PyTypeObject* get_lu_unpack_out_structseq(); +PyTypeObject* get_max_structseq(); +PyTypeObject* get_max_out_structseq(); +PyTypeObject* get_median_structseq(); +PyTypeObject* get_median_out_structseq(); +PyTypeObject* get_min_structseq(); +PyTypeObject* get_min_out_structseq(); +PyTypeObject* get_mode_structseq(); +PyTypeObject* get_mode_out_structseq(); +PyTypeObject* get_nanmedian_structseq(); +PyTypeObject* get_nanmedian_out_structseq(); +PyTypeObject* get_qr_out_structseq(); +PyTypeObject* get_qr_structseq(); +PyTypeObject* get_slogdet_structseq(); +PyTypeObject* get_slogdet_out_structseq(); +PyTypeObject* get_sort_out_structseq(); +PyTypeObject* get_sort_structseq(); +PyTypeObject* get_svd_out_structseq(); +PyTypeObject* get_svd_structseq(); +PyTypeObject* get_topk_out_structseq(); +PyTypeObject* get_topk_structseq(); +PyTypeObject* get_triangular_solve_out_structseq(); +PyTypeObject* get_triangular_solve_structseq(); + +} + +void initReturnTypes(PyObject* module); + +} // namespace autograd +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h new file mode 100644 index 0000000000000000000000000000000000000000..e864ed9e8113fce9111381069a6e494e83ed3c29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h @@ -0,0 +1,784 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// @generated from ../tools/autograd/templates/variable_factories.h + +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#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 +#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 +#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 +#endif + +#include +#include +#include + +namespace torch { + +/// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types +/// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to +/// support it in the future by iterating over all sub-lists to find +/// the largest data type that can represent all of the elements, or by using +/// variadic templates. +/// +/// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` / +/// (nested) braced-init-list of floating-point types always produces a tensor of dtype +/// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior. +/// +/// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` / +/// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong` +/// (aka. int64_t), matching Python `torch.tensor` behavior. +/// +/// NOTE: The following dtypes are not supported by `torch::tensor` currently: +/// - `unsigned int` +/// - `unsigned long int` +/// - `unsigned long long int` +/// - `long long int` +inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) { + return autograd::make_variable( + // note: we remove the requires_grad setting from the TensorOptions because + // it is ignored anyways (and we actually have an assertion that it isn't set + // which would fail otherwise). We handle requires_grad explicitly here + // instead of passing it through to the kernel. + tensor_data_container.convert_to_tensor(options.requires_grad(::std::nullopt)), + options.requires_grad()); +} + +/// A generic deleter function. +using Deleter = std::function; +using at::MemoryFormat; + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor, `strides` the +/// stride in each dimension. The `deleter` function (a +/// `std::function`) will be called on the `data` when the Tensor +/// data would normally be deallocated. The `TensorOptions` specify additional +/// configuration options for the returned tensor, such as what type to +/// interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + at::IntArrayRef strides, + const Deleter& deleter, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, strides, deleter, options.requires_grad(::std::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor, `strides` the +/// stride in each dimension. The `TensorOptions` +/// specify additional configuration options for the returned tensor, such as +/// what type to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + at::IntArrayRef strides, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, strides, options.requires_grad(::std::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor. The `deleter` +/// (a `std::function`) function will be called on the `data` when +/// the Tensor data would normally be deallocated. The `TensorOptions` specify +/// additional configuration options for the returned tensor, such as what type +/// to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + const Deleter& deleter, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, deleter, options.requires_grad(::std::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor. The +/// `TensorOptions` specify additional configuration options for the returned +/// tensor, such as what type to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, options.requires_grad(::std::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +inline at::Tensor _make_dep_token(at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_make_dep_token(at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _cudnn_init_dropout_state(double dropout, bool train, int64_t dropout_seed, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_cudnn_init_dropout_state(dropout, train, dropout_seed, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor arange(const at::Scalar & end, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::arange(end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::arange(start, end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::arange(start, end, step, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor bartlett_window(int64_t window_length, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::bartlett_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor bartlett_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::bartlett_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor blackman_window(int64_t window_length, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::blackman_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor blackman_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::blackman_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty(size, names, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty(at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty(size, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty_permuted(at::IntArrayRef size, at::IntArrayRef physical_layout, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty_permuted(size, physical_layout, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty_permuted_symint(c10::SymIntArrayRef size, at::IntArrayRef physical_layout, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty_permuted_symint(size, physical_layout, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _empty_affine_quantized(at::IntArrayRef size, at::TensorOptions options = {}, double scale = 1, int64_t zero_point = 0, ::std::optional memory_format = c10::MemoryFormat::Contiguous) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_empty_affine_quantized(size, at::TensorOptions(options).requires_grad(::std::nullopt), scale, zero_point, memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _empty_affine_quantized_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}, double scale = 1, int64_t zero_point = 0, ::std::optional memory_format = c10::MemoryFormat::Contiguous) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_empty_affine_quantized_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt), scale, zero_point, memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _empty_per_channel_affine_quantized(at::IntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::TensorOptions options = {}, ::std::optional memory_format = c10::MemoryFormat::Contiguous) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_empty_per_channel_affine_quantized(size, scales, zero_points, axis, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _empty_per_channel_affine_quantized_symint(c10::SymIntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::TensorOptions options = {}, ::std::optional memory_format = c10::MemoryFormat::Contiguous) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_empty_per_channel_affine_quantized_symint(size, scales, zero_points, axis, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty_quantized(at::IntArrayRef size, const at::Tensor & qtensor, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty_quantized(size, qtensor, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty_strided(size, stride, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::empty_strided_symint(size, stride, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor eye(int64_t n, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::eye(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor eye_symint(c10::SymInt n, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::eye_symint(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor eye(int64_t n, int64_t m, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::eye(n, m, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor eye_symint(c10::SymInt n, c10::SymInt m, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::eye_symint(n, m, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::full(size, fill_value, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::full(size, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::full_symint(size, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor full_like(const at::Tensor & self, const at::Scalar & fill_value, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::full_like(self, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor from_file(c10::string_view filename, ::std::optional shared = ::std::nullopt, ::std::optional size = 0, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::from_file(filename, shared, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor hann_window(int64_t window_length, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::hann_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor hann_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::hann_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor hamming_window(int64_t window_length, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::hamming_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor hamming_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::hamming_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::hamming_window(window_length, periodic, alpha, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, double beta, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::hamming_window(window_length, periodic, alpha, beta, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor kaiser_window(int64_t window_length, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::kaiser_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor kaiser_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::kaiser_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor kaiser_window(int64_t window_length, bool periodic, double beta, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::kaiser_window(window_length, periodic, beta, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor linspace(const at::Scalar & start, const at::Scalar & end, int64_t steps, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor linspace(const at::Tensor & start, const at::Tensor & end, int64_t steps, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor linspace(const at::Tensor & start, const at::Scalar & end, int64_t steps, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor linspace(const at::Scalar & start, const at::Tensor & end, int64_t steps, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor logspace(const at::Scalar & start, const at::Scalar & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor logspace(const at::Tensor & start, const at::Tensor & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor logspace(const at::Tensor & start, const at::Scalar & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor logspace(const at::Scalar & start, const at::Tensor & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor ones(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::ones(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor ones(at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::ones(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor ones_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::ones_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor ones_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::ones_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor scalar_tensor(const at::Scalar & s, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::scalar_tensor(s, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand_symint(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand(at::IntArrayRef size, ::std::optional generator, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional generator, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand_symint(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand(at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand(at::IntArrayRef size, ::std::optional generator, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional generator, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand_symint(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor rand_like(const at::Tensor & self, ::std::optional generator, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::rand_like(self, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint(int64_t high, at::IntArrayRef size, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint(high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_symint(c10::SymInt high, c10::SymIntArrayRef size, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_symint(high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint(int64_t high, at::IntArrayRef size, ::std::optional generator, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint(high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_symint(c10::SymInt high, c10::SymIntArrayRef size, ::std::optional generator, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_symint(high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint(int64_t low, int64_t high, at::IntArrayRef size, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint(low, high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_symint(c10::SymInt low, c10::SymInt high, c10::SymIntArrayRef size, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_symint(low, high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint(int64_t low, int64_t high, at::IntArrayRef size, ::std::optional generator, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint(low, high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_symint(c10::SymInt low, c10::SymInt high, c10::SymIntArrayRef size, ::std::optional generator, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_symint(low, high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like(const at::Tensor & self, int64_t high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like(self, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like_symint(self, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like(const at::Tensor & self, int64_t high, ::std::optional generator, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like(self, high, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt high, ::std::optional generator, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like_symint(self, high, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like(const at::Tensor & self, const at::Tensor & high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like(self, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like(const at::Tensor & self, const at::Tensor & high, ::std::optional generator, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like(self, high, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like(self, low, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt low, c10::SymInt high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like_symint(self, low, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, ::std::optional generator, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like(self, low, high, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt low, c10::SymInt high, ::std::optional generator, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randint_like_symint(self, low, high, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn(at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn(at::IntArrayRef size, ::std::optional generator, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional generator, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn_symint(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn_symint(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn(at::IntArrayRef size, ::std::optional generator, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional generator, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn_symint(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randn_like(const at::Tensor & self, ::std::optional generator, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randn_like(self, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randperm(int64_t n, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randperm(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randperm_symint(c10::SymInt n, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randperm_symint(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randperm(int64_t n, ::std::optional generator, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randperm(n, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor randperm_symint(c10::SymInt n, ::std::optional generator, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::randperm_symint(n, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step = 1, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::range(start, end, step, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::range(start, end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor zeros(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::zeros(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _efficientzerotensor(at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_efficientzerotensor(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _efficientzerotensor_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_efficientzerotensor_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor zeros(at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::zeros(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor zeros_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::zeros_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor zeros_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::zeros_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_compressed_tensor_with_dims(int64_t nnz, int64_t dense_dim, at::IntArrayRef size, at::IntArrayRef blocksize, at::ScalarType index_dtype, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_compressed_tensor_with_dims(nnz, dense_dim, size, blocksize, index_dtype, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_compressed_tensor(compressed_indices, plain_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_compressed_tensor_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_compressed_tensor_symint(compressed_indices, plain_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_csr_tensor(crow_indices, col_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_csc_tensor(ccol_indices, row_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_bsr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_bsr_tensor(crow_indices, col_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_bsc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_bsc_tensor(ccol_indices, row_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_compressed_tensor(compressed_indices, plain_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_csr_tensor(crow_indices, col_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_csc_tensor(ccol_indices, row_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_bsr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_bsr_tensor(crow_indices, col_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_bsc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_bsc_tensor(ccol_indices, row_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_compressed_tensor_unsafe(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_compressed_tensor_unsafe(compressed_indices, plain_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_compressed_tensor_unsafe_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_compressed_tensor_unsafe_symint(compressed_indices, plain_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_csr_tensor_unsafe(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_csr_tensor_unsafe(crow_indices, col_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_csc_tensor_unsafe(ccol_indices, row_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_bsr_tensor_unsafe(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_bsr_tensor_unsafe(crow_indices, col_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_bsc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_bsc_tensor_unsafe(ccol_indices, row_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_coo_tensor(at::IntArrayRef size, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_coo_tensor(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options = {}, ::std::optional is_coalesced = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_coo_tensor(indices, values, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional is_coalesced = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::sparse_coo_tensor(indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_coo_tensor_unsafe(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional is_coalesced = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_coo_tensor_unsafe(indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_coo_tensor_unsafe_symint(const at::Tensor & indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options = {}, ::std::optional is_coalesced = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_coo_tensor_unsafe_symint(indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_coo_tensor_with_dims(int64_t sparse_dim, int64_t dense_dim, at::IntArrayRef size, at::TensorOptions options) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_coo_tensor_with_dims(sparse_dim, dense_dim, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_coo_tensor_with_dims_and_tensors(int64_t sparse_dim, int64_t dense_dim, at::IntArrayRef size, const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options, ::std::optional is_coalesced = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_coo_tensor_with_dims_and_tensors(sparse_dim, dense_dim, size, indices, values, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _sparse_coo_tensor_with_dims_and_tensors_symint(int64_t sparse_dim, int64_t dense_dim, c10::SymIntArrayRef size, const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options, ::std::optional is_coalesced = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_sparse_coo_tensor_with_dims_and_tensors_symint(sparse_dim, dense_dim, size, indices, values, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor _to_copy(const at::Tensor & self, at::TensorOptions options = {}, bool non_blocking = false, ::std::optional memory_format = ::std::nullopt) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::_to_copy(self, at::TensorOptions(options).requires_grad(::std::nullopt), non_blocking, memory_format), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor tril_indices(int64_t row, int64_t col, int64_t offset = 0, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::tril_indices(row, col, offset, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset = 0, at::TensorOptions options = at::kLong) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::triu_indices(row, col, offset, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor normal(double mean, double std, at::IntArrayRef size, ::std::optional generator = ::std::nullopt, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::normal(mean, std, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor normal_symint(double mean, double std, c10::SymIntArrayRef size, ::std::optional generator = ::std::nullopt, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::normal_symint(mean, std, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor fft_fftfreq(int64_t n, double d = 1.0, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::fft_fftfreq(n, d, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} +inline at::Tensor fft_rfftfreq(int64_t n, double d = 1.0, at::TensorOptions options = {}) { + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::fft_rfftfreq(n, d, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad()); +} + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_variable_indexing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_variable_indexing.h new file mode 100644 index 0000000000000000000000000000000000000000..009d370359b333baf67352a4a1f51ae79bc4a7fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_variable_indexing.h @@ -0,0 +1,104 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::autograd { + +struct UnpackedSlice { + c10::SymInt start; + c10::SymInt stop; + c10::SymInt step; +}; + +// This mirrors Cpython's PySlice_Unpack method +inline UnpackedSlice __PySlice_Unpack(PyObject* _r) { + PySliceObject* r = (PySliceObject*)_r; + /* this is harder to get right than you might think */ + + c10::SymInt start_sym, stop_sym, step_sym; + + auto clip_val = [](Py_ssize_t val) { + if (val < c10::SymInt::min_representable_int()) { + auto r = PyErr_WarnEx( + PyExc_UserWarning, + "Truncating the start/stop/step " + "of slice. This is likely because of " + "saved old models when the start/stop/step were larger.", + 1); + if (r != 0) { + throw python_error(); + } + return (Py_ssize_t)(c10::SymInt::min_representable_int()); + } + return val; + }; + + if (r->step == Py_None) { + step_sym = c10::SymInt(1); + } else { + if (torch::is_symint(r->step)) { + step_sym = py::handle(r->step).cast(); + } else { + Py_ssize_t step = 0; + if (!_PyEval_SliceIndex(r->step, &step)) { + throw python_error(); + } + if (step == 0) { + PyErr_SetString(PyExc_ValueError, "slice step cannot be zero"); + } + + step = clip_val(step); + step_sym = c10::SymInt(step); + } + } + + if (torch::is_symint(r->start)) { + start_sym = py::handle(r->start).cast(); + } else if (r->start == Py_None) { + start_sym = c10::SymInt(step_sym < 0 ? PY_SSIZE_T_MAX : 0); + } else { + Py_ssize_t start = 0; + if (!_PyEval_SliceIndex(r->start, &start)) { + throw python_error(); + } + start = clip_val(start); + start_sym = c10::SymInt(start); + } + + if (torch::is_symint(r->stop)) { + stop_sym = py::handle(r->stop).cast(); + } else if (r->stop == Py_None) { + stop_sym = c10::SymInt( + step_sym < 0 ? c10::SymInt::min_representable_int() : PY_SSIZE_T_MAX); + } else { + Py_ssize_t stop = 0; + if (!_PyEval_SliceIndex(r->stop, &stop)) { + throw python_error(); + } + stop = clip_val(stop); + stop_sym = c10::SymInt(stop); + } + + return UnpackedSlice{ + std::move(start_sym), std::move(stop_sym), std::move(step_sym)}; +} + +Py_ssize_t THPVariable_length(PyObject* self); +PyObject* THPVariable_getitem(PyObject* self, PyObject* index); +int THPVariable_setitem(PyObject* self, PyObject* index, PyObject* value); + +Variable valueToTensor( + c10::TensorOptions options, + PyObject* value, + const at::Device& device); + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/record_function_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/record_function_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ed8fe935e88debc050b6a669348870569d65b6bd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/record_function_ops.h @@ -0,0 +1,32 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::autograd::profiler { + +struct PythonRecordFunction : public torch::CustomClassHolder { + at::RecordFunction record; + + explicit PythonRecordFunction( + at::RecordScope scope = at::RecordScope::FUNCTION) + : record(scope) {} +}; + +// Creates a new profiling scope using RecordFunction and invokes its starting +// callbacks. +TORCH_API c10::intrusive_ptr record_function_enter_new( + const std::string& name, + const std::optional& args = std::nullopt); + +// Schedules RecordFunction's end callbacks to be run on completion of a future. +TORCH_API c10::intrusive_ptr _call_end_callbacks_on_fut_new( + const c10::intrusive_ptr& record, + const c10::intrusive_ptr& fut); + +} // namespace torch::autograd::profiler + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/saved_variable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/saved_variable.h new file mode 100644 index 0000000000000000000000000000000000000000..c9625cd6fa3dfa8df77b696355afb9e533da6b35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/saved_variable.h @@ -0,0 +1,145 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +#include +#include + +namespace torch::autograd { + +using Variable = at::Tensor; +struct Node; + +TORCH_API extern const char* ERR_BACKWARD_TWICE; + +/// A snapshot of a variable at a certain version. A `SavedVariable` stores +/// enough information to reconstruct a variable from a certain point in time. +class TORCH_API SavedVariable { + public: + SavedVariable() = default; + SavedVariable( + const Variable& variable, + bool is_output, + bool is_inplace_on_view = false); + SavedVariable( + const std::optional& variable, + bool is_output, + bool is_inplace_on_view = false); + SavedVariable(const SavedVariable&) = delete; + SavedVariable(SavedVariable&&) = default; + SavedVariable& operator=(const SavedVariable&) = delete; + SavedVariable& operator=(SavedVariable&&) = default; + ~SavedVariable() { + if (fw_grad_) { + // See note [ Using ForwardGrad ] + fw_grad_->clear(); + } + } + + /// Reconstructs the saved variable. Pass `saved_for` as the gradient + /// function if constructing the `SavedVariable` with it would have caused a + /// circular reference. + Variable unpack(std::shared_ptr saved_for = nullptr) const; + + void register_hooks(std::unique_ptr&& hooks); + + void reset_data(); + + bool has_hooks() const { + return (bool)hooks_; + } + + std::optional get_raw_data() const { + if (hooks_) { + return std::nullopt; + } else { + return data_; + } + } + + // Used by compiled autograd + std::optional> + retrieve_unpack_hook_data() const { + if (!hooks_) { + return std::nullopt; + } + return hooks_->retrieve_unpack_hook_data(); + } + + private: + // This field contains either: + // 1. the variable to save + // 2. or its tensor_data. + // If storing the variable itself would create a circular reference, + // we fall into the second case and its metadata is also saved separately. + // In that case, the grad_fn must be passed in to the unpack function when + // reconstructing the Variable (except when we are doing an inplace operation + // on a view, see below). The field saved_original_ below reflects the two + // cases: its value is true in the first case and false in the second case. + // The value data_.defined() can be false in three cases: + // 1. SavedVariable was constructed without a Tensor (the value to save is + // None), in that case was_default_constructed_ will be kept at true + // 2. The saved variable has been released by calling + // SavedVariable::reset_data(), typically during the backward pass + // 3. Hooks have been registered. In that case, hooks_ will be defined + // instead. Note that the value of saved_original_ only reflects what happened + // during the construction of the SavedVariable. If saved_original_ is true, + // we saved the original tensor in data_, but if the user registers hooks, we + // will no longer have it (despite the saved_original_ still being true) + at::Tensor data_; + + // This field is used to store the forward AD gradients associated with + // the saved Tensor. Note that this shared_ptr must never be shared with + // either the saved Tensor or the unpacked Tensor. See note [ Using + // ForwardGrad ] + std::shared_ptr fw_grad_; + + // Weak version of grad_fn_ that prevents leaks in rebase_history() for + // inplace views. + // This variable is used when the user chooses to create a SavedVariable with + // is_inplace_on_view = true. + // In that case, the grad_fn passed in to the unpack function at unwrapping + // time is unused. + std::weak_ptr weak_grad_fn_; + + uint32_t saved_version_ = 0; + uint32_t output_nr_ = 0; + bool was_default_constructed_ = true; + bool is_inplace_on_view_ = false; + bool saved_original_ = false; + bool is_leaf_ = false; + bool is_output_ = false; + + // Hooks are a pair of functions pack_hook/unpack_hook that provides + // fine-grained control over how the SavedVariable should save its data. + // pack_hook is called upon registration, while unpack_hook is called when + // unpacking. + std::unique_ptr hooks_; + // Fields grad_fn_, grad_accumulator_, and requires_grad_ are only used if + // hooks are defined. They are set before pack_hook is called and used after + // unpack_hook is called. + std::shared_ptr grad_fn_; + // For the usual case where leaf tensors are the input, we expect its + // grad_acc to be kept alive by the graph. The reason SavedVariable holds + // a owning reference is to support the case where a custom autograd Function + // saves an intermediate. + std::shared_ptr grad_accumulator_; + bool requires_grad_ = false; + + void save_metadata(const Variable& data); + static std::unique_ptr get_default_hooks(); + void set_hooks_and_pack_data( + std::unique_ptr&& hooks, + const Variable& data); +}; +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/saved_variable_hooks.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/saved_variable_hooks.h new file mode 100644 index 0000000000000000000000000000000000000000..d3dc67a98424322937b35e1855d487796c3b88bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/saved_variable_hooks.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::autograd { + +struct TORCH_API SavedVariableHooks { + virtual void call_pack_hook(const at::Tensor& tensor) = 0; + virtual at::Tensor call_unpack_hook() = 0; + virtual ~SavedVariableHooks() = default; + virtual std::optional> + retrieve_unpack_hook_data() const { + TORCH_CHECK( + false, "Compiled Autograd only supports python saved tensor hooks "); + } +}; + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/symbolic.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/symbolic.h new file mode 100644 index 0000000000000000000000000000000000000000..62e235e5f4ef304d86cbe6155b3c228bd8d7d1c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/symbolic.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::autograd { + +struct SymbolicContext { + jit::Block* block; +}; + +struct symbolic_unconvertible : public std::runtime_error { + using std::runtime_error::runtime_error; +}; + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/error_messages.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/error_messages.h new file mode 100644 index 0000000000000000000000000000000000000000..2c29419199a26e9b0c8813b6b4d051c189834831 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/error_messages.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::autograd::utils { + +inline std::string requires_grad_leaf_error(bool requires_grad) { + std::ostringstream oss; + oss << "you can only change requires_grad flags of leaf variables."; + if (requires_grad == false) { + oss << " If you want to use a computed variable in a subgraph " + "that doesn't require differentiation use " + "var_no_grad = var.detach()."; + } + return oss.str(); +} + +} // namespace torch::autograd::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/grad_layout_contract.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/grad_layout_contract.h new file mode 100644 index 0000000000000000000000000000000000000000..e36bb5e295af87a72742c455be169cd188654f4e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/grad_layout_contract.h @@ -0,0 +1,83 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::autograd::utils { + +// Helper functions to enforce the "Gradient Layout Contract" described in +// torch/csrc/autograd/functions/accumulate_grad.h. + +// Checks if grad obeys the contract with variable. +inline bool obeys_layout_contract( + const at::Tensor& grad, + const at::Tensor& variable) { + TORCH_INTERNAL_ASSERT(!grad.is_sparse()); + TORCH_INTERNAL_ASSERT(!grad.is_sparse_csr()); + TORCH_INTERNAL_ASSERT(!variable.is_sparse_csr()); + + // NOLINTNEXTLINE(bugprone-branch-clone) + if (variable.is_nested()) { + // TODO: Nested Tensor does not have an implementation of detach. The + // current implementation of nested tensor likely does obey the gradient + // contract and should return true, but this would likely change in the + // future + return false; + } else if (variable.is_sparse()) { + // Gradient Layout Contract is not applicable for sparse layouts + return false; + } else if (variable.is_non_overlapping_and_dense()) { + // Only look at stride for dimensions that are not of size 1. + const auto& grad_sizes = grad.sym_sizes(); + const auto& grad_strides = grad.sym_strides(); + const auto& variable_strides = variable.sym_strides(); + for (const auto idx : c10::irange(grad_sizes.size())) { + if (grad_sizes[idx] != 1) { + if (grad_strides[idx] != variable_strides[idx]) { + return false; + } + } else { + // This should not be needed but we don't check if a Tensor has views + // before stashing it. And 0-strided Tensors of size 1 are actually + // views for ops like cat. + // TODO: Actually detect views in the accumulateGrad function so that + // this Tensor is not considered at all. + if (grad_strides[idx] == 0) { + return false; + } + } + } + return true; + } else { + return grad.is_contiguous(at::MemoryFormat::Contiguous); + } +} + +// Creates a clone of new_grad that obeys the contract with variable. +// The clone should attach to new_grad's history if GradMode::is_enabled(). +inline at::Tensor clone_obey_contract( + const at::Tensor& new_grad, + const at::Tensor& variable) { + if (variable.is_non_overlapping_and_dense()) { + // (1) + // Does this dicey-looking sequence attach the result to new_grad's + // history if GradMode::is_enabled()? Yes, and @alband says it should. + return std::move(new_grad + .new_empty_strided_symint( + variable.sym_sizes(), + variable.sym_strides(), + variable.options() + .memory_format(std::nullopt) + .dtype(new_grad.dtype())) + .copy_(new_grad)); + } else { + // (2) + return new_grad.clone(at::MemoryFormat::Contiguous); + } +} + +} // namespace torch::autograd::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/lambda_post_hook.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/lambda_post_hook.h new file mode 100644 index 0000000000000000000000000000000000000000..a1d615a45b0be276ac8baff0ca53daae270de14d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/lambda_post_hook.h @@ -0,0 +1,47 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::autograd::utils { + +// Turns lambda into a torch::autograd::FunctionPostHook. +class LambdaPostHook : public torch::autograd::FunctionPostHook { + using variable_list = std::vector; + using fn_type = + std::function; + using compiled_fn_type = std::function; + + public: + // The lambda function takes as arguments the outputs and inputs of the + // autograd function and can modify the outputs of the autograd function by + // returning a new output if needed. + /* implicit */ LambdaPostHook(fn_type fn) : fn_(std::move(fn)) {} + + LambdaPostHook(fn_type fn, compiled_fn_type compiled_fn) + : fn_(std::move(fn)), compiled_fn_(std::move(compiled_fn)) {} + + variable_list operator()( + const variable_list& outputs, + const variable_list& inputs) override { + return fn_(outputs, inputs); + } + + void compiled_args(CompiledNodeArgs& args) const override { + if (compiled_fn_ != nullptr) { + return compiled_fn_(args); + } + return FunctionPostHook::compiled_args(args); + } + + protected: + std::function fn_; + compiled_fn_type compiled_fn_; +}; + +} // namespace torch::autograd::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/python_arg_parsing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/python_arg_parsing.h new file mode 100644 index 0000000000000000000000000000000000000000..409bd1a2a7f0b354d4f103e0e967a52c38e5e1a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/python_arg_parsing.h @@ -0,0 +1,54 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::autograd::utils { + +// The parameter allow_copy is to accept copy for Tensor.to (and by proxy +// PackedSequences.to) but not nn.Module.to. +inline std::tuple< + std::optional, + std::optional, + bool, + bool, + std::optional> +parse_to_conversion(PythonArgs& r, bool allow_copy) { + if (r.idx == 0) { + TORCH_CHECK( + allow_copy || r.isNone(3), ".to() does not accept copy argument"); + return std::make_tuple( + r.deviceOptional(0), + r.scalartypeOptional(1), + r.toBool(2), + r.toBool(3), + r.memoryformatOptional(4)); + } else if (r.idx == 1) { + TORCH_CHECK( + allow_copy || r.isNone(2), ".to() does not accept copy argument"); + return std::make_tuple( + std::nullopt, + r.scalartype(0), + r.toBool(1), + r.toBool(2), + r.memoryformatOptional(3)); + } else { + auto tensor = r.tensor(0); + TORCH_CHECK( + allow_copy || r.isNone(2), ".to() does not accept copy argument"); + return std::make_tuple( + tensor.device(), + tensor.scalar_type(), + r.toBool(1), + r.toBool(2), + r.memoryformatOptional(3)); + } +} +} // namespace torch::autograd::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/warnings.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/warnings.h new file mode 100644 index 0000000000000000000000000000000000000000..53e19820f3188071ed67444f2629fb7a810662bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/warnings.h @@ -0,0 +1,29 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include + +namespace torch::autograd::utils { + +// Warning handler for multi-threaded contexts. Gather warnings from +// all threads into a single queue, then process together at the end +// in the main thread. +class DelayWarningHandler : public at::WarningHandler { + public: + ~DelayWarningHandler() override = default; + void replay_warnings(); + + private: + void process(const c10::Warning& warning) override; + + std::vector warnings_; + std::mutex mutex_; +}; + +} // namespace torch::autograd::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/wrap_outputs.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/wrap_outputs.h new file mode 100644 index 0000000000000000000000000000000000000000..f2f023b0eec7110f7848b62b64a313cefaa68a8a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/wrap_outputs.h @@ -0,0 +1,158 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// Wrap tensor operation outputs as PyObject* + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::autograd::utils { + +inline PyObject* wrap(bool value) { + if (value) { + Py_RETURN_TRUE; + } else { + Py_RETURN_FALSE; + } +} + +inline PyObject* wrap(c10::DeviceIndex value) { + return THPUtils_packDeviceIndex(value); +} + +inline PyObject* wrap(int64_t value) { + return THPUtils_packInt64(value); +} + +inline PyObject* wrap(double value) { + return PyFloat_FromDouble(value); +} + +inline PyObject* wrap(c10::complex value) { + // I could probably also use FromComplex with a reinterpret cast, + // but... eh. + return PyComplex_FromDoubles(value.real(), value.imag()); +} + +inline PyObject* wrap(void* value) { + return PyLong_FromVoidPtr(value); +} + +inline PyObject* wrap(THPDtype* dtype) { + return Py_NewRef(dtype); +} + +inline PyObject* wrap(at::ScalarType scalarType) { + return Py_NewRef(getTHPDtype(scalarType)); +} + +inline PyObject* wrap(THPLayout* layout) { + return Py_NewRef(layout); +} + +inline PyObject* wrap(at::Layout layout) { + return Py_NewRef(getTHPLayout(layout)); +} + +inline PyObject* wrap(const at::Tensor& tensor) { + return THPVariable_Wrap(tensor); +} + +inline PyObject* wrap(at::Tensor&& tensor) { + return THPVariable_Wrap(std::move(tensor)); +} + +inline PyObject* wrap(const at::Scalar& scalar) { + return wrap(scalar_to_tensor(scalar)); +} + +inline PyObject* wrap(at::QScheme qscheme) { + auto* thp_qscheme = torch::utils::getTHPQScheme(qscheme); + Py_INCREF(thp_qscheme); + return thp_qscheme; +} + +inline PyObject* wrap(at::TensorList tl) { + auto r = THPObjectPtr{PyTuple_New(static_cast(tl.size()))}; + if (!r) + throw python_error(); + for (const auto i : c10::irange(tl.size())) { + PyTuple_SET_ITEM(r.get(), i, wrap(tl[i])); + } + return r.release(); +} + +inline PyObject* wrap(at::IntArrayRef list) { + auto r = THPObjectPtr{PyTuple_New(static_cast(list.size()))}; + if (!r) + throw python_error(); + for (const auto i : c10::irange(list.size())) { + PyTuple_SET_ITEM(r.get(), i, wrap(list[i])); + } + return r.release(); +} + +inline PyObject* wrap(at::Stream stream) { + return THPStream_Wrap(stream); +} + +namespace detail { +template +void apply_with_idx_impl( + const F& f, + Tuple& t, + std::index_sequence /*indices*/) { + (void)std::initializer_list{(f(std::get(t), Is), 0)...}; +} + +// For tuple(a, b, c), calls f(a, 0), f(b, 1), f(c, 2) +template +void apply_with_idx(const F& f, std::tuple& t) { + apply_with_idx_impl(f, t, std::index_sequence_for{}); +} +} // namespace detail + +template +PyObject* wrap(std::tuple values) { + auto r = THPObjectPtr{PyTuple_New(sizeof...(Ts))}; + if (!r) + throw python_error(); + detail::apply_with_idx( + [&](auto& value, size_t idx) { + PyTuple_SET_ITEM(r.get(), idx, wrap(std::move(value))); + }, + values); + return r.release(); +} + +template +PyObject* wrap(PyTypeObject* type, std::tuple values) { + auto r = THPObjectPtr{PyStructSequence_New(type)}; + if (!r) + throw python_error(); + detail::apply_with_idx( + [&](auto& value, size_t idx) { + PyStructSequence_SET_ITEM(r.get(), idx, wrap(std::move(value))); + }, + values); + return r.release(); +} + +} // namespace torch::autograd::utils + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable.h new file mode 100644 index 0000000000000000000000000000000000000000..a2282a184d36df55656b102e2dd9cb094d96f24a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable.h @@ -0,0 +1,1016 @@ +#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 + +namespace torch::autograd { + +/// `Variable` is exactly the same as `Tensor` (i.e. we have `using Variable = +/// at::Tensor`). This means you can perform all the usual mathematical and +/// other operations you can perform on `Tensor`s also on `Variable`s. +/// +/// The only reason we are keeping the `Variable` class is backward +/// compatibility with external user's legacy C++ frontend code. Our intention +/// is to eliminate the `Variable` class in the near future. +using Variable = at::Tensor; + +} // namespace torch::autograd + +// The following are all internal APIs and should not be shown in libtorch docs. +// Therefore, we wrap the following code with `#ifndef DOXYGEN_SHOULD_SKIP_THIS +// ... #endif` + +#ifndef DOXYGEN_SHOULD_SKIP_THIS + +namespace torch::autograd { + +/// Check if this type is supported by the autograd engine. +/// If you change this, update the doc at the top of the +/// torch/autograd/__init__.py file and +/// "test_set_requires_grad_only_for_continuous_types" in test/test_autograd.py +inline bool isDifferentiableType(at::ScalarType t) { + return isFloatingType(t) || isComplexType(t); +} + +struct Node; + +///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// Variable +///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// A `Variable` augments a `Tensor` with the ability to interact in our +/// autograd machinery. Conceptually, `Variable`s travel along `Edge`s between +/// `Node`s in the autograd graph. A `Variable` can either be a leaf, like a +/// weight in a neural network, or an interior variable, when it is the result +/// of an operation between variables. Every `Variable` also stores another +/// `Variable` called its `grad` (gradient). If the variable is a leaf, its +/// gradient will be accumulated into this variable. +/// +/// Every Tensor is a Variable, but sometimes we colloquially refer to Variables +/// that don't require gradients as Tensors (since none of the autograd +/// machinery for Variables applies). Historically, Variables and Tensors +/// were separate concepts, but now they are exactly the same (i.e. we have +/// `using Variable = at::Tensor`). +/// +/// Gradient Edges +///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// Furthermore, `Variable`s have the notion of a `gradient_edge`, which is the +/// edge in the autograd graph that connects the variable to a particular input +/// of the gradient function that will be invoked with the variable during the +/// backward pass. More precisely, this gradient function can be one of two +/// things: +/// 1. A `grad_fn`, if the variable is in the interior of the graph. This is the +/// gradient of the function that produced the variable. +/// 2. A `grad_accumulator`, if the variable is a leaf, which accumulates a +/// scalar gradient value into its `grad` variable. +/// +/// Versioning +///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// Another major feature of `Variable`s are *versions*. Versions are +/// incremented when an in-place mutation of a variable occurs. Versions are +/// useful when constructing `SavedVariable`s, which take a snapshot of a +/// `Variable` at a certain version. You can retrieve a `Variable`'s version +/// through its `current_version()` method. +/// +/// Views +///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// It is possible for a `Variable` to be a *view* of another `Variable`, in +/// which case it tracks that `Variable`'s data and autograd history. Beyond +/// construction, the interface of a view is identical to that of a regular +/// `Variable`. You can determine whether `Variable` is in fact a view by +/// probing its `is_view()` method. Note that the *view* semantics are only +/// meaningful for `Variable` relations that are relevant to autograd. +/// See NOTE [ Autograd View Variables ] for more details. +///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +struct AutogradMeta; +struct DifferentiableViewMeta; + +// Private-ish functions for manipulating variables; we don't want to put them +// on Tensor proper +namespace impl { + +// WARNING: This may return a nullptr. If you require AutogradMeta to return +// a materialized structure, use materialize_autograd_meta instead. +TORCH_API AutogradMeta* get_autograd_meta(const at::TensorBase& /*self*/); + +// WARNING: This will return a nullptr if the Tensor is not a view. +TORCH_API DifferentiableViewMeta* get_view_autograd_meta( + const at::TensorBase& /*self*/); + +// Returns the current autograd meta, materializing it if it was previously +// none. This counts as a *mutating* operation, so do not call it on +// "read-only" operators; in particular, this is NOT thread safe +TORCH_API AutogradMeta* materialize_autograd_meta( + const at::TensorBase& /*self*/); + +/// Set the gradient accumulator of the `Variable`. This is only applicable to +/// leaf variables. Interior variables should call `set_gradient_edge()`. +TORCH_API void set_grad_accumulator( + const Variable& /*self*/, + std::weak_ptr grad_accumulator); + +/// Attempts to get a pointer to the gradient accumulator of the `Variable`, +/// if it still exists. If the gradient accumulator function has been +/// destroyed, returns a `nullptr`. +TORCH_API std::shared_ptr try_get_grad_accumulator( + const Variable& /*self*/); +TORCH_API std::shared_ptr try_get_grad_accumulator( + const at::TensorBase& /*self*/); + +/// Gets the gradient accumulator of the `Variable` if it has one, or else +/// create one on the fly and return it. +TORCH_API std::shared_ptr grad_accumulator(const Variable& /*self*/); + +/// Returns the "canonical" gradient edge of this `Variable`, i.e. either the +/// gradient function if this is an interior `Variable`, or the gradient +/// accumulator otherwise. If the `Variable` is interior, the returned `Edge` +/// will store the input index of the `Node` to which this variable is +/// connected in its `input_nr` field. For leaves, the `input_nr` is always +/// zero. Note that `set_gradient_edge` and `gradient_edge` are not +/// symmetric. You must use `set_gradient_edge` to set the `grad_fn` and +/// `set_grad_accumulator` to set the accumulator. +TORCH_API Edge gradient_edge(const Variable& /*self*/); + +/// Set the gradient edge -- i.e. `grad_fn` and `input_nr` -- of the +/// `Variable`. +/// NOTE: This will always set the `grad_fn`, even if this is a leaf variable, +/// and never the `grad_accumulator`. For the latter, use +/// `set_grad_accumulator`. This allows late construction of an interior +/// `Variable`. +TORCH_API void set_gradient_edge(const Variable& /*self*/, Edge edge); + +// Autograd Graph Interaction +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Update the `grad_fn` of an existing Variable. Called after in-place +/// modifications. +/// +/// For View Variables: +/// Called after in-place modifications. Modifies the grad_fn of the base +/// Variable. +TORCH_API void rebase_history(const Variable& /*self*/, Edge gradient_edge); + +/// Gets the raw gradient function pointer, whatever it currently is. +TORCH_API Node* grad_fn_unsafe(const Variable& /*self*/); + +/// Increments the version count of this `Variable`. +TORCH_API void bump_version(const Variable& /*self*/); +TORCH_API void set_version_counter( + const Variable& /*self*/, + const c10::VariableVersion& version_counter); + +/// Retrieves this `Variable`s version counter. +TORCH_API const c10::VariableVersion& version_counter(const Variable& /*self*/); + +TORCH_API void set_name(const Variable& /*self*/, const std::string& name); + +TORCH_API void add_hook( + const at::TensorBase& /*self*/, + std::unique_ptr hook); +TORCH_API std::vector>& hooks( + const Variable& /*self*/); +TORCH_API void clear_hooks(const at::TensorBase& /*self*/); + +TORCH_API void set_post_acc_grad_hooks( + const at::TensorBase& /*self*/, + std::unique_ptr dict); +TORCH_API std::unique_ptr& post_acc_grad_hooks( + const Variable& /*self*/); + +TORCH_API void create_cpp_hook( + const at::TensorBase& /*self*/, + bool is_retains_grad_hooks = false); + +inline bool is_tensor_stealable( + const at::Tensor& new_grad, + size_t num_expected_refs = 1) { + size_t use_count = new_grad.use_count(); + if (use_count <= num_expected_refs) { + return true; + } + if (use_count >= 2 && + new_grad.unsafeGetTensorImpl()->pyobj_slot()->has_unique_reference()) { + // The Python wrapper, if it exists, also has a reference to the Tensor. + num_expected_refs++; + } + return use_count <= num_expected_refs; +} + +} // namespace impl + +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// AutogradMeta +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Each `Variable` has one unique `AutogradMeta` struct, which stores autograd +/// metadata fields that are necessary for tracking the Variable's autograd +/// history. As an optimization, a Variable may store a nullptr, in lieu of a +/// default constructed AutogradMeta. + +struct TORCH_API AutogradMeta : public c10::AutogradMetaInterface { + std::string name_; + + Variable grad_; + std::shared_ptr grad_fn_; + std::weak_ptr grad_accumulator_; + + // This field is used to store all the forward AD gradients + // associated with this AutogradMeta (and the Tensor it corresponds to) + // There is a semantic 1:1 correspondence between AutogradMeta and + // ForwardGrad but: + // - This field is lazily populated. + // - This field is a shared_ptr but it must never be + // shared by multiple Tensors. See Note [ Using ForwardGrad ] + // Any transition from not_initialized to initialized + // must be protected by mutex_ + mutable std::shared_ptr fw_grad_; + + // The hooks_ field is actually reused by both python and cpp logic + // For both cases, we have a data structure, cpp_hooks_list_ (cpp) + // or dict (python) which is the canonical copy. + // Then, for both cases, we always register a single hook to + // hooks_ which wraps all the hooks in the list/dict. + // And, again in both cases, if the grad_fn exists on that tensor + // we will additionally register a single hook to the grad_fn. + // + // Note that the cpp and python use cases aren't actually aware of + // each other, so using both is not defined behavior. + std::vector> hooks_; + std::shared_ptr cpp_hooks_list_; + + // The post_acc_grad_hooks_ field stores only Python hooks + // (PyFunctionTensorPostAccGradHooks) that are called after the + // .grad field has been accumulated into. This is less complicated + // than the hooks_ field, which encapsulates a lot more. + std::unique_ptr post_acc_grad_hooks_ = nullptr; + + // Only meaningful on leaf variables (must be false otherwise) + bool requires_grad_{false}; + + // Only meaningful on non-leaf variables (must be false otherwise) + bool retains_grad_{false}; + + bool is_view_{false}; + + // The "output number" of this variable; e.g., if this variable + // was the second output of a function, then output_nr == 1. + // We use this to make sure we can setup the backwards trace + // correctly when this variable is passed to another function. + uint32_t output_nr_; + + // The dtype of the grad field; when nullopt, defaults to tensor's dtype. + std::optional grad_dtype_; + + // When true, allows gradient dtype to be different from tensor dtype, + // bypassing dtype casting and validation in the autograd engine. + bool allow_grad_dtype_mismatch_{false}; + + // Mutex to ensure that concurrent read operations that modify internal + // state are still thread-safe. Used by grad_fn(), grad_accumulator(), + // fw_grad() and set_fw_grad() + // This is mutable because we need to be able to acquire this from const + // version of this class for the functions above + mutable std::mutex mutex_; + + /// Sets the `requires_grad` property of `Variable`. This should be true for + /// leaf variables that want to accumulate gradients, and false for all other + /// variables. + void set_requires_grad(bool requires_grad, at::TensorImpl* self_impl) final { + TORCH_CHECK( + !requires_grad || + isDifferentiableType(at::typeMetaToScalarType(self_impl->dtype())), + "Only Tensors of floating point and complex dtype can require gradients"); + requires_grad_ = requires_grad; + } + + bool requires_grad() const override { + return requires_grad_ || grad_fn_; + } + + /// Accesses the gradient `Variable` of this `Variable`. + Variable& mutable_grad() override { + return grad_; + } + + const Variable& grad() const override { + return grad_; + } + + const Variable& fw_grad(uint64_t level, const at::TensorBase& self) + const override; + + void set_fw_grad( + const at::TensorBase& new_grad, + const at::TensorBase& self, + uint64_t level, + bool is_inplace_op) override; + + std::optional grad_dtype(const at::TensorBase& self) const; + + void set_grad_dtype( + const std::optional& grad_dtype, + const at::TensorBase& self); + + AutogradMeta( + at::TensorImpl* self_impl = nullptr, + bool requires_grad = false, + Edge gradient_edge = Edge()) + : grad_fn_(std::move(gradient_edge.function)), + + output_nr_(gradient_edge.input_nr) { + // set_requires_grad also checks error conditions. + if (requires_grad) { + TORCH_INTERNAL_ASSERT(self_impl); + set_requires_grad(requires_grad, self_impl); + } + TORCH_CHECK( + !grad_fn_ || !requires_grad_, + "requires_grad should be false if grad_fn is set"); + } + + ~AutogradMeta() override { + // If AutogradMeta is being destroyed, it means that there is no other + // reference to its corresponding Tensor. It implies that no other thread + // can be using this object and so there is no need to lock mutex_ here to + // guard the check if fw_grad_ is populated. + if (fw_grad_) { + // See note [ Using ForwardGrad ] + fw_grad_->clear(); + } + } +}; + +/// Base class for view functions, providing reapplication of a view on a new +/// base. Each view op should get a codegenerated subclass of this class +/// containing any state needed to reconstruct the view. The class also provides +/// convenience accessors for saved SymInts / tensor state. This is useful for +/// e.g. fake-ification, where we want to use symbolic values or fake tensors +/// instead. +struct TORCH_API ViewFunc { + virtual ~ViewFunc() = default; + /// Returns any SymInts in the saved state. + virtual std::vector get_symints() const { + return {}; + } + /// Returns the number of SymInts in the saved state. + virtual size_t num_symints() const { + return 0; + } + /// Returns any tensors in the saved state. + virtual std::vector get_tensors() const { + return {}; + } + /// Returns the number of tensors in the saved state. + virtual size_t num_tensors() const { + return 0; + } + /// Reapplies the view on the given base using the saved state. + virtual at::Tensor operator()(const at::Tensor&) const = 0; + /// Returns a clone of this ViewFunc, optionally with the specified saved + /// state. + virtual std::unique_ptr clone_and_set( + std::optional> = std::nullopt, + std::optional> = std::nullopt) const = 0; + + protected: + /// Sets the values of any SymInts in the saved state. The input vector size + /// must match the number of SymInts in the saved state (i.e. the size of the + /// list returned by get_symints()). + /// NOLINTNEXTLINE(performance-unnecessary-value-param) + virtual void set_symints(std::vector /*unused*/) {} + /// Sets the values of any Tensors in the saved state. The input vector size + /// must match the number of Tensors in the saved state (i.e. the size of the + /// list returned by get_tensors()). + /// NOLINTNEXTLINE(performance-unnecessary-value-param) + virtual void set_tensors(std::vector /*unused*/) {} +}; + +/// ViewFunc that represents a chain of two ViewFuncs. +struct ChainedViewFunc : public ViewFunc { + ChainedViewFunc( + std::unique_ptr first, + std::unique_ptr second) + : first(std::move(first)), second(std::move(second)) {} + ~ChainedViewFunc() override = default; + std::vector get_symints() const override; + size_t num_symints() const override { + return first->num_symints() + second->num_symints(); + } + std::vector get_tensors() const override; + size_t num_tensors() const override { + return first->num_tensors() + second->num_tensors(); + } + at::Tensor operator()( + const at::Tensor& /*input_base*/ /*unused*/) const override; + std::unique_ptr clone_and_set( + std::optional> /*symints*/ /*unused*/ = + std::nullopt, + std::optional> /*tensors*/ /*unused*/ = + std::nullopt) const override; + + private: + std::unique_ptr first; + std::unique_ptr second; +}; + +/// ViewFunc that errors with a specified error message when called. +struct ErroringViewFunc : public ViewFunc { + ErroringViewFunc(std::string error_msg) : error_msg(std::move(error_msg)) {} + ~ErroringViewFunc() override = default; + at::Tensor operator()(const at::Tensor& /*unused*/) const override { + TORCH_CHECK(false, error_msg); + } + std::unique_ptr clone_and_set( + std::optional> /*unused*/ = std::nullopt, + std::optional> /*unused*/ = + std::nullopt) const override { + return std::make_unique(error_msg); + } + + private: + std::string error_msg; +}; + +struct TORCH_API ViewInfo { + /// The base `Variable` + /// If this ViewInfo represents a forward (respectively backward) AD gradient, + /// then this Tensor cannot be a forward (respectively backward) view. + Variable base_; + + /// By default we use as_strided to recover views which is more efficient. + /// view_fn is only saved when as_strided is not supported. + /// If view_fn has value, we use it to recover views in backward. + std::unique_ptr view_fn_; + + /// Analogue of view_fn but in reverse: given a view -> produce the base by + /// applying the inverse view. + std::function rev_view_fn_; + + /// Accessors for the view function + bool has_view_fn() const { + // assume either BOTH or NEITHER of view_fn_ and rev_view_fn_ exist + return view_fn_ != nullptr; + } + + const ViewFunc& view_fn() const { + TORCH_CHECK( + has_view_fn(), "Can only access the view function if it exists."); + return *view_fn_; + } + + std::function rev_view_fn() const { + TORCH_CHECK( + has_view_fn(), + "Can only access the reverse view function if it exists."); + return rev_view_fn_; + } + + /// The chain function can be used to build a new ViewInfo for a + /// differentiable view function. It will return a new view info that + /// accurately represents how "tensor" is a view of this instance's "base_". + /// The "base" and "tensor" are respectively the input and output of the + /// differentiable view function that happened. They are required to properly + /// set the optional view_fn_ when it is not provided. The "view_func", if + /// provided, should be a function that allows to re-do the view between + /// "base" and "tensor". + ViewInfo chain( + const Variable& base, + const Variable& tensor, + std::unique_ptr view_func = nullptr, + std::function rev_view_func = nullptr) const; + + ViewInfo( + Variable base, + std::unique_ptr view_fn, + std::function rev_view_fn) + : base_(std::move(base)), + view_fn_(std::move(view_fn)), + rev_view_fn_(std::move(rev_view_fn)) { + TORCH_CHECK(base_.defined(), "base is undefined"); + } +}; + +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// DifferentiableViewMeta +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// NOTE [ Autograd View Variables ] +/// +/// Many operations return Variable that shares storage with an input Variable. +/// The returned Variable is called a **view** Variable on the input **base** +/// Variable. +/// +/// In PyTorch, we have two types of views: differentiable views, and +/// non-differentiable views. In either type, to support proper version +/// checking, the base and view Variables must always share the same +/// version_counter. +/// +/// +/// Differentiable Views +/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// This class allows to track both forward and backward AD differentiable +/// views. These views can have different base as non-differentiable view for +/// forward and backward mode AD are not the same. +/// +/// Most function are either both forward and backward differentiable views (for +/// example: view, select, narrow, transpose, etc) or both not forward and not +/// backward differentiable views (for example: indices, values, eq, lt, etc). +/// But there are also functions that are forward but not backward +/// differentiable views (only detach for now) or functions that are backward +/// but not forward differentiable view (only make_dual and unpack dual for +/// now). +/// +/// A concrete example of two views with different bases is as follow: +/// +/// # Have: +/// # dual is a dual Tensor that is neither a forward or backward view +/// detached_dual = dual.detach() +/// view = detached_dual.view_as(dual) +/// # The forward base of view is dual +/// # The backward base of view is detached_dual +/// +/// - Backward Mode View +/// Differentiable views are the view variables where you want gradients to flow +/// back to the base variables. Out-of-place operations on views are quite +/// straightforward, but in-place ones are very tricky. Even if the base +/// variable may not require grad when we create the view, we still need to +/// track the view relation because future in-place ops may require back-proping +/// through it. For example, we need to support +/// +/// (1) in-place operation on view, e.g., +/// +/// # Have: +/// # base.requires_grad = False +/// # var.requires_grad = True +/// base[1] = var # i.e., base[1].copy_(var) +/// torch.autograd.grad(base.sum(), var) <- should return an all ones +/// tensor +/// +/// (2) in-place operation on base after view is created, e.g., +/// +/// # Have: +/// # base.requires_grad = False +/// # var.requires_grad = True +/// view = base[1] +/// base.copy_(var) +/// torch.autograd.grad(view.sum(), var) <- should return a tensor with +/// var[1] filled with all ones and +/// zeros everywhere else +/// +/// - Forward Mode View +/// Forward differentiable views follow the same semantic as backward ones but +/// show up differently as they are computed along with the forward evaluation. +/// The hard examples above are thus very similar +/// +/// (1) in-place operation on view, e.g., +/// +/// # Have: +/// # base is a regular Tensor +/// # var is a dual Tensor whose tangent is all ones +/// base[1] = var # i.e., base[1].copy_(var) +/// # Now, base is a dual Tensor +/// _, fw_grad = fwAD.unpack_dual(base) <- fw_grad should be a tensor with +/// fw_grad[1] filled with all ones +/// and zeros everywhere else +/// +/// (2) in-place operation on base after view is created, e.g., +/// +/// # Have: +/// # base is a regular Tensor +/// # var is a dual Tensor whose tangent is all ones +/// view = base[1] +/// base.copy_(var) +/// _, fw_grad = fwAD.unpack_dual(view) <- fw_grad should be an all ones +/// tensor +/// +/// See Note [Forward Grad View/inplace] for more details on how we handle these +/// hard cases. +/// +/// +/// DifferentiableViewMeta is created to support gradient tracking of +/// such **in-place** operations. In particular, +/// + if an in-place op is done on base, the grad_fn field of the view may +/// become stale. So accesses should always go through grad_fn(), which +/// reconstructs an updated grad_fn if the version_counter has incremented. +/// All other fields are always valid. +/// + if an in-place op is done on view, in rebase_history() of view, which is +/// called after every in-place op in VariableType.cpp, the grad_fn of base +/// is updated. +/// + if a single autograd Node returns multiple differentiable views, if any +/// output is modified by an inplace operation, the autograd engine will +/// make an equivalent graph (corresponding to the view operations) without +/// using equivalent graph, where each output is treated as if it were +/// produced by a distinct view operation. This discards the original (e.g., +/// user provided) grad_fn. If the provided grad_fn does more than the +/// backward of the view, then the DifferentiableViewMeta must be created +/// with creation_meta= CreationMeta::MULTI_OUTPUT_NODE to prevent the +/// engine from ignoring the provided grad_fn. +/// +/// Interaction with GradMode: +/// The particular case that we consider here is: +/// +/// # Have: +/// # base.requires_grad = True or False +/// with torch.no_grad(): +/// view = base[1] +/// base.requires_grad_() +/// view.copy_(var) +/// torch.autograd.grad(base.sum(), var) <- what should it return? +/// +/// Given that this particular code example is ambiguous and can easily be +/// replace by either moving both inside the no_grad block or both outside, we +/// explicitly forbid it. For now, it is deprecated by a warning. This is +/// achieved by setting creation_meta=CreationMeta::NO_GRAD_MODE for all +/// differentiable views created in no_grad mode. +/// +/// See Note [View + Inplace update for base tensor] +/// and Note [View + Inplace update for view tensor] for the details how +/// autograd handles inplace update with view ops. +/// +/// Non-Differentiable Views +/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// In certain cases, although function outputs share storage with inputs, they +/// will **never** require gradient history tracking. Instead of registering the +/// view relation via DifferentiableViewMeta in autograd, the views will be +/// using usual AutogradMeta and just share the version counters with the base +/// Variables. +/// Such views include: +/// 1. Views created from .detach() +/// 2. Views that are non-differentiable by its nature. +/// E.g., `sparse_tensor.indices()` is a integral view on a (possibly) +/// floating point tensor. +/// See top of `derivatives.yaml` on how to specify that outputs of a +/// function are non-differentiable. +/// These are called non-differentiable views as the gradients do not flow +/// through the view relation. +/// +/// Relevant logic for both differentiable and non-differentiable views is +/// implemented in make_variable_(non_)differentiable_view below, and +/// wrap_output of gen_variable_type.py. + +/// NOTE [ View + Inplace detection ] +/// +/// We want to detect views followed by inplace as they are often forbidden to +/// ensure correctness of the computed gradients. But since we want to only +/// notify the user when both happen, we tag the DifferentiableViewMeta when the +/// view is created via the `make_variable_*_view()` functions. This tag is then +/// checked by the `check_inplace()` function from `VariableTypeUtils.h` that +/// should be called before every inplace operation and to detect cases where +/// other views are modified and this one is rebased by side effect, we also +/// check in the `VariableHooks::grad_fn()`. + +/// Flag that gives more information about when this view was created: +/// - IN_CUSTOM_FUNCTION should be set when the view is created inside a custom +/// autograd Function is returned. +/// - NO_GRAD_MODE should be set when a view in created when GradMode is +/// disabled +/// - MULTI_OUTPUT_NODE should be set when a Node created by codegen code +/// returns +/// multiple differentiable views +/// - Inference_MODE should be set when a view of normal tensor is created in +/// InferenceMode. +/// - DEFAULT is for all other cases +enum class CreationMeta : uint8_t { + DEFAULT, + IN_CUSTOM_FUNCTION, + MULTI_OUTPUT_NODE, + NO_GRAD_MODE, + INFERENCE_MODE +}; + +/// Handles correctly propagating CreationMeta when a new view is created from a +/// previous view. In general, we don't want the new view to be _less_ +/// restrictive than the previous view (it's okay to be _more_ restrictive). A +/// CreationMeta value of DEFAULT is currently the least restrictive, as the +/// behavior for all other CreationMeta values is to error out for in-place ops. +/// A CreationMeta value of INFERENCE_MODE is currently the most restrictive, so +/// it takes precedence in propagation. If this changes, the logic here will +/// need to be updated to properly handle the new semantics. +inline CreationMeta propagate_creation_meta( + CreationMeta prev_view_creation_meta, + CreationMeta new_view_creation_meta) { + return (new_view_creation_meta == CreationMeta::DEFAULT) + ? prev_view_creation_meta + : (prev_view_creation_meta == CreationMeta::INFERENCE_MODE + ? prev_view_creation_meta + : new_view_creation_meta); +} + +/// Unified function to handle error checking when rebase happens +/// indirect=true means that the caller is not doing the inplace, but the +/// inplace happened somewhere else. +TORCH_API void handle_view_on_rebase( + DifferentiableViewMeta* diff_view_meta, + bool indirect = false); + +struct TORCH_API DifferentiableViewMeta : public AutogradMeta { + private: + /// Information about the views + std::optional backward_info_; + std::optional forward_info_; + + // Optimization to reduce the number of ViewInfo we create. + // In the (very common) case where backward_info_ == forward_info_, we only + // populate backward_info_ (that should be used as both the forward and + // backward view information) and set shared_view_info_ = true. Invariants: + // - If shared_view_info_ is false, there is no special constraints on + // backward_info_ and forward_info_ + // - If shared_view_info_ is true, we must have: + // - backward_info_.has_value() == true + // - forward_info_.has_value() == false + bool shared_view_info_; + + /// The two following fields are extra information that we track to ensure + /// that any operation on this backward view is valid. + + /// The value of the version_counter at the time grad_fn was created. The + /// grad_fn field is stale if attr_version_ != + /// version_counter.current_version(). + uint32_t attr_version_; + CreationMeta creation_meta_; + + public: + /// requires_grad is a backward AD field so we only use the view specific + /// logic for backward differentiable views + bool requires_grad() const override { + return requires_grad_ || grad_fn_ || + (has_bw_view() && get_backward_view().base_.requires_grad()); + } + + bool shared_view_info() const { + return shared_view_info_; + } + + bool has_bw_view() const { + return backward_info_.has_value(); + } + + const ViewInfo& get_backward_view() const { + TORCH_CHECK( + has_bw_view(), "backward view info can only exist for backward views."); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return backward_info_.value(); + } + + uint32_t get_attr_version() const { + TORCH_CHECK( + has_bw_view(), "attr_version can only exist for backward views."); + return attr_version_; + } + + void set_attr_version(uint32_t new_attr_version) { + TORCH_CHECK( + has_bw_view(), "attr_version can only exist for backward views."); + attr_version_ = new_attr_version; + } + + CreationMeta get_creation_meta() const { + TORCH_CHECK( + has_bw_view(), "creation_meta can only exist for backward views."); + return creation_meta_; + } + + void set_creation_meta(CreationMeta new_creation_meta) { + TORCH_CHECK( + has_bw_view(), "creation_meta can only exist for backward views."); + creation_meta_ = new_creation_meta; + } + + bool has_fw_view() const { + return shared_view_info_ || forward_info_.has_value(); + } + + const ViewInfo& get_forward_view() const { + TORCH_CHECK( + has_fw_view(), "forward view info can only exist for forward views."); + TORCH_CHECK( + !shared_view_info_ || has_bw_view(), + "forward view info can only exist for forward views."); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return shared_view_info_ ? backward_info_.value() : forward_info_.value(); + } + + DifferentiableViewMeta( + at::TensorImpl* self_impl, + std::optional backward_info, + std::optional forward_info, + bool shared_view_info, + CreationMeta creation_meta = CreationMeta::DEFAULT); +}; + +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Variable Implementation +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +// Factory Functions +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a `Variable` that is a *view* of another (*base*) variable. +/// The `gradient_edge` is an optional (gradient_function, input_number) pair. +/// `is_differentiable` is a bool that specifies whether this view is +/// differentiable, i.e., whether the relation should be tracked by autograd. +/// See NOTE [ Autograd View Variables ] for details. + +/// NOTE: `allow_tensor_metadata_change` is set to true by default, because +/// there are a lot of call sites to these factory functions that need to change +/// the variable's size or storage afterwards, and they don't expect the +/// original tensor (where the variable is created from) to be updated. Setting +/// `allow_tensor_metadata_change_` to false by default would unnecessarily +/// prevent those changes from happening and is undesirable. + +// See NOTE [ Autograd View Variables ] for details. +// Differentiable view. Track history with DifferentiableViewMeta. +inline Variable make_variable_differentiable_view( + const at::Tensor& data, + std::optional backward_info, + std::optional forward_info, + bool shared_view_info, + CreationMeta creation_meta, + bool allow_tensor_metadata_change = true) { + if (data.defined()) { + TORCH_CHECK( + data.getIntrusivePtr()->autograd_meta() == nullptr, + "Attempted to make a tensor into a differentiable view, but the " + "tensor already had autograd metadata associated with it. If you are " + "using a __torch_dispatch__ mode, the most common cause for this " + "problem is that you used torch.overrides.enable_reentrant_dispatch() " + "improperly; tensors created within the extent of reentrant dispatch " + "MUST NOT be directly returned from __torch_dispatch__; instead, they " + "must be wrapped into fresh tensors that serve as the output. If you " + "are not using wrappers, you probably don't need reentrant dispatch. " + "If this doesn't seem applicable, please file a bug to PyTorch."); + at::TensorImpl* data_impl = data.unsafeGetTensorImpl(); + data_impl->set_allow_tensor_metadata_change(allow_tensor_metadata_change); + data_impl->set_autograd_meta(std::make_unique( + data_impl, + std::move(backward_info), + std::move(forward_info), + shared_view_info, + creation_meta)); + return data; + } + return Variable(); +} + +// See NOTE [ Autograd View Variables ] for details. +// Non-differentiable view. Just share version counter. +inline Variable make_variable_non_differentiable_view( + const Variable& base, + const at::Tensor& data, + bool allow_tensor_metadata_change = true, + bool is_fresh_tensor = false) { + if (data.defined()) { + // If we already allocated a new tensor, no need to + // shallow_copy_and_detach here. (See #163671 history; we tried to + // fan out to _indices and _values and ran into a SparseTensorImpl + // can of worms.) + if (is_fresh_tensor) { + auto* data_impl = data.unsafeGetTensorImpl(); + data_impl->set_version_counter(impl::version_counter(base)); + data_impl->set_allow_tensor_metadata_change(allow_tensor_metadata_change); + data_impl->set_autograd_meta(nullptr); + return data; + } + auto data_impl_copy = data.getIntrusivePtr()->shallow_copy_and_detach( + /*version_counter=*/impl::version_counter(base), + /*allow_tensor_metadata_change=*/allow_tensor_metadata_change); + data_impl_copy->set_autograd_meta(nullptr); + return Variable(std::move(data_impl_copy)); + } + return Variable(); +} + +/// Creates a `Variable` from the given `Tensor`, copying its underlying +/// `TensorImpl`. `requires_grad` should be set only for leaves, and determines +/// whether the `Variable` will accumulate gradients. NOTE: `data` must *not* be +/// a `Variable` already. Its dynamic type *must* be `Tensor`. +/// +/// TODO: Eliminate this function as much as possible, as it can be expressed +/// more clearly as detach() or a no-op in most call sites (especially when +/// there is only one use of the variable). +inline Variable make_variable( + at::Tensor data, + bool requires_grad = false, + bool allow_tensor_metadata_change = true) { + if (data.defined()) { + if (impl::is_tensor_stealable(data) && + data.getIntrusivePtr()->unique_version()) { + auto data_impl = data.unsafeReleaseIntrusivePtr(); + data_impl->set_allow_tensor_metadata_change(allow_tensor_metadata_change); + if (requires_grad) { + data_impl->set_autograd_meta( + std::make_unique(data_impl.get(), requires_grad)); + } else { + data_impl->set_autograd_meta(nullptr); + } + return Variable(std::move(data_impl)); + } else { + auto data_impl_copy = data.getIntrusivePtr()->shallow_copy_and_detach( + /*version_counter=*/0, + /*allow_tensor_metadata_change=*/allow_tensor_metadata_change); + if (requires_grad) { + data_impl_copy->set_autograd_meta(std::make_unique( + data_impl_copy.get(), requires_grad)); + } else { + data_impl_copy->set_autograd_meta(nullptr); + } + return Variable(std::move(data_impl_copy)); + } + } + return Variable(); +} + +/// Creates a `Variable` from the given `Tensor`, copying its underlying +/// `TensorImpl`. `gradient_edge` should be a (function, input_nr) pair +/// specifying the function in the autograd graph, and what particular input of +/// that function, this variable is connected to. +inline Variable make_variable( + const at::Tensor& data, + Edge gradient_edge, + bool allow_tensor_metadata_change = true) { + if (data.defined()) { + auto data_impl_copy = data.getIntrusivePtr()->shallow_copy_and_detach( + /*version_counter=*/0, + /*allow_tensor_metadata_change=*/allow_tensor_metadata_change); + data_impl_copy->set_autograd_meta(std::make_unique( + data_impl_copy.get(), false, std::move(gradient_edge))); + return Variable(std::move(data_impl_copy)); + } + return Variable(); +} + +struct VariableHooks final : at::impl::VariableHooksInterface { + at::TensorBase tensor_data( + const at::TensorBase& /*self*/ /*unused*/) const override; + at::TensorBase variable_data( + const at::TensorBase& /*self*/ /*unused*/) const override; + const std::shared_ptr& grad_fn( + const at::TensorBase& /*self*/ /*unused*/) const override; + unsigned _register_hook( + const at::TensorBase& /*self*/ /*unused*/, + std::function hook) const override; + void remove_hook(const at::TensorBase& /*self*/ /*unused*/, unsigned pos) + const override; + bool is_view(const at::TensorBase& /*self*/ /*unused*/) const override; + const at::TensorBase& base( + const at::TensorBase& /*self*/ /*unused*/) const override; + const std::string& name( + const at::TensorBase& /*self*/ /*unused*/) const override; + bool is_leaf(const at::TensorBase& /*self*/ /*unused*/) const override; + int64_t output_nr(const at::TensorBase& /*self*/ /*unused*/) const override; + void set_data(const at::TensorBase& self, const at::TensorBase& new_data) + const override; + at::TensorBase data(const at::TensorBase& self) const override; + int64_t _version(const at::TensorBase& self) const override; + void retain_grad(const at::TensorBase& self) const override; + bool retains_grad(const at::TensorBase& self) const override; + void _backward( + const at::Tensor& self, + at::TensorList inputs, + const std::optional& gradient, + std::optional keep_graph, + bool create_graph) const override; + void requires_grad_(const at::TensorBase& self, bool _requires_grad) + const override; + void basic_autograd_not_implemented_fallback( + const c10::OperatorHandle& op, + c10::DispatchKeySet dispatch_keys, + torch::jit::Stack* stack) const override; + std::optional grad_dtype( + const at::TensorBase& /*self*/ /*unused*/) const override; + void set_grad_dtype( + const at::TensorBase& /*self*/ /*unused*/, + const std::optional& /*grad_dtype*/ /*unused*/) + const override; +}; + +namespace utils { + +TORCH_API bool has_same_meta(const Variable& base, const Variable& other); + +} // namespace utils +} // namespace torch::autograd + +#endif /* DOXYGEN_SHOULD_SKIP_THIS */ + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable_info.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable_info.h new file mode 100644 index 0000000000000000000000000000000000000000..e21f59bd26d99ca4728e8390dfa9e2368e3d44c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable_info.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::autograd { + +struct TORCH_API VariableInfo { + explicit VariableInfo(); + explicit VariableInfo(const Variable& var, bool use_zeros_like = false); + + Variable zeros(at::OptionalDeviceGuard& device_guard) const; + + at::Layout layout = at::Layout::Strided; + at::Device device = at::kCPU; + at::ScalarType scalar_type = at::kFloat; + std::vector size; + bool requires_grad; + bool is_empty; + // needed for e.g. NJTs since they only support zeros_like() + std::optional the_var; +}; + +} // namespace torch::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cpu/Module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cpu/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..debcbb08d142cbfdf7aeddf7e4cff4bc2e67bcc9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cpu/Module.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::cpu { + +void initModule(PyObject* module); + +} // namespace torch::cpu + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..d2fc6195e20d0c9b9c3548917c8310ac6c15ba34 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h @@ -0,0 +1,175 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +#include + +namespace torch::cuda::CUDAPluggableAllocator { + +#if defined(USE_ROCM) +using streamType = c10::hip::HIPStream; +#else +using streamType = c10::cuda::CUDAStream; +#endif + +TORCH_CUDA_CPP_API std::shared_ptr< + c10::cuda::CUDACachingAllocator::CUDAAllocator> +getCurrentAllocator(); +TORCH_CUDA_CPP_API std::shared_ptr< + c10::cuda::CUDACachingAllocator::CUDAAllocator> +createCustomAllocator( + std::function alloc_fn, + std::function free_fn); +TORCH_CUDA_CPP_API void changeCurrentAllocator( + const std::shared_ptr& + allocator); + +struct _AllocationMetadata { + _AllocationMetadata(); + _AllocationMetadata( + size_t size, + c10::DeviceIndex device_idx, + cudaStream_t stream); + size_t size; + c10::DeviceIndex device_idx; + cudaStream_t stream{}; +}; + +struct TORCH_CUDA_CPP_API CUDAPluggableAllocator + : public c10::cuda::CUDACachingAllocator::CUDAAllocator { + CUDAPluggableAllocator( + std::function alloc_fn, + std::function free_fn); + + CUDAPluggableAllocator(CUDAPluggableAllocator& other); + CUDAPluggableAllocator(CUDAPluggableAllocator&& other) = delete; + CUDAPluggableAllocator& operator=(const CUDAPluggableAllocator& other) = + delete; + CUDAPluggableAllocator& operator=(CUDAPluggableAllocator&& other) = delete; + ~CUDAPluggableAllocator() override = default; + + void set_init_fn(std::function init_fn); + + void set_reset_fn(std::function reset_fn); + + void set_memory_fraction_fn( + std::function memory_fraction_fn); + + void set_base_alloc_fn(std::function base_alloc_fn); + + void set_record_stream_fn( + std::function record_stream_fn); + + void set_begin_allocate_to_pool( + std::function< + void(int, c10::cuda::MempoolId_t, std::function)> + capture_begin_fn); + + void set_end_allocate_to_pool_fn( + std::function capture_about_to_end_fn); + + void set_release_pool( + std::function capture_destroy_fn); + + void* malloc(size_t size, c10::DeviceIndex device, cudaStream_t stream); + + c10::DataPtr allocate(size_t size) override; + c10::DeleterFnPtr raw_deleter() const override; + + void* raw_alloc(size_t nbytes) override; + void* raw_alloc_with_stream(size_t nbytes, cudaStream_t stream) override; + void raw_delete(void* ptr) override; + void init(int device_count) override; + bool initialized() override; + double getMemoryFraction(c10::DeviceIndex device) override; + void setMemoryFraction(double fraction, c10::DeviceIndex device) override; + std::vector + getExpandableSegmentSizes(c10::DeviceIndex device) override; + void emptyCache(c10::cuda::MempoolId_t mempool_id = {0, 0}) override; + void enable(bool) override {} + bool isEnabled() const override { + return true; + } + void cacheInfo(c10::DeviceIndex device, size_t* largestBlock) override; + void* getBaseAllocation(void* ptr, size_t* size) override; + + void recordStream(const c10::DataPtr&, streamType stream) override; + + c10::CachingDeviceAllocator::DeviceStats getDeviceStats( + c10::DeviceIndex device) override; + void resetAccumulatedStats(c10::DeviceIndex device) override; + void resetPeakStats(c10::DeviceIndex device) override; + c10::cuda::CUDACachingAllocator::SnapshotInfo snapshot( + c10::cuda::MempoolId_t mempool) override; + void beginAllocateToPool( + c10::DeviceIndex device, + c10::cuda::MempoolId_t mempool_id, + std::function) override; + void endAllocateToPool( + c10::DeviceIndex device, + c10::cuda::MempoolId_t mempool_id) override; + void releasePool(c10::DeviceIndex device, c10::cuda::MempoolId_t mempool_id) + override; + std::shared_ptr getIpcDevPtr(std::string handle) override; + c10::cuda::CUDACachingAllocator::ShareableHandle shareIpcHandle( + void*) override; + void recordHistory( + bool enabled, + c10::cuda::CUDACachingAllocator::CreateContextFn context_recorder, + size_t alloc_trace_max_entries, + c10::cuda::CUDACachingAllocator::RecordContext when, + bool clearHistory) override; + void attachOutOfMemoryObserver( + c10::cuda::CUDACachingAllocator::OutOfMemoryObserver observer) override; + void attachAllocatorTraceTracker( + c10::cuda::CUDACachingAllocator::AllocatorTraceTracker tracker) override; + std::shared_ptr + getCheckpointState(c10::DeviceIndex device, at::cuda::MempoolId_t id) + override; + c10::cuda::CUDACachingAllocator::CheckpointDelta setCheckpointPoolState( + c10::DeviceIndex device, + std::shared_ptr pps) + override; + void enablePeerAccess(c10::DeviceIndex dev, c10::DeviceIndex dev_to_access) + override; + cudaError_t memcpyAsync( + void* dst, + int dstDevice, + const void* src, + int srcDevice, + size_t count, + cudaStream_t stream, + bool p2p_enabled) override; + std::string name() override; + void copy_data(void* dest, const void* src, std::size_t count) const final; + + protected: + std::function alloc_fn_; + std::function free_fn_; + std::function init_fn_; + std::function reset_fn_; + std::function memory_fraction_fn_; + std::function base_alloc_fn_; + std::function record_stream_fn_; + std::function< + void(int, c10::cuda::MempoolId_t, std::function)> + begin_allocate_to_pool_fn_; + std::function end_allocate_to_pool_fn_; + std::function relase_pool_fn_; + std::mutex allocator_mutex_; + // We do the bookkeeping here in order to simplify custom allocators + std::unordered_map allocation_metadata_; + + bool initialized_ = false; +}; +} // namespace torch::cuda::CUDAPluggableAllocator + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Event.h new file mode 100644 index 0000000000000000000000000000000000000000..2ce6656b45470bedd99022f77fac4fccadf92478 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Event.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#ifndef THCP_EVENT_INC +#define THCP_EVENT_INC + +#include +#include +#include + +struct THCPEvent : THPEvent { + at::cuda::CUDAEvent cuda_event; +}; +extern PyObject* THCPEventClass; + +void THCPEvent_init(PyObject* module); + +inline bool THCPEvent_Check(PyObject* obj) { + return THCPEventClass && PyObject_IsInstance(obj, THCPEventClass); +} + +#endif // THCP_EVENT_INC + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/GdsFile.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/GdsFile.h new file mode 100644 index 0000000000000000000000000000000000000000..231e335875e3da19689f3e5675a1c7bbfd8b9052 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/GdsFile.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#ifndef THCP_GDSFILE_INC +#define THCP_GDSFILE_INC + +#include + +namespace torch::cuda::shared { +void initGdsBindings(PyObject* module); +} +#endif // THCP_GDSFILE_INC + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..53aeb483bb8a3c0fa3746901aec785d2b5984074 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Module.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#ifndef THCP_CUDA_MODULE_INC +#define THCP_CUDA_MODULE_INC +#include + +PyObject* THCPModule_getDevice_wrap(PyObject* self); +PyObject* THCPModule_setDevice_wrap(PyObject* self, PyObject* arg); +PyObject* THCPModule_getDeviceName_wrap(PyObject* self, PyObject* arg); +PyObject* THCPModule_getDriverVersion(PyObject* self); +PyObject* THCPModule_isDriverSufficient(PyObject* self); +PyObject* THCPModule_getCurrentBlasHandle_wrap(PyObject* self); + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Stream.h new file mode 100644 index 0000000000000000000000000000000000000000..a391e9e519d82106cbe7d21236fe7d49be43c5eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Stream.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#ifndef THCP_STREAM_INC +#define THCP_STREAM_INC + +#include +#include +#include + +// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) +struct THCPStream : THPStream { + at::cuda::CUDAStream cuda_stream; +}; +extern PyObject* THCPStreamClass; + +void THCPStream_init(PyObject* module); + +inline bool THCPStream_Check(PyObject* obj) { + return THCPStreamClass && PyObject_IsInstance(obj, THCPStreamClass); +} + +#endif // THCP_STREAM_INC + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/THCP.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/THCP.h new file mode 100644 index 0000000000000000000000000000000000000000..f6a031a30bd634229250b0b41ca6ab19e924cbb2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/THCP.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/comm.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/comm.h new file mode 100644 index 0000000000000000000000000000000000000000..dffa548a07a51025cd39231c90399b89b3211c9c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/comm.h @@ -0,0 +1,57 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::cuda { + +using tensor_list2d = std::vector>; + +TORCH_CUDA_CU_API std::vector& broadcast_out( + const at::Tensor& tensor, + std::vector& out_tensors); +TORCH_CUDA_CU_API std::vector broadcast( + const at::Tensor& tensor, + at::IntArrayRef devices); +TORCH_CUDA_CU_API tensor_list2d broadcast_coalesced( + at::TensorList tensors, + at::IntArrayRef devices, + size_t buffer_size); + +TORCH_CUDA_CU_API std::vector& scatter_out( + const at::Tensor& tensor, + std::vector& out_tensors, + int64_t dim = 0, + const std::optional>>& + streams = std::nullopt); + +TORCH_CUDA_CU_API std::vector scatter( + const at::Tensor& tensor, + at::IntArrayRef devices, + const std::optional>& chunk_sizes = std::nullopt, + int64_t dim = 0, + const std::optional>>& + streams = std::nullopt); + +TORCH_CUDA_CU_API at::Tensor& gather_out( + at::TensorList tensors, + at::Tensor& out_tensor, + int64_t dim); + +TORCH_CUDA_CU_API at::Tensor gather( + at::TensorList tensors, + int64_t dim, + std::optional destination_index); + +} // namespace torch::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/device_set.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/device_set.h new file mode 100644 index 0000000000000000000000000000000000000000..433bb223b08a7274c23ba12205a930269c6be64b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/device_set.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch { + +using device_set = std::bitset; + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/memory_snapshot.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/memory_snapshot.h new file mode 100644 index 0000000000000000000000000000000000000000..10760e16d7463da729df435124e4915f939fe89e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/memory_snapshot.h @@ -0,0 +1,38 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::cuda { + +// C++-only versions of these, for python use +// those defined in cuda/Module.cpp which also record python state. +TORCH_CUDA_CU_API void _record_memory_history( + bool enabled, + bool record_context = true, + int64_t trace_alloc_max_entries = 1, + bool trace_alloc_record_context = false, + bool record_cpp_context = false, + bool clearHistory = false, + bool compileContext = false, + bool globalRecordAllocations = false); + +TORCH_CUDA_CU_API void _record_memory_history( + std::optional enabled = "all", + std::optional context = "all", + const std::string& stacks = "all", + size_t max_entries = SIZE_MAX, + bool clearHistory = false, + bool compileContext = false, + bool globalRecordAllocations = false); + +TORCH_CUDA_CU_API std::string _memory_snapshot_pickled(); + +} // namespace torch::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/nccl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/nccl.h new file mode 100644 index 0000000000000000000000000000000000000000..f7970e441d853f97c27c29fc824a306eeac217dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/nccl.h @@ -0,0 +1,224 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +// NCCL BFloat16 is enabled only for CUDA 11+ and NCCL versions 2.10+, or for +// HIP 3.1+ +#if defined(__CUDA_BF16_TYPES_EXIST__) +#define HAS_NCCL_BF16_DATATYPE \ + ((NCCL_MAJOR > 2) || (NCCL_MAJOR == 2) && (NCCL_MINOR >= 10)) +#elif defined(USE_ROCM) && (TORCH_HIP_VERSION >= 301) +#define HAS_NCCL_BF16_DATATYPE 1 +#else +#define HAS_NCCL_BF16_DATATYPE 0 +#endif + +namespace torch::cuda::nccl { + +/* The following are copied from and redefined in torch::cuda::nccl + * namespace */ +/* pytorch should only use the following definition within pytorch scope */ + +/* Opaque handle to communicator to ncclComm*, this will reinterpret as ncclComm + * in nccl.cpp */ +typedef void* ncclComm_t; + +/** redefine nccl unique ID in torch scope. this should be identical to native + * nccl impp. */ +#define NCCL_UNIQUE_ID_BYTES 128 +typedef struct { + // NOLINTNEXTLINE(*array*) + char internal[NCCL_UNIQUE_ID_BYTES]; +} ncclUniqueId; + +/* Error type */ +enum class ncclResult { + Success = 0, + UnhandledCudaError = 1, + SystemError = 2, + InternalError = 3, + InvalidArgument = 4, + InvalidUsage = 5, + RemoteError = 6, + InProgress = 7, + NumResults = 8 +}; + +/* Reduction operation selector */ +enum class ncclRedOp { Sum = 0, Prod = 1, Max = 2, Min = 3, NumOps = 4 }; + +/* Data types */ +enum class ncclDataType { + Int8 = 0, + Char = 0, + Uint8 = 1, + Int32 = 2, + Int = 2, + Uint32 = 3, + Int64 = 4, + Uint64 = 5, + Float16 = 6, + Half = 6, + Float32 = 7, + Float = 7, + Float64 = 8, + Double = 8, + Bfloat16 = 9, + NumTypes = 10 +}; + +// RAII helper class to manage NCCL group API and CUDA free mutex. +// The destructor is allowed to throw since this helper class only +// manages group and lock lifetimes. +struct TORCH_CUDA_CPP_API AutoNcclGroup { + AutoNcclGroup(); + AutoNcclGroup(ncclComm_t comm, bool comm_nonblocking); + ~AutoNcclGroup() noexcept(false); + ncclComm_t comm_; + bool comm_nonblocking_; +}; + +// NOTE: this is exposed only so that python_nccl.cpp can some of these helpers. +// Don't use them outside of these files. +namespace detail { + +TORCH_CUDA_CPP_API void throw_nccl_error(ncclResult status); + +inline void NCCL_CHECK(ncclResult status) { + if (status != ncclResult::Success) { + throw_nccl_error(status); + } +} + +TORCH_CUDA_CPP_API at::ArrayRef get_communicators( + at::TensorList inputs); +TORCH_CUDA_CPP_API void check_inputs( + at::TensorList inputs, + at::TensorList outputs, + size_t input_multiplier, + size_t output_multiplier); +TORCH_CUDA_CPP_API void check_inputs( + at::TensorList inputs, + const at::Tensor& output, + int root, + size_t input_multiplier, + size_t output_multiplier); + +} // namespace detail + +using comm_list = std::vector; +using stream_list = std::vector>; + +TORCH_CUDA_CPP_API std::uint64_t version(); +TORCH_CUDA_CPP_API const char* version_suffix(); + +bool is_available(at::TensorList tensors); + +TORCH_CUDA_CPP_API void get_unique_id(ncclUniqueId& id); +TORCH_CUDA_CPP_API ncclComm_t +comm_init_rank(int nranks, const ncclUniqueId& comm_id, int rank); +TORCH_CUDA_CPP_API void comm_destroy(ncclComm_t comm); + +TORCH_CUDA_CPP_API void broadcast( + at::TensorList tensors, + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +size_t get_max_count(); + +TORCH_CUDA_CPP_API void reduce( + const std::vector& inputs, + at::Tensor& output, + int32_t root = 0, + int32_t op = static_cast(ncclRedOp::Sum), + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void reduce( + std::vector& inputs, + int32_t root = 0, + int32_t op = static_cast(ncclRedOp::Sum), + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void all_reduce( + const std::vector& inputs, + std::vector& outputs, + int32_t op = static_cast(ncclRedOp::Sum), + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void reduce_scatter( + const std::vector& inputs, + std::vector& outputs, + int32_t op = static_cast(ncclRedOp::Sum), + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void scatter( + const std::vector& inputs, + at::Tensor& outputs, + ncclComm_t comm, + at::cuda::CUDAStream& stream, + int32_t root = 0); + +TORCH_CUDA_CPP_API void all_gather( + const std::vector& inputs, + std::vector& outputs, + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void gather( + const at::Tensor& inputs, + std::vector& outputs, + ncclComm_t comm, + at::cuda::CUDAStream& stream, + int32_t root = 0); + +TORCH_CUDA_CPP_API void all2all_single_equal_split( + at::Tensor& input, + at::Tensor& output, + int size, + ncclComm_t comm, + at::cuda::CUDAStream& stream); + +TORCH_CUDA_CPP_API void all2all_single_unequal_split( + void* sendbuff, + const size_t* sendcounts, + const size_t* senddispls, + void* recvbuff, + const size_t* recvcounts, + const size_t* recvdispls, + size_t size, + c10::ScalarType type, + ncclComm_t comm, + at::cuda::CUDAStream& stream); + +TORCH_CUDA_CPP_API void all2all( + std::vector& outputTensors, + std::vector& inputTensors, + ncclComm_t _comm, + at::cuda::CUDAStream& stream); + +TORCH_CUDA_CPP_API void send( + const at::Tensor& input, + ncclComm_t comm, + at::cuda::CUDAStream stream, + int dst); + +TORCH_CUDA_CPP_API void recv( + at::Tensor& output, + ncclComm_t comm, + at::cuda::CUDAStream stream, + int src); +} // namespace torch::cuda::nccl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_comm.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_comm.h new file mode 100644 index 0000000000000000000000000000000000000000..a6451476ed54ff9a095ac2dcaf702d4e48d0d19a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_comm.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +namespace torch::cuda::python { + +void initCommMethods(PyObject* module); + +} // namespace torch::cuda::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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_nccl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_nccl.h new file mode 100644 index 0000000000000000000000000000000000000000..c8981d5ba7bd6362a87fc346483ee02722d0fb5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_nccl.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +PyObject* THCPModule_nccl_version(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_version_suffix(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_unique_id(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_init_rank(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_reduce(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_all_reduce(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_broadcast(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_all_gather(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_reduce_scatter(PyObject* self, PyObject* args); + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..3803c7c90e18edb3ca4138105aa8669539c113c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/utils.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +std::vector> +THPUtils_PySequence_to_CUDAStreamList(PyObject* obj); + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/Placement.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/Placement.h new file mode 100644 index 0000000000000000000000000000000000000000..70bc90c0f0c47908103ddefbe58468774fbcc628 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/Placement.h @@ -0,0 +1,120 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +/** + * The implementations in this file are coupled with + * torch/distributed/tensor/placement_types.py. + */ + +#include +#include +#include +#include + +namespace torch::distributed { + +class Placement { + public: + Placement() = default; + virtual ~Placement() = default; + + Placement(const Placement&) = default; + Placement& operator=(const Placement&) = default; + Placement(Placement&&) noexcept = default; + Placement& operator=(Placement&&) noexcept = default; + + virtual bool is_shard(std::optional dim) const { + return false; + } + + virtual bool is_replicate() const { + return false; + } + + virtual bool is_partial( + std::optional reduce_op = std::nullopt) const { + return false; + } +}; + +class Shard : public Placement { + public: + std::int64_t dim; + explicit Shard(std::int64_t dim) : dim(dim) {} + + bool is_shard(std::optional dim_) const override { + if (typeid(*this) != typeid(Shard)) { + return false; + } + return !dim_.has_value() || *dim_ == dim; + } + + bool operator==(const Shard& rhs) const { + return dim == rhs.dim; + } + + bool operator!=(const Shard& rhs) const { + return !operator==(rhs); + } +}; + +class StridedShard : public Placement { + public: + std::int64_t dim; + std::int64_t split_factor; + explicit StridedShard(std::int64_t dim, std::int64_t split_factor_) + : dim(dim), split_factor(split_factor_) {} + + bool operator==(const StridedShard& rhs) const { + return dim == rhs.dim && split_factor == rhs.split_factor; + } + + bool operator!=(const StridedShard& rhs) const { + return !operator==(rhs); + } +}; + +class Replicate : public Placement { + public: + bool is_replicate() const override { + return true; + } + + bool operator==(const Replicate& rhs) const { + return true; + } + + bool operator!=(const Replicate& rhs) const { + return false; + } +}; + +class Partial : public Placement { + public: + std::string reduce_op; + + Partial() : Partial("sum") {} + + explicit Partial(std::optional reduce_op_) + : reduce_op( + reduce_op_.has_value() ? std::move(*reduce_op_) + : std::string("sum")) {} + + bool is_partial( + std::optional op = std::nullopt) const override { + return !op.has_value() || *op == reduce_op; + } + + bool operator==(const Partial& rhs) const { + return reduce_op == rhs.reduce_op; + } + + bool operator!=(const Partial& rhs) const { + return !operator==(rhs); + } +}; + +} // namespace torch::distributed + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/autograd.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..8aa0d835c9d52fac0c36d6ed52038dc0b26a9357 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/autograd.h @@ -0,0 +1,41 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::autograd { + +using torch::autograd::variable_list; + +/// C++ API of Distributed Autograd that kicks off the distributed backward pass +/// using the provided roots. This currently implements the +/// :ref:`fast-mode-algorithm` which assumes all RPC messages sent in the same +/// distributed autograd context across workers would be part of the autograd +/// graph during the backward pass. +/// +/// We use the provided roots to discover the autograd graph and compute +/// appropriate dependencies. This method blocks until the entire +/// autograd computation is done. +/// This function accumulates gradients in the leaves - you might need to zero +/// them before calling it. +/// +/// \param context_id The autograd context id for which we should retrieve the +/// gradients. +/// \param roots Tensors which represent the roots of the autograd computation. +/// All the tensors should be scalars. +/// \param retain_graph If `false`, the graph used to compute the grad will be +/// freed. Note that in nearly all cases setting this +/// option to `true` is not needed and often can be worked +/// around in a much more efficient way. Usually, you need +/// to set this to `true` to run backward multiple times. +TORCH_API void backward( + int64_t context_id, + const variable_list& roots, + bool retain_graph = false); + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/container.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/container.h new file mode 100644 index 0000000000000000000000000000000000000000..c28137cb4fbf2f19118ba4b546d6c612aefaf35c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/container.h @@ -0,0 +1,167 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::distributed::autograd { + +// Singleton class per worker which is responsible for storing the distributed +// autograd context for each autograd pass and also cleans up data for an +// autograd pass once its done. +// +// Each autograd pass is assigned a unique autograd_context_id and all data for +// that pass (DistAutogradContext) is stored in this container indexed by the +// autograd_context_id. The autograd_context_id itself is a 64 bit globally +// unique id. The first 16 bits is the worker_id and the next 48 bits is an +// auto-incrementing id for each worker. +// +// This container is also responsible for maintaining a globally unique message +// id, which is used to associate send/recv autograd function pairs. The format +// is similar to the autograd_context_id where we have a 64 bit integer with +// first 16 bits being the worker id and next 48 bits are auto-incrementing. +class TORCH_API DistAutogradContainer { + public: + explicit DistAutogradContainer(uint32_t num_shards); + + // One time initialization of the container. + static DistAutogradContainer& init(int64_t worker_id); + + // Retrieve the singleton instance of the container, ensures we have + // initialized the container. + static DistAutogradContainer& getInstance(); + + // Create a new context for a distributed autograd pass. + const ContextPtr newContext(); + + // Clean up resources for a given context_id once the autograd pass is done. + // Sends RPC to other workers this worker knows about, telling them to clean + // up their context as well. Throws an exception if the context_id does not + // exist. + void releaseContext(int64_t context_id); + + // Releases an autograd context if it is present on this node. Also sends RPC + // to other workers this worker knows about, telling them to clean up their + // context. Does nothing if it is not present. + void releaseContextIfPresent(int64_t context_id); + + // Checks if the passed in context_id is valid. + void isValidContext(int64_t context_id); + + // Retrieve the autograd context for a given context_id. + ContextPtr retrieveContext(int64_t context_id); + + // Retrieves the currently active autograd context for the current thread. + ContextPtr currentContext(); + + // Checks whether or not the current thread has a valid autograd context. + bool hasValidContext() const; + + // Generate a new autograd_message_id for send/recv autograd functions. + int64_t newAutogradMessageId(); + + // Creates a new autograd context with the provided context_id. If a context + // already exists with the provided context_id, we just return it. + // This does not set the current context for the current thread. + ContextPtr getOrCreateContext(int64_t context_id); + + // Retrieves the maximum possible autograd_context_id/autograd_message_id that + // can be generated by this worker. + int64_t getMaxId(); + + // Retrieves the worker ID for this node + rpc::worker_id_t getWorkerId() const; + + // Can set current context id if there is no valid context yet + static void setCurrentContextId(int64_t contextId); + + // Forcibly sets the thread local current context id. Should only be used in + // cases where you know what you're doing and need to override the thread + // local. Otherwise, use setCurrentContextId instead. + static void forceCurrentContextId(int64_t contextId); + + // Clear current context id + void clearCurrentContext(); + + // Returns the number of autograd contexts in the container. + size_t numAutogradContexts() const; + + // Returns the current thread local context id for this thread. + static int64_t currentContextId(); + + DistAutogradContainer() = delete; + ~DistAutogradContainer() = default; + DistAutogradContainer(const DistAutogradContainer&) = delete; + DistAutogradContainer& operator=(const DistAutogradContainer&) = delete; + DistAutogradContainer(DistAutogradContainer&&) = delete; + DistAutogradContainer& operator=(DistAutogradContainer&&) = delete; + + private: + // Number of shards for the map storing autograd contexts. We'd like this + // to be a power of 2 and we don't expect a value much higher than the + // number of cores would provide much benefit. + static constexpr uint32_t kNumDefaultShards = 128; + + // Use cache line size for alignment. + static constexpr int kCacheLineSize = 64; + + // Structure holding one shard of the sharded autograd context map with its + // associated lock. Align to cache line size to avoid contention between + // adjacent entries. + struct alignas(kCacheLineSize) ContextsShard { + // Lock for this shard. + mutable std::mutex lock; + + // Map storing autograd contexts for this shard. + std::unordered_map contexts; + }; + + static DistAutogradContainer& getInstanceInternal(); + + // Retrieve the shard for given context_id. + ContextsShard& getShard(int64_t context_id); + + // Sends an RPC to the workers that have a context corresponding to passed in + // context_id. This function should be called with the lock. + void sendReleaseContextRpc( + const std::unordered_set& workerIds, + int64_t context_id); + + // Erase context_id from the autograd context map, and reset the thread local + // current context id if it corresponds to the passed in context id. This + // function should be called with the lock. + void eraseContextIdAndReset(ContextsShard& shard, int64_t context_id); + + // Compute the number of shards for the autograd_contexts_ map. + static uint32_t computeNumShards(); + + // Auto incrementing context id used to identify unique autograd passes. + // Initialized with the first 16 bits being the worker_id. + std::atomic next_context_id_; + + // Unique id to identify a worker in the distributed setting. + int16_t worker_id_; + + // Whether or not the container has been initialized appropriately. + bool initialized_; + + // Sharded autograd context map. + std::vector autograd_contexts_; + + // Number of shards for the sharded autograd_contexts_ map. + uint32_t num_shards_; + + // Autograd message id to identify unique send/recv autograd function pairs. + std::atomic next_autograd_message_id_; + + // Maximum allowed value for autograd_context_id or autograd_message_id. + int64_t max_id_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h new file mode 100644 index 0000000000000000000000000000000000000000..09de23c1154c2c496ba6af372f993e3a9477a310 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h @@ -0,0 +1,176 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::distributed::autograd { + +class RecvRpcBackward; + +// DistAutogradContext which stores information for a single distributed +// autograd pass on a worker. +class TORCH_API DistAutogradContext { + public: + using GradCallback = std::function; + + explicit DistAutogradContext(int64_t contextId); + ~DistAutogradContext() = default; + + // Retrieves the autograd context id for this context. + int64_t contextId() const; + + // Records a 'send' autograd function for this context with the provided + // message id. + void addSendFunction( + const std::shared_ptr& func, + int64_t autograd_message_id); + + // Records a 'recv' autograd function for this context with the provided + // message id. + void addRecvFunction( + std::shared_ptr& func, + int64_t autograd_message_id); + + // Given an autograd_message_id, retrieve the appropriate send function. + std::shared_ptr retrieveSendFunction( + int64_t autograd_message_id); + + // Return all send functions for this context. + std::unordered_map> sendFunctions() + const; + + // Return all recv functions for this context. + std::unordered_map> recvFunctions() + const; + + // Adds a future message recording an outstanding RPC. + void addOutstandingRpc(const c10::intrusive_ptr& jitFuture); + + // Returns all gradients. + const c10::Dict getGradients() const; + + // This function gives a mutable grad reference to the callback. + // If the callback returns true, it means the grad in the context + // needs to be updated. + void runGradCallbackForVariable( + const torch::autograd::Variable& variable, + const GradCallback& cb); + + DistAutogradContext(const DistAutogradContext&) = delete; + DistAutogradContext& operator=(const DistAutogradContext&) = delete; + DistAutogradContext(DistAutogradContext&&) = delete; + DistAutogradContext& operator=(DistAutogradContext&&) = delete; + + // records the workerID of a node that we sent an RPC to. + // workerIDs are added here when we attach a send function to this autograd + // context + void addKnownWorkerId(const rpc::worker_id_t workerId); + + // Retrieves a set containing the known workerIds for this context + // These are the different workers that this context has sent RPCs to. + std::unordered_set getKnownWorkerIds() const; + + private: + friend class BackwardPassCleanupGuard; + friend class DistEngine; + friend class RecvRpcBackward; + friend class DistAccumulateGradCaptureHook; + + // Record that we would like to accumulate the provided gradient on the given + // variable. + void accumulateGrad( + const torch::autograd::Variable& variable, + const torch::Tensor& grad, + size_t num_expected_refs); + + // Retrieve the GraphTask. + std::shared_ptr retrieveGraphTask(); + + // Set the appropriate graph task for the backward pass. Can be called only + // once. + void setGraphTask(std::shared_ptr graphTask); + + // Resets the graph task to ensure we can run another distributed backward + // pass for the same autograd context. + void resetGraphTask(); + + // Waits for all outstanding RPCs for this context to finish and clears all + // outstanding rpcs held in this context. This should be called only once. + c10::intrusive_ptr clearAndWaitForOutstandingRpcsAsync(); + + void clearOutstandingRpcs(); + + // Record an event to mark the completion of gradient computation. These + // events will later help to properly synchronize gradients consumptions + // in getGradients(). We need these events because backward and + // optimizer.step are separate RPC calls, and will occur on different CUDA + // streams. Without synchronization, it is possible that gradients are + // consumed before they are ready. + void recordGradEvent(c10::Device device); + + const int64_t contextId_; + + // Set containing known worker IDs, used in cleaning up autograd context. + // Whenever a sendRpcBackward is attached to the autograd graph for this + // context, the destination is added here. + std::unordered_set knownWorkerIds_; + + // Map from autograd_message_id to appropriate 'send' autograd function. + std::unordered_map> + sendAutogradFunctions_; + + // Map from autograd_message_id to appropriate 'recv' autograd function. + std::unordered_map> + recvAutogradFunctions_; + + // Gradients accumulated in this context so far. The key is the variable on + // which the gradient needs to be accumulated and the value is the gradient + // that needs to be accumulated on that variable.. + c10::Dict accumulatedGrads_; + + // See comments for recordGradEvent(c10::Device device); + std::unordered_map gradReadyEvents_; + const c10::impl::VirtualGuardImpl impl_; + + // The autograd GraphTask for the backward pass on this node for this context. + std::shared_ptr graphTask_; + + // List of futures for RPCs initiated by this node to propagate gradients to + // other nodes. The distributed autograd engine on this node can return + // successfully only if all these futures are done and are successful. + std::vector> outStandingRpcs_; + + // Lock to protect concurrent modification of the context. + mutable std::mutex lock_; +}; + +using ContextPtr = std::shared_ptr; + +// This class stores a shared_ptr to a DistAutogradContext instance in a +// thread local variable. The instance is given by the call site. The class +// doesn't know the current context. It's just a util class. +class TORCH_API ThreadLocalDistAutogradContext { + public: + // Store 'new_context' to the thread local variable maintained by this class. + explicit ThreadLocalDistAutogradContext(ContextPtr&& new_context); + ~ThreadLocalDistAutogradContext(); + + // Retrieve the stored DistAutogradContext instance. + static ContextPtr getContextPtr(); + + private: + ContextPtr prev_context_ptr_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/engine/dist_engine.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/engine/dist_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..aef84bb4113f439f667d3745a426266db14ccbaa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/engine/dist_engine.h @@ -0,0 +1,177 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace torch::distributed::autograd { + +// Forward declaration. +class BackwardPassCleanupGuard; + +// This is a singleton class responsible for running distributed backward +// passes. This engine relies heavily on the vanilla autograd engine and tries +// to reuse it as much as possible. This class is mostly responsible for the +// distributed aspects of autograd and tries to hook into the autograd engine +// where convenient. + +// Unlike the vanilla autograd engine, the distributed autograd engine +// accumulates the gradients in the appropriate DistAutogradContext. This avoids +// multiple trainer nodes stomping on each others gradients. +class TORCH_API DistEngine { + public: + // Retrieve the singleton instance. + static DistEngine& getInstance(); + + // Given a list of root variables, start the distributed backwards pass from + // these variables and accumulate all the gradients in the current autograd + // context on each node. This method is used to kickoff distributed autograd + // on a single node. + void execute( + int64_t context_id, + const torch::autograd::variable_list& roots, + bool retainGraph); + + // Given a send function to execute in the autograd engine, ensures we compute + // dependencies once for this node and enqueues the send function for execute + // in the engine. + // This method is used to kick off the autograd computation on a node when it + // receives gradients from the corresponding 'recv' method on another node. + // The gradients are accumulated in the provided autograd context. + c10::intrusive_ptr executeSendFunctionAsync( + const ContextPtr& autogradContext, + const std::shared_ptr& sendFunction, + bool retainGraph); + + // Number of backward passes currently running for the Distributed Engine. + size_t numBackwardPasses() const; + + // Returns key-value pairs consisting of useful debugging information related + // to distributed autograd. + std::unordered_map getDebugInfo() const; + + DistEngine(const DistEngine&) = delete; + DistEngine& operator=(const DistEngine&) = delete; + DistEngine(DistEngine&&) = delete; + DistEngine& operator=(DistEngine&&) = delete; + + private: + // Make sure this is a singleton. + DistEngine(); + ~DistEngine(); + + // Validates the input roots for the backward computations and retrieves the + // appropriate root edges and corresponding gradients. Populates root_edges + // with the appropriate gradient edges and grads with the gradients for each + // edge. + void validateRootsAndRetrieveEdges( + const torch::autograd::variable_list& roots, + torch::autograd::edge_list& rootEdges, + torch::autograd::variable_list& grads); + + // Given the autograd context, root edges and grads, we compute dependencies + // for the local node and fill out the provided GraphTask and GraphRoot with + // appropriate information for the local autograd engine. + // We also determine all leaf nodes(functions) in the graph and accumulate + // them in outputEdges. + void computeDependencies( + const ContextPtr& context, + const torch::autograd::edge_list& rootEdges, + const torch::autograd::variable_list& grads, + const std::shared_ptr& graphRoot, + torch::autograd::edge_list& outputEdges, + bool retainGraph); + + // Given a pre-populated GraphTask and a root node, compute the backward pass + // for the autograd graph until the graph task ready queue is empty. + // + // This method assumes that the appropriate GraphTask has already been + // initialized appropriately. It will construct a local ready queue to + // traverse the GraphTask instead of using the GraphTask embedded + // cpu_ready_queue, this is because dist engine might run the same GraphTask + // from different SendFunctions concurrently in different threads. The method + // will only mark the GraphTask as completed when it needs to, which means it + // might not mark as completed for every call as dist engine would like to + // keep the GraphTask alive when it not receives all gradients. + // + // When `incrementOutstandingTasks=false`, the function does not increment + // 'outstanding_tasks_' in the appropriate GraphTask. It is assumed we've + // already done this before hand for this task (to ensure we don't pre-mark + // this graph_task as completed). This is useful in the distributed autograd + // case where we need to increment 'outstanding_tasks_' first to indicate the + // local autograd engine the graph task is not completed until it receives the + // signals from other workers over the network. + // + // XXX: calling this function assumes that we will have NO GPU nodetasks be + // executed for the graph_task, the caller of this function need to ensure + // this otherwise there will be undefined behaviors. A correct way to fix this + // is to re-design the autograd engine so that GPU worker thread to behave the + // same as CPU caller thread, record the operation/thread for the device, and + // reuse it in backward. + // TODO: 1. Add assert in the dist engine to ensure no GPU NodeTasks during + // backward + // 2. properly setup the thread local ready queue to enable reentrant + // backwards + void execute_graph_task_until_ready_queue_empty( + torch::autograd::NodeTask&& node_task, + bool incrementOutstandingTasks = true); + + // Run the local autograd engine using the provided graphTask and graphRoot + // and accumulate the gradients part 'outputEdges' in the provided autograd + // context. + c10::intrusive_ptr runEngineAndAccumulateGradients( + const ContextPtr& autogradContext, + const std::shared_ptr& graphRoot, + const torch::autograd::edge_list& outputEdges, + bool incrementOutStandingTasks = true); + + // Run after the backward pass is done to appropriately cleanup structures. + void cleanupBackwardPass(const ContextPtr& autogradContext); + + // Global thread to execute CPU continuations. + void globalCpuThread( + const std::shared_ptr& ready_queue); + + // Set of autograd context_ids, which we have already initialized for + // distributed autograd on this node (e.g.: already computed dependencies) + std::unordered_set initializedContextIds_; + + mutable std::mutex initializedContextIdsLock_; + + // Reference to local autograd engine. + torch::autograd::Engine& engine_; + + // Ready queue used by the CPU thread in distributed engine. + // See Note [GPU to CPU continuations] + std::shared_ptr global_cpu_ready_queue_; + + // See Note [GPU to CPU continuations] + std::thread global_cpu_thread_; + + friend class BackwardPassCleanupGuard; +}; + +// Guard to clean up resources once the backward pass is done. +class BackwardPassCleanupGuard { + public: + explicit BackwardPassCleanupGuard(ContextPtr autogradContext) + : autogradContext_(std::move(autogradContext)) {} + + ~BackwardPassCleanupGuard() { + DistEngine::getInstance().cleanupBackwardPass(autogradContext_); + } + + private: + ContextPtr autogradContext_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..ec9959de9fc137a3da052c0be05e566ede4c6bdb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::autograd { + +// Forward declarations. +class DistAutogradContext; + +// As part of our distributed autograd implementation, whenever we receive an +// RPC from a node, we add a 'RecvRpcBackward' autograd function to the +// autograd graph. This is more or less a placeholder function that is used to +// pass gradients to the remote host during the backward pass. The inputs to the +// RPC function are the inputs to this autograd function. +class TORCH_API RecvRpcBackward : public torch::autograd::Node { + public: + explicit RecvRpcBackward( + const AutogradMetadata& autogradMetadata, + const std::shared_ptr& autogradContext, + rpc::worker_id_t fromWorkerId, + rpc::DeviceMap deviceMap); + + torch::autograd::variable_list apply( + torch::autograd::variable_list&& grads) override; + + private: + const AutogradMetadata autogradMetadata_; + + // Hold a weak reference to the autograd context to avoid circular + // dependencies with the context (since it holds a reference to + // RecvRpcBackward). + std::weak_ptr autogradContext_; + + // The worker id from which the RPC was received. During the backward pass, + // we need to propagate the gradients to this workerId. + rpc::worker_id_t fromWorkerId_; + + // Device mapping for tensors sent over RPC. + const rpc::DeviceMap deviceMap_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/sendrpc_backward.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/sendrpc_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..e9d651a206361595c8c5f82d67545f29811d8b51 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/sendrpc_backward.h @@ -0,0 +1,38 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::autograd { + +// As part of our distributed autograd implementation, whenever we send an RPC +// from one node to another, we add a 'SendRpcBackward' autograd function to the +// autograd graph. This is more or less a placeholder function that is used to +// kickoff the autograd engine on the current worker on the backward pass. The +// edges for this autograd function are the inputs to the RPC method. +// +// During the backward pass, this function is queued for execution in the +// autograd engine which eventually runs the rest of the autograd graph. +struct TORCH_API SendRpcBackward : public torch::autograd::Node { + public: + torch::autograd::variable_list apply( + torch::autograd::variable_list&& inputs) override; + + // SendRpcBackward is actually the root of an autograd graph on the local + // node. As a result, it doesn't receive any 'inputs', but rather the RPC + // framework passes gradients over to this function to kickoff local autograd + // computation. + void setGrads(const torch::autograd::variable_list& grads); + + // Retrieve the grads for the function. + const torch::autograd::variable_list& getGrads() const; + + private: + torch::autograd::variable_list grads_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/python_autograd.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/python_autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..2dd0604b70cc367ced7f549ec00841affbe4b7f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/python_autograd.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::autograd { + +PyMethodDef* python_functions(); + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..c6b35f8f5c9590e55195de8618c6acc6de15e719 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h @@ -0,0 +1,26 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::autograd { + +// This structure represents autograd metadata that we need to pass across +// different nodes when we call an RPC which needs autograd computation. +struct TORCH_API AutogradMetadata { + AutogradMetadata(int64_t autogradContextId, int64_t autogradMessageId); + + // autogradContextId_ is a globally unique integer that identifies a + // particular distributed autograd pass. + int64_t autogradContextId; + // autogradMessageId_ is a globally unique integer that identifies a pair + // of send/recv autograd functions. + int64_t autogradMessageId; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_req.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_req.h new file mode 100644 index 0000000000000000000000000000000000000000..94948652d8f95a90343351b180433f10db90b353 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_req.h @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::distributed::autograd { + +// Used to request other workers to clean up their autograd context. +class TORCH_API CleanupAutogradContextReq : public rpc::RpcCommandBase { + public: + explicit CleanupAutogradContextReq(int64_t context_id); + // Serialization and deserialization methods. + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const rpc::Message& message); + + // Retrieve the context id we are cleaning up with this message. + int64_t getContextId(); + + private: + int64_t context_id_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h new file mode 100644 index 0000000000000000000000000000000000000000..6b1733c5aa61bd1c39837e7b84bbb748a3c7bc77 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::autograd { + +// Empty response for CleanupAutogradContextReq. Send to acknowledge receipt of +// a CleanupAutogradContextReq. +class TORCH_API CleanupAutogradContextResp : public rpc::RpcCommandBase { + public: + CleanupAutogradContextResp() = default; + // Serialization and deserialization methods. + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const rpc::Message& message); +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h new file mode 100644 index 0000000000000000000000000000000000000000..e56f32af955b8653fecf6dd92c06eddc76ab1c2a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::autograd { + +// Used to propagate gradients from one node to another during a distributed +// backwards pass. This RPC call is invoked when we hit a `recv` autograd +// function during backward pass execution. +class TORCH_API PropagateGradientsReq : public rpc::RpcCommandBase { + public: + PropagateGradientsReq( + const AutogradMetadata& autogradMetadata, + std::vector grads, + bool retainGraph = false); + + const AutogradMetadata& getAutogradMetadata(); + + const std::vector& getGrads(); + + // Serialization and deserialization methods. + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const rpc::Message& message); + + // Whether or not to retain the autograd graph. + bool retainGraph(); + + private: + AutogradMetadata autogradMetadata_; + std::vector grads_; + bool retainGraph_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h new file mode 100644 index 0000000000000000000000000000000000000000..4e2fd092c76b3a36479d61e4376dd8b4e5da5135 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::autograd { + +// Response for the PropagateGradients call. Currently, this class is mostly +// just a placeholder and sends an empty message over the wire. The purpose of +// this RPC command is to indicate whether or not the PropagateGradientsReq call +// was successfully or not. +class TORCH_API PropagateGradientsResp : public rpc::RpcCommandBase { + public: + PropagateGradientsResp() = default; + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const rpc::Message& message); +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_autograd.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..66df8c943e9d3d2a9af59fa135ab584cc95ae8f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_autograd.h @@ -0,0 +1,99 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::distributed::autograd { + +// Represents an RPC that includes autograd information. This class basically +// wraps another `RpcCommandBase` object which represents the actual RPC and has +// additional autograd information associated with that RPC. +class TORCH_API RpcWithAutograd final : public rpc::RpcCommandBase { + public: + // Used when we are sending an RPC over the wire. + RpcWithAutograd( + rpc::worker_id_t fromWorkerId, + rpc::MessageType messageType, + const AutogradMetadata& autogradMetadata, + c10::intrusive_ptr wrappedMessage, + rpc::DeviceMap deviceMap = {}); + + // Used when receiving an RPC over the wire. + RpcWithAutograd( + rpc::worker_id_t fromWorkerId, + rpc::MessageType messageType, + const AutogradMetadata& autogradMetadata, + std::unique_ptr wrappedRpc, + rpc::MessageType wrappedMessageType, + std::vector tensors, + rpc::DeviceMap deviceMap = {}); + + c10::intrusive_ptr toMessageImpl() && override; + + static std::unique_ptr fromMessage( + const rpc::Message& message); + + // Retrieves tensors as part of this RPC, which need to be considered for + // autograd computations. + std::vector& tensors(); + + const AutogradMetadata& autogradMetadata() const; + + RpcCommandBase& wrappedRpc(); + + void setWrappedRpc(std::unique_ptr wrappedRpc); + + std::unique_ptr moveWrappedRpc() &&; + + // Message type of the wrapped RPC. + rpc::MessageType wrappedMessageType() const; + + // Retrieve the worker id from which the RPC originated. + rpc::worker_id_t fromWorkerId() const; + + // Retrieve the device map. + const rpc::DeviceMap& deviceMap(); + + private: + // WorkerId from which this RPC originated. This is necessary for knowing + // which worker we need to contact during the backward pass. + rpc::worker_id_t fromWorkerId_; + + // Message type for this call. + rpc::MessageType messageType_; + + AutogradMetadata autogradMetadata_; + + // Since wrappedMessage_ is destructively constructed from wrappedRpc_, + // they are valid exclusively. They are used for different purpose. + // wrappedRpc_ is used while constructing receive rpcWithAutograd; + // wrappedMessage_ is used while constructing send rpcWithAutograd; + + // When receive rpcWithAutograd is constructed fromMessage, it is valid; + // When send rpcWithAutograd is constructed before toMessage, it is nullptr; + std::unique_ptr wrappedRpc_; + + // Serialized message representing wrappedRpc_. Used mostly as a cache to + // avoid serializing the request twice. + // When receive rpcWithAutograd is constructed fromMessage, it is nullptr; + // When send rpcWithAutograd is constructed before toMessage, it is valid; + c10::intrusive_ptr wrappedMessage_; + + // message type of the wrappedMessage, this is stored separately since + // wrappedMessage_ is not always guaranteed to be populated. + rpc::MessageType wrappedMessageType_; + + // Tensors part of the wrappedRpc that need to be considered for autograd. + std::vector tensors_; + + // Device mapping for tensors that are sent across an RPC to another node. + rpc::DeviceMap deviceMap_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h new file mode 100644 index 0000000000000000000000000000000000000000..8bfc2764e9e172cc63d8325cc363ffd35589106e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h @@ -0,0 +1,66 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::distributed::autograd { + +class TORCH_API RpcWithProfilingReq : public rpc::RpcCommandBase { + public: + // For sending RPCs, invoked when client is creating this RPC command. + RpcWithProfilingReq( + rpc::MessageType messageType, + c10::intrusive_ptr wrappedMessage, + torch::autograd::profiler::ProfilerConfig&& profilerConfig, + rpc::ProfilingId profilingKeyId); + + // For receiving an RPC + // Used in fromMessage. + RpcWithProfilingReq( + rpc::MessageType messageType, + std::unique_ptr wrappedRpc, + rpc::MessageType wrappedMessageType, + std::vector tensors, + torch::autograd::profiler::ProfilerConfig&& profilerConfig, + rpc::ProfilingId profilingKeyId); + + // Convert this RPC Command to a Message that can be sent over the wire. + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const rpc::Message& message); + + // Retrieve the profiling data that is associated with this command. + torch::autograd::profiler::ProfilerConfig getProfilingConfig() const; + // Retrieve the globally unique profiling ID corresponding to this command. + const rpc::ProfilingId& getProfilingId() const; + // Retrieve the original RPC which this ProfilingRPC wraps. + RpcCommandBase& wrappedRpc(); + // Destructively move the wrapped RPC. + std::unique_ptr moveWrappedRpc() &&; + // Message type of the wrapped RPC + rpc::MessageType wrappedMessageType() const; + void setWrappedRpc(std::unique_ptr wrappedRpc); + + private: + // message type + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const rpc::MessageType messageType_; + // wrapped message + c10::intrusive_ptr wrappedMessage_; + std::unique_ptr wrappedRpc_; + rpc::MessageType wrappedMessageType_; + std::vector tensors_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const torch::autograd::profiler::ProfilerConfig profilerConfig_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const rpc::ProfilingId profilingKeyId_; +}; +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h new file mode 100644 index 0000000000000000000000000000000000000000..fb9db4ccb84e2f961a3829d2ec28dfec7fcb2136 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h @@ -0,0 +1,63 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::distributed::autograd { +class TORCH_API RpcWithProfilingResp : public rpc::RpcCommandBase { + public: + // For sending RPCs over the wire + RpcWithProfilingResp( + rpc::MessageType messageType, + c10::intrusive_ptr wrappedMessage, + std::vector profiledEvents, + rpc::ProfilingId profilingId); + + // For receiving RPCs. Used in from message when converting a message received + // over the wire. + RpcWithProfilingResp( + rpc::MessageType messageType, + std::unique_ptr wrappedRpc, + rpc::MessageType wrappedMessageType, + std::vector tensors, + std::vector profiledEvents, + rpc::ProfilingId profilingId); + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const rpc::Message& message); + // Retrieve remote Events + std::vector getProfiledEvents() const; + // Retrieve the globally unique profiling ID corresponding to this command. + const rpc::ProfilingId& getProfilingId() const; + // Retrieve the original RPC which this ProfilingRPC wraps. + RpcCommandBase& wrappedRpc(); + // Destructively move the wrapped RPC. + std::unique_ptr moveWrappedRpc() &&; + // Message type of the wrapped RPC + rpc::MessageType wrappedMessageType() const; + // Set the wrapped RPC for this RPC. + void setWrappedRpc(std::unique_ptr wrappedRpc); + + private: + // message type + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const rpc::MessageType messageType_; + // wrapped message + c10::intrusive_ptr wrappedMessage_; + std::unique_ptr wrappedRpc_; + rpc::MessageType wrappedMessageType_; + std::vector tensors_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::vector profiledEvents_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const rpc::ProfilingId profilingId_; +}; +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_req.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_req.h new file mode 100644 index 0000000000000000000000000000000000000000..1cb78980aa6deeef29a2e918eaf87ed970b7a127 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_req.h @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::distributed::autograd { + +// Internal system RPC to invoke distributed backward pass on remote nodes when +// 'rref.backward()' is invoked. +class TORCH_API RRefBackwardReq : public rpc::RpcCommandBase { + public: + RRefBackwardReq( + const rpc::RRefId& rrefId, + int64_t autogradContextId, + bool retainGraph = false); + + const rpc::RRefId& getRRefId() const; + + int64_t getAutogradContextId() const; + + bool retainGraph() const; + + // Serialization and deserialization methods. + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const rpc::Message& message); + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const rpc::RRefId rrefId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const int64_t autogradContextId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool retainGraph_; +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h new file mode 100644 index 0000000000000000000000000000000000000000..c4bf412302ced62d07a5ca8a24675376f1ed2b68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::autograd { + +// Response for the RRefBackwardReq. +class TORCH_API RRefBackwardResp : public rpc::RpcCommandBase { + public: + RRefBackwardResp() = default; + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const rpc::Message& message); +}; + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..47903ceb5e9bf2491e8896cdc2fed920b03e9448 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/utils.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::autograd { + +// This method is used to attach the 'send' autograd function to the autograd +// graph when we use RPC. This method creates a new 'send' autograd function +// and attaches the provided tensors as next_edges to the 'send' function. In +// addition to this, it also registers the send function in the provided +// autograd context. Finally, the RPC message is updated with appropriate +// autograd information for the recipient. +TORCH_API void addSendRpcBackward( + const ContextPtr& autogradContext, + const AutogradMetadata& autogradMetadata, + std::vector& tensors); + +// This method is used to attach the 'recv' autograd function to the autograd +// graph when we use RPC. This method creates a new 'recv' autograd function +// and attaches the provided tensors as inputs to the 'recv' function. It +// creates a new autograd context if needed and registers the 'recv' function +// with this context. +// +// Returns a pointer to the autograd context created. +TORCH_API ContextPtr addRecvRpcBackward( + const AutogradMetadata& autogradMetadata, + std::vector& tensors, + rpc::worker_id_t fromWorkerId, + const rpc::DeviceMap& deviceMap); + +// This method is a wrapper utility used internally to wrap autograd info +// and attach autograd function for each type of rpc call if it has valid +// context and tensors require grads or forceGradRecording is true, in this +// case, return RpcWithAutograd message; otherwise return original rpc message. +// NB: forceGradRecording is useful when the request does not contain any tensor +// but the corresponding response does. +TORCH_API c10::intrusive_ptr getMessageWithAutograd( + const rpc::worker_id_t dstId, + c10::intrusive_ptr wrappedRpcMsg, + rpc::MessageType msgType, + bool forceGradRecording = false, + const rpc::DeviceMap& deviceMap = {}); + +// Send message after autograd checking +TORCH_API c10::intrusive_ptr sendMessageWithAutograd( + rpc::RpcAgent& agent, + const rpc::WorkerInfo& dst, + c10::intrusive_ptr wrappedRpcMsg, + bool forceGradRecording = false, + const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout, + bool forceDisableProfiling = false); + +} // namespace torch::distributed::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Backend.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Backend.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d8a979143f9119d48da9dac1a89a943ddf4a85f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Backend.hpp @@ -0,0 +1,535 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +constexpr auto kBackendDefaultTimeout = + std::chrono::milliseconds(30 * 60 * 1000); + +namespace c10d { + +enum class ErrorType { + SUCCESS = 0, + TIMEOUT = 1, + // e.g., NCCL error, etc + COMM_ERROR = 2, + // TODO, do we need to distinguish between remote timeout or remote COMM + // errors? + REMOTE_ERROR = 3 +}; + +class TORCH_API Backend : public torch::CustomClassHolder { + public: + // Backend Options is a base struct that defines the basic options + // when constructing a Backend. Each Backend subclass should + // extend this struct and define its options if it wants to provide more + // config options (beyond basic ones defined here) to end user. + struct TORCH_API Options : torch::CustomClassHolder { + explicit Options( + std::string backend, + std::chrono::milliseconds timeout = kBackendDefaultTimeout) + : timeout(timeout), backend(std::move(backend)) {} + ~Options() override = default; + + std::chrono::milliseconds timeout; + + // backend name + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::string backend; + std::string group_name; + std::vector global_ranks_in_group; + }; + + explicit Backend(int rank, int size); + ~Backend() override = 0; + + int getRank() const { + return rank_; + } + + int getSize() const { + return size_; + } + + // Returns an unique opaque ID of this backend that can be used to correlate + // with its collectives. + int64_t getID() const { + return reinterpret_cast(this); + } + + virtual bool supportsSplitting() const { + return false; + } + + virtual bool supportsCoalescing() const { + return false; + } + + virtual bool supportsTimeEstimation() const { + return false; + } + + virtual bool supportsShrinking() const { + return false; + } + + // Shrink the backend by excluding specified ranks. Backends that support + // communicator shrinking should override this and return a new backend + // instance representing the shrunken group. Backends may use opts_override + // to supply backend-specific options for the new group. + virtual c10::intrusive_ptr shrink( + const std::vector& /*ranks_to_exclude*/, + int /*shrink_flags*/ = 0, + const c10::intrusive_ptr& /*opts_override*/ = nullptr) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support shrink")); + } + + virtual void setTimeout(std::chrono::milliseconds timeout) { + TORCH_CHECK( + false, + c10::str( + "Backend ", getBackendName(), " does not support setting timeout")); + } + + virtual void startCoalescing() { + TORCH_CHECK( + false, + c10::str( + "Backend ", + getBackendName(), + " does not implement startCoalescing")); + } + + virtual c10::intrusive_ptr endCoalescing() { + TORCH_CHECK( + false, + c10::str( + "Backend ", getBackendName(), " does not implement endCoalescing")); + } + + // Subclasses must override this method to return the backend name + virtual const std::string getBackendName() const { + TORCH_INTERNAL_ASSERT(false, "getBackendName is not implemented."); + } + + // Subclasses must override this method to return the backend name + virtual c10::intrusive_ptr getBackendOptions() { + TORCH_CHECK( + false, + c10::str( + "Backend ", + getBackendName(), + " does not implement getBackendOptions.")); + } + + virtual c10::intrusive_ptr broadcast( + std::vector& /* tensors */, + const BroadcastOptions& /* opts */ = BroadcastOptions()) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support broadcast")); + } + + virtual c10::intrusive_ptr allreduce( + std::vector& /* tensors */, + const AllreduceOptions& /* opts */ = AllreduceOptions()) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support allreduce")); + } + + virtual c10::intrusive_ptr allreduce_sparse( + std::vector& /* tensors */, + const AllreduceOptions& /* opts */ = AllreduceOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", + getBackendName(), + " does not support allreduce sparse")); + } + + virtual c10::intrusive_ptr allreduce_coalesced( + std::vector& /* tensors */, + const AllreduceCoalescedOptions& /* opts */ = + AllreduceCoalescedOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", + getBackendName(), + " does not support allreduce_coalesced")); + } + + virtual c10::intrusive_ptr reduce( + std::vector& /* tensors */, + const ReduceOptions& /* opts */ = ReduceOptions()) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support reduce")); + } + + virtual c10::intrusive_ptr allgather( + std::vector>& /* outputTensors */, + std::vector& /* inputTensors */, + const AllgatherOptions& /* opts */ = AllgatherOptions()) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support allgather")); + } + + // Gathers a single tensor inputBuffer into a single buffer outputBuffer that + // is interpreted as a contiguous collection of size inputBuffer * WORLD_SIZE. + // For implementers of ProcessGroup API and advanced users only. + // Note: this function will be deprecated in near future. + virtual c10::intrusive_ptr _allgather_base( + at::Tensor& /* outputBuffer */, + at::Tensor& /* inputBuffer */, + const AllgatherOptions& /* opts */ = AllgatherOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", getBackendName(), " does not support _allgather_base")); + } + + // This function is deprecated and will be moved out of Backend to comms: + // * do not add dependencies on this function, + // * do not implement it in your Backend, implement _allgather_base + // instead. + virtual c10::intrusive_ptr allgather_coalesced( + std::vector>& /* outputTensorLists */, + std::vector& /* inputTensors */, + const AllgatherOptions& /* opts */ = AllgatherOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", + getBackendName(), + " does not support allgather_coalesced")); + } + + // This function is a coalesced version of `allgather_into_tensor` (currently + // still named as `_allgather_base`). Each tensor in the vector corresponds to + // an input/output of one `allgather_into_tensor` operation. + virtual c10::intrusive_ptr allgather_into_tensor_coalesced( + std::vector& /* outputs */, + std::vector& /* inputs */, + const AllgatherOptions& /* opts */ = AllgatherOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", + getBackendName(), + " does not support allgather_into_tensor_coalesced")); + } + + virtual c10::intrusive_ptr gather( + std::vector>& /* outputTensors */, + std::vector& /* inputTensors */, + const GatherOptions& /* opts */ = GatherOptions()) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support gather")); + } + + virtual c10::intrusive_ptr scatter( + std::vector& /* outputTensors */, + std::vector>& /* inputTensors */, + const ScatterOptions& /* opts */ = ScatterOptions()) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support scatter")); + } + + virtual c10::intrusive_ptr reduce_scatter( + std::vector& /* outputTensors */, + std::vector>& /* inputTensors */, + const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", getBackendName(), " does not support reduce_scatter")); + } + + virtual c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& /* outputBuffer */, + at::Tensor& /* inputBuffer */, + const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", + getBackendName(), + " does not support _reduce_scatter_base")); + } + + // This function is a coalesced version of `reduce_scatter_tensor` (currently + // still named as `_reduce_scatter_base`). Each tensor in the vector + // corresponds to an input/output of one `reduce_scatter_tensor` operation. + virtual c10::intrusive_ptr reduce_scatter_tensor_coalesced( + std::vector& /* outputs */, + std::vector& /* inputs */, + const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", + getBackendName(), + " does not support reduce_scatter_tensor_coalesced")); + } + + virtual c10::intrusive_ptr alltoall_base( + at::Tensor& /* outputBuffer */, + at::Tensor& /* inputBuffer */, + std::vector& /* outputSplitSizes */, + std::vector& /* inputSplitSizes */, + const AllToAllOptions& /* opts */ = AllToAllOptions()) { + TORCH_CHECK( + false, + c10::str( + "Backend ", getBackendName(), " does not support alltoall_base")); + } + + virtual c10::intrusive_ptr alltoall( + std::vector& /* outputTensors */, + std::vector& /* inputTensors */, + const AllToAllOptions& opts = AllToAllOptions()) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support alltoall")); + } + + virtual void monitoredBarrier( + const BarrierOptions& /* unused */, + bool /* unused */ = false) { + auto backendName = getBackendName(); + TORCH_CHECK( + false, + c10::str( + "Backend ", + backendName, + " does not support monitoredBarrier, only GLOO supports monitored barrier.")); + } + + // Agrees on an initial sequence number for the whole group by having rank 0 + // create it and broadcast it to other ranks using the store. Only implemented + // for GLOO and NCCL backends currently. + virtual void setSequenceNumberForGroup() { + auto backendName = getBackendName(); + TORCH_CHECK( + false, + c10::str( + "Backend ", + backendName, + " does not yet support sequence numbers.")); + } + + // Retrieves the current sequence number for the whole group, which should be + // in sync. If the returned number is not consistent across the group, it + // may indicate that there is some sort of collective desynchronization. + virtual uint64_t getSequenceNumberForGroup() { + auto backendName = getBackendName(); + TORCH_CHECK( + false, + c10::str( + "Backend ", + backendName, + " does not yet support sequence numbers.")); + } + + virtual c10::intrusive_ptr send( + std::vector& /* tensors */, + int /* dstRank */, + int /* tag */) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support send")); + } + + virtual c10::intrusive_ptr recv( + std::vector& /* tensors */, + int /* srcRank */, + int /* tag */) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support recv")); + } + + virtual c10::intrusive_ptr recvAnysource( + std::vector& /* tensors */, + int /* tag */) { + TORCH_CHECK( + false, + c10::str( + "Backend ", getBackendName(), " does not support recvAnysource")); + } + + virtual c10::intrusive_ptr barrier( + const BarrierOptions& /* opts */ = BarrierOptions()) { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support barrier")); + } + + virtual void registerOnCompletionHook( + std::function)>&& hook) { + TORCH_CHECK( + false, + "Only ProcessGrouppNCCL supports onCompletion hook, but got ", + getBackendName(), + " backend."); + } + + virtual void waitForPendingWorks() { + TORCH_CHECK( + false, + "Only ProcessGrouppNCCL supports waitForPendingWorks, but got ", + getBackendName(), + " backend."); + } + + virtual void enableCollectivesTiming() { + TORCH_CHECK( + false, + "Backend ", + getBackendName(), + " is missing implementation of enableCollectivesTiming."); + } + + virtual c10::intrusive_ptr split( + const c10::intrusive_ptr& store, + const std::vector& ranks, + const c10::intrusive_ptr& opts) { + TORCH_CHECK( + false, + "Backend ", + getBackendName(), + " is missing implementation of split."); + } + + virtual c10::intrusive_ptr merge( + const c10::intrusive_ptr& store, + const c10::intrusive_ptr& opts, + const int& rank, + const int& size) { + TORCH_CHECK( + false, + "Backend ", + getBackendName(), + " is missing implementation of merge."); + } + + bool hasHooks() const { + return onCompletionHook_ != nullptr; + } + + // Do not call this directly, use ProcessGroup::setGroupName instead. + virtual void setGroupUid(const std::string& pg_uid) { + pg_uid_ = pg_uid; + } + + const std::string& getGroupUid() const { + return pg_uid_; + } + + void setGroupDesc(const std::string& desc) { + pg_desc_ = desc; + } + + const std::string& getGroupDesc() const { + return pg_desc_; + } + + // See similar functions in ProcessGroup.hpp for context. + std::optional getBoundDeviceId() const { + return bound_device_id_; + } + + // Perform an eager connect to the specified device if the backend supports + // it. + virtual void eagerConnectSingleDevice(at::Device device) { + // no-op in the default case; this is an optimization some + // backends may perform + } + + void setBoundDeviceId(std::optional device) { + if (device) { + TORCH_CHECK(device->has_index(), "setBoundDeviceId must have an index"); + } + bound_device_id_ = device; + } + + virtual ErrorType getError() { + TORCH_CHECK( + false, + c10::str("Backend ", getBackendName(), " does not support getError")); + } + + virtual std::shared_ptr getMemAllocator() { + TORCH_CHECK( + false, + c10::str( + "Backend ", getBackendName(), " does not support getMemAllocator")); + } + + // Allocate tensor (aten::empty) from backend's communication-optimized memory + // pool + virtual at::Tensor allocateTensor(long size, at::TensorOptions options = {}) { + TORCH_CHECK( + false, + c10::str( + "Backend ", getBackendName(), " does not support allocateTensor")); + } + + // Returns true if backend supports tensor allocation + virtual bool supportsTensorAlloc(c10::DeviceIndex deviceIdx) { + // Change to true in concrete backend if supported + return false; + } + + // Aborts all pending operations and connections in the backend if the backend + // supports it. + virtual void abort() {} + + // Shutdown the backend if the backend supports it. This should be used for + // normal shutdown. + virtual void shutdown() {} + + protected: + // Implementations of this interface need to call this to setup + // appropriate logging etc. + void init(); + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const int rank_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const int size_; + // Debug level setting. It is parsed once when ProcessGroup is constructed and + // remains the same across use of this process group. + DebugLevel dist_debug_level_; + std::string pg_uid_; + std::string pg_desc_; + + std::function)> onCompletionHook_; + + std::optional bound_device_id_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Backoff.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Backoff.hpp new file mode 100644 index 0000000000000000000000000000000000000000..329dc1f97857e93886096a508bcde1b20c75146d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Backoff.hpp @@ -0,0 +1,57 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace c10d { + +class TORCH_API Backoff { + public: + virtual ~Backoff() = default; + + virtual std::chrono::milliseconds nextBackoff() = 0; + virtual void reset() = 0; + + void sleepBackoff() { + std::this_thread::sleep_for(nextBackoff()); + } +}; + +class TORCH_API ExponentialBackoffWithJitter : public Backoff { + public: + ExponentialBackoffWithJitter(); + + std::chrono::milliseconds nextBackoff() override; + void reset() override; + + public: + std::chrono::milliseconds initialInterval{500}; + double randomizationFactor{0.5}; + double multiplier{1.5}; + std::chrono::milliseconds maxInterval{60000}; + + private: + std::mt19937 gen_; + std::chrono::milliseconds currentInterval_{0}; +}; + +class TORCH_API FixedBackoff : public Backoff { + public: + FixedBackoff(std::chrono::milliseconds interval); + + std::chrono::milliseconds nextBackoff() override; + void reset() override; + + private: + std::chrono::milliseconds interval_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FakeProcessGroup.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FakeProcessGroup.hpp new file mode 100644 index 0000000000000000000000000000000000000000..453d2f4e64f83cf9466ce951e8be8a4f666a1393 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FakeProcessGroup.hpp @@ -0,0 +1,258 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace c10d { + +class FakeWork : public Work { + public: + int seq_id = -1; + bool wait(std::chrono::milliseconds timeout = kNoTimeout) override { + return true; + } + + c10::intrusive_ptr getFuture() override { + auto fut = c10::make_intrusive(c10::NoneType::get()); + fut->markCompleted(); + return fut; + } +}; + +class FakeProcessGroup : public Backend { + public: + struct Options : Backend::Options { + explicit Options() : Backend::Options("fake") {} + + int fake_option = 0; + bool error_on_collective = false; + }; + + // Static factory method for official APIs + static c10::intrusive_ptr _create_internal( + int rank, + int size, + c10::intrusive_ptr options = c10::make_intrusive()) { + return c10::make_intrusive( + rank, size, std::move(options)); + } + + const std::string getBackendName() const override { + return "fake"; + } + + c10::intrusive_ptr getBackendOptions() override { + return c10::static_intrusive_pointer_cast(options_); + } + + c10::intrusive_ptr broadcast( + std::vector& /* tensors */, + const BroadcastOptions& /* opts */ = BroadcastOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr allreduce( + std::vector& /* tensors */, + const AllreduceOptions& /* opts */ = AllreduceOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr allreduce_sparse( + std::vector& /* tensors */, + const AllreduceOptions& /* opts */ = AllreduceOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr allreduce_coalesced( + std::vector& /* tensors */, + const AllreduceCoalescedOptions& /* opts */ = + AllreduceCoalescedOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr reduce( + std::vector& /* tensors */, + const ReduceOptions& /* opts */ = ReduceOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + // NOTE [allgather on FakeProcessGroup] + // Assume each rank have the same input tensor so we just copy to the results + // since it's not a real allgather, we simply make this copying logic to let + // some simple validation works (i.e. calling allgather to see if each rank + // have the same tensor or not). + // + // NOTE: in general it's not good form to try to make FakeProcessGroup work + // with real data, but the reasoning here is that we want FakeProcessGroup to + // work with DeviceMesh's init code that have the data validation, which + // makes it worth the tradeoff. + c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& /* opts */ = AllgatherOptions()) override { + checkCollectiveError(); + for (auto& tensor : outputTensors[0]) { + tensor.copy_(inputTensors[0]); + } + return c10::make_intrusive(); + } + + c10::intrusive_ptr _allgather_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + const AllgatherOptions& /* opts */ = AllgatherOptions()) override { + checkCollectiveError(); + auto chunks = outputBuffer.chunk(size_); + for (auto& tensor : chunks) { + tensor.copy_(inputBuffer); + } + return c10::make_intrusive(); + } + + c10::intrusive_ptr allgather_coalesced( + std::vector>& /* outputTensorLists */, + std::vector& /* inputTensors */, + const AllgatherOptions& /* opts */ = AllgatherOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr allgather_into_tensor_coalesced( + std::vector& outputs, + std::vector& inputs, + const AllgatherOptions& /* opts */ = AllgatherOptions()) override { + checkCollectiveError(); + for (size_t i = 0; i < outputs.size(); ++i) { + auto chunks = outputs[i].chunk(size_); + for (auto& chunk : chunks) { + chunk.copy_(inputs[i]); + } + } + return c10::make_intrusive(); + } + + c10::intrusive_ptr gather( + std::vector>& /* outputTensors */, + std::vector& /* inputTensors */, + const GatherOptions& /* opts */ = GatherOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr scatter( + std::vector& /* outputTensors */, + std::vector>& /* inputTensors */, + const ScatterOptions& /* opts */ = ScatterOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr reduce_scatter( + std::vector& /* outputTensors */, + std::vector>& /* inputTensors */, + const ReduceScatterOptions& /* opts */ = + ReduceScatterOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& /* outputBuffer */, + at::Tensor& /* inputBuffer */, + const ReduceScatterOptions& /* opts */ = + ReduceScatterOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr reduce_scatter_tensor_coalesced( + std::vector& /* outputs */, + std::vector& /* inputs */, + const ReduceScatterOptions& /* opts */ = + ReduceScatterOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr alltoall_base( + at::Tensor& /* outputBuffer */, + at::Tensor& /* inputBuffer */, + std::vector& /* outputSplitSizes */, + std::vector& /* inputSplitSizes */, + const AllToAllOptions& /* opts */ = AllToAllOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr alltoall( + std::vector& /* outputTensors */, + std::vector& /* inputTensors */, + const AllToAllOptions& opts = AllToAllOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr send( + std::vector& /* tensors */, + int /* dstRank */, + int /* tag */) override { + return c10::make_intrusive(); + } + + c10::intrusive_ptr recv( + std::vector& /* tensors */, + int /* srcRank */, + int /* tag */) override { + return c10::make_intrusive(); + } + + c10::intrusive_ptr recvAnysource( + std::vector& /* tensors */, + int /* tag */) override { + return c10::make_intrusive(); + } + + void startCoalescing() override { + // No-op + } + + c10::intrusive_ptr endCoalescing(OpType /* optype */) { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr endCoalescing() override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + c10::intrusive_ptr barrier( + const BarrierOptions& /* opts */ = BarrierOptions()) override { + checkCollectiveError(); + return c10::make_intrusive(); + } + + // Private constructor used by official APIs + FakeProcessGroup(int rank, int size, c10::intrusive_ptr options) + : Backend(rank, size), options_(std::move(options)) {} + c10::intrusive_ptr options_; + + private: + void checkCollectiveError() { + TORCH_CHECK( + !options_ || !options_->error_on_collective, + "FakeProcessGroup collective operation error (error_on_collective=true)"); + } +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FileStore.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FileStore.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7725d9856572a906d688992dd6eaa284d019887d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FileStore.hpp @@ -0,0 +1,72 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +#include + +namespace c10d { + +class TORCH_API FileStore : public Store { + public: + explicit FileStore(std::string path, int numWorkers); + + c10::intrusive_ptr clone() override; + + ~FileStore() override; + + void set(const std::string& key, const std::vector& value) override; + + std::vector compareSet( + const std::string& key, + const std::vector& expectedValue, + const std::vector& desiredValue) override; + + std::vector get(const std::string& key) override; + + int64_t add(const std::string& key, int64_t value) override; + + int64_t getNumKeys() override; + + bool deleteKey(const std::string& key) override; + + bool check(const std::vector& keys) override; + + void wait(const std::vector& keys) override; + + void wait( + const std::vector& keys, + const std::chrono::milliseconds& timeout) override; + + // Returns the path used by the FileStore. + const std::string& getPath() const noexcept { + return path_; + } + + std::vector listKeys() override; + + protected: + int64_t addHelper(const std::string& key, int64_t i); + + std::string path_; + off_t pos_{0}; + + int numWorkers_; + const std::string cleanupKey_; + const std::string refCountKey_; + const std::string regularPrefix_; + const std::string deletePrefix_; + + std::unordered_map> cache_; + + std::mutex activeFileOpLock_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FlightRecorder.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FlightRecorder.hpp new file mode 100644 index 0000000000000000000000000000000000000000..87a2cce06f6c36d365988cd664464a6827b2f068 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FlightRecorder.hpp @@ -0,0 +1,333 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace c10d { + +#define DEFINE_CONSTANT(name, value) \ + static c10::IValue name = value; \ + static std::string name##_str = value; +// Update whenever changing contents or formatting of the dump +// (minor when adding fields, major when changing existing fields) +// Also update both JSON and Pickle dumps to make use of the newly defined +// field(s). +DEFINE_CONSTANT(version_val, "2.10") +DEFINE_CONSTANT(entries_key, "entries") +DEFINE_CONSTANT(nccl_comm_key, "nccl_comm_state") +DEFINE_CONSTANT(comm_lib_version_key, "comm_lib_version") +DEFINE_CONSTANT(version_key, "version") +DEFINE_CONSTANT(pg_config_key, "pg_config") +DEFINE_CONSTANT(pg_status_key, "pg_status") +DEFINE_CONSTANT(record_id_key, "record_id") +DEFINE_CONSTANT(pg_id_key, "pg_id") +DEFINE_CONSTANT(pg_name_key, "process_group") +DEFINE_CONSTANT(collective_seq_id_key, "collective_seq_id") +DEFINE_CONSTANT(p2p_seq_id_key, "p2p_seq_id") +DEFINE_CONSTANT(is_p2p_key, "is_p2p") +DEFINE_CONSTANT(op_id_key, "op_id") +DEFINE_CONSTANT(profiling_name_key, "profiling_name") +DEFINE_CONSTANT(input_sizes_key, "input_sizes") +DEFINE_CONSTANT(input_dtypes_key, "input_dtypes") +DEFINE_CONSTANT(output_sizes_key, "output_sizes") +DEFINE_CONSTANT(output_dtypes_key, "output_dtypes") +DEFINE_CONSTANT(time_created_key, "time_created_ns") +DEFINE_CONSTANT(duration_key, "duration_ms") +DEFINE_CONSTANT(timeout_key, "timeout_ms") +DEFINE_CONSTANT(frames_key, "frames") +DEFINE_CONSTANT(state_key, "state") +DEFINE_CONSTANT(line_key, "line") +DEFINE_CONSTANT(name_key, "name") +DEFINE_CONSTANT(filename_key, "filename") +DEFINE_CONSTANT(retired_key, "retired") +DEFINE_CONSTANT(time_discovered_started_key, "time_discovered_started_ns") +DEFINE_CONSTANT(time_discovered_completed_key, "time_discovered_completed_ns") +DEFINE_CONSTANT(completed_state, "completed") +DEFINE_CONSTANT(scheduled_state, "scheduled") +DEFINE_CONSTANT(started_state, "started") +DEFINE_CONSTANT(thread_id_key, "thread_id") +DEFINE_CONSTANT(thread_name_key, "thread_name") +#undef DEFINE_CONSTANT + +// Write NCCL debug info to local disk or any storage users define. +// There are some constrains we set for the debug info writer: +// 1. The writer should only be registered once. +// 2. Once registered, users cannot change it including un-register. +// 3. It is recommended to register the customized writer in the trainer setup, +// If users don't register before calling launchAsyncDebugDump, then users +// lose the chance to register (and the default writer will be +// auto-registered). +class TORCH_API DebugInfoWriter { + public: + virtual ~DebugInfoWriter() = default; + virtual void write(const std::string& trace); + static DebugInfoWriter& getWriter(int rank); + static void registerWriter(std::unique_ptr writer); + virtual std::string getWriterTarget() { + return filename_; + } + + protected: + DebugInfoWriter( + const std::string& namePrefix, + int rank, + bool enableDynamicFilename = false) { + filename_ = c10::str(namePrefix, rank); + enable_dynamic_filename_ = enableDynamicFilename; + rank_ = rank; + } + std::string filename_; + int rank_; + bool enable_dynamic_filename_; + + private: + static std::unique_ptr writer_; + static std::atomic hasWriterRegistered_; +}; + +template +struct FlightRecorder { + static FlightRecorder* get() { + // intentionally leak on exit + // because this will hold python state that may get destructed + static FlightRecorder* instance = + new FlightRecorder(); + return instance; + } + FlightRecorder() { + max_entries_ = + getCvarInt({"TORCH_FR_BUFFER_SIZE", "TORCH_NCCL_TRACE_BUFFER_SIZE"}, 0); + capture_cpp_stack_ = getCvarBool( + {"TORCH_FR_CPP_STACK", "TORCH_NCCL_TRACE_CPP_STACK"}, false); + enabled_ = max_entries_ > 0; + reset_epoch_start_idx_[0] = 0; + } + struct Entry { + size_t id_; // incremented id in the trace buffer + // used to figure out where in the circular entries + // buffer this entry will be located to + // update state information + size_t reset_epoch_; // epoch when this entry was created + size_t pg_id_; + std::tuple pg_name_; // + + // collective_seq_id and p2p_seq_id refer to actual kernel launches (e.g. 1 + // per coalesced group). + // collective_seq_id only increments for true collective operations (over + // all ranks in the group). p2p_seq_id only increments over non-collective + // operations in the group. op_id refers to logical operations (e.g. one per + // op inside coalesced group) + size_t collective_seq_id_; + size_t p2p_seq_id_; + size_t op_id_; + std::string profiling_name_; + + std::shared_ptr traceback_; + // we borrow pointers to start_ and end_ so we can query the state + // on reporting. However, once the event is completed, the call + // to `complete` will clear these. + EventType *start_, *end_; + + // timestamp when the entry was created, likely close to the time the work + // was 'enqueued'- not necessarily started + c10::time_t time_created_; + + // configured timeout for this entry + c10::time_t timeout_ms_; + + // Is this a P2P event? + bool isP2P_; + + std::optional duration_; + + // timestamp when our CPU threads discovered that the kernel started. + // will always be _after_ it actually started, and can be very late + // if the watchdog thread got stuck on CUDA APIs. + std::optional time_discovered_started_; + + // timestamp when our CPU threads discovered that the kernel completed. + // will always be _after_ it actually completed, and can be the same time + // as the discovery of the start if the watchdog thread is stuck on CUDA + // APIs + std::optional time_discovered_completed_; + + // size information for input/output tensors + c10::SmallVector input_dims_; + std::vector input_dtypes_; + c10::SmallVector output_dims_; + std::vector output_dtypes_; + c10::SmallVector sizes_; // flattened from inputs, outputs + std::thread::id thread_id_; + std::string thread_name_; + bool retired_ = false; // is this work entry no longer in the workMetaList_? + // a retired but not completed event has timed out + + // Returns the traceback of current entry, in string form. + // Note: `getTraceback` invokes `torch::symbolize`, which may need to + // acquire the GIL. If you don't want to block the current thread or take + // the risk of a GIL deadlock, you can use an asynchronous calling mechanism + // like std::async. + TORCH_API std::string getTraceback(); + }; + + bool enabled_ = false; + bool capture_cpp_stack_ = false; + std::mutex mutex_; + std::vector entries_; + size_t max_entries_ = 0; + size_t next_ = 0; + size_t id_ = 0; + size_t reset_epoch_ = 0; + std::unordered_map + reset_epoch_start_idx_; // maps reset_epoch to the idx where it starts + std::map> all_pg_status_; + std::map, std::vector> + pg_name_to_ranks_; + std::string comm_lib_version_; + + struct TraceIdentifier { + std::optional id; + std::optional reset_epoch; + }; + + TraceIdentifier recordWithResetEnabled( + size_t pg_id, + const std::tuple& pg_name, + size_t collective_seq_id, + size_t p2p_seq_id, + size_t op_id, + std::string profiling_name, + const std::vector& inputs, + const std::vector& outputs, + EventType* start, + EventType* end, + std::chrono::milliseconds timeout_ms, + std::shared_ptr pg_status, + bool isP2P); + + std::optional record( + size_t pg_id, + const std::tuple& pg_name, + size_t collective_seq_id, + size_t p2p_seq_id, + size_t op_id, + std::string profiling_name, + const std::vector& inputs, + const std::vector& outputs, + EventType* start, + EventType* end, + std::chrono::milliseconds timeout_ms, + std::shared_ptr pg_status, + bool isP2P); + + TORCH_API void record_pg_ranks( + const std::tuple& pg_name, + std::vector ranks); + + void record_accelerator_version(const std::string comm_lib_version); + + void update_state(Entry& r); + + std::vector dump_entries(); + + // Returns the index in entries_ for the given id and reset_epoch. + // Caller must hold mutex_lock before calling this method. + size_t getIdxFromId(size_t id, size_t reset_epoch) const; + + // Returns the entry with the given id and reset_epoch, if it exists. + // Otherwise, returns std::nullopt. + TORCH_API std::optional getEntry( + std::optional id, + std::optional reset_epoch); + + TORCH_API std::optional getEntry(std::optional id); + + /* + Mark an Event as completed and free its events. + This is called by the watchdog thread, and is asynchronous from the + perspective of the main thread. + compute_duration defaults to true since retire_id is only called in the + watchdog thread, which is currently a place we call cuda APIs which may hang, + but care should be taken to avoid computing duration in any function that must + never hang. (timing must also be enabled for compute_duration - see + TORCH_NCCL_ENABLE_TIMING). + */ + TORCH_API void retire_id( + std::optional id, + std::optional reset_epoch, + bool compute_duration = true); + + TORCH_API void retire_id( + std::optional id, + bool compute_duration = true); + + TORCH_API void reset_all(); + + const c10::List getCollectiveTrace( + bool includeStacktraces, + bool onlyActive); + + // dump pg_entries + const c10::Dict getPgConfig(); + + const std::map> + getPgConfigJson(); + + // dump pg_status + const c10::Dict getPgStatus(); + + const std::map> + getPgStatusJson(); + + std::string dump_json( + const std::optional>>& extraDumpMap, + bool includeCollectives, + bool onlyActive); + + std::string dump( + const std::optional>>& extraDumpMap, + bool includeCollectives, + bool includeStackTraces, + bool onlyActive); +}; + +// Whether to include stack trace in the Flight Recorder trace (default true) +static std::vector TORCH_INCLUDE_STACK_TRACE = { + "TORCH_INCLUDE_STACK_TRACE"}; + +// Whether to include only active collectives in the Flight Recorder trace +// (default false) +static std::vector TORCH_INCLUDE_ONLY_ACTIVE = { + "TORCH_INCLUDE_ONLY_ACTIVE"}; + +// Dumps the fr traces and additional information about the Process +// Group. +TORCH_API std::string dump_fr_trace( + bool includeCollectives, + bool includeStackTraces, + bool onlyActive); + +// Dumps the fr traces and additional information about the Process +// Group in JSON formatted string. +// We don't include stack traces in JSON format as it is far too much data. +TORCH_API std::string dump_fr_trace_json( + bool includeCollectives, + bool onlyActive); +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FlightRecorderDetail.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FlightRecorderDetail.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0567b3076c3e534363aa0ad13c0a763c73ff5065 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FlightRecorderDetail.hpp @@ -0,0 +1,641 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +#include +#include + +#include + +namespace c10d { + +template +float getDurationFromEvent(EventType& start, EventType& end); + +// Returns the traceback of current entry, in string form. +// Note: `getTraceback` invokes `torch::symbolize`, which may need to acquire +// the GIL. If you don't want to block the current thread or take the risk of a +// GIL deadlock, you can use an asynchronous calling mechanism like std::async. +template +std::string FlightRecorder::Entry::getTraceback() { + torch::CapturedTraceback* traceback = traceback_.get(); + torch::SymbolizedTracebacks s_tbs = torch::symbolize({traceback}); + // We use 0 because we only have one traceback here. + const auto& s_tb = s_tbs.tracebacks.at(0); + std::stringstream oss; + for (auto idx : c10::irange(s_tb.size())) { + auto frame_id = s_tb[idx]; + const auto& frame = s_tbs.all_frames.at(frame_id); + oss << '#' << idx << ' ' << frame.funcname << " from " << frame.filename + << ':' << frame.lineno << '\n'; + } + /* Resulted format is like: + #0 all_reduce from pytorch/torch/distributed/distributed_c10d.py:2696 + #1 wrapper from pytorch/torch/distributed/c10d_logger.py:83 + #2 bar from /home/user/repro.py:15 + #3 foo from /home/user/repro.py:24 + #4 main from /home/user/repro.py:34 + #5 from /home/user/repro.py:40 + */ + return oss.str(); +} + +template +std::optional FlightRecorder::record( + size_t pg_id, + const std::tuple& pg_name, + size_t collective_seq_id, + size_t p2p_seq_id, + size_t op_id, + std::string profiling_name, + const std::vector& inputs, + const std::vector& outputs, + EventType* start, + EventType* end, + std::chrono::milliseconds timeout_ms, + std::shared_ptr pg_status, + bool isP2P) { + auto result = recordWithResetEnabled( + pg_id, + pg_name, + collective_seq_id, + p2p_seq_id, + op_id, + std::move(profiling_name), + inputs, + outputs, + start, + end, + timeout_ms, + std::move(pg_status), + isP2P); + return result.id; +} + +template +typename FlightRecorder::TraceIdentifier FlightRecorder:: + recordWithResetEnabled( + size_t pg_id, + const std::tuple& pg_name, + size_t collective_seq_id, + size_t p2p_seq_id, + size_t op_id, + std::string profiling_name, + const std::vector& inputs, + const std::vector& outputs, + EventType* start, + EventType* end, + std::chrono::milliseconds timeout_ms, + std::shared_ptr pg_status, + bool isP2P) { + if (!enabled_) { + return TraceIdentifier{std::nullopt, std::nullopt}; + } + if (all_pg_status_.find(pg_id) == all_pg_status_.end()) { + // Current pg_status is not in FR. + all_pg_status_[pg_id] = std::move(pg_status); + } + auto traceback = + torch::CapturedTraceback::gather(true, true, capture_cpp_stack_); + std::lock_guard guard(mutex_); + + TORCH_CHECK( + reset_epoch_start_idx_.find(reset_epoch_) != + reset_epoch_start_idx_.end()); + + auto te = Entry{ + id_, + reset_epoch_, + pg_id, + pg_name, + collective_seq_id, + p2p_seq_id, + op_id, + std::move(profiling_name), + std::move(traceback), + start, + end, + c10::getTime(), + timeout_ms.count(), + isP2P, + std::nullopt, + std::nullopt, + std::nullopt, + {}, + {}, + {}, + {}, + {}, + std::this_thread::get_id(), + c10::getThreadName(), + false}; + + for (const auto& input : inputs) { + c10::IntArrayRef sizes = input.sizes(); + te.input_dtypes_.push_back(input.dtype().toScalarType()); + te.input_dims_.push_back(static_cast(sizes.size())); + te.sizes_.insert(te.sizes_.end(), sizes.begin(), sizes.end()); + } + + for (const auto& output : outputs) { + c10::IntArrayRef sizes = output.sizes(); + te.output_dtypes_.push_back(output.dtype().toScalarType()); + te.output_dims_.push_back(static_cast(sizes.size())); + te.sizes_.insert(te.sizes_.end(), sizes.begin(), sizes.end()); + } + + const auto next = next_++; + + if (entries_.size() < max_entries_) { + entries_.emplace_back(std::move(te)); + } else { + entries_[next] = std::move(te); + } + + if (next_ == max_entries_) { + next_ = 0; + } + + const auto id = id_++; + return TraceIdentifier{id, reset_epoch_}; +} + +template +void FlightRecorder::record_pg_ranks( + const std::tuple& pg_name, + std::vector ranks) { + if (!enabled_) { + return; + } + std::lock_guard guard(mutex_); + pg_name_to_ranks_[pg_name] = std::move(ranks); +} + +template +void FlightRecorder::record_accelerator_version( + const std::string comm_lib_version) { + if (!enabled_) { + return; + } + std::lock_guard guard(mutex_); + comm_lib_version_ = std::move(comm_lib_version); +} + +template +void FlightRecorder::update_state(Entry& r) { + try { + if (r.start_ != nullptr) { + bool started = r.start_->query(); + if (started && !r.time_discovered_started_) { + r.time_discovered_started_ = c10::getTime(); + } + } + if (r.end_ != nullptr) { + bool completed = r.end_->query(); + if (completed && !r.time_discovered_completed_) { + r.time_discovered_completed_ = c10::getTime(); + } + } + } catch (std::exception& e) { + LOG(ERROR) << "Failed to update state for entry " << r.id_ << ": " + << r.profiling_name_ << " with error: " << e.what(); + } +} + +template +std::vector::Entry> FlightRecorder< + EventType>::dump_entries() { + std::vector result; + { + std::lock_guard guard(mutex_); + // Filter entries during insertion - only keep entries from current epoch + auto filter = [this](const Entry& e) { + return e.reset_epoch_ == reset_epoch_; + }; + std::copy_if( + entries_.begin() + static_cast(next_), + entries_.end(), + std::back_inserter(result), + filter); + std::copy_if( + entries_.begin(), + entries_.begin() + static_cast(next_), + std::back_inserter(result), + filter); + } + // query any remaining events + for (auto& r : result) { + update_state(r); + r.start_ = r.end_ = nullptr; + } + return result; +} + +template +// Returns the index in entries_ for the given id and reset_epoch. +// Caller must hold mutex_lock before calling this method. +size_t FlightRecorder::getIdxFromId(size_t id, size_t reset_epoch) + const { + // Look up the starting idx for the given reset epoch + auto it = reset_epoch_start_idx_.find(reset_epoch); + TORCH_CHECK(it != reset_epoch_start_idx_.end()); + // Calculate idx based on where the epoch started + return (it->second + id) % max_entries_; +} + +template +// Returns the entry with the given id and reset_epoch, if it exists. Otherwise, +// returns std::nullopt. +std::optional::Entry> FlightRecorder< + EventType>:: + getEntry(std::optional id, std::optional reset_epoch) { + if (!enabled_ || !id || !reset_epoch) { + return std::nullopt; + } + + std::unique_lock guard(mutex_); + Entry entry = entries_.at(getIdxFromId(*id, *reset_epoch)); + if (entry.id_ == *id && entry.reset_epoch_ == *reset_epoch) { + return entry; + } + return std::nullopt; +} + +template +std::optional::Entry> FlightRecorder< + EventType>::getEntry(std::optional id) { + return getEntry(id, 0); +} + +template +void FlightRecorder::retire_id( + std::optional id, + std::optional reset_epoch, + bool compute_duration) { + if (!enabled_ || !id || !reset_epoch) { + return; + } + + bool can_compute_duration = false; + EventType* startEvent = nullptr; + EventType* endEvent = nullptr; + std::optional duration = std::nullopt; + + std::unique_lock guard(mutex_); + + Entry* entry = &entries_.at(getIdxFromId(*id, *reset_epoch)); + if (entry->id_ == *id && entry->reset_epoch_ == *reset_epoch) { + update_state(*entry); + + if (compute_duration) { + can_compute_duration = entry->time_discovered_completed_.has_value() && + entry->start_ && entry->end_; + startEvent = entry->start_; + endEvent = entry->end_; + } + entry->retired_ = true; + entry->start_ = entry->end_ = nullptr; + } + + if (can_compute_duration) { + // Compute duration without without holding the lock, because + // cudaEventDuration() can hang, and we need to acquire the lock before we + // can dump(), which we never want to block. + guard.unlock(); + duration = getDurationFromEvent(*startEvent, *endEvent); + guard.lock(); + + // Refresh the entry pointer, see if the entry has been overwritten + entry = &entries_.at(getIdxFromId(*id, *reset_epoch)); + if (!(entry->id_ == *id && entry->reset_epoch_ == *reset_epoch)) { + LOG(INFO) << "retire_id abandoned for id " << *id + << ", event was overwritten while waiting to compute duration."; + return; + } + if (duration.has_value()) { + entry->duration_ = duration; + } + } +} + +template +void FlightRecorder::retire_id( + std::optional id, + bool compute_duration) { + retire_id(id, 0, compute_duration); +} + +template +void FlightRecorder::reset_all() { + std::lock_guard guard(mutex_); + if (!entries_.empty()) { + // Soft delete: increment epoch to mark all existing entries as old + // Store where the new epoch starts in the circular buffer + reset_epoch_++; + reset_epoch_start_idx_[reset_epoch_] = next_; + id_ = 0; + } +} + +template +const c10::List FlightRecorder::getCollectiveTrace( + bool includeStacktraces, + bool onlyActive) { + auto entries = new_list(); + // Entries are returned in the order they were recorded + auto result = dump_entries(); + std::vector tracebacks; + torch::SymbolizedTracebacks stracebacks; + std::vector all_frames; + if (includeStacktraces) { + for (auto& e : result) { + tracebacks.push_back(e.traceback_.get()); + } + stracebacks = torch::symbolize(tracebacks); + for (const auto& f : stracebacks.all_frames) { + auto d = new_dict(); + d.insert(name_key, f.funcname); + d.insert(filename_key, f.filename); + d.insert(line_key, int64_t(f.lineno)); + all_frames.emplace_back(std::move(d)); + } + } + for (auto i : c10::irange(result.size())) { + auto dict = new_dict(); + auto& e = result.at(i); + // Skip completed events + if (onlyActive && e.time_discovered_completed_.has_value()) { + continue; + } + if (includeStacktraces) { + auto& tb = stracebacks.tracebacks.at(i); + auto frames = new_list(); + for (auto frame : tb) { + frames.push_back(all_frames.at(frame)); + } + dict.insert(frames_key, frames); + } + + dict.insert(record_id_key, int64_t(e.id_)); + dict.insert(pg_id_key, int64_t(e.pg_id_)); + dict.insert(pg_name_key, e.pg_name_); + dict.insert(thread_name_key, e.thread_name_); + dict.insert(thread_id_key, c10::str(e.thread_id_)); + dict.insert(collective_seq_id_key, int64_t(e.collective_seq_id_)); + dict.insert(p2p_seq_id_key, int64_t(e.p2p_seq_id_)); + dict.insert(op_id_key, int64_t(e.op_id_)); + dict.insert(profiling_name_key, e.profiling_name_); + dict.insert(time_created_key, int64_t(e.time_created_)); + if (e.duration_) { + dict.insert(duration_key, *e.duration_); + } + + auto it = e.sizes_.begin(); + auto read_sizes = [&](const c10::SmallVector& dims) { + auto sizes = new_list(); + for (auto dim : dims) { + auto arg_sizes = new_list(); + for ([[maybe_unused]] auto i : c10::irange(dim)) { + arg_sizes.push_back(*it++); + } + sizes.push_back(arg_sizes); + } + return sizes; + }; + + dict.insert(input_sizes_key, read_sizes(e.input_dims_)); + std::vector input_dtypes_strs; + input_dtypes_strs.reserve(e.input_dtypes_.size()); + for (const auto& input_dtype : e.input_dtypes_) { + input_dtypes_strs.emplace_back(c10::toString(input_dtype)); + } + dict.insert(input_dtypes_key, input_dtypes_strs); + dict.insert(output_sizes_key, read_sizes(e.output_dims_)); + std::vector output_dtypes_strs; + output_dtypes_strs.reserve(e.output_dtypes_.size()); + for (const auto& output_dtype : e.output_dtypes_) { + output_dtypes_strs.emplace_back(c10::toString(output_dtype)); + } + dict.insert(output_dtypes_key, output_dtypes_strs); + if (e.time_discovered_completed_.has_value()) { + dict.insert(state_key, completed_state); + } else if (e.time_discovered_started_.has_value()) { + dict.insert(state_key, started_state); + } else { + dict.insert(state_key, scheduled_state); + } + + dict.insert( + time_discovered_started_key, + e.time_discovered_started_.has_value() + ? int64_t(*e.time_discovered_started_) + : c10::IValue()); + dict.insert( + time_discovered_completed_key, + e.time_discovered_completed_.has_value() + ? int64_t(*e.time_discovered_completed_) + : c10::IValue()); + dict.insert(retired_key, e.retired_); + dict.insert(timeout_key, e.timeout_ms_); + dict.insert(is_p2p_key, e.isP2P_); + + entries.push_back(dict); + } + return entries; +} + +template +const c10::Dict FlightRecorder< + EventType>::getPgConfig() { + auto pg_config = new_dict(); + for (const auto& [pg_name, ranks] : pg_name_to_ranks_) { + auto pg_info = new_dict(); + pg_info.insert("name", std::get<0>(pg_name)); + pg_info.insert("desc", std::get<1>(pg_name)); + pg_info.insert("ranks", ranks_str(ranks)); + pg_config.insert(std::get<0>(pg_name), pg_info); + } + return pg_config; +} + +template +const std::map> FlightRecorder< + EventType>::getPgConfigJson() { + std::map> result; + for (const auto& [pg_name, ranks] : pg_name_to_ranks_) { + auto pg_info = std::map(); + pg_info["name"] = std::get<0>(pg_name); + pg_info["desc"] = std::get<1>(pg_name); + pg_info["ranks"] = ranks_str(ranks); + result.emplace(std::get<0>(pg_name), pg_info); + } + return result; +} + +template +const c10::Dict FlightRecorder< + EventType>::getPgStatus() { + auto all_pg_status = new_dict(); + for (const auto& [pg_id, status] : all_pg_status_) { + auto pg_status = new_dict(); + pg_status.insert("last_enqueued_collective", status->lastEnqueuedSeq); + pg_status.insert("last_started_collective", status->lastStartedSeq); + pg_status.insert("last_completed_collective", status->lastCompletedSeq); + all_pg_status.insert(std::to_string(pg_id), pg_status); + } + return all_pg_status; +} + +template +const std::map> FlightRecorder< + EventType>::getPgStatusJson() { + std::map> result; + for (const auto& [pg_id, status] : all_pg_status_) { + auto pg_status = std::map(); + pg_status["last_enqueued_collective"] = + std::to_string(status->lastEnqueuedSeq); + pg_status["last_started_collective"] = + std::to_string(status->lastStartedSeq); + pg_status["last_completed_collective"] = + std::to_string(status->lastCompletedSeq); + result[std::to_string(pg_id)] = pg_status; + } + return result; +} + +using json = nlohmann::json; +template +std::string FlightRecorder::dump_json( + const std::optional>>& extraDumpMap, + bool includeCollectives, + bool onlyActive) { + json result; + result[version_key_str] = version_val_str; + result[comm_lib_version_key_str] = comm_lib_version_; + result[pg_config_key_str] = getPgConfigJson(); + result[pg_status_key_str] = getPgStatusJson(); + + // collective trace + if (includeCollectives) { + std::list entries; + for (auto& e : dump_entries()) { + json j; + if (onlyActive && e.time_discovered_completed_.has_value()) { + continue; + } + j[record_id_key_str] = int64_t(e.id_); + j[pg_id_key_str] = int64_t(e.pg_id_); + j[pg_name_key_str] = e.pg_name_; + j[thread_name_key_str] = e.thread_name_; + j[thread_id_key_str] = c10::str(e.thread_id_); + j[collective_seq_id_key_str] = int64_t(e.collective_seq_id_); + j[p2p_seq_id_key_str] = int64_t(e.p2p_seq_id_); + j[op_id_key_str] = int64_t(e.op_id_); + j[profiling_name_key_str] = e.profiling_name_; + j[time_created_key_str] = int64_t(e.time_created_); + if (e.duration_) { + j[duration_key_str] = *e.duration_; + } + auto it = e.sizes_.begin(); + auto read_sizes = [&](const c10::SmallVector& dims) { + auto sizes = std::list>(); + for (auto dim : dims) { + auto arg_sizes = std::list(); + for (auto i : c10::irange(dim)) { + (void)i; + arg_sizes.push_back(*it++); + } + sizes.push_back(arg_sizes); + } + return sizes; + }; + j[input_sizes_key_str] = read_sizes(e.input_dims_); + std::vector input_dtypes_strs; + input_dtypes_strs.reserve(e.input_dtypes_.size()); + for (const auto& input_dtype : e.input_dtypes_) { + input_dtypes_strs.emplace_back(c10::toString(input_dtype)); + } + j[input_dtypes_key_str] = input_dtypes_strs; + j[output_sizes_key_str] = read_sizes(e.output_dims_); + std::vector output_dtypes_strs; + output_dtypes_strs.reserve(e.output_dtypes_.size()); + for (const auto& output_dtype : e.output_dtypes_) { + output_dtypes_strs.emplace_back(c10::toString(output_dtype)); + } + j[output_dtypes_key_str] = output_dtypes_strs; + if (e.time_discovered_completed_.has_value()) { + j[state_key_str] = completed_state_str; + } else if (e.time_discovered_started_.has_value()) { + j[state_key_str] = started_state_str; + } else { + j[state_key_str] = scheduled_state_str; + } + j[time_discovered_started_key_str] = + e.time_discovered_started_.has_value() + ? int64_t(*e.time_discovered_started_) + : 0; + j[time_discovered_completed_key_str] = + e.time_discovered_completed_.has_value() + ? int64_t(*e.time_discovered_completed_) + : 0; + j[retired_key_str] = e.retired_; + j[timeout_key_str] = e.timeout_ms_; + j[is_p2p_key_str] = e.isP2P_; + entries.emplace_back(j); + } + + if (!entries.empty()) { + result[entries_key_str] = entries; + } + } + + if (extraDumpMap.has_value()) { + result[nccl_comm_key_str] = extraDumpMap.value(); + } + return result.dump(); +} + +template +std::string FlightRecorder::dump( + const std::optional>>& extraDumpMap, + bool includeCollectives, + bool includeStackTraces, + bool onlyActive) { + STATIC_SCOPED_WAIT_COUNTER(pytorch.wait_counter.FlightRecorder__dump); + auto result = new_dict(); + // common values + result.insert(version_key, version_val); + result.insert(pg_config_key, getPgConfig()); + result.insert(comm_lib_version_key_str, comm_lib_version_); + result.insert(pg_status_key, getPgStatus()); + + // collective trace + if (includeCollectives) { + result.insert( + entries_key, getCollectiveTrace(includeStackTraces, onlyActive)); + } + + // convert extraDumpMap into a dictionary + auto per_comm_dict = new_dict(); + if (extraDumpMap.has_value()) { + for (const auto& [ncclId, ncclDump] : extraDumpMap.value()) { + auto inner_dict = new_dict(); + for (const auto& [key, value] : ncclDump) { + inner_dict.insert(key, value); + } + per_comm_dict.insert(ncclId, inner_dict); + } + } + if (!per_comm_dict.empty()) { + result.insert(nccl_comm_key, per_comm_dict); + } + return pickle_str(result); +} +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Functional.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Functional.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b171a3ac776f56fd1ff7d6e74c5449449ced9cec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Functional.hpp @@ -0,0 +1,90 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace c10d { + +C10_EXPORT at::Tensor& all_reduce_( + at::Tensor& input, + std::string reduce_op, + std::string group_name); + +C10_EXPORT at::Tensor all_reduce( + const at::Tensor& input, + std::string reduce_op, + std::string group_name); + +C10_EXPORT std::vector all_reduce_coalesced_( + std::vector inputs, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::string reduce_op, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::string group_name); + +C10_EXPORT std::vector all_reduce_coalesced( + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::vector inputs, + std::string reduce_op, + std::string group_name); + +C10_EXPORT std::vector all_gather_into_tensor_coalesced( + std::vector inputs, + int64_t group_size, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::string group_name); + +C10_EXPORT at::Tensor all_gather_into_tensor( + const at::Tensor& input, + int64_t group_size, + std::string group_name); + +C10_EXPORT at::Tensor& all_gather_into_tensor_out( + at::Tensor& input, + int64_t group_size, + const std::string& group_name, + at::Tensor& output); + +C10_EXPORT std::vector reduce_scatter_tensor_coalesced( + std::vector inputs, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::string reduce_op, + int64_t group_size, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::string group_name); + +C10_EXPORT at::Tensor reduce_scatter_tensor( + const at::Tensor& input, + std::string reduce_op, + int64_t group_size, + std::string group_name); + +C10_EXPORT at::Tensor reduce_scatter_tensor_out( + const at::Tensor& input, + std::string reduce_op, + int64_t group_size, + std::string group_name, + at::Tensor& output); + +C10_EXPORT at::Tensor all_to_all_single( + const at::Tensor& input, + at::SymIntArrayRef output_split_sizes, + at::SymIntArrayRef input_split_sizes, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::string group_name); + +C10_EXPORT at::Tensor& broadcast_( + at::Tensor& input, + int64_t src, + std::string group_name); + +C10_EXPORT at::Tensor broadcast( + const at::Tensor& input, + int64_t src, + std::string group_name); + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/GlooDeviceFactory.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/GlooDeviceFactory.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9770bbe9f3822bc68fa8c3344e92c17b95004dff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/GlooDeviceFactory.hpp @@ -0,0 +1,40 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_GLOO + +#include + +#include +#include +#include + +namespace c10d { + +class TORCH_API GlooDeviceFactory { + public: + // Create new device instance for specific interface. + static std::shared_ptr<::gloo::transport::Device> makeDeviceForInterface( + const std::string& interface, + bool lazyInit); + + // Create new device instance for specific hostname or address. + static std::shared_ptr<::gloo::transport::Device> makeDeviceForHostname( + const std::string& hostname, + bool lazyInit); +}; + +TORCH_DECLARE_SHARED_REGISTRY( + GlooDeviceRegistry, + ::gloo::transport::Device, + const std::string&, /* interface */ + const std::string&, /* hostname */ + bool /* lazyInit */); + +} // namespace c10d + +#endif // USE_C10D_GLOO + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/GroupRegistry.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/GroupRegistry.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4df50c8b39e5fbfc27e74477651d865a5d3dc06d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/GroupRegistry.hpp @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace c10d { + +C10_EXPORT void set_thread_isolation_mode(bool enable); + +bool get_thread_isolation_mode(); + +C10_EXPORT void register_process_group( + const std::string& group_name, + const c10::intrusive_ptr& group); + +C10_EXPORT c10::intrusive_ptr resolve_process_group( + const std::string& group_name); + +C10_EXPORT void unregister_process_group(const std::string& group_name); + +C10_EXPORT void unregister_all_process_groups(); + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/HashStore.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/HashStore.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e9b6186ef3bbf413ade67ddc83b764c43e655fa6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/HashStore.hpp @@ -0,0 +1,86 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace c10d { + +class TORCH_API HashStore : public Store { + public: + c10::intrusive_ptr clone() override; + + ~HashStore() override = default; + + void set(const std::string& key, const std::vector& data) override; + + std::vector compareSet( + const std::string& key, + const std::vector& expectedValue, + const std::vector& desiredValue) override; + + std::vector get(const std::string& key) override; + + void wait(const std::vector& keys) override { + wait(keys, timeout_); + } + + void wait( + const std::vector& keys, + const std::chrono::milliseconds& timeout) override; + + int64_t add(const std::string& key, int64_t value) override; + + int64_t getNumKeys() override; + + bool check(const std::vector& keys) override; + + bool deleteKey(const std::string& key) override; + + void append(const std::string& key, const std::vector& value) + override; + + std::vector> multiGet( + const std::vector& keys) override; + + void multiSet( + const std::vector& keys, + const std::vector>& values) override; + + // Returns true if this store support append, multiGet and multiSet + bool hasExtendedApi() const override; + + void queuePush(const std::string& key, const std::vector& value) + override; + + std::vector queuePop(const std::string& key, bool block) override; + + int64_t queueLen(const std::string& key) override; + + std::vector listKeys() override; + + protected: + bool checkLocked( + const std::unique_lock& lock, + const std::vector& keys); + + void waitLocked( + std::unique_lock& lock, + const std::vector& keys, + const std::chrono::milliseconds& timeout); + + protected: + std::unordered_map> map_; + std::unordered_map>> queues_; + std::mutex m_; + std::condition_variable cv_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/NCCLUtils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/NCCLUtils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..87417b52ae59481ef89a4cfb2c9c377d1941eae4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/NCCLUtils.hpp @@ -0,0 +1,448 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_NCCL + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +constexpr int64_t kCommInitBusyWaitMillis = 2; + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 14, 0) +#define NCCL_HAS_COMM_NONBLOCKING +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 18, 0) +#define NCCL_HAS_COMM_SPLIT +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 23, 0) +#define NCCL_HAS_INIT_RANK_SCALABLE +#endif + +// ncclGetLastError() is enabled only for NCCL versions 2.13+ +// ncclRemoteError only exists in NCCL versions 2.13+ +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 13, 0) +#define ENABLE_NCCL_GET_LAST_ERROR +#define NCCL_REMOTE_ERROR +#endif + +static_assert( + NCCL_VERSION_CODE >= NCCL_VERSION(2, 7, 0), + "NCCL version must be 2.7 or later"); +// The following macros represent features supported prior to NCCL 2.7, +// therefore we can define them unconditionally, given the static_assert above. +// TODO: remove these macros from code. +#define ENABLE_NCCL_ERROR_CHECKING +#define ENABLE_NCCL_P2P_SUPPORT +// End of macros for NCCL 2.7 and below. + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 11, 0) +#define ENABLE_NCCL_PREMUL_SUM_SUPPORT +#endif + +// Note: the first version that supports ncclConfig_t is 2.14. Here we +// fast-forward the version requirement to 2.17 where ncclConfig_t has CTA and +// CGA fields because they have already been pybinded out. +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 17, 0) +#define NCCL_HAS_CONFIG +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 19, 0) +#define NCCL_HAS_COMM_REGISTER +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 27, 0) +#define NCCL_HAS_COMM_WINDOW_REGISTER +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 19, 0) +#define NCCL_HAS_MEM_ALLOC +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 26, 0) +#define NCCL_HAS_QOS +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 24, 0) +#define NCCL_SUPPORTS_FP8 +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 27, 0) +#define NCCL_HAS_COLLNET +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 27, 0) +#define NCCL_HAS_CTA_POLICY +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 27, 0) +#define NCCL_HAS_NVLS_CTAS +#endif + +#if NCCL_VERSION_CODE >= NCCL_VERSION(2, 27, 0) +#define NCCL_HAS_COMM_SHRINK +#endif + +// Macro to throw on a non-successful NCCL return value. +#define C10D_NCCL_CHECK(cmd, failureReason) \ + do { \ + ncclResult_t result = cmd; \ + if (result != ncclSuccess) { \ + std::string err = "NCCL error in: " + std::string(__FILE__) + ":" + \ + std::to_string(__LINE__) + ", " + ncclGetErrorWithVersion(result) + \ + "\n" + getNcclErrorDetailStr(result, failureReason); \ + TORCH_CHECK_WITH(DistBackendError, false, err); \ + } \ + } while (0) + +// Macro to throw on a non-successful NCCL return value for NONBLOCKING calls. +#define C10D_NCCL_CHECK_NONBLOCKING(cmd, failureReason) \ + do { \ + ncclResult_t result = cmd; \ + if (result != ncclSuccess && result != ncclInProgress) { \ + std::string err = "NCCL error in: " + std::string(__FILE__) + ":" + \ + std::to_string(__LINE__) + ", " + ncclGetErrorWithVersion(result) + \ + "\n" + getNcclErrorDetailStr(result, failureReason); \ + TORCH_CHECK_WITH(DistBackendError, false, err); \ + } \ + } while (0) + +// Error out if (current time - startTime) is greater than timeout (sec). +#define C10D_CHECK_TIMEOUT(startTime, timeout) \ + do { \ + auto currentTime = std::chrono::steady_clock::now(); \ + auto timeElapsed = std::chrono::duration_cast( \ + currentTime - startTime) \ + .count(); \ + if (timeElapsed > timeout) { \ + std::string err = "NCCL timeout in: " + std::string(__FILE__) + ":" + \ + std::to_string(__LINE__); \ + TORCH_CHECK_WITH(DistBackendError, false, err); \ + } \ + } while (0) + +// Macro to throw on a non-successful NCCL return value, non-blocking. +// Thread-safe: uses NCCLComm wrapper's getAsyncError() which acquires mutex +// before calling ncclCommGetAsyncError to prevent race conditions between +// watchdog and main threads. +#define C10D_NCCL_CHECK_TIMEOUT_BASE( \ + cmd, commWrapper, failureReason, yield_fn) \ + do { \ + ncclResult_t result = cmd; \ + auto startTimepoint = std::chrono::steady_clock::now(); \ + auto timeout = nccl_nonblocking_timeout(); \ + while (result == ncclInProgress) { \ + C10D_CHECK_TIMEOUT(startTimepoint, timeout); \ + yield_fn; \ + commWrapper->getAsyncError(&result); \ + } \ + if (result != ncclSuccess) { \ + std::string err = "NCCL error in: " + std::string(__FILE__) + ":" + \ + std::to_string(__LINE__) + ", " + ncclGetErrorWithVersion(result) + \ + "\n" + getNcclErrorDetailStr(result, failureReason); \ + TORCH_CHECK_WITH(DistBackendError, false, err); \ + } \ + } while (0) + +// Sleep for kCommInitBusyWaitMillis milliseconds. +#define C10D_SCHED_SLEEP() \ + std::this_thread::sleep_for( \ + std::chrono::milliseconds(kCommInitBusyWaitMillis)) + +// Macro to throw exception on a non-successful NCCL return value or timeout. +// This macro uses sched_yield() to yield the CPU. +// Thus suitable for NCCL calls that would quickly turn ncclSuccess, e.g. +// collectives. +#define C10D_NCCL_CHECK_TIMEOUT(cmd, commWrapper, failureReason) \ + C10D_NCCL_CHECK_TIMEOUT_BASE(cmd, commWrapper, failureReason, sched_yield()) + +// Macro to throw exception on a non-successful NCCL return value or timeout. +// This macro uses sleep to yield the CPU. +// Thus suitable for NCCL calls that would take longer to turn ncclSuccess, e.g. +// ncclCommInitRankConfig, ncclCommFinalize, etc. +#define C10D_NCCL_CHECK_TIMEOUT_SLEEP(cmd, commWrapper, failureReason) \ + C10D_NCCL_CHECK_TIMEOUT_BASE( \ + cmd, commWrapper, failureReason, C10D_SCHED_SLEEP()) + +#define C10D_NCCL_CHECK_TIMEOUT_GROUPEND(cmd, comm, failureReason) \ + do { \ + ncclResult_t state = cmd; \ + auto startTimepoint = std::chrono::steady_clock::now(); \ + auto timeout = nccl_nonblocking_timeout(); \ + if (state == ncclInProgress) { \ + do { \ + C10D_CHECK_TIMEOUT(startTimepoint, timeout); \ + sched_yield(); \ + comm->getAsyncError(&state); \ + } while (state == ncclInProgress); \ + } \ + if (state != ncclSuccess) { \ + std::string err = "NCCL error in: " + std::string(__FILE__) + ":" + \ + std::to_string(__LINE__) + ", " + ncclGetErrorWithVersion(state) + \ + "\n" + getNcclErrorDetailStr(state, failureReason); \ + TORCH_CHECK_WITH(DistBackendError, false, err); \ + } \ + } while (0) + +// Macro to print and abort on a non-successful NCCL return value. +#define C10D_NCCL_ASSERT(cmd) \ + do { \ + ncclResult_t result = cmd; \ + if (result != ncclSuccess) { \ + std::string err = ncclGetErrorWithVersion(result); \ + fprintf( \ + stderr, \ + "NCCL error in: %s:%d, %s\n", \ + __FILE__, \ + __LINE__, \ + err.c_str()); \ + abort(); \ + } \ + } while (0) + +namespace c10d { + +// NCCL type typing +static std::map ncclDataType = { + {at::kChar, ncclInt8}, + {at::kByte, ncclUint8}, + {at::kFloat, ncclFloat}, + {at::kDouble, ncclDouble}, + {at::kInt, ncclInt32}, + {at::kLong, ncclInt64}, + {at::kHalf, ncclHalf}, + {at::kBool, ncclUint8}, +#ifdef NCCL_SUPPORTS_FP8 + {at::kFloat8_e5m2, ncclFloat8e5m2}, + {at::kFloat8_e4m3fn, ncclFloat8e4m3}, +#else + {at::kFloat8_e5m2, ncclUint8}, + {at::kFloat8_e4m3fn, ncclUint8}, +#endif + // NVIDIA GPUs does not support the UZ version standing for "no negative + // zero". See https://onnx.ai/onnx/technical/float8.html + {at::kFloat8_e4m3fnuz, ncclUint8}, + {at::kFloat8_e5m2fnuz, ncclUint8}, +#if HAS_NCCL_BF16_DATATYPE + {at::kBFloat16, ncclBfloat16}, +#endif // HAS_NCCL_BF16_DATATYPE +}; + +TORCH_API size_t hashTensors(const std::vector& tensors); +TORCH_API int genNcclSplitColor(const std::vector& ranks); +TORCH_API std::string getNcclVersion(); +TORCH_API std::tuple getNcclVersionTuple(); +TORCH_API int getNcclVersionNumber(); +TORCH_API std::string ncclGetErrorWithVersion(ncclResult_t error); +int nccl_nonblocking_timeout(); + +// Provides additional detail into NCCL error codes based on when these are +// thrown in the NCCL codebase. +TORCH_API std::string getNcclErrorDetailStr( + ncclResult_t error, + std::optional processGroupFailureReason = std::nullopt); + +// Helper function that gets the data type and issues error if not supported +ncclDataType_t getNcclDataType(at::ScalarType type); + +// RAII wrapper for NCCL communicator +class NCCLComm { + using MutexType = std::recursive_mutex; + using LockType = std::unique_lock; + + public: + explicit NCCLComm(ncclComm_t ncclComm); + + NCCLComm() = default; + + ~NCCLComm() noexcept; + + void setUniqueHash(ncclUniqueId ncclId); + void setUniqueHash(std::string hash); + std::string getUniqueHash(); + + static std::shared_ptr create( + int numRanks, + int rank, + ncclUniqueId commId, + at::DeviceIndex deviceIndex); + +#ifdef NCCL_HAS_CONFIG + static std::shared_ptr create( + int numRanks, + int rank, + ncclUniqueId commId, + at::DeviceIndex deviceIndex, + ncclConfig_t& config); +#ifdef NCCL_HAS_INIT_RANK_SCALABLE + static std::shared_ptr create_scalable( + int numRanks, + int rank, + std::vector& commIds, + at::DeviceIndex deviceIndex, + ncclConfig_t& config); +#endif // NCCL_HAS_INIT_RANK_SCALABLE +#endif // NCCL_HAS_CONFIG + +#ifdef NCCL_HAS_COMM_SPLIT + static std::shared_ptr split( + NCCLComm* source, + int color_id, + int rank, + ncclConfig_t& config); +#endif // NCCL_HAS_COMM_SPLIT + +#ifdef NCCL_HAS_COMM_SHRINK + static std::shared_ptr shrink( + NCCLComm* source, + std::vector& ranks_to_exclude, + ncclConfig_t* config, + int shrinkFlags = 0); +#endif // NCCL_HAS_COMM_SHRINK + +#if (defined(IS_NCCLX) || defined(USE_ROCM)) && defined(NCCL_COMM_DUMP) + std::unordered_map ncclCommDump(); +#endif + + at::DeviceIndex getDeviceIndex(); + + // Must not be copyable + NCCLComm(const NCCLComm&) = delete; + NCCLComm& operator=(const NCCLComm&) = delete; + + // Do not support move assignment as there is no valid use case + NCCLComm& operator=(NCCLComm&& other) = delete; + + // Move constructable + // NOLINTNEXTLINE(*-noexcept-move-*) + NCCLComm(NCCLComm&& other); + + ncclComm_t getNcclComm(); + + // Wait for the communicator to be ready. This is a blocking function. + // Useful in nonblocking mode: NCCL requires the communicator to be ready + // before issuing a second command. + // Arguments: + // longInterval: if true, wait with sleep of an interval; otherwise, wait + // with `sched_yield` which is faster (but acquires CPU more frequently). + // Use `longInterval=true` when waiting for initialization or finalize to + // complete. Use `longInterval=false` when waiting collective call to return + // ncclSuccess. + void waitReady(bool longInterval); + + std::optional getNcclCommFailureReason() const; + + void abort(std::optional commFailureReason = std::nullopt); + + // Finalize a communicator -- asking it to flush its operations. When the + // communicator is marked as nonblocking, this is a nonblocking function; + // otherwise, it will block till all operations complete. + void finalize(); + + // Destroy a communicator. This is a blocking function. + void destroy(); + + bool isInitialized() const; + + bool isAborted() const; + + uint64_t getCommSplitCounter() const; + + ncclResult_t checkForNcclError(); + + // Thread-safe wrapper for ncclCommGetAsyncError that acquires the mutex + // before calling the NCCL API. This is needed because NCCL does not provide + // thread-safety guarantees for ncclCommGetAsyncError, and both the main + // thread and watchdog thread may call it concurrently. + ncclResult_t getAsyncError(ncclResult_t* asyncError); + + ncclResult_t registerSegment( + void* ptr, + size_t size, + bool errorOnRereg = true, + bool window = false); + + ncclResult_t deregisterSegment(void* ptr, bool window = false); + + std::string repr() const; + + friend class ProcessGroupNCCL; + + protected: + // Unique hash for this communicator. + std::string uniqueHash_; + bool aborted_{false}; + uint64_t ncclCommSplitCounter_{0}; + ncclResult_t ncclAsyncErr_{ncclSuccess}; + mutable MutexType mutex_; + // Rank that this communicator corresponds to. + int rank_{}; + // Optional reason for communicator failure, provided by ProcessGroupNCCL for + // better error messaging. + std::optional commFailureReason_; + bool initialized_{false}; + // Whether this communicator is using nonblocking mode. Recorded during comm + // creation or split. For safety, we give a default value of true (more + // protection). + bool nonBlocking_{true}; + // Device index for which the NCCL comm is created + at::DeviceIndex deviceIndex_{-1}; +#ifdef NCCL_HAS_COMM_REGISTER + // Stores handlers for tensors registered by NCCL + std::unordered_map registeredSegmentHandles_; +#endif // NCCL_HAS_COMM_REGISTER + + private: + ncclComm_t ncclComm_{nullptr}; +}; + +// Helper that automatically cleans up premul sums. +struct ncclRedOpRAII { + ncclRedOpRAII() = default; + ncclRedOpRAII(ncclRedOp_t op) : op_(op) {} + ncclRedOpRAII(ncclRedOp_t op, ncclComm_t comm) + : op_(op), comm_(comm), premul_sum_(true) {} + ncclRedOpRAII(const ncclRedOpRAII&) = delete; + ncclRedOpRAII& operator=(const ncclRedOpRAII&) = delete; + ncclRedOpRAII(ncclRedOpRAII&& tmp) noexcept : ncclRedOpRAII() { + std::swap(tmp.op_, this->op_); + std::swap(tmp.comm_, this->comm_); + std::swap(tmp.premul_sum_, this->premul_sum_); + } +#if defined(ENABLE_NCCL_PREMUL_SUM_SUPPORT) + ~ncclRedOpRAII() { + if (premul_sum_) { + ncclRedOpDestroy(op_, comm_); + } + } +#endif // ENABLE_NCCL_PREMUL_SUM_SUPPORT + operator ncclRedOp_t() const { + return op_; + } + ncclRedOp_t op_{}; + ncclComm_t comm_{}; + bool premul_sum_ = false; +}; + +void printNcclCommProxyTrace( + const std::string& dumpReason, + const std::unordered_map& dumpMap); +} // namespace c10d + +#endif // USE_C10D_NCCL + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/NanCheck.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/NanCheck.hpp new file mode 100644 index 0000000000000000000000000000000000000000..53915ea60411f46bb381ae2ed314d5e9348f97aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/NanCheck.hpp @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_NCCL + +#include +#include + +namespace c10d { + +// Check for NaNs in a tensor on a given stream. If any are found, throw a +// device-side error. +void checkForNan(const at::Tensor& tensor, at::cuda::CUDAStream& stream); + +} // namespace c10d + +#endif // USE_C10D_NCCL + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ParamCommsUtils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ParamCommsUtils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1d1b140dfa054f4326ce078b532ab2db1007f88f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ParamCommsUtils.hpp @@ -0,0 +1,185 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch { + +class TORCH_API ParamCommsDebugInfo : public c10::DebugInfoBase { + public: + ParamCommsDebugInfo() = default; + ParamCommsDebugInfo( + std::tuple pgName, + int rank, + std::string&& collName, + int64_t inNelems, + int64_t outNelems, + at::ScalarType dType, + std::vector inSplitSizes, + std::vector outSplitSizes, + int globalRankStart, + int globalRankStride, + int worldSize); + + ~ParamCommsDebugInfo() override = default; + + const std::string getProcessGroupName() const { + return std::get<0>(pgName_); + } + + const std::string getProcessGroupDesc() const { + return std::get<1>(pgName_); + } + + int getRank() const { + return rank_; + } + + int getWorldSize() const { + return worldSize_; + } + + int getGlobalRankStart() const { + return globalRankStart_; + } + + int getGlobalRankStride() const { + return globalRankStride_; + } + + const std::string getCollectiveName() const { + return collectiveName_; + } + + int64_t getInMessageNelems() const { + return inMessageNelems_; + } + + int64_t getOutMessageNelems() const { + return outMessageNelems_; + } + + at::ScalarType getDType() const { + return dType_; + } + + const std::vector& getInputSplitSizes() const { + return inputSplitSizes_; + } + + const std::vector& getOutputSplitSizes() const { + return outputSplitSizes_; + } + + const std::vector& getGroupRanks() const { + return groupRanks_; + } + + private: + std::tuple pgName_; // + int rank_{}; + int worldSize_{}; + std::string collectiveName_; + int64_t inMessageNelems_{}; + int64_t outMessageNelems_{}; + at::ScalarType dType_ = at::kByte; + std::vector inputSplitSizes_; + std::vector outputSplitSizes_; + int globalRankStart_{}; + int globalRankStride_{}; + std::vector groupRanks_; +}; + +#define RECORD_PARAM_COMMS( \ + seq, \ + pgName, \ + rank, \ + collName, \ + inNelems, \ + outNelems, \ + dType, \ + inSplitSizes, \ + outSplitSizes, \ + globalRankStart, \ + globalRankStride, \ + worldSize) \ + auto paramCommsInfo = std::make_shared( \ + pgName, \ + rank, \ + collName, \ + inNelems, \ + outNelems, \ + dType, \ + inSplitSizes, \ + outSplitSizes, \ + globalRankStart, \ + globalRankStride, \ + worldSize); \ + c10::DebugInfoGuard g(c10::DebugInfoKind::PARAM_COMMS_INFO, paramCommsInfo); \ + std::initializer_list paramList = { \ + seq, \ + pgName, \ + rank, \ + collName, \ + inSplitSizes, \ + outSplitSizes, \ + globalRankStart, \ + globalRankStride, \ + worldSize}; \ + c10::ArrayRef paramInputs(paramList); \ + RECORD_FUNCTION(at::kParamCommsCallName, paramInputs); + +#define RECORD_PARAM_COMMS_DATA( \ + seq, \ + pgName, \ + InputTensors, \ + OutputTensors, \ + rank, \ + collName, \ + inNelems, \ + outNelems, \ + dType, \ + inSplitSizes, \ + outSplitSizes, \ + globalRankStart, \ + globalRankStride, \ + worldSize) \ + auto paramCommsInfo = std::make_shared( \ + pgName, \ + rank, \ + collName, \ + inNelems, \ + outNelems, \ + dType, \ + inSplitSizes, \ + outSplitSizes, \ + globalRankStart, \ + globalRankStride, \ + worldSize); \ + c10::DebugInfoGuard g(c10::DebugInfoKind::PARAM_COMMS_INFO, paramCommsInfo); \ + std::initializer_list paramList = { \ + c10::IValue(InputTensors), \ + seq, \ + pgName, \ + rank, \ + collName, \ + inSplitSizes, \ + outSplitSizes, \ + globalRankStart, \ + globalRankStride, \ + worldSize}; \ + c10::ArrayRef paramInputs(paramList); \ + RECORD_FUNCTION_WITH_INPUTS_OUTPUTS( \ + at::kParamCommsCallName, \ + paramInputs, \ + std::vector(1, c10::IValue(OutputTensors))); +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/PrefixStore.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/PrefixStore.hpp new file mode 100644 index 0000000000000000000000000000000000000000..48411dd8182e462c0e2592f30e0714a70769cc63 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/PrefixStore.hpp @@ -0,0 +1,82 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace c10d { + +class TORCH_API PrefixStore : public Store { + public: + explicit PrefixStore(std::string prefix, c10::intrusive_ptr store); + + c10::intrusive_ptr clone() override; + + using Store::set; + void set(const std::string& key, const std::vector& value) override; + + using Store::compareSet; + std::vector compareSet( + const std::string& key, + const std::vector& expectedValue, + const std::vector& desiredValue) override; + + std::vector get(const std::string& key) override; + + int64_t add(const std::string& key, int64_t value) override; + + bool deleteKey(const std::string& key) override; + + int64_t getNumKeys() override; + + bool check(const std::vector& keys) override; + + void wait(const std::vector& keys) override; + + void wait( + const std::vector& keys, + const std::chrono::milliseconds& timeout) override; + + const std::chrono::milliseconds& getTimeout() const noexcept override; + + void setTimeout(const std::chrono::milliseconds& timeout) override; + + void append(const std::string& key, const std::vector& value) + override; + + std::vector> multiGet( + const std::vector& keys) override; + + void multiSet( + const std::vector& keys, + const std::vector>& values) override; + + // Returns true if this store support append, multiGet and multiSet + bool hasExtendedApi() const override; + + void queuePush(const std::string& key, const std::vector& value) + override; + + std::vector queuePop(const std::string& key, bool block) override; + + int64_t queueLen(const std::string& key) override; + + c10::intrusive_ptr getUnderlyingStore(); + + // Recursively to fetch the store before layers of wrapping with PrefixStore. + c10::intrusive_ptr getUnderlyingNonPrefixStore(); + + std::vector listKeys() override; + + protected: + std::string prefix_; + c10::intrusive_ptr store_; + + std::string joinKey(const std::string& key); + std::vector joinKeys(const std::vector& keys); +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroup.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroup.hpp new file mode 100644 index 0000000000000000000000000000000000000000..535b3d8c2bcd45ef7280670199fa3054fc61a520 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroup.hpp @@ -0,0 +1,1037 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +// ************************************************************************* +// PROCESS GROUP collective communication API IS BEING CHANGED BETWEEN +// versions 1.7 and 1.8. +// PLEASE DO NOT ADD ANY DEPENDENCIES. +// SEE RFC: https://github.com/pytorch/pytorch/issues/39662 +// ************************************************************************* + +constexpr auto kProcessGroupDefaultTimeout = + std::chrono::milliseconds(30 * 60 * 1000); + +namespace c10d { + +// We only call `register_work()` in two cases: +// 1. If the work object is created from a functional collective call. +// 2. If the work object is created from a non-functional collective call within +// the `with allow_inflight_collective_as_graph_input_ctx()` context manager. +C10_EXPORT void register_work( + const at::Tensor& tensor, + const c10::intrusive_ptr& work); + +C10_EXPORT at::Tensor wait_tensor(const at::Tensor& tensor); + +// We only call `unregister_work()` in one case: +// 1. If the work object is created from a non-functional collective call within +// the `with allow_inflight_collective_as_graph_input_ctx()` context manager. +// +// Q: What about the functional collective case? +// A: The unregistration of work object for functional collective is done in +// the required user-side explicit call to `wait_tensor()`. +C10_EXPORT void unregister_work(const c10::intrusive_ptr& work); + +C10_EXPORT size_t get_work_registry_size(); + +C10_EXPORT void set_allow_inflight_collective_as_graph_input(bool value); + +C10_EXPORT bool allow_inflight_collective_as_graph_input(); + +// ProcessGroup is a base class that captures collective and point to +// point communication in a fixed set of processes. +// +// The functions specified in the class below describe the API alone; +// implementations are provided in subclasses. +// +// Every function that performs I/O is executed asynchronously by a +// thread pool owned by the ProcessGroup (by default). They return an +// object that can be used to wait for completion or error. +// +// The ProcessGroup can instantiate subgroups with fewer or an equal +// number of members. Implementations must take care that multiple +// process groups can be used in parallel and synchronize accordingly. +// +// The ProcessGroup assumes a fixed set of processes. If the set +// changes, existing instances must be destructed and instantiation +// and initialization must start from scratch. For members of the +// process group to find each other (referred to as rendezvous from +// hereon) +// +class TORCH_API ProcessGroup : public torch::CustomClassHolder { + public: + struct TORCH_API MergeOptions : torch::CustomClassHolder { + explicit MergeOptions( + const std::chrono::milliseconds timeout = kProcessGroupDefaultTimeout, + const std::optional group_name = std::nullopt, + const std::optional group_desc = std::nullopt) + : timeout(timeout), group_name(group_name), group_desc(group_desc) {} + ~MergeOptions() override = default; + MergeOptions(const MergeOptions&) = delete; + MergeOptions& operator=(const MergeOptions&) = delete; + + std::chrono::milliseconds timeout; + std::optional group_name; + std::optional group_desc; + }; + + enum BackendType : uint8_t { + UNDEFINED = 0, + GLOO = 1, + NCCL = 2, + UCC = 3, + MPI = 4, + XCCL = 5, + CUSTOM = 6, + }; + + static std::string backendTypeToString(const BackendType& type) { + switch (type) { + case BackendType::GLOO: + return "gloo"; + case BackendType::NCCL: + return "nccl"; + case BackendType::XCCL: + return "xccl"; + case BackendType::UCC: + return "ucc"; + case BackendType::MPI: + return "mpi"; + case BackendType::UNDEFINED: + return "undefined"; + case BackendType::CUSTOM: + return "custom"; + default: + TORCH_CHECK(false, "THis should never happen!"); + } + } + + static BackendType strToBackendType(const std::string& backend) { + if (backend == "undefined") { + return BackendType::UNDEFINED; + } else if (backend == "gloo") { + return BackendType::GLOO; + } else if (backend == "nccl") { + return BackendType::NCCL; + } else if (backend == "xccl") { + return BackendType::XCCL; + } else if (backend == "ucc") { + return BackendType::UCC; + } else if (backend == "mpi") { + return BackendType::MPI; + } else { + return BackendType::CUSTOM; + } + } + + // Not used, set for backwards compatibility and only used for TypeDef in + // Ops.cpp + explicit ProcessGroup(int rank, int size); + + explicit ProcessGroup( + c10::intrusive_ptr<::c10d::Store> store, + int rank, + int size); + ~ProcessGroup() override; + + virtual int getRank() const { + return rank_; + } + + virtual int getSize() const { + return size_; + } + + // Returns an unique opaque ID of this process group object. + int64_t getID() const { + return reinterpret_cast(this); + } + + // Returns an unique opaque ID of a backend for the specific backend type + // that can correlate with this process group's collectives. + int64_t getBackendID(BackendType backend_type) const { + return reinterpret_cast(getBackend(backend_type).get()); + } + + virtual const std::string getBackendName() const { + return backendTypeToString(backendType_); + } + + BackendType getBackendType() const { + return backendType_; + } + + inline bool backendSupportsSequenceNumbers(BackendType backendType) { + if (backendType == BackendType::GLOO || backendType == BackendType::NCCL || + backendType == BackendType::XCCL || backendType == BackendType::UCC) + return true; + return false; + } + + virtual void setTimeout(std::chrono::milliseconds timeout) { + for (auto& backend : backendTypeToBackend_) { + backend.second->setTimeout(timeout); + } + } + + int64_t incrementSplitCount() { + return splitCounter_++; + } + + virtual void startCoalescing(c10::DeviceType deviceType) { + // only nccl has implemented startCoalescing so only execute for nccl + // backends + auto backend = getBackend(deviceType); + backend->startCoalescing(); + } + + virtual c10::intrusive_ptr endCoalescing(c10::DeviceType deviceType) { + // only nccl has implemented endCoalescing so only execute for nccl + // backends + auto backend = getBackend(deviceType); + auto work = backend->endCoalescing(); + return work; + } + + virtual c10::intrusive_ptr broadcast( + std::vector& tensors, + const BroadcastOptions& opts = BroadcastOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::broadcast_", "") + .typed< + std::tuple, c10::intrusive_ptr>( + at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + int64_t, + int64_t, + bool, + int64_t)>(); + // It's awakward to unbox the opts here and box them again in the custom C++ + // op. But it's also complicated to make opts as a CustomClassHolder. Leave + // it as it is now. + auto work = std::get<1>(op.call( + tensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.rootRank, + opts.rootTensor, + opts.asyncOp, + opts.timeout.count())); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : tensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr allreduce( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::allreduce_", "") + .typed< + std::tuple, c10::intrusive_ptr>( + at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + const c10::intrusive_ptr<::c10d::ReduceOp>&, + const std::optional& sparse_indices, + bool, + int64_t)>(); + + auto work = std::get<1>(op.call( + tensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + c10::make_intrusive(opts.reduceOp), + opts.sparseIndices, + opts.asyncOp, + opts.timeout.count())); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : tensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = AllreduceCoalescedOptions()) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::allreduce_coalesced_", "") + .typed( + at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + const c10::intrusive_ptr<::c10d::ReduceOp>&, + bool, + int64_t)>(); + + auto work = op.call( + tensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + c10::make_intrusive(opts.reduceOp), + opts.asyncOp, + opts.timeout.count()); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : tensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr reduce( + std::vector& tensors, + const ReduceOptions& opts = ReduceOptions()) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::reduce_", "") + .typed( + at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + const c10::intrusive_ptr<::c10d::ReduceOp>&, + int64_t, + int64_t, + bool, + int64_t)>(); + auto work = op.call( + tensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + c10::make_intrusive(opts.reduceOp), + opts.rootRank, + opts.rootTensor, + opts.asyncOp, + opts.timeout.count()); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : tensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::allgather_", "") + .typed>, + c10::intrusive_ptr>( + const std::vector>&, + at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + bool, + int64_t)>(); + + auto work = std::get<1>(op.call( + outputTensors, + inputTensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.asyncOp, + opts.timeout.count())); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor_list : outputTensors) { + for (const auto& tensor : tensor_list) { + c10d::register_work(tensor, work); + } + } + } + return work; + } + + // Gathers a single tensor inputBuffer into a single buffer outputBuffer that + // is interpreted as a contiguous collection of size inputBuffer * WORLD_SIZE. + // For implementers of ProcessGroup API and advanced users only. + // Note: this function will be deprecated in near future. + virtual c10::intrusive_ptr _allgather_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + const AllgatherOptions& opts = AllgatherOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::_allgather_base_", "") + .typed>( + at::Tensor&, + at::Tensor&, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + bool, + int64_t)>(); + + auto work = std::get<1>(op.call( + outputBuffer, + inputBuffer, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.asyncOp, + opts.timeout.count())); + + if (c10d::allow_inflight_collective_as_graph_input()) { + c10d::register_work(outputBuffer, work); + } + return work; + } + + // This function is deprecated and will be moved out of ProcessGroup to comms: + // * do not add dependencies on this function, + // * do not implement it in your ProcessGroup, implement _allgather_base + // instead. + virtual c10::intrusive_ptr allgather_coalesced( + std::vector>& outputTensorLists, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::allgather_coalesced_", "") + .typed( + const std::vector>&, + const at::TensorList&, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + bool)>(); + + auto work = op.call( + outputTensorLists, + inputTensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.asyncOp); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor_list : outputTensorLists) { + for (const auto& tensor : tensor_list) { + c10d::register_work(tensor, work); + } + } + } + return work; + } + + // This function is a coalesced version of `allgather_into_tensor` (currently + // still named as `_allgather_base`). Each tensor in the vector corresponds to + // an input/output of one `allgather_into_tensor` operation. + virtual c10::intrusive_ptr allgather_into_tensor_coalesced( + std::vector& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::allgather_into_tensor_coalesced_", "") + .typed( + const at::TensorList, + const at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + bool)>(); + + auto work = op.call( + outputTensors, + inputTensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.asyncOp); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : outputTensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr gather( + std::vector>& outputTensors, + std::vector& inputTensors, + const GatherOptions& opts = GatherOptions()) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::gather_", "") + .typed( + const std::vector>&, + const at::TensorList&, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + int64_t, + bool, + int64_t)>(); + auto work = op.call( + outputTensors, + inputTensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.rootRank, + opts.asyncOp, + opts.timeout.count()); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor_list : outputTensors) { + for (const auto& tensor : tensor_list) { + c10d::register_work(tensor, work); + } + } + } + return work; + } + + virtual c10::intrusive_ptr scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ScatterOptions& opts = ScatterOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::scatter_", "") + .typed< + std::tuple, c10::intrusive_ptr>( + const at::TensorList&, + const std::vector>&, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + int64_t, + bool, + int64_t)>(); + auto work = std::get<1>(op.call( + outputTensors, + inputTensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.rootRank, + opts.asyncOp, + opts.timeout.count())); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : outputTensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr reduce_scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::reduce_scatter_", "") + .typed< + std::tuple, c10::intrusive_ptr>( + const at::TensorList&, + const std::vector>&, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + const c10::intrusive_ptr<::c10d::ReduceOp>&, + bool, + int64_t)>(); + auto work = std::get<1>(op.call( + outputTensors, + inputTensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + c10::make_intrusive<::c10d::ReduceOp>(opts.reduceOp), + opts.asyncOp, + opts.timeout.count())); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : outputTensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + const ReduceScatterOptions& opts = ReduceScatterOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::_reduce_scatter_base_", "") + .typed>( + at::Tensor&, + at::Tensor&, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + const c10::intrusive_ptr<::c10d::ReduceOp>&, + bool, + int64_t)>(); + auto work = std::get<1>(op.call( + outputBuffer, + inputBuffer, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + c10::make_intrusive<::c10d::ReduceOp>(opts.reduceOp), + opts.asyncOp, + opts.timeout.count())); + + if (c10d::allow_inflight_collective_as_graph_input()) { + c10d::register_work(outputBuffer, work); + } + return work; + } + + // This function is a coalesced version of `reduce_scatter_tensor` (currently + // still named as `_reduce_scatter_base`). Each tensor in the vector + // corresponds to an input/output of one `reduce_scatter_tensor` operation. + virtual c10::intrusive_ptr reduce_scatter_tensor_coalesced( + std::vector& outputTensors, + std::vector& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::reduce_scatter_tensor_coalesced_", "") + .typed( + const at::TensorList, + const at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + const c10::intrusive_ptr<::c10d::ReduceOp>&, + bool, + int64_t)>(); + + auto work = op.call( + outputTensors, + inputTensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + c10::make_intrusive<::c10d::ReduceOp>(opts.reduceOp), + opts.asyncOp, + opts.timeout.count()); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : outputTensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr alltoall_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + std::vector& outputSplitSizes, + std::vector& inputSplitSizes, + const AllToAllOptions& opts = AllToAllOptions()) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::alltoall_base_", "") + .typed( + at::Tensor&, + at::Tensor&, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + std::vector, + std::vector, + bool, + int64_t)>(); + auto work = op.call( + outputBuffer, + inputBuffer, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + outputSplitSizes, + inputSplitSizes, + opts.asyncOp, + opts.timeout.count()); + + if (c10d::allow_inflight_collective_as_graph_input()) { + c10d::register_work(outputBuffer, work); + } + return work; + } + + virtual c10::intrusive_ptr alltoall( + std::vector& outputTensors, + std::vector& inputTensors, + const AllToAllOptions& opts = AllToAllOptions()) { + static auto op = + c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::alltoall_", "") + .typed< + std::tuple, c10::intrusive_ptr>( + const at::TensorList&, + const at::TensorList&, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + bool, + int64_t)>(); + auto work = std::get<1>(op.call( + outputTensors, + inputTensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.asyncOp, + opts.timeout.count())); + + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : outputTensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual void monitoredBarrier( + const BarrierOptions& opts, + bool wait_all_ranks = false) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::monitored_barrier_", "") + .typed&, + const std::vector&, + int64_t, + bool)>(); + // Default to using cpu implementation, monitored barrier is only for GLOO + at::Tensor tensor = at::empty({0}, at::TensorOptions().device(at::kCPU)); + op.call( + tensor, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.device_ids, + opts.timeout.count(), + wait_all_ranks); + } + + // Agrees on an initial sequence number for the whole group by having rank 0 + // create it and broadcast it to other ranks using the store. Only implemented + // for GLOO and NCCL backends currently. + virtual void setSequenceNumberForGroup() { + auto backendType = getBackendType(); + // TODO: HACK for backend name to get sequence number for that backend. + if (backendSupportsSequenceNumbers(backendType)) { + getDefaultBackend()->setSequenceNumberForGroup(); + } else { + TORCH_CHECK( + false, + c10::str( + "ProcessGroup ", + getBackendName(), + " does not yet support sequence numbers.")); + } + } + + // Retrieves the current sequence number for the whole group, which should be + // in sync. If the returned number is not consistent across the group, it + // may indicate that there is some sort of collective desynchronization. + virtual uint64_t getSequenceNumberForGroup() { + auto backendType = getBackendType(); + + // TODO: HACK for backend name to get sequence number for that backend. + if (backendSupportsSequenceNumbers(backendType)) { + return getDefaultBackend()->getSequenceNumberForGroup(); + } else { + TORCH_CHECK( + false, + c10::str( + "ProcessGroup ", + getBackendName(), + " does not yet support sequence numbers.")); + } + } + + virtual c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::send", "") + .typed( + at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + int64_t, + int64_t)>(); + auto work = op.call( + tensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + dstRank, + tag); + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : tensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::recv_", "") + .typed( + at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + int64_t, + int64_t)>(); + auto work = op.call( + tensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + srcRank, + tag); + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : tensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr recvAnysource( + std::vector& tensors, + int tag) { + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::recv_any_source_", "") + .typed( + at::TensorList, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + int64_t)>(); + auto work = op.call( + tensors, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + tag); + if (c10d::allow_inflight_collective_as_graph_input()) { + for (const auto& tensor : tensors) { + c10d::register_work(tensor, work); + } + } + return work; + } + + virtual c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) { + static at::Tensor tensor; + // TODO: if nccl was specified then use it + auto device = opts.device; + if (device.has_value()) { + // set device tensor from argument + tensor = at::empty( + {1}, at::TensorOptions().device(device.value()).dtype(at::kByte)); + } else if (backendType_ == c10d::ProcessGroup::BackendType::NCCL) { + // set cuda tensor + tensor = at::empty( + {1}, + at::TensorOptions().device(at::DeviceType::CUDA).dtype(at::kByte)); + } else if (backendType_ == c10d::ProcessGroup::BackendType::XCCL) { + // set xpu tensor for override cpu dispatch + tensor = at::empty( + {1}, + at::TensorOptions().device(at::DeviceType::XPU).dtype(at::kByte)); + } else { + // Default to using cpu implementation + tensor = at::empty( + {1}, + at::TensorOptions().device(at::DeviceType::CPU).dtype(at::kByte)); + } + + static auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow("c10d::barrier", "") + .typed( + at::Tensor, + const c10::intrusive_ptr<::c10d::ProcessGroup>&, + const std::vector&, + bool, + int64_t)>(); + + auto work = op.call( + tensor, + c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this), + opts.device_ids, + opts.asyncOp, + opts.timeout.count()); + if (c10d::allow_inflight_collective_as_graph_input()) { + c10d::register_work(tensor, work); + } + return work; + } + + bool hasBackends() { + return !deviceTypeToBackendType_.empty(); + } + + void setBackend( + c10::DeviceType deviceType, + BackendType backendType, + const std::optional>& backend) { + // TODO: should we add these entries after the backend setting succeeds? + deviceTypeToBackendType_[deviceType] = backendType; + deviceTypes_.insert(deviceType); + // if the backendType is already set then reuse it for this device + if (backendTypeToBackend_.find(backendType) != + backendTypeToBackend_.end()) { + auto existingBackend = backendTypeToBackend_.at(backendType); + deviceTypeToBackend_[deviceType] = existingBackend; + TORCH_CHECK( + existingBackend->getBoundDeviceId() == + (*backend)->getBoundDeviceId()); + } else { + // check if backend has value + if (backend.has_value()) { + deviceTypeToBackend_[deviceType] = backend.value(); + backendTypeToBackend_[backendType] = backend.value(); + (*backend)->setBoundDeviceId(bound_device_id_); + } + } + } + + c10::intrusive_ptr getDefaultBackend() const { + auto backend_iter = backendTypeToBackend_.find(backendType_); + TORCH_CHECK( + backend_iter != backendTypeToBackend_.end(), + "Could not find the default backend type ", + uint16_t(backendType_), + " for Process Group with name ", + getBackendName(), + "."); + return backend_iter->second; + } + + void setDefaultBackend(const BackendType& backendType) { + backendType_ = backendType; + } + + void setDefaultBackend(const std::string& backend) { + backendType_ = strToBackendType(backend); + } + + c10::intrusive_ptr getBackend(c10::DeviceType deviceType); + + c10::intrusive_ptr getBackend(BackendType backendType) const { + TORCH_CHECK( + backendTypeToBackend_.find(backendType) != backendTypeToBackend_.end(), + "Could not find backend type ", + uint16_t(backendType), + " for Process Group with name ", + backendTypeToString(backendType), + "."); + return backendTypeToBackend_.at(backendType); + } + + // Return device types supported by this ProcessGroup. + // Note: the return type is `Device` rather than `DeviceType` for the purpose + // of easy comparison at Python level. The `Device` will have default index + // (-1). + std::vector getDeviceTypes() const { + std::vector devices; + devices.reserve(deviceTypes_.size()); + for (auto& dt : deviceTypes_) { + devices.emplace_back(dt); + } + return devices; + } + + void registerOnCompletionHook( + std::function)>&& hook) { + getDefaultBackend()->registerOnCompletionHook(std::move(hook)); + } + + void waitForPendingWorks() { + getDefaultBackend()->waitForPendingWorks(); + } + + virtual void shutdown() { + for (auto& backend : backendTypeToBackend_) { + backend.second->shutdown(); + } + } + + virtual void abort() { + for (auto& backend : backendTypeToBackend_) { + backend.second->abort(); + } + } + + bool hasHooks() const { + auto backend_iter = backendTypeToBackend_.find(backendType_); + if (backend_iter == backendTypeToBackend_.end()) { + TORCH_WARN( + "No backend of type ", + uint16_t(backendType_), + " found for Process Group with name ", + getBackendName(), + ". Assuming no hooks are registered."); + return false; + } + + return backend_iter->second->hasHooks(); + } + + virtual const std::string& getGroupName() const; + virtual void setGroupName(const std::string& name); + virtual const std::string& getGroupDesc() const; + virtual void setGroupDesc(const std::string& name); + void enableCollectivesTiming(); + + void release_resources() override; + + // ProcessGroups optionally can be "bound" to a specific device. + // Currently this is only for nccl and allows for some opt-in + // optimizations such as automatic use of ncclCommSplit. The device + // is specified in `init_process_group` and eventually makes it + // here and then down into the actual backend instances. + std::optional getBoundDeviceId() const { + return bound_device_id_; + } + + c10::intrusive_ptr getStore() const { + return store_; + } + + void setBoundDeviceId(std::optional device) { + if (device) { + TORCH_CHECK(device->has_index(), "setBoundDeviceId must have an index"); + } + bound_device_id_ = device; + } + + // This creates a new subgroup using the specified ranks. + // The current rank must be included in the list of new_ranks. + virtual c10::intrusive_ptr splitGroup( + const std::vector& ranks, + const std::optional& timeout, + const std::optional>& opts, + const std::optional& name, + const std::optional& groupDesc); + + // This creates a new subgroup using the specified ranks. + // The current rank must be included in the list of new_ranks. + virtual c10::intrusive_ptr mergeRemoteGroup( + const c10::intrusive_ptr& store, + const MergeOptions& opts, + const int& size); + + protected: + // Implementations of this interface need to call this to setup + // appropriate logging etc. + void init(); + + c10::intrusive_ptr store_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const int rank_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const int size_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + BackendType backendType_; + std::string pg_desc_; + int64_t splitCounter_; + + // Debug level setting. It is parsed once when ProcessGroup is constructed and + // remains the same across use of this process group. + DebugLevel dist_debug_level_{DebugLevel::Off}; + + // Backend classes for this ProcessGroup + std::unordered_set deviceTypes_; + // This mapping is ordered, as splitGroup must call split on the underlying + // backends in a consistent order. + std::map deviceTypeToBackendType_; + std::unordered_map> + deviceTypeToBackend_; + std::unordered_map> + backendTypeToBackend_; + + std::optional bound_device_id_; +}; + +// Thread local functions for managing the currently active process group. +TORCH_API c10::intrusive_ptr& currentProcessGroup(); +TORCH_API void setProcessGroup(c10::intrusive_ptr processGroup); + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGloo.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGloo.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2b4bed946be7bdaaf3601e1dd847410ef5b64f5f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGloo.hpp @@ -0,0 +1,503 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_GLOO + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include + +namespace c10d { + +constexpr const char* GLOO_BACKEND_NAME = "gloo"; + +// Control whether or not connections are established in a full mesh or lazily +// as needed. +static std::vector TORCH_GLOO_LAZY_INIT = {"TORCH_GLOO_LAZY_INIT"}; + +// Returns default value for lazyInit. +bool TORCH_API getDefaultGlooLazyInit(); + +// ProcessGroupGloo implements Gloo bindings for c10d. +// +// All functions on this class are expected to be called in the same +// order across processes in the group. This is the only way that we +// can guarantee to match up the same calls across processes. For +// multi-threaded usage of process groups, you can consider using +// multiple process group instances. +// +class TORCH_API ProcessGroupGloo : public Backend { + public: + // AsyncWork is the Gloo specific superclass for asynchronous work items. + // We can split asynchronous work into 3 phases: + // 1) Sanity checks and prepare input (e.g. memcpy) + // 2) Run operation on background thread + // 3) Synchronize with completion on foreground thread + // + // There is state to be shared between these 3 phases and all of this state + // is captured in the AsyncWork class and its derivatives. + // + // Note: while we are porting operations to use new style collectives, there + // is a split between operations using the existing caching approach and + // operations using the new AsyncWork base class. Over time we will port + // all operations and perform needed cleanup. + // + // FIXME: This probably should be called WorkGloo since the work is executed + // in sync mode by a background thread. + class TORCH_API AsyncWork : public Work { + public: + explicit AsyncWork( + std::shared_ptr context, + std::vector> outputTensors, + OpType opType, + uint64_t seq, + std::chrono::milliseconds timeout, + const char* profilingTitle = nullptr, + const std::optional>& inputTensors = + std::nullopt); + + ~AsyncWork() override = default; + + static void execute(const c10::intrusive_ptr& work); + + virtual void run() = 0; + + std::vector result() override; + + c10::intrusive_ptr getFuture() override; + uint64_t getSequencenumber() const override; + std::chrono::milliseconds getTimeout() const; + virtual const std::vector getInputTensors() = 0; + virtual const std::vector getOutputTensors() = 0; + inline std::string getProfilerTitle() const { + return profilingTitle_; + } + inline at::ThreadLocalState getTLS() const { + return tls_; + } + + protected: + friend class ProcessGroupGloo; + // unique id used to tell the trace buffer that this + // work has completed + std::optional trace_id_; + std::optional trace_reset_epoch_; + std::shared_ptr context_; + const std::chrono::milliseconds timeout_; + + private: + void finishWorkGloo(); + void finishWorkGlooError(const std::exception_ptr& eptr); + inline void recordAsyncWorkProfilingInfo( + const char* profilingTitle, + const std::optional>& inputTensors); + + const std::vector> outputTensors_; + c10::intrusive_ptr future_; + std::function recordFunctionBeforeCallback_; + const uint64_t seq_; + std::string profilingTitle_; + at::ThreadLocalState tls_; + }; + + // Wrap c10d store as Gloo store + class TORCH_API GlooStore : public ::gloo::rendezvous::Store { + public: + GlooStore(c10::intrusive_ptr<::c10d::Store> store) + : store_(std::move(store)) {} + + void setUint(const std::string& key, const std::vector& value) { + store_->set(key, value); + } + + void set(const std::string& key, const std::vector& value) override { + std::vector tmp(value.begin(), value.end()); + store_->set(key, tmp); + } + + std::vector getUint(const std::string& key) { + auto value = store_->get(key); + return value; + } + + std::vector get(const std::string& key) override { + auto value = store_->get(key); + return std::vector(value.begin(), value.end()); + } + + void wait(const std::vector& keys) override { + store_->wait(keys, ::c10d::Store::kDefaultTimeout); + } + + void wait( + const std::vector& keys, + const std::chrono::milliseconds& timeout) override { + store_->wait(keys, timeout); + } + +#ifdef GLOO_STORE_HAS_STORE_V2 + bool has_v2_support() override { + return store_->hasExtendedApi(); + } + + std::vector> multi_get( + const std::vector& keys) override { + std::vector> res; + for (auto& value : store_->multiGet(keys)) { + res.emplace_back(value.begin(), value.end()); + } + return res; + } + + void multi_set( + const std::vector& keys, + const std::vector>& values) override { + std::vector> u_values; + u_values.reserve(values.size()); + for (auto& value : values) { + u_values.emplace_back(value.begin(), value.end()); + } + store_->multiSet(keys, u_values); + } + + void append(const std::string& key, const std::vector& value) + override { + std::vector tmp(value.begin(), value.end()); + return store_->append(key, tmp); + } + + int64_t add(const std::string& key, int64_t value) override { + return store_->add(key, value); + } +#endif + + const c10::intrusive_ptr<::c10d::Store>& _getStore() const { + return store_; + } + + protected: + c10::intrusive_ptr<::c10d::Store> store_; + }; + + // For send and recv operations there is no need to pass them to the + // thread pool as they are entirely completed by the device thread. + // This work object is used to synchronize completion of the send or + // recv operation. It keeps a reference to the tensor it is + // operating on to prevent it from being deallocated while the + // operation is still in flight. + class TORCH_API SendWork : public Work { + public: + explicit SendWork( + at::Tensor& tensor, + std::unique_ptr<::gloo::transport::UnboundBuffer> buffer, + uint64_t seq); + + bool wait(std::chrono::milliseconds timeout = kNoTimeout) override; + + void abort() override; + + uint64_t getSequencenumber() const override; + + protected: + at::Tensor tensor_; + std::unique_ptr<::gloo::transport::UnboundBuffer> buffer_; + const uint64_t seq_; + }; + + class TORCH_API RecvWork : public Work { + public: + explicit RecvWork( + at::Tensor& tensor, + std::unique_ptr<::gloo::transport::UnboundBuffer> buffer, + OpType opType, + uint64_t seq, + const char* profilingTitle = nullptr); + + int sourceRank() const override; + + bool wait(std::chrono::milliseconds timeout = kNoTimeout) override; + + void abort() override; + + uint64_t getSequencenumber() const override; + + protected: + at::Tensor tensor_; + std::unique_ptr<::gloo::transport::UnboundBuffer> buffer_; + int srcRank_; + const uint64_t seq_; + }; + + struct TORCH_API Options : public Backend::Options { + explicit Options( + std::chrono::milliseconds timeout = kBackendDefaultTimeout); + + // return intrusive_ptr of the object + static c10::intrusive_ptr create( + std::chrono::milliseconds timeout = kBackendDefaultTimeout) { + return c10::make_intrusive(timeout); + } + + static c10::intrusive_ptr create_default( + std::chrono::milliseconds timeout = kBackendDefaultTimeout); + + std::vector> devices; + int threads; + }; + + const std::string getBackendName() const override { + return std::string(GLOO_BACKEND_NAME); + } + + bool supportsSplitting() const override { + return true; + } + + // Helper functions to create a new device object. + // They are static functions on this class to keep them logically + // separate from the rest of the code base (e.g. torch/csrc/distributed). + + // Create new device instance for specific interface. + static std::shared_ptr<::gloo::transport::Device> createDeviceForInterface( + const std::string& interface, + bool lazyInit = false); + + // Create new device instance for specific hostname or address. + static std::shared_ptr<::gloo::transport::Device> createDeviceForHostname( + const std::string& hostname, + bool lazyInit = false); + + // Create new device instance. + // It tries to resolve this machine's hostname and bind to that address. + // If that fails (i.e. the hostname doesn't resolve to an address), it + // falls back to binding to the loopback address. + static std::shared_ptr<::gloo::transport::Device> createDefaultDevice( + bool lazyInit = false); + + explicit ProcessGroupGloo( + const c10::intrusive_ptr& store, + int rank, + int size, + c10::intrusive_ptr options = Options::create()); + + ~ProcessGroupGloo() override; + + c10::intrusive_ptr getOptions() { + return options_; + } + + void setTimeout(std::chrono::milliseconds timeout) override { + options_->timeout = timeout; + for (auto& context : contexts_) { + context->setTimeout(timeout); + } + } + + c10::intrusive_ptr getBackendOptions() override { + return c10::static_intrusive_pointer_cast(options_); + } + + c10::intrusive_ptr split( + const c10::intrusive_ptr& store, + const std::vector& ranks, + const c10::intrusive_ptr& opts) override; + + c10::intrusive_ptr merge( + const c10::intrusive_ptr& store, + const c10::intrusive_ptr& opts, + const int& rank, + const int& size) override; + + const std::vector& groupRanks() const; + + c10::intrusive_ptr broadcast( + std::vector& tensors, + const BroadcastOptions& opts = BroadcastOptions()) override; + + c10::intrusive_ptr allreduce( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce_sparse( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = + AllreduceCoalescedOptions()) override; + + c10::intrusive_ptr reduce( + std::vector& tensors, + const ReduceOptions& opts = ReduceOptions()) override; + + c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr _allgather_base( + at::Tensor& output_tensor, + at::Tensor& input_tensor, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr allgather( + std::vector>& outputs, + std::vector& inputs, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr allgather_coalesced( + std::vector>& output_lists, + std::vector& input_list, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr allgather_into_tensor_coalesced( + std::vector& outputs, + std::vector& inputs, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr gather( + std::vector>& outputs, + std::vector& inputs, + const GatherOptions& opts = GatherOptions()) override; + + c10::intrusive_ptr scatter( + std::vector& outputs, + std::vector>& inputs, + const ScatterOptions& opts = ScatterOptions()) override; + + c10::intrusive_ptr reduce_scatter( + std::vector& outputs, + std::vector>& inputs, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr reduce_scatter_tensor_coalesced( + std::vector& outputTensors, + std::vector& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr alltoall_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + std::vector& outputCounts, + std::vector& inputCounts, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) override; + + c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) override; + + c10::intrusive_ptr recvAnysource( + std::vector& tensors, + int tag) override; + + c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) override; + + void enableCollectivesTiming() override; + + const std::shared_ptr<::gloo::rendezvous::Store>& _getStore() const { + return store_; + } + + // Similar to barrier(), but blocks rank 0 until all other ranks have + // acknowledged that they are alive (through send/recv from rank 0). Rank 0 + // is able to report all failed ranks if waitAllRanks = true, otherwise + // reports the first rank it detected as failed. + void monitoredBarrier( + const BarrierOptions& opts = BarrierOptions(), + bool waitAllRanks = false) override; + + // Agrees on an initial sequence number for the whole group by having rank 0 + // create it and broadcast it to other ranks using the store. + void setSequenceNumberForGroup() override; + + // Retrieves the current sequence number for the whole group, which should be + // in sync. If the returned number is not consistent across the group, it + // may indicate that there is some sort of collective desynchronization. + uint64_t getSequenceNumberForGroup() override; + + int getNumThreads() { + return options_->threads; + } + + protected: + std::shared_ptr<::gloo::rendezvous::Store> store_; + const c10::intrusive_ptr options_; + + // Every Gloo context represents a set of connections to its peers. + // In order to use more than one device (or allow for parallelism on + // a single device), you need multiple contexts. + std::vector> contexts_; + std::vector threads_; + bool stop_; + + // Incremented for every collective we kick off. + // The value is used as tag for collective operations. Collectives are kicked + // off in identical order across processes. Therefore the tag can be used + // to match up operations during concurrent execution. + uint32_t collectiveCounter_; + + // Returns next collective tag to use (uses collectiveCounter_). + uint32_t nextTag(); + + // Returns the context to use for the specified tag. + // With `nextTag` returning an increasing number, this should lead + // to contexts being used in a round-robin fashion. + std::shared_ptr<::gloo::Context> getContext(uint32_t tag); + + // Entrypoint for worker threads. + void runLoop(int workerIndex); + + // Queue work to run on worker thread. + void enqueue(c10::intrusive_ptr work); + + // Keep both a queue of pending work, and a vector with in progress work. + // Both of these can only be mutated when holding the queue lock. + // We keep both around instead of just the queue, so we can grab a weak_ptr + // to all in progress and pending work when executing a barrier. + // When executing a barrier, we need to ensure that all prior work + // has completed before completing itself. + std::deque> workQueue_; + std::vector> workInProgress_; + std::mutex workMutex_; + std::condition_variable workProduceCV_; + std::condition_variable workConsumeCV_; + uint64_t seq_{0}; + size_t local_id_; + std::shared_ptr pgStatus_ = + std::make_shared(); +}; + +} // namespace c10d + +#endif // USE_C10D_GLOO + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGlooDetail.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGlooDetail.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4fa60b50e78683e889c9b153fd2e816350c1d44b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGlooDetail.hpp @@ -0,0 +1,679 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_GLOO + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#define GENERATE_ALL_TYPES(type, func, ...) \ + switch (type) { \ + case ::at::ScalarType::Float: \ + func(__VA_ARGS__); \ + break; \ + case ::at::ScalarType::Double: \ + func(__VA_ARGS__); \ + break; \ + case ::at::ScalarType::Half: \ + func(__VA_ARGS__); \ + break; \ + case ::at::ScalarType::BFloat16: \ + func(__VA_ARGS__); \ + break; \ + case ::at::ScalarType::Char: \ + func(__VA_ARGS__); \ + break; \ + case ::at::ScalarType::Byte: \ + case ::at::ScalarType::Bool: \ + func(__VA_ARGS__); \ + break; \ + case ::at::ScalarType::Int: \ + func(__VA_ARGS__); \ + break; \ + case ::at::ScalarType::Long: \ + func(__VA_ARGS__); \ + break; \ + default: \ + TORCH_CHECK(false, "Invalid scalar type"); \ + } + +#define HOST_NAME_MAX 256 +#else +#define GENERATE_ALL_TYPES(type, func, args...) \ + switch (type) { \ + case ::at::ScalarType::Float: \ + func(args); \ + break; \ + case ::at::ScalarType::Double: \ + func(args); \ + break; \ + case ::at::ScalarType::Half: \ + func(args); \ + break; \ + case ::at::ScalarType::BFloat16: \ + func(args); \ + break; \ + case ::at::ScalarType::Char: \ + func(args); \ + break; \ + case ::at::ScalarType::Byte: \ + case ::at::ScalarType::Bool: \ + func(args); \ + break; \ + case ::at::ScalarType::Int: \ + func(args); \ + break; \ + case ::at::ScalarType::Long: \ + func(args); \ + break; \ + default: \ + TORCH_CHECK(false, "Invalid scalar type"); \ + } +#endif + +namespace c10d { + +TORCH_DECLARE_TYPED_REGISTRY( + GlooAllreduceRegistry, + c10::DeviceType, + ProcessGroupGloo::AsyncWork, + c10::intrusive_ptr, + std::shared_ptr, + std::vector&, + ReduceOp, + uint32_t, + uint64_t, + std::chrono::milliseconds); + +// This function initializes a vector of CUDA streams, one for every +// tensor in the input tensor vector, and ensures that these streams are +// synchronized with the current default streams. This is needed so +// that new work on the new streams is serialized w.r.t. all operations +// on the tensors. +TORCH_API void initializeStreamsEvents( + const std::vector& tensors, + std::vector& streams, + std::vector& events); + +// This function initializes a vector of CUDA streams, one per device, +// and ensures that these streams are synchronized with the current default +// streams. It is assumed that the tensors in the nested tensor vectors are +// on the same device. +TORCH_API void initializeStreamsEvents( + std::vector>& tensors, + std::vector& streams, + std::vector& events); + +typedef void (*ReduceFunc)(void*, const void*, const void*, size_t); + +template , int> = 0> +ReduceFunc toFunction(const ReduceOp& r) { + switch (r) { + case ReduceOp::SUM: + case ReduceOp::AVG: + return ReduceFunc(&::gloo::sum); + case ReduceOp::PRODUCT: + return ReduceFunc(&::gloo::product); + case ReduceOp::MIN: + return ReduceFunc(&::gloo::min); + case ReduceOp::MAX: + return ReduceFunc(&::gloo::max); + case ReduceOp::BAND: + TORCH_CHECK(false, "Cannot use ReduceOp.BAND with non-integral dtype"); + break; + case ReduceOp::BOR: + TORCH_CHECK(false, "Cannot use ReduceOp.BOR with non-integral dtype"); + break; + case ReduceOp::BXOR: + TORCH_CHECK(false, "Cannot use ReduceOp.BXOR with non-integral dtype"); + break; + case ReduceOp::PREMUL_SUM: + TORCH_CHECK(false, "Cannot use ReduceOp.PREMUL_SUM with Gloo"); + break; + case ReduceOp::UNUSED: + default: + break; + } + + TORCH_CHECK(false, "Unhandled ReduceOp"); +} + +// Bitwise AND with SFINAE guard for integral types. +template , int> = 0> +void band(void* c, const void* a, const void* b, size_t n) { + auto tc = static_cast(c); + auto ta = static_cast(a); + auto tb = static_cast(b); + for (const auto i : c10::irange(n)) { + tc[i] = ta[i] & tb[i]; + } +} + +// Bitwise OR with SFINAE guard for integral types. +template , int> = 0> +void bor(void* c, const void* a, const void* b, size_t n) { + auto tc = static_cast(c); + auto ta = static_cast(a); + auto tb = static_cast(b); + for (const auto i : c10::irange(n)) { + tc[i] = ta[i] | tb[i]; + } +} + +// Bitwise XOR with SFINAE guard for integral types. +template , int> = 0> +void bxor(void* c, const void* a, const void* b, size_t n) { + auto tc = static_cast(c); + auto ta = static_cast(a); + auto tb = static_cast(b); + for (const auto i : c10::irange(n)) { + tc[i] = ta[i] ^ tb[i]; + } +} + +template , int> = 0> +ReduceFunc toFunction(const ReduceOp& r) { + switch (r) { + case ReduceOp::SUM: + case ReduceOp::AVG: + return ReduceFunc(&::gloo::sum); + case ReduceOp::PRODUCT: + return ReduceFunc(&::gloo::product); + case ReduceOp::MIN: + return ReduceFunc(&::gloo::min); + case ReduceOp::MAX: + return ReduceFunc(&::gloo::max); + case ReduceOp::BAND: + return ReduceFunc(&band); + case ReduceOp::BOR: + return ReduceFunc(&bor); + case ReduceOp::BXOR: + return ReduceFunc(&bxor); + case ReduceOp::PREMUL_SUM: + TORCH_CHECK(false, "Cannot use ReduceOp.PREMUL_SUM with Gloo"); + break; + case ReduceOp::UNUSED: + default: + break; + } + + TORCH_CHECK(false, "Unhandled ReduceOp"); +} + +template +void setInputs(O& opts, std::vector& tensors) { + opts.setInputs(getDataPointers(tensors), tensors[0].numel()); +} + +template +void setInput(O& opts, at::Tensor& tensor) { + opts.setInput(getDataPointer(tensor), tensor.numel()); +} + +template +void setInput(O& opts, at::Tensor& tensor, std::vector& counts) { + opts.setInput(getDataPointer(tensor), counts); +} + +template +void setInput(O& opts, at::Tensor& tensor, std::vector& counts) { + opts.setInput(getDataPointer(tensor), counts); +} + +template +void setOutputs(O& opts, std::vector& tensors, int64_t count) { + opts.setOutputs(getDataPointers(tensors), count); +} + +template +void setOutput(O& opts, at::Tensor& tensor) { + opts.setOutput(getDataPointer(tensor), tensor.numel()); +} + +template +void setOutput(O& opts, at::Tensor& tensor, std::vector& counts) { + opts.setOutput(getDataPointer(tensor), counts); +} + +template +void setOutput(O& opts, at::Tensor& tensor, std::vector& counts) { + opts.setOutput(getDataPointer(tensor), counts); +} + +static at::Tensor pinnedLike(at::Tensor& tensor) { + auto* allocator = at::detail::getCUDAHooks().getPinnedMemoryAllocator(); + auto storage = c10::Storage( + c10::Storage::use_byte_size_t(), + static_cast(at::detail::computeStorageNbytes( + tensor.sizes(), tensor.strides(), tensor.dtype().itemsize())), + allocator, + /*resizable=*/false); + return at::empty({0}, tensor.options().device(at::kCPU)) + .set_(storage, 0, tensor.sizes(), tensor.strides()); +} + +class AsyncAllreduceWork : public ProcessGroupGloo::AsyncWork { + public: + AsyncAllreduceWork( + std::shared_ptr context, + std::vector& inputs, + ReduceOp reduceOp, + uint32_t tag, + uint64_t seq, + std::chrono::milliseconds timeout) + : ProcessGroupGloo::AsyncWork( + std::move(context), + {inputs}, + OpType::ALLREDUCE, + seq, + timeout, + "gloo:all_reduce", + inputs), + inputs(inputs), + reduceOp(std::move(reduceOp)), + tag(tag) {} + + std::vector inputs; + const ReduceOp reduceOp; + const uint32_t tag; + + void allreduce(std::vector& tensors) { + auto tensor = tensors[0]; + if (tensor.is_complex()) { + TORCH_CHECK( + c10d::isComplexViewAsRealAllowed(reduceOp), + "all_reduce does not support", + reduceOp, + "on complex tensors"); + tensor = at::view_as_real(tensor); + } + gloo::AllreduceOptions opts(context_); + const auto& scalarType = tensor.scalar_type(); + opts.setReduceFunction(getFunction(scalarType, reduceOp)); + opts.setTag(tag); + opts.setTimeout(timeout_); + // Use tensor.numel() instead of tensors[0].numel() to + // get the right number of elements when tensors[0] is complex + GENERATE_ALL_TYPES(scalarType, setOutputs, opts, tensors, tensor.numel()); + gloo::allreduce(opts); + + // Gloo doesn't support AVG so we use SUM + division. + if (reduceOp == ReduceOp::AVG) { + tensors[0] /= context_->size; + } + } + + const std::vector getInputTensors() override { + return inputs; + } + + const std::vector getOutputTensors() override { + return inputs; + } + + void run() override { + allreduce(inputs); + } + + template + void getFunction(gloo::AllreduceOptions::Func& fn, const ReduceOp op) { + fn = toFunction(op); + } + + gloo::AllreduceOptions::Func getFunction( + const at::ScalarType& dtype, + const ReduceOp& op) { + gloo::AllreduceOptions::Func fn; + GENERATE_ALL_TYPES(dtype, getFunction, fn, op); + return fn; + } +}; + +class AsyncAllreduceCoalescedWork : public AsyncAllreduceWork { + public: + AsyncAllreduceCoalescedWork( + const std::shared_ptr& context, + std::vector& inputs, + ReduceOp reduceOp, + uint32_t tag, + uint64_t seq, + std::chrono::milliseconds timeout) + : AsyncAllreduceWork( + context, + inputs, + std::move(reduceOp), + tag, + seq, + timeout) {} + + void run() override { + allreduceCoalesced(inputs); + } + + private: + void allreduceCoalesced(std::vector& tensors) { + // reduce coalesced, flattened tensors. + at::Tensor coalescedTensor = flattenDenseTensors(tensors); + std::vector allreduceInput = {coalescedTensor}; + allreduce(allreduceInput); + + // separate and reshape tensors. + size_t offset = 0; + for (at::Tensor& tensor : tensors) { + const int64_t tensorNumel = tensor.numel(); + const c10::IntArrayRef tensorShape = tensor.sizes(); + tensor.copy_(coalescedTensor.slice(0, offset, offset + tensorNumel) + .view(tensorShape)); + offset += tensorNumel; + } + } +}; + +class AsyncSparseAllreduceWork : public ProcessGroupGloo::AsyncWork { + public: + AsyncSparseAllreduceWork( + std::shared_ptr context, + std::vector& inputs, + uint32_t tag, + uint64_t seq, + std::chrono::milliseconds timeout) + : ProcessGroupGloo::AsyncWork( + std::move(context), + {inputs}, + OpType::_ALLREDUCE_SPARSE, + seq, + timeout, + "gloo:sparse_all_reduce", + inputs), + inputs(inputs), + tag(tag) {} + + std::vector inputs; + const uint32_t tag; + + // We share dimensionality about the sparse tensors before collecting + // their contents. We assume here that the maximum number of sparse + // and dense dimensions is 4. This is stored in a contiguous piece of + // memory so that we can easily run allgather on it. + // + // The layout of this memory is as follows: + // + // - [0:4]: sparse dims + // - [4:8]: dense dims + // - [8]: nnz + // + class SparseTensorMetadata { + public: + static constexpr auto dim = 9; + + // Construct from an existing metadata tensor to facilitate structured + // access to metadata from peers, after gathering it. + explicit SparseTensorMetadata(at::Tensor metadata) + : metadata_(std::move(metadata)), + data_(metadata_.mutable_data_ptr()) { + AT_ASSERT(metadata_.scalar_type() == at::kLong); + AT_ASSERT(metadata_.dim() == 1); + AT_ASSERT(metadata_.size(0) == dim); + } + + // Populate the metadata. + void populate_from_sparse_tensor(const at::Tensor& tensor) { + const auto sparse_dim = tensor.sparse_dim(); + AT_ASSERT(sparse_dim <= 4); + for (const auto i : c10::irange(4)) { + if (i < sparse_dim) { + data_[i] = tensor.size(i); + } + } + const auto dense_dim = tensor.dense_dim(); + AT_ASSERT(dense_dim <= 4); + for (const auto i : c10::irange(4)) { + if (i < dense_dim) { + data_[i + 4] = tensor.size(sparse_dim + i); + } + } + data_[8] = tensor._nnz(); + } + + std::vector sizes() const { + std::vector sizes; + // Sparse sizes + for (const auto i : c10::irange(4)) { + if (data_[i] <= 0) { + break; + } + sizes.push_back(data_[i]); + } + // Dense sizes + for (const auto i : c10::irange(4, 8)) { + if (data_[i] <= 0) { + break; + } + sizes.push_back(data_[i]); + } + return sizes; + } + + int64_t nnz() const { + return data_[8]; + } + + protected: + at::Tensor metadata_; + int64_t* data_; + }; + + // Sparse allreduce is implemented with allgather on indices and values. + // Every process then sums the resulting sparse tensors locally. + // The nnz for sparse tensors may be different across processes, so first + // we run allgather on the nnz, and then allgather with max(nnz). + at::Tensor allreduce(std::vector& tensors) { + // TODO: This is a massive hack! There is some confusion about + // Variable/Tensor inside the body of this function. Turning off + // grad smooths over the confusion for now. This fixes + // test/test_c10d_gloo.py ProcessGroupGlooTest.test_sparse_allreduce_basics + // + // The correct fix is to stop allocating tensors that are not variables, + // but to conveniently do this c10d must depend on torch not ATen + at::AutoDispatchBelowAutograd guard; + auto input = tensors[0]; + + // Perform local reduction if we have multiple inputs. + for (const auto i : c10::irange(1, tensors.size())) { + input += tensors[i]; + } + + // Need to coalesce before we can access indices and values. + input = input.coalesce(); + + // Gather metadata information from all ranks. + auto metadata = allgather_metadata(input); + + // Sanity check dimensionality across ranks. + { + const auto expected = metadata[context_->rank].sizes(); + for (const auto i : c10::irange(context_->size)) { + if (i == context_->rank) { + continue; + } + const auto actual = metadata[i].sizes(); + TORCH_CHECK(actual == expected, "Sparse dimensions do not match"); + } + } + + // Gather all indices and all values. + auto indices = allgather_indices(input, metadata); + auto values = allgather_values(input, metadata); + + // Perform global reduction. + AT_ASSERT(static_cast(indices.size()) == context_->size); + AT_ASSERT(static_cast(values.size()) == context_->size); + auto output = at::sparse_coo_tensor( + indices[0], values[0], input.sizes(), input.options()); + for (const auto i : c10::irange(1, context_->size)) { + output += at::sparse_coo_tensor( + indices[i], values[i], input.sizes(), input.options()); + } + + // Coalesce for good measure. + return output.coalesce(); + } + + void run() override { + auto output = allreduce(inputs); + + // This copy is needed when we run a multi-gpu version of reduce (multiple + // inputs per rank). + for (const auto i : c10::irange(inputs.size())) { + inputs[i].copy_(output); + } + } + + const std::vector getInputTensors() override { + return inputs; + } + + const std::vector getOutputTensors() override { + return inputs; + } + + private: + std::vector allgather_metadata( + const at::Tensor& tensor) { + auto buffer = + at::zeros({context_->size, SparseTensorMetadata::dim}, at::kLong); + + // Prepare metadata vector (1 entry per rank) + std::vector metadata; + metadata.reserve(context_->size); + for (const auto i : c10::irange(context_->size)) { + metadata.emplace_back(buffer.select(0, i)); + } + + // Populate data for this rank + metadata[context_->rank].populate_from_sparse_tensor(tensor); + + // Allgather metadata + gloo::AllgatherOptions opts(context_); + opts.setOutput(buffer.mutable_data_ptr(), buffer.numel()); + opts.setTag(tag); + opts.setTimeout(timeout_); + gloo::allgather(opts); + + return metadata; + } + + std::vector allgather_indices( + const at::Tensor& tensor, + const std::vector& metadata) { + const auto sparseDim = tensor.sparse_dim(); + + std::vector counts(context_->size); + size_t totalSize = 0; + for (const auto i : c10::irange(metadata.size())) { + counts[i] = metadata[i].nnz() * sparseDim; + totalSize += counts[i]; + } + + auto output = at::empty({static_cast(totalSize)}, at::kLong); + + // tensors copied from cuda may not be contiguous, get a contiguous + // tensor before use its data_ptr + auto input = tensor.indices().contiguous(); + + // Allgatherv indices. + gloo::AllgathervOptions opts(context_); + opts.setInput( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + const_cast(input.const_data_ptr()), + input.numel()); + opts.setOutput(output.mutable_data_ptr(), counts); + opts.setTag(tag); + opts.setTimeout(timeout_); + gloo::allgatherv(opts); + + // Compile indices tensor per rank. + std::vector indices; + indices.reserve(metadata.size()); + int64_t offset = 0; + for (const auto& i : metadata) { + const auto nnz = i.nnz(); + const auto numel = sparseDim * nnz; + indices.push_back( + output.narrow(0, offset, numel).reshape({sparseDim, nnz})); + offset += numel; + } + + return indices; + } + + std::vector allgather_values( + const at::Tensor& tensor, + const std::vector& metadata) { + // There are nnz #dense_dim()-dimensional tensors per rank. + const auto valueShape = tensor.sizes().slice(tensor.sparse_dim()); + int64_t denseNumel = 1; + for (auto dim : valueShape) { + denseNumel *= dim; + } + + std::vector counts(context_->size); + int64_t totalSize = 0; + for (const auto i : c10::irange(metadata.size())) { + counts[i] = metadata[i].nnz() * denseNumel; + totalSize += static_cast(counts[i]); + } + + auto output = at::empty({totalSize}, tensor.scalar_type()); + + // Allgatherv indices. + gloo::AllgathervOptions opts(context_); + // tensors copied from cuda may not be contiguous, get a contiguous + // tensor before use its data_ptr + at::Tensor valueTensor = tensor.values().contiguous(); + GENERATE_ALL_TYPES(valueTensor.scalar_type(), setInput, opts, valueTensor); + GENERATE_ALL_TYPES( + valueTensor.scalar_type(), setOutput, opts, output, counts); + opts.setTag(tag); + opts.setTimeout(timeout_); + gloo::allgatherv(opts); + + // Compile values tensor per rank. + std::vector values; + values.reserve(metadata.size()); + int64_t offset = 0; + for (const auto& i : metadata) { + const auto nnz = i.nnz(); + const auto numel = denseNumel * nnz; + auto tensorShape = std::vector({(int64_t)nnz}); + std::copy( + valueShape.begin(), + valueShape.end(), + std::back_inserter(tensorShape)); + values.push_back(output.narrow(0, offset, numel).reshape(tensorShape)); + offset += numel; + } + + return values; + } +}; + +} // namespace c10d + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupMPI.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupMPI.hpp new file mode 100644 index 0000000000000000000000000000000000000000..66d592145e2a8cc0d5ebe5a97c43e660788a6606 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupMPI.hpp @@ -0,0 +1,278 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_MPI + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include + +namespace c10d { + +constexpr const char* MPI_BACKEND_NAME = "mpi"; + +// WorkEntry is the state associated with a single MPI run instance. +// It include the source Tensor list and destination Tensor list, as well as +// The actual run function that will operate either on src or dst or both. +struct WorkEntry { + explicit WorkEntry( + std::vector* srcPtr, + std::vector* dstPtr, + std::function&)> run) + : dst(dstPtr ? *dstPtr : std::vector()), run(std::move(run)) { + if (srcPtr) { + src = *srcPtr; + } + } + + // Not copyable + WorkEntry(const WorkEntry&) = delete; + // Not copy assignable + WorkEntry& operator=(const WorkEntry&) = delete; + + // For input and output tensors (in-place), we will always use src + std::vector src; + + // Copy of user provided outputs. + const std::vector dst; + + // src rank returned, for recv only + int* srcRank = nullptr; + std::function&)> run; +}; + +// ProcessGroupMPI implements MPI bindings for c10d. +// +// All functions on this class are expected to be called in the same +// order across processes in the group. This is the only way that we +// can guarantee to match up the same calls across processes. +// +// All MPI functions provided by this class is asynchronously scheduled on a +// Worker thread. Therefore, ProcessGroupMPI requires the MPI implementation +// that is used to have a minimum thread support value of MPI_THREAD_SERIALIZED. +// That is, The process may be multi-threaded, and multiple threads may make +// MPI calls, but only one at a time: MPI calls are not made concurrently from +// two distinct threads (all MPI calls are serialized). However, with +// MPI_THREAD_SERIALIZED, ProcessGroupMPI will only support a single process +// group. In other words, no more than 1 process group can be created globally. +// +// If you would like to use multiple ProcessGroupMPI, it requires your MPI +// implementation to have a thread support value of MPI_THREAD_MULTIPLE, that +// is, multiple threads may call MPI, with no restriction. +// +// Also note that ProcessGroupMPI only supports a single Tensor operation. In +// other words, the size of the input Tensor vector should always be 1. +// +// CUDA tensor can be supported if the MPI used is CUDA-aware MPI, and +// ProcessGroupMPI will automatically detect this support. +class TORCH_API ProcessGroupMPI : public Backend { + public: + class WorkMPI : public Work { + public: + explicit WorkMPI( + std::vector outputTensors, + const char* profilingTitle = nullptr, + const std::optional>& inputTensors = + std::nullopt) + : Work(-1, OpType::UNKNOWN, profilingTitle, inputTensors), + outputTensors_(std::move(outputTensors)), + future_(c10::make_intrusive( + c10::ListType::create(c10::TensorType::get()))) {} + + std::vector result() override; + + c10::intrusive_ptr getFuture() override; + + protected: + friend class ProcessGroupMPI; + + private: + void finishWorkMPI(); + void finishWorkMPIError(const std::exception_ptr& eptr); + + std::vector outputTensors_; + c10::intrusive_ptr future_; + }; + + class AsyncWork : public Work { + public: + AsyncWork( + MPI_Request request, + std::vector outputTensors, + const char* profilingTitle = nullptr, + const std::optional>& inputTensors = + std::nullopt); + + ~AsyncWork() override; + + bool isCompleted() override; + + bool isSuccess() const override; + + int sourceRank() const override; + + bool wait(std::chrono::milliseconds timeout = kUnsetTimeout) override; + + void abort() override; + + std::vector result() override; + + protected: + void populateException(); + + private: + const std::vector outputTensors_; + MPI_Request request_; + MPI_Status status_{}; + }; + + // Constructor will spawn up the worker thread loop + explicit ProcessGroupMPI(int rank, int size, MPI_Comm pgComm); + + ~ProcessGroupMPI() override; + + // Abort the MPI program, needs to be called when exception is detected + void abort() override; + + const std::string getBackendName() const override { + return std::string(MPI_BACKEND_NAME); + } + + c10::intrusive_ptr broadcast( + std::vector& data, + const BroadcastOptions& opts = BroadcastOptions()) override; + + c10::intrusive_ptr allreduce( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = + AllreduceCoalescedOptions()) override; + + c10::intrusive_ptr reduce( + std::vector& tensors, + const ReduceOptions& opts = ReduceOptions()) override; + + c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr _allgather_base( + at::Tensor& outputbuffer, + at::Tensor& inputbuffer, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr allgather_coalesced( + std::vector>& outputTensorLists, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr gather( + std::vector>& outputTensors, + std::vector& inputTensors, + const GatherOptions& opts = GatherOptions()) override; + + c10::intrusive_ptr scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ScatterOptions& opts = ScatterOptions()) override; + + c10::intrusive_ptr reduce_scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr alltoall_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + std::vector& outputSplitSizes, + std::vector& inputSplitSizes, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr alltoall( + std::vector& outputTensors, + std::vector& inputTensors, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) override; + + c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) override; + + c10::intrusive_ptr recvAnysource( + std::vector& tensor, + int tag) override; + + c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) override; + + // Creating a new ProcessGroupMPI, will initialize MPI if not initialized + static c10::intrusive_ptr createProcessGroupMPI( + std::vector ranks = {}); + + protected: + using WorkType = + std::tuple, c10::intrusive_ptr>; + // Worker thread loop + void runLoop(); + // Helper function that is called by the destructor + void destroy(); + + c10::intrusive_ptr enqueue( + std::unique_ptr entry, + const char* profilingTitle = nullptr, + const std::optional>& inputTensors = + std::nullopt); + + bool stop_; + + std::mutex pgMutex_; + std::thread workerThread_; + + std::deque queue_; + std::condition_variable queueProduceCV_; + std::condition_variable queueConsumeCV_; + + // Global states + static void initMPIOnce(); + static void mpiExit(); + + static std::mutex pgGlobalMutex_; + static int mpiThreadSupport_; + + MPI_Comm pgComm_; +}; + +} // namespace c10d + +#endif // USE_C10D_MPI + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp new file mode 100644 index 0000000000000000000000000000000000000000..262f50440c2f6550d4449aac19f737b70c1f22bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp @@ -0,0 +1,1535 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_NCCL + +#if defined(__linux__) +#include +#include +#include +#include +#endif + +#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 c10d { + +// Control broadcasting of NCCL uniqueId +static std::vector TORCH_NCCL_BCAST_UNIQUEID = { + "TORCH_NCCL_BCAST_UNIQUEID"}; + +// Control EagerInit P2P serialization warning +static std::vector + TORCH_NCCL_SHOW_EAGER_INIT_P2P_SERIALIZATION_WARNING = { + "TORCH_NCCL_SHOW_EAGER_INIT_P2P_SERIALIZATION_WARNING"}; + +// Control whether to always use high priority streams +static std::vector TORCH_NCCL_HIGH_PRIORITY = { + "TORCH_NCCL_HIGH_PRIORITY"}; + +// Control whether or not wait() is blocking or non-blocking. +static std::vector TORCH_NCCL_BLOCKING_WAIT = { + "TORCH_NCCL_BLOCKING_WAIT", + "NCCL_BLOCKING_WAIT"}; + +// TODO: We want to eventually remove this variable and make users to use +// the default value (3 - SkipCleanUp). +// Control whether or not we perform Async Error Handling with NCCL. +static std::vector TORCH_NCCL_ASYNC_ERROR_HANDLING = { + "TORCH_NCCL_ASYNC_ERROR_HANDLING", + "NCCL_ASYNC_ERROR_HANDLING"}; + +// Control whether dumping debug info on watchdog +// timeout is enabled. This variable must be set together with +// TORCH_NCCL_ENABLE_MONITORING=1 and TORCH_NCCL_TRACE_BUFFER_SIZE > 0. +static std::vector TORCH_NCCL_DUMP_ON_TIMEOUT = { + "TORCH_NCCL_DUMP_ON_TIMEOUT"}; + +// Control whether to propagate NCCL errors to all ranks through TCPStore. +static std::vector TORCH_NCCL_PROPAGATE_ERROR = { + "TORCH_NCCL_PROPAGATE_ERROR"}; + +// Control whether Desync Debug is enabled. This variable must be set +// together with TORCH_NCCL_ASYNC_ERROR_HANDLING. +static std::vector TORCH_NCCL_DESYNC_DEBUG = { + "TORCH_NCCL_DESYNC_DEBUG", + "NCCL_DESYNC_DEBUG"}; + +// Enable recording start-events for all ProcessGroupNCCL collectives, and +// compute accurate collective timing per-collective. (Note: end-events are +// recorded by default. Turn on this flag can increase chances of a watchdog +// hang due to performing a CUDA event query which eventually calls +// cudaEventElapsedTime() API. +static std::vector TORCH_NCCL_ENABLE_TIMING = { + "TORCH_NCCL_ENABLE_TIMING", + "NCCL_ENABLE_TIMING"}; + +// Enable monitoring thread which aborts the process when the ProcessGroupNCCL +// Watchdog thread gets stuck and no heartbeat is detected after +// TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC. This can happen due to calling CUDA/NCCL +// APIs that may hang. It is Useful to prevent jobs being stuck for a prolonged +// time than necessary tying up cluster resources. +static std::vector TORCH_NCCL_ENABLE_MONITORING = { + "TORCH_NCCL_ENABLE_MONITORING"}; + +// Control the watchdog heartbeat timeout period after which the monitoring +// thread will abort the process. +static std::vector TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC = { + "TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC"}; + +// Whether to rethrow CUDA Errors in the watchdog (default true) +static std::vector TORCH_NCCL_RETHROW_CUDA_ERRORS = { + "TORCH_NCCL_RETHROW_CUDA_ERRORS"}; + +// The maximum number of events we store in the flight recorder's ring buffer. +// (One event could be the start or end of a collective, for example). +static std::vector TORCH_NCCL_TRACE_BUFFER_SIZE = { + "TORCH_NCCL_TRACE_BUFFER_SIZE"}; + +// Control how much extra time we will wait for dumping the debugging info +// before we exit and throws timeout exception. +static std::vector TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC = { + "TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC"}; + +// Control the interval inside the monitoring thread to check the coordinated +// signal from other ranks, e.g. to dump the debugging information. +static std::vector TORCH_NCCL_COORD_CHECK_MILSEC = { + "TORCH_NCCL_COORD_CHECK_MILSEC"}; + +// Whether to log C++ stack traces on unclean shutdown (default true) +static std::vector TORCH_NCCL_LOG_CPP_STACK_ON_UNCLEAN_SHUTDOWN = { + "TORCH_NCCL_LOG_CPP_STACK_ON_UNCLEAN_SHUTDOWN"}; + +// Whether to include only active collectives in the Flight Recorder trace +// (default false) +static std::vector TORCH_NCCL_EXTRA_DUMP_ON_EXEC = { + "TORCH_NCCL_EXTRA_DUMP_ON_EXEC"}; + +// Control whether to use CudaEventCache for the collective in watchdog thread. +// We noticed in the past when cuda global lock is held, destroying CudaEvent +// can cause a hang. +static std::vector TORCH_NCCL_CUDA_EVENT_CACHE = { + "TORCH_NCCL_CUDA_EVENT_CACHE"}; + +// Control the number of ranks each root can cover during NCCL comm init. +static std::vector TORCH_NCCL_RANKS_PER_ROOT = { + "TORCH_NCCL_RANKS_PER_ROOT"}; + +static std::vector TORCH_NCCL_NAN_CHECK = {"TORCH_NCCL_NAN_CHECK"}; + +constexpr const char* NCCL_BACKEND_NAME = "nccl"; + +constexpr const char* kStoreDumpKey = "exception_dump"; + +constexpr const char* kStoreErrorSignalKey = "remote_error"; + +constexpr const int kWorkStatusUpdatePeriodMs = 30 * 1000; // 30 seconds + +constexpr auto kProcessGroupNCCLDefaultTimeout = + std::chrono::milliseconds(10 * 60 * 1000); + +// NoHandling: do not handle asynchronous NCCL errors +// TearDown: tear down process upon error, see `WorkNCCL::handleException` +// CleanUpOnly: just clean up collectives and abort communicators without +// tearing down process SkipCleanUp: (this is a temporary option and can be +// removed in future) tear down process without cleaning up NCCL communicators. +// This should be used as a last resort in case `ncclCommAbort` itself is +// hanging +enum ErrorHandlingMode { + NoHandling = 0, + TearDown = 1, + CleanUpOnly = 2, + SkipCleanUp = 3 +}; + +#define SHOULD_CLEAN_UP(a) (a != NoHandling && a != SkipCleanUp) + +#define SHOULD_TEAR_DOWN(a) (a != NoHandling && a != CleanUpOnly) + +#define PRINT_COLLECTIVE_HASH_SIGNATURE(phase, opType, numel, hashValue) \ + LOG(WARNING) << logPrefix() << "Hash of " << phase << " to NCCL " << opType \ + << " with size " << numel << " is " << hashValue; + +// If set, ProcessGroupNCCL doesn't use recordStream calls to ensure +// caching allocator safety for tensors used on both user-facing and +// internal comm streams. +// Instead, it stashes live references to those tensors until after +// user-facing streams are synced with comm streams. +// See stashed_for_allocator_safety_ below. +static std::vector TORCH_NCCL_AVOID_RECORD_STREAMS = { + "TORCH_NCCL_AVOID_RECORD_STREAMS"}; + +// If set, ProcessGroupNCCL registers postAlloc and preFree hooks to cuda cache +// allocator so that whenever a tensor is allocated or freed, ProcessGroupNCCL +// can register/deregister the tensor on all available NCCL communicators. +static std::vector TORCH_NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK = + {"TORCH_NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK", + "NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK"}; + +#if defined(__linux__) +struct DumpPipe { + DumpPipe(int rank) { + std::string fileStem = + getCvarString({"TORCH_NCCL_DEBUG_INFO_PIPE_FILE"}, ""); + if (fileStem.empty() || + getCvarInt({"TORCH_NCCL_TRACE_BUFFER_SIZE"}, 0) <= 0) { + return; + } + TORCH_CHECK(!fileStem.empty(), "TORCH_NCCL_DEBUG_INFO_PIPE_FILE is empty"); + std::string filename = c10::str(fileStem, rank, ".pipe"); + TORCH_CHECK( + unlink(filename.c_str()) != -1 || errno == ENOENT, + "Error removing existing named pipe ", + filename, + ", Error: ", + std::strerror(errno)); + TORCH_CHECK( + mkfifo(filename.c_str(), 0666) != -1, + "Error creating named pipe ", + filename, + ", Error: ", + std::strerror(errno)); + fd_ = open(filename.c_str(), O_RDONLY | O_NONBLOCK); + LOG(INFO) << "Pipe file " << filename + << " has been opened, write to it to trigger NCCL Debug Dump."; + TORCH_CHECK(fd_ != -1, "Error opening named pipe ", filename); + } + bool shouldDump() { + if (fd_ == -1) { + return false; + } + // NOLINTNEXTLINE(*array*) + char buf[128]{}; + // non-blocking from O_NONBLOCK above. + // Ignore EINTR because we already will poll this + // again later. + ssize_t bytesRead = read(fd_, &buf, 128); + return bytesRead > 0; + } + ~DumpPipe() { + if (fd_ != -1) { + close(fd_); + } + } + + private: + int fd_ = -1; +}; +#else +struct DumpPipe { + DumpPipe(int rank) {} + bool shouldDump() { + return false; + } +}; +#endif + +// A shelf for stashing tensors between op call and `work.wait()`. +// Used in case of async ops. +class TensorShelf { + public: + // Stash tensors so that CachingAllocator cannot recycle them prematurely. + void stash(std::vector& tensors); + // Stash tensors from another shelf. + void stash(TensorShelf& other); + // Unstage the stashed tensors so that CachingAllocator can recycle them. + // Same as `clear()`. + void unstash(); + // Whether shelf is empty. + bool empty(); + // Clear the shelf. + void clear(); + + protected: + // Get the inner tensor vector. Use with caution as it is not protected by + // mutex. + std::vector& get(); + + private: + std::vector tVector_; + // Need a mutex to protect `tVector_` because it can be potentially accessed + // from both main thread and watchdog thread. + std::mutex mutex_; +}; + +// ProcessGroupNCCL implements NCCL bindings for c10d. +// +// All functions of the class are expected to be called in the same order +// across all processes in the process group. This is the only way that we +// can guarantee to match up the same calls among all processes. +// +// All NCCL functions provided by this class are asynchronous functions. More +// specifically, each NCCL call is scheduled on a separate CUDA stream that is +// different from the current CUDA stream. This is for the purpose of +// achieving potentially concurrency and better performance. As a result, +// it is the callers' responsibility to make sure that the CUDA stream their +// code works on needs to wait for the NCCL operation from +// this class. +// +// This can be done by calling: +// +// either WorkNCCL::wait() or WorkNCCL::synchronize(), both achieves the same +// functionality and are synonyms. +// +// Also note that WorkNCCL::finishedGPUExecution() is a helper function only +// provided by ProcessGroupNCCL to check if the NCCL operation of WorkNCCL has +// finished execution on the GPU (not just scheduled). +// +// Example on using the NCCL process group +// +// ProcessGroupNCCL pg(store, rank, size); +// std::shared_ptr work = pg.allreduce(tensors); +// +// // At this point, NCCL kernel has already by queued successfully +// // Now, let current stream wait for the NCCL to finish, this function is +// // async operation as well +// +// work->wait() +// +// // Now continue on other work in the current stream. +class TORCH_API ProcessGroupNCCL : public Backend { + public: + class WorkNCCL : public Work, public std::enable_shared_from_this { + public: + friend struct WorkInfo; + + // Constructor takes a list of CUDA devices + WorkNCCL( + std::string pgUID, + std::string pgDesc, + at::Device& device, + int rank, + OpType opType, + uint64_t seq, + bool isP2P = false, + const char* profilingTitle = nullptr, + const std::optional>& inputs = std::nullopt, + bool enableTiming = false, + bool cudaEventCacheEnabled = false, + DebugLevel distDebugLevel = DebugLevel::Off); + // Copy constructor doing partial copy without outputs_. Cleanup thread + // monitors and removes finished works. However it will deadlock when + // destructs outputs_ tensors who are view tensors in autograd graph. + WorkNCCL(const WorkNCCL& w); + + ~WorkNCCL() override = default; + + // Checks if the NCCL kernel has started to execute. + bool isStarted(); + + // Checks if request has completed. In this specific case of NCCL, it checks + // if the NCCL operation has completed on the GPU in its own NCCL stream. + // Non-blocking operation. + bool isCompleted() override; + + bool isSuccess() const override; + + // Same as calling synchronize() for NCCL work if timeout is not set. + // Otherwise, it will block the CPU thread until the NCCL work is completed + // or timed out. If timeout, exception will be thrown. + bool wait(std::chrono::milliseconds timeout = kNoTimeout) override; + + void blockCurrentStream() override { + synchronize(); + } + + void abort() override; + + // Let current stream wait on the completion of the NCCL work + // Throws on exceptions. + void synchronize() override; + + // Synchronize streams by blocking each on the NCCL stream + void synchronizeStream(); + + // Helper function to handle exception (throw if needed). + void handleException(ErrorHandlingMode asyncErrorHandling); + + // Helper function that checks if the NCCL kernels have finished + // execution on the GPUs + bool finishedGPUExecution(); + + // Get a Future object that will be marked as completed internally. + c10::intrusive_ptr getFuture() override; + + // Get a Future result of each work (e.g. success, different error types). + // instead of the tensor output. + c10::intrusive_ptr getFutureResult() override; + + float getDuration() const override; + + uint64_t getSequencenumber() const override; + + const std::string& logPrefix() const; + + // Helper function that sets an exception_ptr on the WorkNCCL object. + void setException(std::exception_ptr exception_ptr); + + // Helper function that returns True if the WorkNCCL object has timed out + // and False otherwise. + // In case of timeout, set exception on the WorkNCCL object. + bool checkTimeout( + std::optional timeout = std::nullopt); + + // Print the traceback of the collective at call time + void printTraceback() const; + + std::string getTraceback() const; + + std::vector result() override; + + protected: + // The process group unique id + std::string pgUID_; + + // The process group description + std::string pgDesc_; + + // The cached list of CUDA devices to operate on + at::Device device_; + + // The start CUDA event of NCCL operator tracking this work item. These + // start CUDA events are needed by desync debugging if enabled. + std::shared_ptr ncclStartEvent_; + + // The end CUDA event of NCCL operator tracking this work item. + std::shared_ptr ncclEndEvent_; + + // The NCCL communicator used for this work item. + std::shared_ptr ncclComm_; + + // whether this work is a barrier op + bool isBarrierOp_{false}; + + // Clone of blockingWait_ from ProcessGroupNCCL. + bool blockingWait_{false}; + + // Clone of opTimeout_ from ProcessGroupNCCL. + std::chrono::milliseconds opTimeout_{}; + + // Ephemeral timeouts are owned by exactly one work, + // and reset after that work completes. + // There may be more than one ephemeral timeout active at the same time, + // and this variable is used to track the ownership of ephemeral timeout. + std::chrono::milliseconds ownedEphermeralTimeout_ = + std::chrono::milliseconds(0); + + // Time point representing when the work started. + std::chrono::time_point workStartTime_; + + // Record the sequential number of collective or p2p. + uint64_t seq_; + bool isP2P_; + + // Indicates if the nccl start event has been updated to the store trace. + // This will be used by desync debug. + bool startTraceUpdated_{false}; + + // Record collective sizes for debug. We only record the size on the first + // device as multi-device per process is deprecated + size_t numelIn_ = 0; + size_t numelOut_ = 0; + + // Wrapper method for the static checkForNCCLErrors which can be overridden + // for tests. + virtual std::exception_ptr checkForNCCLErrors(); + + friend std::ostream& operator<<( + std::ostream& output, + const WorkNCCL& workNCCL); + + // Checks for NCCL errors and sets an appropriate exception_ptr. + void checkAndSetException(); + + // Just checks whether GPU execution has started, without modifying + // exception_ptr. + bool startedGPUExecutionInternal() const; + + // Just checks whether GPU execution has completed, without modifying + // exception_ptr. + bool finishedGPUExecutionInternal() const; + + // Reference to the store so that we can write aborted communicators + // to the store. + c10::intrusive_ptr store_; + + // Store a reference to NCCL collective's outputs, used by result and to + // give a more descriptive message when representing the Work as a string. + std::shared_ptr> outputs_; + + // TORCH_NCCL_AVOID_RECORD_STREAMS implementation helper. + // Stores references to participating non-output tensors (ie inputs, + // flattened intermediates). + // We'll clear this list in synchronizeStream, just after user-facing + // stream(s) are synced with the nccl work stream(s). + // By keeping these refs (as well as outputs_) alive until after the + // collective's work rejoins the user-facing streams, we achieve + // caching allocator safety without any recordStream calls. + // For in-place collectives, some refs stashed here may alias outputs_, + // but that doesn't do any harm. + std::shared_ptr stashed_for_allocator_safety_; + + // The future returned by getFuture. + c10::intrusive_ptr future_; + + // the future result (e.g., success or failure) of the work + c10::intrusive_ptr futureWorkResult_; + + bool timingEnabled_; + // unique id used to tell the trace buffer that this + // work has completed + std::optional trace_id_; + std::optional trace_reset_epoch_; + DebugLevel distDebugLevel_; + friend class ProcessGroupNCCL; + }; + + struct Options : Backend::Options { + // NOTE: timeout in ProcessGroupNCCL::Options denote the timeout for + // operations. This is only used when blockingWait_ is enabled. + explicit Options(bool is_high_priority_stream = false); + + // return intrusive_ptr of the object + static c10::intrusive_ptr create( + bool is_high_priority_stream = false) { + return c10::make_intrusive(is_high_priority_stream); + } + + // Schedule NCCL operations on high priority CUDA streams + bool is_high_priority_stream; + +#ifdef NCCL_HAS_CONFIG + // Configure ranks + ncclConfig_t config = NCCL_CONFIG_INITIALIZER; +#endif + + // Optional "parent" backend and color to create communicators from + // via `ncclCommSplit` + c10::intrusive_ptr split_from; + // Color to use for `ncclCommSplit`, values: + // * Non-negative value: in group; + // * NCCL_SPLIT_NOCOLOR (-1): not in group; + // * NCCL_SPLIT_NOCOLOR - 1: uninitialized. + // [Note 1]: the type must be `int` instead of `int64_t` because NCCL API + // accepts int. Otherwise, an implicit conversion may happen at the API call + // and the value may become negative. + // [Note 2]: this member is pybinded to Python, the value passed from Python + // must be within the numerical range of C++ int. Otherwise, Python will + // raise a RuntimeError saying type is incompatible. See also + // `_process_group_color` in `distributed_c10d.py`. +#ifdef NCCL_HAS_COMM_SPLIT + int split_color{NCCL_SPLIT_NOCOLOR - 1}; +#else + // [Note 3]: for older NCCL versions, NCCL_SPLIT_NOCOLOR is not defined. But + // `split_color` is pybinded to Python, so we need to define it. So we use + // the int value of `NCCL_SPLIT_NOCOLOR` (-1) instead. + int split_color{-2}; +#endif + }; + + // Helper class related to TORCH_NCCL_DESYNC_DEBUG + class DesyncDebugger { + public: + // Initialize and enable DesyncDebugger + void init( + int rank, + int size, + int globalRank, + int pgId, + c10::intrusive_ptr store); + + // Run desync debug. This function is called by watchdog at time of timeout. + void run(); + + // Log work start to store. + void logWorkStart(WorkNCCL& work); + + // Log work end to store. + void logWorkEnd(WorkNCCL& work); + + private: + // Whether desync debug is enabled. + // If false, all functions are no-op. + bool enabled_{false}; + + // From ProcessGroupNCCL + int rank_; + int size_; + int globalRank_; + int pgId_; + + // Reference to the store so that we can log start/end event. + c10::intrusive_ptr store_; + + // The store keys to trace the last NCCL collective kernel CUDA events - + // start event and end event respectively. These are used to do desync root + // cause analysis. + std::string traceKeyStart_; + std::string traceKeyEnd_; + }; + + // Class that runs as a separate thread aside from watchdog + // thread because we need to check the heartbeat from watchdog thread + // so that when we get stuck in some NCCL/CUDA calls, + // we can dump the debugging information and abort the process. + class HeartbeatMonitor { + public: + HeartbeatMonitor(ProcessGroupNCCL* pg); + virtual ~HeartbeatMonitor() = default; + + // Start the heartbeat monitor thread. + void start(); + + // Join the heartbeat monitor thread. + void join(); + + // Run the actual loop to check watchdog heartbeat. + virtual void runLoop(); + + // Set the terminal flag and notify the heartbeat monitor thread to stop. + void stop(); + + // Set the last update time of watchdog thread. + void setLastWorkListUpdateTime( + std::chrono::time_point time); + + int getDumpTimeout() const; + + // Util function to get the timeout error message + std::string getNCCLWatchdogTimeoutErrorMsg(const std::string& extraMsg); + + // Util function to get the timeout exit message + std::string getNCCLWatchdogTimeoutExitMsg(const std::string& exitReason); + + protected: + // We need to keep a reference to the PG instance so that we can access + // the member functions of the PG instance. We store a raw pointer on + // purpose because the heartbeat monitor thread now still lives within the + // lifetime of the PG instance. + ProcessGroupNCCL* pg_; + + private: + // Whether or not to print C++ stack traces to logs on unclean shutdown. + bool logCppStackOnUncleanShutdown_; + + // The time interval used for deciding whether there is no watchdog + // heartbeat. + int heartbeatTimeoutInSec_; + + // timeout for the dump to finish. + int waitTimeoutDumpInMilSec_; + + // Interval of check coordinated signals in ProcessGroupNCCL from other + // ranks e.g., trigger the dump of the debugging info for timeout when + // notified. + int coordCheckIntervalMilSec_; + + // We gate the heartbeat monitor thread so that we can roll it out + // gradually. + bool watchdogHeartbeatMonitorEnabled_; + + // Monitor thread which checks the heartbeat of Watchdog thread. + // If the monitor thread finds there is no heartbeat, it will dump debug + // info and then kill the watchdog thread to avoid hang. + std::thread ncclHeartbeatMonitorThread_; + + // Whether or not we should terminate the heartbeat monitoring threads. + std::atomic terminateHeartbeatMonitorThread_{false}; + + // Condition Variable for monitor thread to wake up early + std::condition_variable monitorWakeUpCV_; + + // Whether or not to dump debug info on exception including both watchdog + // timeout and nccl errors. + bool dumpOnTimeoutOrEx_; + + // Mutex to Guard monitorWakeUpCV_ + std::mutex monitorMutex_; + + // The last update time of WorkList inside watchdog thread. + std::chrono::time_point lastWorkListUpdateTime_; + }; + + // Class that runs as a side thread to check whether the NCCL collective + // is timed out or errors on the cached NCCL communicators. + class Watchdog { + public: + Watchdog(ProcessGroupNCCL* pg); + virtual ~Watchdog() = default; + + // Start the watchdog thread. + void start(); + + // Join the watchdog thread. + void join(); + + // Function that runs as part of a separate thread and checks for errors on + // NCCL communicators. We need a separate thread to check for NCCL errors + // since we can't rely on the user calling certain methods like wait(), + // isCompleted() etc. to detect and remediate errors. In addition to this, + // we need a mechanism to safely abort and remove NCCL communicators from + // our cache. This can be done cleanly by having a thread for the + // ProcessGroupNCCL class. Attempting to modify the communicator cache from + // the WorkNCCL class might run into issues with object lifetime since the + // ProcessGroupNCCL object might get destroyed before the WorkNCCL object. + void run(); + + // Watchdog's inside loop. + // Takes care of cleaning up completed work, and aborting upon failure or + // timeout. + void runLoop(); + + // Notify the loop inside watchdog. + void notify(); + + void checkAndSetRemoteError(); + + // A helper function to get the src rank of a signal from the Store. This is + // nonblocking function returning -1 if the signal is not available yet. + int getSignalSrcRank( + c10::intrusive_ptr& store, + const std::string& signal); + + uint64_t getHeartbt() const; + + void setDesyncDebug(bool desyncDebug); + + private: + std::thread ncclCommWatchdogThread_; + + // We need to keep a reference to the PG instance so that we can access + // the member functions of the PG instance. We store a raw pointer on + // purpose because the watchdog thread now still lives within the + // lifetime of the PG instance. + ProcessGroupNCCL* pg_; + + // Whether the NCCL watchdog should rethrow CUDA errors. + bool rethrowCUDAErrors_ = false; + + std::exception_ptr watchDogException_ = nullptr; + + // Condition Variable for watchdog thread sleep + std::condition_variable workMetaListCV_; + + // Heartbeat of watchdog thread. + std::atomic_uint64_t heartbeat_; + + // Whether or not to propagate detected errors to all ranks in the same PG + // through TCPStore. + bool propagatePgError_; + + // Whether or not to enable timeout root cause analysis. + bool desyncDebug_; + + DesyncDebugger desyncDebugger_; + }; + + // If you wish to create multiple process groups, each with a potentially + // different rank and size, you can do so by passing a new store instance + // to each one. If you have only a single store object, you can + // use the `c10d::PrefixStore` to derive scoped instances. + // This is also what the Python API in torch.distributed does. + // + // The process group instance keeps a reference to the store because + // it may be used long after the constructor runs. In fact, the constructor + // doesn't create any NCCL communicators. A single NCCL communicator can + // only be used on a specific set of devices, and are therefore created + // on-demand when a collective runs. If another collective is executed later, + // against a different set of devices, the process group creates another NCCL + // communicator. These NCCL communicators are cached and reused if possible. + // + ProcessGroupNCCL( + c10::intrusive_ptr store, + int rank, + int size, + c10::intrusive_ptr options = Options::create()); + + // This constructor includes the deprecated `groupName` argument. + // If you have existing code that uses the `groupName`, you can replace + // it by specifying a `c10d::PrefixStore(groupName, store)` for store. + C10_DEPRECATED ProcessGroupNCCL( + const c10::intrusive_ptr& store, + int rank, + int size, + const std::string& groupName, + c10::intrusive_ptr options = Options::create()) + : ProcessGroupNCCL(store, rank, size, std::move(options)) {} + + ~ProcessGroupNCCL() override; + + // This function returns a local uid for ProcessGroupNCCL. + uint64_t getUid() { + return static_cast(local_id_); + } + + c10::intrusive_ptr getOptions() { + return options_; + } + + c10::intrusive_ptr getBackendOptions() override { + return c10::static_intrusive_pointer_cast(options_); + } + + const std::string getBackendName() const override { + return std::string(NCCL_BACKEND_NAME); + } + + bool supportsSplitting() const override { + return true; + } + + bool supportsCoalescing() const override { + return true; + } + + bool supportsTimeEstimation() const override { +#ifdef NCCL_SIM_INFO_INITIALIZER + return true; +#else + return false; +#endif + } + + void setTimeout(std::chrono::milliseconds timeout) override { + options_->timeout = timeout; + } + + void startCoalescing() override; + + c10::intrusive_ptr endCoalescing() override; + + void startTimeEstimate(); + + float endTimeEstimate(); + + // For specifying a composite optype, such as ALLGATHER and REDUCE_SCATTER + c10::intrusive_ptr endCoalescing(OpType optype); + + c10::intrusive_ptr broadcast( + std::vector& tensors, + const BroadcastOptions& opts = BroadcastOptions()) override; + + c10::intrusive_ptr _broadcast_oop( + at::Tensor& outputTensors, + at::Tensor& inputTensors, + const BroadcastOptions& opts = BroadcastOptions()); + + c10::intrusive_ptr allreduce_sparse( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = + AllreduceCoalescedOptions()) override; + + c10::intrusive_ptr reduce( + std::vector& tensors, + const ReduceOptions& opts = ReduceOptions()) override; + + c10::intrusive_ptr _reduce_oop( + at::Tensor& outputTensors, + at::Tensor& inputTensors, + const ReduceOptions& opts = ReduceOptions()); + + c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr _allgather_base( + at::Tensor& outputbuffer, + at::Tensor& inputbuffer, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr allgather_coalesced( + std::vector>& outputTensorLists, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr allgather_into_tensor_coalesced( + std::vector& outputs, + std::vector& inputs, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr reduce_scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr reduce_scatter_tensor_coalesced( + std::vector& outputs, + std::vector& inputs, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) override; + + c10::intrusive_ptr alltoall_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + std::vector& outputSplitSizes, + std::vector& inputSplitSizes, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr alltoall( + std::vector& outputTensors, + std::vector& inputTensors, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) override; + + c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) override; + + int64_t getCommPtr(); + + void groupStart(); + + void groupEnd(); + + void groupEndNonblocking(const std::shared_ptr& comm); + + c10::intrusive_ptr gather( + std::vector>& outputTensors, + std::vector& inputTensors, + const GatherOptions& opts = GatherOptions()) override; + + c10::intrusive_ptr scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ScatterOptions& opts = ScatterOptions()) override; + + // Unsupported Ops + c10::intrusive_ptr recvAnysource( + std::vector& tensors, + int tag) override; + + // Agrees on an initial sequence number for the whole group by having rank 0 + // create it and broadcast it to other ranks using the store. + void setSequenceNumberForGroup() override; + + // Retrieves the current sequence number for the whole group, which should be + // in sync. If the returned number is not consistent across the group, it + // may indicate that there is some sort of collective desynchronization. + uint64_t getSequenceNumberForGroup() override; + + // Return the total number of splits the communicators held by this process + // group have performed. Counts ncclCommCreateFromRanks() for ncclx v2.21.5+ + uint64_t getCommSplitCounter() const; + + void registerOnCompletionHook( + std::function)>&& hook) override; + void waitForPendingWorks() override; + + void enableCollectivesTiming() override; + + c10::intrusive_ptr split( + const c10::intrusive_ptr& store, + const std::vector& ranks, + const c10::intrusive_ptr& opts) override; + + c10::intrusive_ptr merge( + const c10::intrusive_ptr& store, + const c10::intrusive_ptr& opts, + const int& rank, + const int& size) override; + + // Helper function for iteratively aborting communicators in the provided map + void abortCommsFromMap( + std::unordered_map>& ncclCommsMap, + const std::optional& abortReason); + + c10::intrusive_ptr initIntraNodeComm(); + + // Destroy (shutdown) this backend -- normal exit. + void shutdown() override; + + // Provides an API to abort the ProcessGroup (similar to ncclCommAbort) + // instead of relying on ProcessGroupNCCL destructor. + void abort() override; + + void eagerConnectSingleDevice(at::Device device) override; + + void performNocolorSplit(at::Device device); + + // If all comms on this PG are fully initialized, return true. + bool isInitialized(); + + ErrorType getError() override; + + bool supportsShrinking() const override { +#ifdef NCCL_HAS_COMM_SHRINK + return true; +#else + return false; +#endif + } + + // Backend-style shrink override that returns a Backend instance. + c10::intrusive_ptr shrink( + const std::vector& ranks_to_exclude, + int shrink_flags = 0, + const c10::intrusive_ptr& opts_override = + nullptr) override; + + std::shared_ptr getMemAllocator() override; + + // Allocate tensor from communication-optimized memory pool + at::Tensor allocateTensor(long size, at::TensorOptions options = {}) override; + + // Whether tensor allocation from NCCL memory pool is supported + bool supportsTensorAlloc(c10::DeviceIndex deviceIdx) override; + + // Performs NCCL user buffer registration for all buffers in + // the given MemPool + void registerMemPool(at::cuda::MemPool* pool, bool symm = false); + + // Performs NCCL user buffer de-registration for all buffers in + // the given MemPool + void deregisterMemPool(at::cuda::MemPool* pool); + + // This method adds a temporary extension for the timeout period, + // applying to all collectives between the calling of this API and + // the completion of the first collective on the GPU. While this feature + // provides flexibility in specific scenarios, it introduces statefulness + // to timeout setting. Therefore, it is advisable to use this API sparingly + // and consider alternative approaches, such as directly setting the timeout + // or utilizing a barrier collective (one can set any timeout to the barrier), + // whenever feasible. + void addEphemeralTimeout(const std::chrono::milliseconds& timeout); + + // This function is only intended for testing purposes because we don't + // want to expose the `WorkNCCL` via pybind. It verifies whether the + // `opTimeout_` of the provided WorkNCCL instance is the same as the specified + // timeout. + bool verifyWorkTimeoutForTest( + const c10::intrusive_ptr& work, + const std::chrono::milliseconds& timeout); + + void setEnableNanCheck(bool enableNanCheck); + + protected: + uint64_t getWatchdogHeartbt() const; + + // Instance of the heartbeat monitor thread. + std::unique_ptr heartbeatMonitor_; + + // Instance of the watchdog thread. + std::unique_ptr watchdog_; + + // Helper that broadcasts nccl unique ID to all ranks through the store + void broadcastUniqueNCCLID( + ncclUniqueId* ncclID, + bool isSingleP2POp, + const std::string& devicesKey, + int p2pRank); + + // Helper that allgathers nccl unique IDs to all ranks through the store + void allgatherUniqueNCCLIDs( + int rootIdx, + ncclUniqueId* ncclID, + std::vector& ncclIDs); + + // Helper that looks up the cached NCCL communicators only + std::shared_ptr getNCCLComm(const std::string& deviceKey); + + std::shared_ptr initNCCLComm( + const std::string& deviceKey, + at::Device& device, + OpType opType, + int p2pRank = 0, + bool isSendRecvSelf = false); + + // Initialize device-specific state (comm, stream, event, bookkeeping) for a + // given communicator on this process group instance. + void initializeDeviceStateForComm( + const at::Device& device, + std::shared_ptr comm); + + // Wrapper method which can be overridden for tests. + virtual std::exception_ptr checkForNCCLErrors( + std::shared_ptr& ncclComm); + + // Ensure thaht if record is True, the work obj will be enqueued via + // workEnqueue + virtual c10::intrusive_ptr initWork( + at::Device& device, + int rank, + OpType opType, + bool isP2P, + const char* profilingTitle = nullptr, + const std::vector& inputs = {}, + const std::vector& outputs = {}, + bool record = false); + + // In the timeout case and we will dump debug info such as the NCCL flight + // recorder to storage. Down the road, if we have more complicated or blocking + // operations, we might need to use a side thread to do it. + bool dumpDebuggingInfo( + bool includeStackTrace = true, + bool onlyActive = false); + + void dumpExtraDebuggingInfo(); + + // Abort all communicators on this rank. + bool abortComms(const std::optional& abortReason = std::nullopt); + + // A helper function to check if nonblocking API mode should be used. + // Use this helper instead of directly checking `useNonblocking_` variable. + bool useNonblocking(); + + protected: + int globalRankStart_{}; + int globalRankStride_{}; + + private: + bool eagerInit_{false}; + bool showSerializationWarning_{true}; + + // Helper that encapsulates work shared across all collective communication + // primitives. The callbacks have the following signatures: + // + // ncclResult_t fn(at::Tensor& input, at::Tensor& output, + // ncclComm_t, at::cuda::CUDAStream&); + // void {pre,post}(std::vector); + template + c10::intrusive_ptr collective( + at::Tensor& input, + at::Tensor& output, + Fn fn, + OpType opType, + bool asyncOp, + const char* profilingTitle = nullptr, + bool nanCheck = true); + + template + c10::intrusive_ptr collective( + at::Tensor& input, + at::Tensor& output, + Fn fn, + PreProcess pre, + PostProcess post, + OpType opType, + bool asyncOp, + const char* profilingTitle = nullptr, + bool nanCheck = true); + + template + c10::intrusive_ptr collective( + std::vector& inputs, + std::vector& outputs, + Fn fn, + PreProcess pre, + PostProcess post, + OpType opType, + bool asyncOp, + const char* profilingTitle = nullptr, + bool nanCheck = true); + + template + c10::intrusive_ptr collectiveCoalesced( + std::vector& input, + std::vector& output, + Fn fn, + OpType opType, + bool asyncOp, + const char* profilingTitle = nullptr); + + // Helper that encapsulates work shared across point-to-point communication + // primitives. It is the same structure as the helper used for collective + // communication primitives. + template + c10::intrusive_ptr pointToPoint( + at::Tensor& tensor, + Fn fn, + int peer, + OpType opType, + const char* profilingTitle = nullptr); + + template + c10::intrusive_ptr pointToPoint( + at::Tensor& tensor, + Fn fn, + int peer, + OpType opType, + PreProcess pre, + PostProcess post, + const char* profilingTitle); + + c10::intrusive_ptr allreduce_impl( + at::Tensor& tensor, + const char* profilingTitle = "nccl:all_reduce", + const AllreduceOptions& opts = AllreduceOptions()); + + // Checks for NCCL errors on each of the communicators and returns an + // appropriate exception_ptr (nullptr if no errors). + static std::exception_ptr checkForNCCLErrorsInternal( + std::shared_ptr& ncclComm); + + // Return the CUDA device most likely associated with this backend. + // If we aren't bound to a specific device, there is no strict + // guarantee that this heuristic is the correct assignment of ranks + // to GPUs that Python layers use, but in practice it tends to be. + // Fortunately we don't rely on this for correctness of any tensor + // operations, just for ancillary uses like barriers. + at::Device guessDeviceForRank() const; + + // Destroys initialized NCCL communicators in devNCCLComMap_ given by input + // key. Throws if there are no communicators to destroy. Also removes + // communicators from the cache and clears used device indices. + void destroyNCCLComms(const std::string& devNCCLCommMapKey); + + void runHookLoop(); + + // Generates a prefix that is unique to this process group and rank, for + // disambiguating logs + std::string createLogPrefix() const; + + // Returns the unique prefix created in createLogPrefix + const std::string& logPrefix() const; + + // Returns the global rank of the device. This function assumes that users + // always create a default global process group(PG) which includes all + // devices. It is called in the constructor of ProcessGroupNCCL, so it always + // return the rank_ of the very first PG created, aka, default global PG. + const int& globalRank() const; + + const c10::intrusive_ptr& globalStore() const; + + // Returns the global ranks of a PG. + const std::vector& groupRanks() const; + + // Util function to assign timeout to each work. + void assignTimeoutToWork( + const c10::intrusive_ptr& work, + const c10::intrusive_ptr& option); + + // Broadcast flight-recorder dump signal + void broadcastDumpSignal(); + + // A helper function to broadcast a signal (key) from a src rank to all other + // ranks using the specified store. + void broadcastSignal( + c10::intrusive_ptr& store, + const std::string& signal, + int srcRank); + + protected: + // Function that directly trigger std::abort so that the whole process + // gets terminated. + virtual void terminateProcess(const std::string& errMsg); + + // A helper function to wait for a future to complete or timeout. + // Returns true if the future completes before timeout, false otherwise. + bool waitForFutureOrTimeout( + std::future& fut, + const std::chrono::milliseconds& timeOutMilSec, + const std::string& futDescription, + ::c10d::C10dLoggingData& debugLog, + bool throwException = false); + + // A helper function to guess the device id of the current rank, based on + // bounded device or used device. Do not use this function if you already know + // the device id to operate on. + c10::DeviceIndex guessDeviceId() const; + + static const int64_t kWatchdogThreadSleepMillis; + + // The store is used to broadcast the NCCL unique ID of rank 0. This store + // comes with prefix and it is different across ProcessGroup NCCL instances + // (aka, different ProcessGroups). + c10::intrusive_ptr store_; + + // Reference to the store without prefix so that keys are same across all + // ProcessGroup NCCL instances and (key, value) pairs written to the store are + // global. + c10::intrusive_ptr globalStore_; + + // The lock which protects the write/read of + // ephemeralTimeoutActive_/ephemeralTimeoutInflight_. + // TODO(fduwjj): We need to have an audit on all mutexes we are adding here. + // And consolidate them if possible. + std::mutex mtxTimeoutExtension_; + + // The ephemeral timeout added on top of existing timeout for works issued + // before first work finishes. + std::chrono::milliseconds ephemeralTimeoutActive_ = + std::chrono::milliseconds(0); + + // The ephemeral timeout addition which has been already applied to work. + std::chrono::milliseconds ephemeralTimeoutInflight_ = + std::chrono::milliseconds(0); + + const c10::intrusive_ptr options_; + + // The number of NCCL communicators that have been created during + // the lifetime of this process group. This sequence number is + // used to scope keys used in the store. + uint64_t ncclCommCounter_{0}; + + // The NCCL communicator that the process group has cached. + // + // For collective operations: + // The key is a list of GPU devices that an operation is operating on + // The GPU devices are stored in a device sequence and the cache NCCL + // communicator is associated with this GPU device sequence + // + // e.g. If the process group op only uses device 0, then the value of + // the used device string stored (value of the hashmap) would be "0". + // + // If the process group op uses device 0 - 7 and the each tensor of the + // input tensor list is on device, 0, 1, 2, 3, 4, 5, 6, 7 separately, + // then the value of the used device string (key) stored would be + // "0,1,2,3,4,5,6,7" + // + // If the process group op uses device 0 - 7 and the each tensor of the + // input tensor list is on device, 0, 4, 5, 6, 7, 1, 2, 3 separately, + // then the value of the used device string stored would be + // "0,4,5,6,7,1,2,3" + // + // Note that the order of the device for the tensor list matters. + // + // For point-to-point operations: + // The key is a string of my current rank and the peer process rank. + // e.g. If process 1 and process 2 are involved in a point-to-point + // communication, the key will be "1:2" on both processes. Note: this is for + // the scenario where there is only 1 GPU per process. When it comes to + // multiple GPUs per process, this part may need to redesigned. + // TODO: we probably need a separate map for P2P comms + std::unordered_map> devNCCLCommMap_; + + // The NCCL communicators currently in process of being initialized. + std::unordered_map> + inInitializationCommMap_; + + // Mutex to guard maps like devNCCLCommMap_. + std::mutex mutex_; + + // Size of ring buffer where we store NCCL Traces for debugging. + int traceBufferSize_; + + // We gate the cudaEventCache so that we can roll it out gradually. + std::atomic cudaEventCacheEnabled_; + + std::thread onCompletionHookThread_; + + // Whether or not we should terminate the watchdog and workCleanup threads. + std::atomic terminateProcessGroup_; + + // Whether there are hooks pending to be fired + std::atomic hasPendingHooks_; + + // This is the signal from watchdog threads to indicate whether the monitor + // thread should dump. Making it static so that it is accessible from all the + // PGs. With this flag, monitor thread would dump debug info under any one of + // the three conditions: + // + // 1: watchdog thread of any PG detects a collective timeout. + // 2: timeout signal is received from other ranks through tcpstore. + // 3: current PG's watchdog heartbeat timeout occurs. + // + // Note that only the monitor thread from PG0 will dump the debug info for + // case one and two so that the debug info is only dumped once. + static std::atomic shouldDump_; + + // Mutex to Guard workMetaList_ + std::mutex workMetaListMutex_; + + bool writeDebugInfo_ = false; + + // Vector to store WorkNCCL pointers + std::list workMetaList_; + + // Mutex to Guard workMetaList_ + std::mutex completedWorkListMutex_; + + // Condition Variable for watchdog thread sleep + std::condition_variable completedWorkListCV_; + + std::list completedWorkList_; + + // Add Work Pointer to workVector + void workEnqueue(const c10::intrusive_ptr&); + + // The CUDA streams used by NCCL kernels + std::unordered_map ncclStreams_; + + // The CUDA events used to sync NCCL streams + std::unordered_map ncclEvents_; + + // Device Indexes used for all collectives in this group + std::set usedDeviceIdxs_; + + // Flag to denote if a coalescing groupStart/groupEnd block is active + int coalescing_state_ = 0; + + // Stores device indexes for all collectives run inside a coalescing block + at::Device coalescedDevice_ = at::Device("cuda"); + + // Stores communicators for all collectives run inside a coalescing block + std::shared_ptr coalescedComm_ = nullptr; + + // Whether the coalesced calls are sync or async. + bool coalescedAsync_{}; + + // keeps track of input and output tensors when coalescing is in flight. Will + // hand over these tensors to WorkNCCL's stash when coalescing is ended. + TensorShelf coalescedTensors_; + + // Some ops may have completed, but user still hasn't called `work.wait()`. + // When watchdog detects this, it transfers the TensorShelf from `work` to + // this `shelves` structure. Next time we execute ProcessGroupNCCL's methods + // on main thread, we clear the `shelves` in one shot. This is mainly because + // watchdog (a side thread) unstashing the shelf directly seems to cause some + // problem. + std::vector> shelvesToUnstash_; + std::mutex shelvesMutex_; + + // Whether or not wait() and synchronize() are blocking operations that wait + // for the operation to complete. + bool blockingWait_ = false; + + // Whether or not the workCleanupThread is used to perform async error + // handling. + ErrorHandlingMode asyncErrorHandling_ = NoHandling; + + ErrorType error_ = ErrorType::SUCCESS; + + std::mutex errorMutex_; + + // Whether or not to sleep after an exception is thrown in the watchdog. + bool sleepAfterException_{}; + + // Whether or not to enable nan check for input tensors to collectives. + bool enableNanCheck_; + + // Whether or not to create start CUDAEvent and enable timing for start + // and end events. Note that enableTiming_ is always true if desyncDebug_ + // is set to true. + std::atomic enableTiming_; + + // Flag to enable the print of hash value of input/output of collectives for + // verification. + std::atomic enableCollectiveHashDebug_; + + // Whether or not TORCH_NCCL_AVOID_RECORD_STREAMS was set + bool avoidRecordStreams_ = false; + + // The number of active ncclGroupStart() calls. This counter will be increased + // by 1 when ncclGroupStart() is called and decreased by 1 when ncclGroupEnd() + // is called. + static thread_local uint64_t ncclActiveGroupCounter_; + + // Counting for the sequential number of NCCL collective call. + // (specifically, how many actual kernels we launched, which differs from + // op_id_ when coalescing is enabled) + uint64_t seqCollective_{0}; + + // Counting for the sequential number of NCCL P2P calls. + uint64_t seqP2P_{0}; + + // Incrementing counter for logical operations (collective or p2p) issued on + // the ProcessGroup + uint64_t op_id_{0}; + + // The number of ProcessGroupNCCL created on the current rank. + size_t local_id_; + + std::string logPrefix_; + + c10::intrusive_ptr intraNodeComm_; + + // Number of devices on this node. + int localDeviceCount_{0}; + + std::shared_ptr pgStatus_ = + std::make_shared(); + + // Internal cached value: use NCCL non-blocking API mode or not. + // Use `useNonblocking()` method instead of accessing this variable directly. + std::optional useNonblocking_{std::nullopt}; + + // Communication-optimized memory pool associated with this PG + std::unique_ptr memPool_ = nullptr; +}; + +// Reset the flighrecorder recordings for the current rank. +TORCH_API void reset_nccl_trace(); + +// Dumps the NCCL comm traces and additional information about the Process +// Group. +TORCH_API std::string dump_nccl_trace( + bool includeCollectives, + bool includeStackTraces, + bool onlyActive); + +// Dumps the NCCL comm traces and additional information about the Process +// Group in JSON formatted string. +// We don't include stack traces in JSON format as it is far too much data. +TORCH_API std::string dump_nccl_trace_json( + bool includeCollectives, + bool onlyActive); + +// Gets a mutable reference to a global optional function.Heartbeat Monitor +// will use this function to dump traces, if available. Inside fbcode, we +// store a function here that uses an internal tool for process tracing +TORCH_API std::optional< + std::function)>>& +get_cpp_trace_dumper(); + +// Similar to get_cpp_trace_dumper, this stores a function defined in +// torch-python layer that lets us check whether the GIL can be acquired, +// helpful for instrumenting in cases where a hang was observed. +typedef bool (*gil_checker_t)(); + +TORCH_API gil_checker_t& get_gil_checker(); +} // namespace c10d + +#endif // USE_C10D_NCCL + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupUCC.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupUCC.hpp new file mode 100644 index 0000000000000000000000000000000000000000..12e737b61df23a0fc5503b60fc7a6136d311aaeb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupUCC.hpp @@ -0,0 +1,363 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_UCC + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#ifdef USE_CUDA +#include +#include +#endif + +namespace c10d { + +#define TORCH_UCC_DEVICE_NOT_SET -2 + +#ifdef USE_CUDA +#define SAVE_TENSORS(_TENSORS, _DATA) \ + do { \ + if ((_TENSORS)[0].device().is_cuda()) { \ + for (const auto i : c10::irange((_TENSORS).size())) { \ + c10::cuda::CUDACachingAllocator::recordStream( \ + (_TENSORS)[i].storage().data_ptr(), (*stream)); \ + } \ + } else { \ + (_DATA) = (_TENSORS); \ + } \ + } while (0) + +#else +#define SAVE_TENSORS(_TENSORS, _DATA) (_DATA) = (_TENSORS); +#endif + +constexpr const char* UCC_BACKEND_NAME = "ucc"; + +struct event_pool_t { +#ifdef USE_CUDA + std::queue> event_pool; +#endif + std::mutex event_pool_mutex; +}; + +class Comm; + +// UCC does not support multiple CUDA devices per process. +class TORCH_API ProcessGroupUCC : public Backend { + private: + void set_timeout(ucc_coll_args_t& args); + + public: + class WorkData { + public: + std::vector src; + std::vector dst; + std::vector flat; + WorkData() {} + virtual ~WorkData() = default; + }; + class AlltoallWorkData : public WorkData { + public: + AlltoallWorkData(int size) + : send_lengths(size), + send_offsets(size), + recv_lengths(size), + recv_offsets(size) {} + std::vector send_lengths; + std::vector send_offsets; + std::vector recv_lengths; + std::vector recv_offsets; + }; + + class AllgathervWorkData : public WorkData { + public: + AllgathervWorkData(int size) : recv_lengths(size), recv_offsets(size) {} + std::vector recv_lengths; + std::vector recv_offsets; + }; + + class ScattervWorkData : public WorkData { + public: + ScattervWorkData(int size) : send_lengths(size), send_offsets(size) {} + std::vector send_lengths; + std::vector send_offsets; + }; + + class ProgressEntry { + friend class ProcessGroupUCC; + friend class Comm; + + public: + ProgressEntry(CommBase* comm, ucc_coll_req_h request) + : status_(UCC_INPROGRESS), comm_(comm), request_(request) {} + // Finalizes UCC status or exception of collective request. + void finalize(std::exception_ptr eptr = nullptr); + ucc_status_t status_; + CommBase* comm_; + ucc_coll_req_h request_; + std::unique_ptr data; + c10::intrusive_ptr future_; + std::exception_ptr eptr_; + }; + + class WorkUCC : public Work { + friend class ProcessGroupUCC; + friend class Comm; + + public: + WorkUCC( + OpType opType, + uint64_t seq, + const char* prof_title, + const std::optional>& inputs, + const c10::intrusive_ptr& logger) + : Work(-1, opType, prof_title, inputs), logger_(logger), seq_(seq) {} + ~WorkUCC(); + void setException(); + void setAndThrowException(); + bool isCompleted() override; + bool isSuccess() const override; + bool wait(std::chrono::milliseconds timeout = kUnsetTimeout) override; + c10::intrusive_ptr getFuture() override; + std::vector result() override; + int sourceRank() const override; +#ifdef USE_CUDA + std::unique_ptr fence = nullptr; + event_pool_t* ep = nullptr; +#endif + int sourceRank_; + + protected: + std::shared_ptr entry_; + c10::intrusive_ptr logger_; + uint64_t seq_; + + private: + // The future returned by getFuture. + c10::intrusive_ptr future_; + // Store a reference to collective's outputs, used by result + std::shared_ptr> outputs_; + }; + + explicit ProcessGroupUCC( + const c10::intrusive_ptr& store, + int rank = -1, + int size = -1, + std::chrono::duration timeout = kBackendDefaultTimeout); + + void initComm(c10::Device dev); + + ~ProcessGroupUCC() override; + + const std::string getBackendName() const override { + return std::string(UCC_BACKEND_NAME); + } + +#ifdef USE_CUDA + std::unique_ptr getPooledEvent(); +#endif + + // Performs a health check by initializing dummy UCC & UCX communicators and + // then destroying them. This will help indicate and signal any + // UCC/UCX-related issues prior to the first collective. The actual + // initialization and subsequent destruction is ran on a separate thread and + // the main thread is signalled about timeouts/errors to report to the + // application. + void runHealthCheck(); + + template + c10::intrusive_ptr collective_post( + OpType opType, + PreProcess preproc, + PostProcess postproc, + ucc_coll_args_t& coll, + std::unique_ptr data, + c10::Device dev, + std::vector& inputTensors, + std::vector& outputTensors, + const char* prof_title); + + c10::intrusive_ptr broadcast( + std::vector& data, + const BroadcastOptions& opts = BroadcastOptions()) override; + + c10::intrusive_ptr allreduce( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = + AllreduceCoalescedOptions()) override; + + c10::intrusive_ptr reduce( + std::vector& tensors, + const ReduceOptions& opts = ReduceOptions()) override; + + c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr _allgather_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) override; + + c10::intrusive_ptr gather( + std::vector>& outputTensors, + std::vector& inputTensors, + const GatherOptions& opts = GatherOptions()) override; + + c10::intrusive_ptr scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ScatterOptions& opts = ScatterOptions()) override; + + c10::intrusive_ptr reduce_scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr alltoall_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + std::vector& outputSplitSizes, + std::vector& inputSplitSizes, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr alltoall( + std::vector& outputTensors, + std::vector& inputTensors, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) override; + + c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) override; + + // Counting for the sequential number of UCC collective_post call. + uint64_t seq_{0}; + + // Agrees on an initial sequence number for the whole group by having rank 0 + // create it and broadcast it to other ranks using the store. + void setSequenceNumberForGroup() override; + + // Retrieves the current sequence number for the whole group, which should be + // in sync. If the returned number is not consistent across the group, it + // may indicate that there is some sort of collective desynchronization. + uint64_t getSequenceNumberForGroup() override; + + static c10::intrusive_ptr createProcessGroupUCC( + const c10::intrusive_ptr<::c10d::Store>& store, + int rank, + int size, + const std::chrono::duration& timeout); + + protected: + const std::chrono::duration timeout_; + std::shared_ptr oob; + std::shared_ptr comm = {nullptr}; + uint32_t comm_id; + ucc_team_h team{nullptr}; + ucc_ee_h cuda_ee{nullptr}; + ucc_ee_h cuda_ee_p2p[2]{nullptr, nullptr}; + +#ifdef USE_CUDA + std::unique_ptr stream = nullptr; + std::unique_ptr stream_p2p[2] = {nullptr, nullptr}; + event_pool_t ep; +#endif + c10::intrusive_ptr logger; +}; + +class Comm { + c10::intrusive_ptr logger; + std::shared_ptr oob; + CommUCC ucc_comm; + std::mutex mutex; + std::thread progress_thread; + std::condition_variable queue_produce_cv; + std::condition_variable queue_consume_cv; + std::deque> progress_queue; + bool stop_progress_loop; + bool collective_inprogress; + torch_ucc_phase_t finalize_phase; + + public: + c10::DeviceIndex cuda_device_index; + Comm( + const c10::intrusive_ptr& logger, + std::shared_ptr oob, + c10::Device dev, + bool is_health_check); + + ~Comm(); + + void ucc_create_team( + ucc_team_h& team, + std::shared_ptr oob); + + void ucc_destroy_team(ucc_team_h& team); + + c10::intrusive_ptr enqueue_p2p( + OpType opType, + ucc_coll_req_h request, + const char* prof_title); + +#ifdef USE_CUDA + void enqueue_cuda_collective( + std::unique_ptr data, + c10::intrusive_ptr work, + ucc_coll_args_t& coll, + ucc_team_h team, + ucc_ee_h ee); +#endif + + void enqueue_collective( + std::unique_ptr data, + c10::intrusive_ptr work, + ucc_coll_args_t& coll, + ucc_team_h team); + + static std::shared_ptr get_comm( + uint32_t& id, + c10::Device dev, + std::shared_ptr oob, + const c10::intrusive_ptr& logger, + bool is_health_check = false); + + void progress_loop(); +}; + +} // namespace c10d + +#endif // USE_C10D_UCC + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp new file mode 100644 index 0000000000000000000000000000000000000000..29c66431b1aba7bd74be896f4bf4d070c1f59d26 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp @@ -0,0 +1,145 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_GLOO + +#include +#include +#include + +namespace c10d { + +class TORCH_API ProcessGroupWrapper : public Backend { + public: + explicit ProcessGroupWrapper( + const c10::intrusive_ptr& backend, + c10::intrusive_ptr glooBackend); + + const std::string getBackendName() const override; + + c10::intrusive_ptr broadcast( + std::vector& data, + const BroadcastOptions& opts = BroadcastOptions()) override; + + c10::intrusive_ptr allreduce( + std::vector& data, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = + AllreduceCoalescedOptions()) override; + + c10::intrusive_ptr reduce( + std::vector& tensors, + const ReduceOptions& opts = ReduceOptions()) override; + + c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr _allgather_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + const AllgatherOptions& opts = AllgatherOptions()) override; + + // This function is deprecated and will be moved out of ProcessGroup to comms: + // * do not add dependencies on this function, + // * do not implement it in your ProcessGroup, implement _allgather_base + // instead. + c10::intrusive_ptr allgather_coalesced( + std::vector>& outputTensorLists, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr gather( + std::vector>& outputTensors, + std::vector& inputTensors, + const GatherOptions& opts = GatherOptions()) override; + + c10::intrusive_ptr scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ScatterOptions& opts = ScatterOptions()) override; + + c10::intrusive_ptr reduce_scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr alltoall_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + std::vector& outputSplitSizes, + std::vector& inputSplitSizes, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr alltoall( + std::vector& outputTensors, + std::vector& inputTensors, + const AllToAllOptions& opts = AllToAllOptions()) override; + + void monitoredBarrier(const BarrierOptions& opts, bool waitAllRanks = false) + override; + + // Agrees on an initial sequence number for the whole group by having rank 0 + // create it and broadcast it to other ranks using the store. Only implemented + // for GLOO and NCCL backends currently. + // dont implement this + void setSequenceNumberForGroup() override; + + // Retrieves the current sequence number for the whole group, which should be + // in sync. If the returned number is not consistent across the group, it + // may indicate that there is some sort of collective desynchronization. + uint64_t getSequenceNumberForGroup() override; // just call underlying + + c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) override; + + c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) override; + + c10::intrusive_ptr recvAnysource( + std::vector& tensors, + int tag) override; + + c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) override; + + c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + const ReduceScatterOptions& opts) override; + + void startCoalescing() override; + + c10::intrusive_ptr endCoalescing() override; + + c10::intrusive_ptr getWrappedPg() const; + + private: + // Underlying process group that actual application collectives will be + // dispatched to + c10::intrusive_ptr backend_; + // Gloo process group responsible for internal coordination such as monitored + // barrier, sequence number checking, collective fingerprint collecting. + c10::intrusive_ptr glooBackend_; + // Conducts several checks to ensure that the underlying collective is well + // formed with the goal of notifying the user about incorrect collective use + // in the application. + void runCollectiveChecks( + OpType op_type, + const std::vector& tensors); +}; +} // namespace c10d + +#endif // USE_C10D_GLOO + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/PyProcessGroup.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/PyProcessGroup.hpp new file mode 100644 index 0000000000000000000000000000000000000000..dd974d19037a5e7ae362dd5c4218c4bfcf4ea34f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/PyProcessGroup.hpp @@ -0,0 +1,361 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace c10d { + +// PyProcessGroup is a pybind11 trampoline class to allow a Python +// class to inherit from torch.distributed.ProcessGroup +class PyProcessGroup : public ProcessGroup { + public: + // PyWork is a pybind11 trampoline class to allow a Python + // class to inherit from torch.distributed.Work + class TORCH_PYTHON_API PyWork : public Work { + public: + PyWork() = default; + + bool wait(std::chrono::milliseconds timeout = kNoTimeout) override { + PYBIND11_OVERRIDE( + bool, /* Return type */ + Work, /* Parent class */ + wait, /* Name of function in C++ */ + timeout); + } + + c10::intrusive_ptr getFuture() override { + // We cannot use PYBIND11_OVERRIDE because: + // 1. We have to >MANUALLY< unwrap the PyFutureWrapper and + // 2. The python name is get_future + pybind11::gil_scoped_acquire gil; + auto override = + pybind11::get_override(static_cast(this), "get_future"); + + if (override) { + py::object o = override(); + auto futWrapper = + o.cast>(); + return futWrapper->fut; + } + + return Work::getFuture(); + } + }; + +#define WORK_OVERRIDE(cname, name, ...) \ + do { \ + pybind11::gil_scoped_acquire gil; \ + pybind11::function override = \ + pybind11::get_override(static_cast(this), #name); \ + if (override) { \ + auto o = override(__VA_ARGS__); \ + return c10::make_intrusive(o); \ + } \ + return cname::name(__VA_ARGS__); \ + } while (false) + + // This class is used to wrap a PyWork trampoline with it's corresponding + // Python object to prevent the Python object from being garbage collected. + class PyWorkHolder : public Work { + public: + PyWorkHolder(const c10::intrusive_ptr& work, py::object pyWork) + : work_(work), pyWork_(std::move(pyWork)) {} + + PyWorkHolder(py::object pyWork) + : work_(pyWork.cast>()), + pyWork_(std::move(pyWork)) {} + + ~PyWorkHolder() override { + // GIL must be held when freeing python objects. + py::gil_scoped_acquire gil; + pyWork_ = py::object(); + } + + bool wait(std::chrono::milliseconds timeout = kNoTimeout) override { + return work_->wait(timeout); + } + + c10::intrusive_ptr getFuture() override { + return work_->getFuture(); + } + + private: + c10::intrusive_ptr work_; + py::object pyWork_; + }; + + using ProcessGroup::ProcessGroup; + + const std::string getBackendName() const override { + PYBIND11_OVERRIDE( + std::string, /* Return type */ + ProcessGroup, /* Parent class */ + getBackendName, /* Name of function in C++ */ + ); + } + + int getRank() const override { + PYBIND11_OVERRIDE( + int, /* Return type */ + ProcessGroup, /* Parent class */ + getRank, /* Name of function in C++ */ + ); + } + + int getSize() const override { + PYBIND11_OVERRIDE( + int, /* Return type */ + ProcessGroup, /* Parent class */ + getSize, /* Name of function in C++ */ + ); + } + + void abort() override { + PYBIND11_OVERRIDE( + void, /* Return type */ + ProcessGroup, /* Parent class */ + abort, /* Name of function in C++ */ + ); + } + + const std::string& getGroupName() const override { + PYBIND11_OVERRIDE( + const std::string&, /* Return type */ + ProcessGroup, /* Parent class */ + getGroupName, /* Name of function in C++ */ + ); + } + + void setGroupName(const std::string& group_name) override { + PYBIND11_OVERRIDE( + void, /* Return type */ + ProcessGroup, /* Parent class */ + setGroupName, /* Name of function in C++ */ + group_name); + } + + const std::string& getGroupDesc() const override { + PYBIND11_OVERRIDE( + const std::string&, /* Return type */ + ProcessGroup, /* Parent class */ + getGroupDesc, /* Name of function in C++ */ + ); + } + + void setGroupDesc(const std::string& group_desc) override { + PYBIND11_OVERRIDE( + void, /* Return type */ + ProcessGroup, /* Parent class */ + setGroupDesc, /* Name of function in C++ */ + group_desc); + } + + c10::intrusive_ptr splitGroup( + const std::vector& ranks, + const std::optional& timeout, + const std::optional>& opts, + const std::optional& group_name, + const std::optional& group_desc) override { + PYBIND11_OVERRIDE( + c10::intrusive_ptr, /* Return type */ + ProcessGroup, /* Parent class */ + splitGroup, /* Name of function in C++ */ + ranks, + timeout, + opts, + group_name, + group_desc); + } + + c10::intrusive_ptr mergeRemoteGroup( + const c10::intrusive_ptr& store, + const MergeOptions& opts, + const int& size) override { + PYBIND11_OVERRIDE( + c10::intrusive_ptr, /* Return type */ + ProcessGroup, /* Parent class */ + mergeRemoteGroup, /* Name of function in C++ */ + store, + opts, + size); + } + + c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + allgather, /* Name of function in C++ */ + outputTensors, + inputTensors, + opts); + } + + c10::intrusive_ptr allgather_into_tensor_coalesced( + std::vector& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + allgather_into_tensor_coalesced, /* Name of function in C++ */ + outputTensors, + inputTensors, + opts); + } + + c10::intrusive_ptr allreduce( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override { + WORK_OVERRIDE( + // py::object, /* Return type */ + ProcessGroup, /* Parent class */ + allreduce, /* Name of function in C++ */ + tensors, + opts); + } + + c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = + AllreduceCoalescedOptions()) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + allreduce_coalesced, /* Name of function in C++ */ + tensors, + opts); + } + + c10::intrusive_ptr alltoall_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + std::vector& outputSplitSizes, + std::vector& inputSplitSizes, + const AllToAllOptions& opts = AllToAllOptions()) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + alltoall_base, /* Name of function in C++ */ + outputBuffer, + inputBuffer, + outputSplitSizes, + inputSplitSizes, + opts); + } + + c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + barrier, /* Name of function in C++ */ + opts); + } + + c10::intrusive_ptr broadcast( + std::vector& tensors, + const BroadcastOptions& opts = BroadcastOptions()) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + broadcast, /* Name of function in C++ */ + tensors, + opts); + } + + c10::intrusive_ptr reduce_scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + reduce_scatter, /* Name of function in C++ */ + outputTensors, + inputTensors, + opts); + } + + c10::intrusive_ptr reduce_scatter_tensor_coalesced( + std::vector& outputTensors, + std::vector& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + reduce_scatter_tensor_coalesced, /* Name of function in C++ */ + outputTensors, + inputTensors, + opts); + } + + c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + send, /* Name of function in C++ */ + tensors, + dstRank, + tag); + } + + c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) override { + WORK_OVERRIDE( + ProcessGroup, /* Parent class */ + recv, /* Name of function in C++ */ + tensors, + srcRank, + tag); + } +}; + +class TORCH_PYTHON_API PythonOnCompletionHook { + public: + // Wraps a py::object hook and acquires Python GIL in dtor before + // destructing the hook object. + PythonOnCompletionHook(py::object hook) : hook_(std::move(hook)) {} + PythonOnCompletionHook(const PythonOnCompletionHook&) = default; + + // NOLINTNEXTLINE(bugprone-exception-escape) + ~PythonOnCompletionHook() { + py::gil_scoped_acquire ag; + hook_.dec_ref(); + // Explicitly set hook_ to nullptr to prevent py::object's dtor + // to decref on the PyObject again. + // See Note [Destructing py::object] in python_ivalue.h + hook_.ptr() = nullptr; + } + + void operator()(const std::shared_ptr& workInfo) const { + std::exception_ptr eptr; + { + py::gil_scoped_acquire acquire; + try { + hook_(workInfo); + } catch (py::error_already_set& e) { + // py::error_already_set requires GIL to destruct, take + // special care. + eptr = std::make_exception_ptr(std::runtime_error(e.what())); + e.restore(); + PyErr_Clear(); + } catch (std::exception&) { + eptr = std::current_exception(); + } + } + // No more Python-related stuff at this point, i.e., this + // exception can be captured and handled by PG backend. + if (eptr) + std::rethrow_exception(eptr); + } + + private: + py::object hook_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..de3e5e2f95ff92bec1e9bbc6c457c777cb4f578d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp @@ -0,0 +1,78 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) + +#pragma once + +#include + +#include + +namespace c10d { + +// `RankLocal` maintains a unique instance of T for each non-autograd thread. +// For non-autograd threads, `RankLocal::get()` functions similar to +// thread_local. For autograd threads, `RankLocal::get()` returns the +// instance of T corresponding to the enqueuing non-autograd thread. The +// mechanism allows for rank-specific context shared between forward and +// backward. It works for both the one-rank-per-process and one-rank-per-thread +// scenarios. +// +// NOTE: RankLocal doesn't make the underlying objects thread-safe. +template +class RankLocal { + public: + RankLocal(const RankLocal&) = delete; + RankLocal& operator=(const RankLocal&) = delete; + + static T& get() { + // Fast path: non-autograd threads can simply return + // the object reference cached in TLS. + if (cached_ != nullptr) { + return *cached_; + } + const auto node = torch::autograd::get_current_node(); + auto fwd_thread_id = node == nullptr ? at::RecordFunction::currentThreadId() + : node->thread_id(); + // Optimistically acquire the read lock first, since most likely we are in + // an autograd thread and the object has already been constructed. + { + std::shared_lock read_lock(lock_); + auto it = thread_id_to_rank_local_.find(fwd_thread_id); + if (it != thread_id_to_rank_local_.end()) { + // Cache for non-autograd threads + if (node == nullptr) { + cached_ = &it->second; + } + return it->second; + } + } + + std::unique_lock write_lock(lock_); + auto [it, _] = thread_id_to_rank_local_.try_emplace(fwd_thread_id); + // Cache for non-autograd threads + if (node == nullptr) { + cached_ = &it->second; + } + return it->second; + } + + private: + RankLocal() = default; + thread_local static T* cached_; + static std::unordered_map thread_id_to_rank_local_; + static std::shared_mutex lock_; +}; + +template +thread_local T* RankLocal::cached_ = nullptr; + +template +std::unordered_map RankLocal::thread_id_to_rank_local_; + +template +std::shared_mutex RankLocal::lock_; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Store.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Store.hpp new file mode 100644 index 0000000000000000000000000000000000000000..641bc6a36aebde20dfd33309da1609a55e27dea6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Store.hpp @@ -0,0 +1,159 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace c10d { + +// callback function will be given arguments (std::optional oldValue, +// std::optional newValue) +using WatchKeyCallback = + std::function, std::optional)>; + +class TORCH_API Store : public torch::CustomClassHolder { + public: + static constexpr std::chrono::milliseconds kDefaultTimeout = + std::chrono::seconds(300); + static constexpr std::chrono::milliseconds kNoTimeout = + std::chrono::milliseconds::zero(); + + Store() : timeout_(kDefaultTimeout) {} + + explicit Store(const std::chrono::milliseconds& timeout) + : timeout_(timeout) {} + + Store(const Store&) = default; + Store(Store&&) noexcept = default; + + ~Store() override = default; + + // Clone a thread safe copy of this store object that points to the same + // underlying store. + virtual c10::intrusive_ptr clone() = 0; + + void set(const std::string& key, const std::string& value); + + virtual void set( + const std::string& key, + const std::vector& value) = 0; + + std::string compareSet( + const std::string& key, + const std::string& currentValue, + const std::string& newValue); + + virtual std::vector compareSet( + const std::string& key, + const std::vector& currentValue, + const std::vector& newValue) { + C10_THROW_ERROR(NotImplementedError, "Not implemented."); + } + + std::string get_to_str(const std::string& key); + + virtual std::vector get(const std::string& key) = 0; + + virtual int64_t add(const std::string& key, int64_t value) = 0; + + virtual bool deleteKey(const std::string& key) = 0; + + virtual bool check(const std::vector& keys) = 0; + + virtual int64_t getNumKeys() = 0; + + virtual void wait(const std::vector& keys) = 0; + + virtual void wait( + const std::vector& keys, + const std::chrono::milliseconds& timeout) = 0; + + virtual const std::chrono::milliseconds& getTimeout() const noexcept; + + virtual void setTimeout(const std::chrono::milliseconds& timeout); + + // watchKey() is deprecated and no longer supported. + virtual void watchKey( + const std::string& /* unused */, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + WatchKeyCallback /* unused */) { + C10_THROW_ERROR( + NotImplementedError, + "watchKey is deprecated, no implementation support it."); + } + + virtual void append( + const std::string& key, + const std::vector& value); + + virtual std::vector> multiGet( + const std::vector& keys); + + virtual void multiSet( + const std::vector& keys, + const std::vector>& values); + + // Returns true if this store support append, multiGet and multiSet + virtual bool hasExtendedApi() const; + + virtual void queuePush( + const std::string& key, + const std::vector& value) { + C10_THROW_ERROR(NotImplementedError, "queue support is not implemented."); + } + + virtual std::vector queuePop(const std::string& key, bool block) { + C10_THROW_ERROR(NotImplementedError, "queue support is not implemented."); + } + + virtual int64_t queueLen(const std::string& key) { + C10_THROW_ERROR(NotImplementedError, "queue support is not implemented."); + } + + virtual std::vector listKeys() { + C10_THROW_ERROR( + NotImplementedError, "listKeys support is not implemented."); + } + + protected: + std::chrono::milliseconds timeout_; +}; + +/* +StoreTimeoutGuard is a RAII guard that will set the store timeout and restore it +when it returns. +*/ +class StoreTimeoutGuard { + public: + explicit StoreTimeoutGuard( + Store& store, + const std::chrono::milliseconds& timeout) + : store_(store), oldTimeout_(store.getTimeout()) { + store.setTimeout(timeout); + } + + ~StoreTimeoutGuard() { + store_.setTimeout(oldTimeout_); + } + + /* Disabling copy and move semantics */ + StoreTimeoutGuard(const StoreTimeoutGuard&) = delete; + StoreTimeoutGuard& operator=(const StoreTimeoutGuard&) = delete; + StoreTimeoutGuard(StoreTimeoutGuard&&) = delete; + StoreTimeoutGuard& operator=(StoreTimeoutGuard&&) = delete; + + private: + Store& store_; + std::chrono::milliseconds oldTimeout_{}; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ea3272d25b465ae53a8b73f8b440253892a92e41 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp @@ -0,0 +1,176 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace c10d { +namespace detail { + +// TCPStore is a key-value store used by PyTorch mainly for distributed +// rendezvous, but for other purposes as well. (e.g., a centralized storage for +// synchronization among different processes.) +// +// It is run via a classic client-server architecture, where the server runs +// a separate background thread (alternatively we call it daemon thread). The +// client and server communicate via TCP sockets. +// +// Currently we have two types of server backends: +// 1. TCPStoreBackend: a single thread to handle all incoming request +// synchronously. +// 2. LibUVTCPStoreBackend: an event-driven asynchronous stream processing that +// leverages libuv library (https://github.com/libuv/libuv) for better +// performance. And this backend now is recommended to users. (We set the +// default value of `useLibUV` inside `TCPStoreOptions` to true now, so users +// should get it by default). +// +// Code structure: +// ├── TCPStore client side API and server setup code: +// │ TCPStore.hpp/TCPStore.cpp +// ├── TCPStoreBackend server side API implementation code: +// │ TCPStoreBackend.hpp/TCPStoreBackend.cpp +// | (actual class:`TCPStoreMasterDaemon`) +// ├── LibUVTCPStoreBackend +// │ TCPStoreLibUvBackend.cpp +// | (actual class: `LibUVStoreDaemon`) + +class TCPServer; + +class TCPClient; + +struct SocketAddress { + std::string host; + std::uint16_t port{}; +}; + +} // namespace detail + +struct TCPStoreOptions { + static constexpr std::uint16_t kDefaultPort = 29500; + + std::uint16_t port = kDefaultPort; + bool isServer = false; + std::optional numWorkers = std::nullopt; + bool waitWorkers = true; + std::chrono::milliseconds timeout = Store::kDefaultTimeout; + + // A boolean value indicating whether multiple store instances can be + // initialized with the same host:port pair. + bool multiTenant = false; + + // If specified, and if isServer is true, the underlying TCPServer will take + // over the bound socket associated to this fd. This option is useful to avoid + // port assignment races in certain scenarios. + std::optional masterListenFd = std::nullopt; + + // A boolean value indicating whether to use the experimental libUV backend. + bool useLibUV = true; +}; + +class TORCH_API TCPStore : public Store { + public: + static constexpr std::chrono::milliseconds kConnectRetryDelay{1000}; + + explicit TCPStore(std::string host, const TCPStoreOptions& opts = {}); + + ~TCPStore() override; + + c10::intrusive_ptr clone() override; + + void set(const std::string& key, const std::vector& value) override; + + std::vector compareSet( + const std::string& key, + const std::vector& expectedValue, + const std::vector& desiredValue) override; + + std::vector get(const std::string& key) override; + + int64_t add(const std::string& key, int64_t value) override; + + bool deleteKey(const std::string& key) override; + + bool check(const std::vector& keys) override; + + int64_t getNumKeys() override; + + void wait(const std::vector& keys) override; + + void wait( + const std::vector& keys, + const std::chrono::milliseconds& timeout) override; + + void append(const std::string& key, const std::vector& value) + override; + + std::vector> multiGet( + const std::vector& keys) override; + + void multiSet( + const std::vector& keys, + const std::vector>& values) override; + + bool hasExtendedApi() const override; + + void queuePush(const std::string& key, const std::vector& value) + override; + + std::vector queuePop(const std::string& key, bool block) override; + + int64_t queueLen(const std::string& key) override; + + std::vector listKeys() override; + + // Waits for all workers to join. + void waitForWorkers(); + + // Returns the hostname used by the TCPStore. + const std::string& getHost() const noexcept { + return addr_.host; + } + + // Returns the port used by the TCPStore. + std::uint16_t getPort() const noexcept { + return addr_.port; + } + + bool isLibUvBackend() const noexcept { + return usingLibUv_; + } + + // note(xilunwu): this function is only for internal testing + void _splitSet(const std::string& key, const std::vector& data); + + std::string repr() const; + + private: + int64_t incrementValueBy(const std::string& key, int64_t delta); + + void ping(); + void validate(); + + std::vector doGet(const std::string& key); + + void doWait( + c10::ArrayRef keys, + std::chrono::milliseconds timeout); + + detail::SocketAddress addr_; + std::shared_ptr server_; + std::unique_ptr client_; + std::optional numWorkers_; + + const std::string initKey_ = "init/"; + const std::string keyPrefix_ = "/"; + std::mutex activeOpLock_; + bool usingLibUv_ = true; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStoreBackend.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStoreBackend.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bed050e1cb26c70b5955a5d29f521be86bf6194a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStoreBackend.hpp @@ -0,0 +1,83 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#endif + +namespace c10d::detail { + +// Magic number for client validation. +static const uint32_t validationMagicNumber = 0x3C85F7CE; + +enum class QueryType : uint8_t { + VALIDATE, + SET, + COMPARE_SET, + GET, + ADD, + CHECK, + WAIT, + GETNUMKEYS, + DELETE_KEY, + APPEND, + MULTI_GET, + MULTI_SET, + CANCEL_WAIT, + PING, + QUEUE_PUSH, + QUEUE_POP, + QUEUE_LEN, + LIST_KEYS, +}; + +enum class CheckResponseType : uint8_t { READY, NOT_READY }; + +enum class WaitResponseType : uint8_t { STOP_WAITING, WAIT_CANCELED }; + +// Abstract base class to handle thread state for TCPStoreMasterDaemon. +// Contains the windows/unix implementations to signal a +// shutdown sequence for the thread +class BackgroundThread { + public: + explicit BackgroundThread(); + + virtual ~BackgroundThread() = 0; + virtual std::uint16_t port() const = 0; + + void start(); + bool stop_requested(); + + protected: + void dispose(); + virtual void run() = 0; + virtual void stop() = 0; + bool is_running() { + return is_running_.load(); + } + + private: + std::atomic is_running_{false}; + std::thread daemonThread_; +}; + +std::unique_ptr create_tcpstore_backend( + const TCPStoreOptions& opts); +std::unique_ptr create_libuv_tcpstore_backend( + const TCPStoreOptions& opts); +bool is_libuv_tcpstore_backend_available(); + +} // namespace c10d::detail + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TraceUtils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TraceUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..8e584ac92c5c2a8aaf092cd25fc273f1fe1740f2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TraceUtils.h @@ -0,0 +1,324 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include // optional, for ostream fallback +#include // for fmt::join + +#include +#include +#include +#include +#include +#include + +namespace c10d { + +inline std::string getTraceStartKey(const std::string& pgName, int rank) { + return fmt::format(FMT_COMPILE("{}_{}_trace_start"), pgName, rank); +} + +inline std::string getTraceEndKey(const std::string& pgName, int rank) { + return fmt::format(FMT_COMPILE("{}_{}_trace_end"), pgName, rank); +} + +inline bool traceUpdate( + c10::intrusive_ptr& store, + const std::string& key, + uint64_t seq, + const std::string& col) { + std::vector value(col.size() + sizeof(seq) + 1); + std::memcpy(value.data(), &seq, sizeof(seq)); + std::memcpy(value.data() + sizeof(seq), col.data(), col.size()); + try { + store->set(key, value); + return true; + } catch (...) { + LOG(ERROR) << "Store is down while updating #" << seq << " with key " + << key; + return false; + } + return true; +} + +enum TraceDebugEvent { + kEventStart, + kEventEnd, +}; +// >> +using TraceMap = + std::map>>; + +inline std::string ranksToString(const std::vector& ranks) { + return fmt::to_string(fmt::join(ranks, ", ")); +} + +inline std::string ranksFromTrace( + const std::vector>& items) { + fmt::memory_buffer buf; + bool first = true; + for (const auto& [rank, _] : items) { + if (!first) { + fmt::format_to(std::back_inserter(buf), ", "); + } + fmt::format_to(std::back_inserter(buf), "{}", rank); + first = false; + } + return fmt::to_string(buf); +} + +inline std::string analyzeMissingRanks(const std::vector& missingRanks) { + return c10::str( + "\n\t - To our best knowledge, ranks [", + ranksToString(missingRanks), + "] are the lagging ranks that caused this timeout. " + "They never joined any collectives"); +} + +inline std::string analyzeLaggingRanks(const TraceMap& traceMap) { + uint64_t lagSeq = traceMap.begin()->first; + std::vector startRanks; + std::vector endRanks; + for (auto& p : traceMap.begin()->second) { + if (p.second.second == kEventStart) { + startRanks.push_back(p.first); + } else { + endRanks.push_back(p.first); + } + } + std::string report = + "\n\t - To our best knowledge, the lagging/dead/mismatched ranks " + "that caused the desync are:"; + if (!startRanks.empty()) { + report += c10::str( + "\n\t - [", + ranksToString(startRanks), + "] joined but didn't finish collective #", + lagSeq, + " (count from 1)"); + } + if (!endRanks.empty()) { + report += c10::str( + "\n\t [", + ranksToString(endRanks), + "] finished collective #", + lagSeq, + ", but didn't join collective #", + lagSeq + 1, + " (count from 1)"); + } + return report; +} + +inline std::string dumpSnapshot(TraceMap& traceMap) { + std::string report = "\n\t - Snapshot of ranks' latest states:"; + for (auto& tracePair : traceMap) { + uint64_t seq = tracePair.first; + std::map>& subMap = + tracePair.second; + + std::unordered_map> collectivesStart; + std::unordered_map> collectivesEnd; + for (const auto& p : subMap) { + int rank = p.first; + const std::string& col = p.second.first; + if (p.second.second == kEventStart) { + collectivesStart[col].push_back(rank); + } else { + collectivesEnd[col].push_back(rank); + } + } + + if (!collectivesStart.empty()) { + report += c10::str("\n\t #", seq, " started ranks:"); + for (auto& mapPair : collectivesStart) { + report += c10::str( + "\n\t [", + ranksToString(mapPair.second), + "] started ", + mapPair.first); + } + } + if (!collectivesEnd.empty()) { + report += c10::str("\n\t #", seq, " finished ranks:"); + for (auto& mapPair : collectivesEnd) { + report += c10::str( + "\n\t [", + ranksToString(mapPair.second), + "] finished ", + mapPair.first); + } + } + } + return report; +} + +inline bool parseTraceValue( + c10::intrusive_ptr& store, + const std::string& key, + uint64_t& seq, + std::string& col) { + try { + std::vector traceValue = store->get(key); + std::memcpy(&seq, traceValue.data(), sizeof(seq)); + std::string colName((char*)traceValue.data() + sizeof(seq)); + col = colName; + return true; + } catch (...) { + LOG(ERROR) << "Store is down while getting key " << key; + return false; + } + return true; +} + +inline std::string retrieveDesyncReport( + c10::intrusive_ptr& store, + const std::string& pgName, + int myRank, + int worldSize) { + std::string report; + + uint64_t thisSeq = 0; + std::string thisCol; + + std::vector missingRanks; + TraceMap traceMap; + + for (const auto rank : c10::irange(worldSize)) { + // Build traceMapStart. + uint64_t seqStart = 0; + { + std::string traceKeyStart = getTraceStartKey(pgName, rank); + if (!store->check({traceKeyStart})) { + missingRanks.push_back(rank); + continue; + } + std::string col; + if (!parseTraceValue(store, traceKeyStart, seqStart, col)) { + return report; + } + traceMap[seqStart].emplace(rank, std::make_pair(col, kEventStart)); + if (rank == myRank) { + thisSeq = seqStart; + thisCol = std::move(col); + } + } + + // Build traceMapEnd. + { + std::string traceKeyEnd = getTraceEndKey(pgName, rank); + if (!store->check({traceKeyEnd})) { + continue; + } + uint64_t seq = 0; + std::string col; + if (!parseTraceValue(store, traceKeyEnd, seq, col)) { + return report; + } + if (seq == seqStart) { + traceMap[seq][rank].second = kEventEnd; + } + } + } + + TORCH_INTERNAL_ASSERT( + !missingRanks.empty() || !traceMap.empty(), + "Trace shouldn't be empty while enabled GLOO_ASYNC_TIMEOUT_DEBUG"); + TORCH_INTERNAL_ASSERT( + !thisCol.empty(), + "Timeout rank [", + myRank, + "] must have collective tracking iteam in c10::Store trace"); + TORCH_INTERNAL_ASSERT( + traceMap[thisSeq][myRank].second == kEventStart, + "Timeout rank [", + myRank, + "] last trace item must be kEventStart. thisSeq = ", + thisSeq, + ", col = ", + thisCol); + + report += c10::str( + "\n\t - [", myRank, "] Timeout at collective: ", thisCol, ", #", thisSeq); + + if (!missingRanks.empty()) { + report += analyzeMissingRanks(missingRanks); + } else { + report += analyzeLaggingRanks(traceMap); + report += dumpSnapshot(traceMap); + } + + return report; +} + +inline std::string pickle_str(const c10::IValue& v) { + std::vector result; + { + auto writer = [&](const char* data, size_t size) { + result.insert(result.end(), data, data + size); + }; + torch::jit::Pickler pickler( + writer, nullptr, nullptr, nullptr, nullptr, false); + pickler.protocol(); + pickler.pushIValue(v); + pickler.stop(); + } + return std::string(result.begin(), result.end()); +} + +inline std::string get_python_cpp_trace() { + // usage: + // LOG(INFO) << "stacktrace: " + // << get_python_cpp_trace(); + // warn: might be slow in getting cpp traces + // because of slow/broken addr2line + // in different system libs + std::shared_ptr tb = + torch::CapturedTraceback::gather( + /*python=*/true, /*script=*/true, /*cpp=*/true); + torch::SymbolizedTracebacks s_tbs = torch::symbolize({tb.get()}); + const auto& s_tb = s_tbs.tracebacks.at(0); + constexpr auto TB_FMT_CSTR = FMT_COMPILE("#{} {} from {}:{}\n"); + fmt::memory_buffer buf; + auto buf_iter = std::back_inserter(buf); + for (auto idx : c10::irange(s_tb.size())) { + auto frame_id = s_tb[idx]; + const auto& frame = s_tbs.all_frames.at(frame_id); + fmt::format_to( + buf_iter, + TB_FMT_CSTR, + idx, + frame.funcname, + frame.filename, + frame.lineno); + } + return fmt::to_string(buf); +} + +inline c10::Dict new_dict() { + return c10::Dict( + c10::AnyType::get(), c10::AnyType::get()); +} + +inline c10::List new_list() { + return c10::List(c10::AnyType::get()); +} + +inline std::string ranks_str(const std::vector& ranks) { + return fmt::format("[{}]", fmt::join(ranks, ", ")); +} + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c02edd2ef0eb6f4a04b6abe2976d1c9cd20e2e90 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp @@ -0,0 +1,190 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +#include +#include + +#include +#include + +namespace c10d { + +// Base class for supplementary data potentially needed by ReduceOps +struct TORCH_API _SupplementBase : torch::CustomClassHolder { + ~_SupplementBase() override = default; +}; + +// Supplementary data specific to NCCL PREMUL_SUM +// The point of use in ProcessGroupNCCL knows how to unpack it. +struct NCCLPreMulSumSupplement : _SupplementBase { + double double_factor{0.0}; + at::Tensor tensor_factor; + NCCLPreMulSumSupplement(double f) : double_factor{f} {} + NCCLPreMulSumSupplement(at::Tensor t) : tensor_factor{std::move(t)} { + TORCH_CHECK_EQ(tensor_factor.numel(), 1); + } +}; + +// Other ReduceOps that need different supplementary data can also +// derive from _SupplementBase. +struct TORCH_API ReduceOp : torch::CustomClassHolder { + // note(crcrpar): RedOpType could be defined outside of `ReduceOp` + enum RedOpType : uint8_t { + SUM = 0, + AVG = 1, + PRODUCT = 2, + MIN = 3, + MAX = 4, + BAND = 5, // Bitwise AND + BOR = 6, // Bitwise OR + BXOR = 7, // Bitwise XOR + PREMUL_SUM = 8, // Multiply by a user-supplied constant before summing. + UNUSED = 9 + }; + + ReduceOp() = default; + + ReduceOp(RedOpType op) : op_(op) { + TORCH_INTERNAL_ASSERT( + op_ != PREMUL_SUM, + "Use `torch.distributed._make_nccl_premul_sum` to create an instance of ReduceOp with PREMUL_SUM"); + } + + ReduceOp( + RedOpType op, + const c10::intrusive_ptr<_SupplementBase>& optional_supplement) { + if (optional_supplement) { + op_ = op; + } else { + supplement_ = optional_supplement; + } + } + + // The heap resource supplement_, if it exists, is managed by a + // c10::intrusive_ptr, so constructors and operator= can be simple + ReduceOp(const ReduceOp& other) = default; + ReduceOp& operator=(const ReduceOp& other) = default; + + ReduceOp(ReduceOp&& other) = default; + ReduceOp& operator=(ReduceOp&& other) = default; + ~ReduceOp() override = default; + + operator RedOpType() const { + return op_; + } + + bool operator==(const std::uint8_t other) { + TORCH_INTERNAL_ASSERT(other < 9, "Invalid other op value"); + return other == op_; + } + + bool operator==(const ReduceOp::RedOpType other) { + return *this == static_cast(other); + } + + // todo(crcrpar): Handle `RedOpType::PREMUL_SUM` with its scaling factor. + bool operator==(const ReduceOp& other) { + return *this == other.op_; + } + + RedOpType op_ = SUM; + // supplement_ is "type-erased" storage for optional supplementary + // data the op might need. + // The point of use will know the derived type supplement_ really is, + // and downcast its pointer to extract the data as the needed type(s). + // Right now, only PREMUL_SUM needs supplementary data, but the same + // mechanism could extend to support other nontrivial reduce ops with + // different supplementary payloads. + c10::intrusive_ptr<_SupplementBase> supplement_; +}; + +template +ReduceOp makeNCCLPreMulSum(const T& factor) { + ReduceOp rop; + rop.op_ = ReduceOp::PREMUL_SUM; + rop.supplement_ = c10::make_intrusive(factor); + return rop; +} + +TORCH_API bool isComplexViewAsRealAllowed(const ReduceOp& reduceOp); + +constexpr auto kUnsetTimeout = std::chrono::milliseconds(-1); + +struct BroadcastOptions { + int64_t rootRank = 0; + int64_t rootTensor = 0; + std::chrono::milliseconds timeout = kUnsetTimeout; + bool asyncOp = true; +}; + +struct AllreduceOptions { + ReduceOp reduceOp = ReduceOp::SUM; + std::chrono::milliseconds timeout = kUnsetTimeout; + bool asyncOp = true; + std::optional sparseIndices = std::nullopt; +}; + +struct AllreduceCoalescedOptions : AllreduceOptions {}; + +struct ReduceOptions { + ReduceOp reduceOp = ReduceOp::SUM; + int64_t rootRank = 0; + int64_t rootTensor = 0; + std::chrono::milliseconds timeout = kUnsetTimeout; + bool asyncOp = true; +}; + +struct AllgatherOptions { + std::chrono::milliseconds timeout = kUnsetTimeout; + bool asyncOp = true; +}; + +struct GatherOptions { + int64_t rootRank = 0; + std::chrono::milliseconds timeout = kUnsetTimeout; + bool asyncOp = true; +}; + +struct ScatterOptions { + int64_t rootRank = 0; + std::chrono::milliseconds timeout = kUnsetTimeout; + bool asyncOp = true; +}; + +struct ReduceScatterOptions { + ReduceOp reduceOp = ReduceOp::SUM; + std::chrono::milliseconds timeout = kUnsetTimeout; + bool asyncOp = true; +}; + +struct AllToAllOptions { + std::chrono::milliseconds timeout = kUnsetTimeout; + bool asyncOp = true; +}; + +struct BarrierOptions { + std::vector device_ids; + std::chrono::milliseconds timeout = kUnsetTimeout; + std::optional device; + bool asyncOp = true; +}; + +struct DistributedBackendOptions { + c10::intrusive_ptr<::c10d::Store> store; + int group_rank; + int group_size; + std::chrono::duration timeout; + std::string group_id; + std::vector global_ranks_in_group; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCTracing.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCTracing.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6e53aa7a21fb3a67135d15b2add0fe344d05dab6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCTracing.hpp @@ -0,0 +1,63 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_UCC + +#include + +namespace c10d { + +#define RECORD_COMMS_TRACE( \ + _comms_tracer, _work, _opType, _rank, _comm_size, _inTensors, _outTensors) \ + do { \ + if (torch_ucc_config.enable_comms_logger) { \ + _comms_tracer->recordComms( \ + opTypeToString(_opType), \ + (uintptr_t)_work.get(), \ + _rank, \ + _comm_size, \ + _inTensors, \ + _outTensors); \ + } \ + } while (0) + +// interfaces to collect communication traces +class TORCH_API CommTraceLogger : public torch::CustomClassHolder { + private: + std::vector comms_trace_; + std::vector curBlocks_; /* unused */ + std::vector curOutSplitSizes_; + std::vector curInSplitSizes_; + int curRoot_ = -1; + unsigned long seqnum = 0; + + public: + void setCurBlock(const std::string& name); /* unused */ + void popBlock(); /* unused */ + // record root info if applicable, e.g., broadcast, gather, scatter + void recordOptionalInfo(int root = -1); + // record input/output splits of Alltoallv + void recordOptionalInfo( + const std::vector& outputSplitSizes = {}, + const std::vector& inputSplitSizes = {}); + // record essential comms information + void recordComms( + const std::string& collName, + const uintptr_t workReq = 0, + const int rank = -1, + const int world_size = -1, + const std::vector& inputTensors = {}, + const std::vector& outputTensor = {}); + // return collected comms traces + std::vector& getCommsTrace() { + return comms_trace_; + } +}; + +} // namespace c10d + +#endif // USE_C10D_UCC + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..66357622a880f36d1cad25d5a1642478482bcf05 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp @@ -0,0 +1,192 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_C10D_UCC + +#include +#include +#include + +namespace c10d { + +// Macro to generate the error message on a non-successful UCC return value. +#define TORCH_UCC_GET_ERROR_MSG(_err, _error_msg, _result) \ + do { \ + _err = c10::str( \ + "[", \ + std::string(__FILE__), \ + ":", \ + std::to_string(__LINE__), \ + "] ", \ + logger->getLogPrefix(), \ + _error_msg, \ + ", error code ", \ + _result, \ + ": ", \ + ucc_status_string(_result), \ + ", system error code ", \ + errno); \ + } while (0) + +// Macro to throw on a non-successful UCC return value. +#define TORCH_UCC_CHECK(_cmd, _error_msg) \ + do { \ + ucc_status_t result = _cmd; \ + if (result != UCC_OK) { \ + std::string err; \ + TORCH_UCC_GET_ERROR_MSG(err, _error_msg, result); \ + TORCH_CHECK(false, err); \ + } \ + } while (0) + +// Macro and throw on a non-successful UCC return value and free its request. +#define TORCH_UCC_CHECK_REQUEST(_request, _cmd, _error_msg) \ + do { \ + ucc_status_t result = _cmd; \ + if (result != UCC_OK) { \ + std::string err; \ + TORCH_UCC_GET_ERROR_MSG(err, _error_msg, result); \ + if (_request != nullptr) { \ + ucc_collective_finalize(_request); \ + } \ + TORCH_CHECK(false, err); \ + } \ + } while (0) + +// Macros to print logs with unified format +#define TORCH_UCC_LOG_ERROR(_phase, _msg) \ + LOG(ERROR) << logger->getLogPrefix(_phase) << "[ERROR] " << _msg; +#define TORCH_UCC_LOG_INFO(_phase, _msg) \ + LOG(INFO) << logger->getLogPrefix(_phase) << "[INFO] " << _msg; +#define TORCH_UCC_LOG_DEBUG(_phase, _msg) \ + VLOG(1) << logger->getLogPrefix(_phase) << "[DEBUG] " << _msg; + +enum torch_ucc_phase_t { + TORCH_UCC_UNKNOWN = -1, + TORCH_UCC_INIT, + TORCH_UCC_HEALTH_CHECK, + TORCH_UCC_READY, + TORCH_UCC_COLL_POST, + TORCH_UCC_COLL_PROGRESS, + TORCH_UCC_FINALIZE, +}; + +const std::map ucc_phase_map = { + {TORCH_UCC_UNKNOWN, "UNKNOWN"}, + {TORCH_UCC_INIT, "INIT"}, + {TORCH_UCC_HEALTH_CHECK, "HEALTH_CHECK"}, + {TORCH_UCC_READY, "READY"}, + {TORCH_UCC_COLL_POST, "COLL_POST"}, + {TORCH_UCC_COLL_PROGRESS, "COLL_PROGRESS"}, + {TORCH_UCC_FINALIZE, "FINALIZE"}, +}; + +class CommTraceLogger; + +class TORCH_API ProcessGroupUCCLogger : public torch::CustomClassHolder { + public: + ProcessGroupUCCLogger(); + ProcessGroupUCCLogger(std::string log_prefix, torch_ucc_phase_t phase); + + std::string getLogPrefix(torch_ucc_phase_t phase = TORCH_UCC_UNKNOWN); + void setLogPrefix(std::string log_prefix); + inline void setPhase(torch_ucc_phase_t phase) { + local_phase = phase; + } + + void initCommsTracer(); + void flushComms(int rank, int world_size); + std::shared_ptr trace_generator = nullptr; + + protected: + std::string log_prefix; + torch_ucc_phase_t local_phase = TORCH_UCC_UNKNOWN; + bool initialized_CommTraceLogger = false; +}; + +struct torch_ucc_oob_coll_info_t { + c10::intrusive_ptr store; + uint32_t comm_id; + int rank; + int size; + void* rbuf; + size_t msglen; + std::string getKey(std::string key) { + return std::to_string(comm_id) + key; + } +}; + +class CommBase { + public: + CommBase(const c10::intrusive_ptr& logger_) + : logger(logger_) {} + virtual void progress() = 0; + virtual void free_request(ucc_coll_req_h request) = 0; + virtual ~CommBase() {} + c10::intrusive_ptr logger; +}; +class CommUCC : public CommBase { + public: + ucc_lib_h lib{nullptr}; + ucc_context_h context{nullptr}; + + public: + void progress() override; + CommUCC( + std::shared_ptr oob, + const c10::intrusive_ptr& logger); + void free_request(ucc_coll_req_h request) override; + ~CommUCC(); +}; + +ucc_status_t oob_allgather( + void* sbuf, + void* rbuf, + size_t msglen, + void* coll_info, + void** req); + +ucc_status_t oob_allgather_test(void* req); + +ucc_status_t oob_allgather_free(void* req); + +// trim: remove spaces before and after the string view +// implementation borrowed from https://stackoverflow.com/a/17976541 +inline std::string_view trim(std::string_view s) { + auto wsfront = std::find_if_not( + s.begin(), s.end(), [](int c) { return std::isspace(c); }); + auto wsback = std::find_if_not(s.rbegin(), s.rend(), [](int c) { + return std::isspace(c); + }).base(); + return ( + wsback <= wsfront ? "" : s.substr(wsfront - s.begin(), wsback - wsfront)); +} + +inline std::string tolower(std::string_view s) { + std::string result; + result.reserve(s.size()); + for (auto c : s) { + result.push_back(std::tolower(c)); + } + return result; +} + +inline std::vector parse_list(std::string list) { + std::vector result; + list = tolower(trim(list)); + while (!list.empty()) { + const auto end_pos = list.find_first_of(','); + const auto token = trim(list.substr(0, end_pos)); + result.push_back(std::string(token)); + list = (end_pos != std::string_view::npos) ? list.substr(end_pos + 1) : ""; + } + return result; +} + +} // namespace c10d + +#endif // USE_C10D_UCC + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UnixSockUtils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UnixSockUtils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4293911d1faea1f3595eea7af19f7094afcfac60 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UnixSockUtils.hpp @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace c10d::tcputil { + +#define CONNECT_SOCKET_OFFSET 2 + +inline int poll(struct pollfd* fds, unsigned long nfds, int timeout) { + return ::poll(fds, nfds, timeout); +} + +inline void addPollfd( + std::vector& fds, + int socket, + short events) { + fds.push_back({.fd = socket, .events = events}); +} + +inline struct ::pollfd getPollfd(int socket, short events) { + struct ::pollfd res = {.fd = socket, .events = events}; + return res; +} + +} // namespace c10d::tcputil + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Utils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Utils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fedb64349bbbb088ea87d493c37c0e8efaef2e65 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Utils.hpp @@ -0,0 +1,750 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +typedef SSIZE_T ssize_t; +#pragma comment(lib, "Ws2_32.lib") +#else +#include +#include +#include +#include +#include +#endif + +#include + +#include +#include +#include +#include +#include + +namespace c10d { + +TORCH_API size_t getTensorsNumel(const std::vector& tensors); + +// Retrieve tensor shapes from a given tensor. +TORCH_API std::vector getTensorShapes( + const std::vector& tensors); + +// Use -2 to represent unset state of env vars +#define C10D_ENV_NOT_SET -2 + +#define WARN_ENV_VAR_ONCE(deprecated_env, new_env) \ + TORCH_WARN_ONCE( \ + "Environment variable " + deprecated_env + " is deprecated; use " + \ + new_env + " instead"); + +// Turns at::IntArrayRef into "(1, 2, 3, 4)". +inline std::string toString(at::IntArrayRef l) { + std::stringstream ss; + ss << '('; + for (const auto i : c10::irange(l.size())) { + if (i > 0) { + ss << ", "; + } + ss << l[i]; + } + ss << ')'; + return ss.str(); +} + +inline std::string toString(const c10::Layout& layout) { + std::stringstream ss; + ss << layout; + return ss.str(); +} + +inline void assertSameType( + const at::DeprecatedTypeProperties& type, + const std::vector& tensors) { + for (const auto i : c10::irange(tensors.size())) { + if (!tensors[i].options().type_equal(type.options())) { + const std::string expected = type.toString(); + const std::string actual = tensors[i].toString(); + throw std::invalid_argument( + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + "mixed types (" + expected + " and " + actual + ")"); + } + } +} + +inline std::vector split( + char separator, + const std::string& string) { + std::vector pieces; + std::stringstream ss(string); + std::string item; + while (std::getline(ss, item, separator)) { + pieces.push_back(std::move(item)); + } + return pieces; +} + +inline std::string getCvarString( + const std::vector& env, + const char* def) { + std::string ret(def); + + if (env.empty()) { + TORCH_CHECK(false, "No environment variables passed"); + return ret; + } + + /* parse environment variable in reverse order, so the early + * versions of a variable get higher priority than the latter + * versions of the same variable */ + for (ssize_t i = static_cast(env.size()) - 1; i >= 0; i--) { + auto val = c10::utils::get_env(env[i].c_str()); + if (!val.has_value()) { + continue; + } else if (i) { + WARN_ENV_VAR_ONCE(env[i], env[0]); + } + + ret = val.value(); + } + + return ret; +} + +inline int getCvarInt(const std::vector& env, int def) { + int ret = def; + + if (env.empty()) { + TORCH_CHECK(false, "No environment variables passed"); + return ret; + } + + /* parse environment variable in reverse order, so the early + * versions of a variable get higher priority than the latter + * versions of the same variable */ + for (ssize_t i = static_cast(env.size()) - 1; i >= 0; i--) { + const auto val = c10::utils::get_env(env[i].c_str()); + if (!val.has_value()) { + continue; + } else if (i) { + WARN_ENV_VAR_ONCE(env[i], env[0]); + } + + try { + ret = std::stoi(val.value()); + } catch (std::exception&) { + TORCH_CHECK(false, "Invalid value for environment variable: " + env[i]); + } + } + + return ret; +} + +inline bool getCvarBool(const std::vector& env, bool def) { + bool ret = def; + + if (env.empty()) { + TORCH_CHECK(false, "No environment variables passed"); + return ret; + } + + /* parse environment variable in reverse order, so the early + * versions of a variable get higher priority than the latter + * versions of the same variable */ + for (ssize_t i = static_cast(env.size()) - 1; i >= 0; i--) { + auto val = c10::utils::get_env(env[i].c_str()); + if (!val.has_value()) { + continue; + } else if (i) { + WARN_ENV_VAR_ONCE(env[i], env[0]); + } + + for (auto& x : val.value()) { + // NOLINTNEXTLINE(*-narrowing-conversions) + x = std::tolower(x); + } + + if (val == "y" || val == "yes" || val == "1" || val == "t" || + val == "true") { + ret = true; + } else if ( + val == "n" || val == "no" || val == "0" || val == "f" || + val == "false") { + ret = false; + } else { + TORCH_CHECK(false, "Invalid value for environment variable: " + env[i]); + return ret; + } + } + + return ret; +} + +inline void assertSameSizes( + const at::IntArrayRef& sizes, + const std::vector& tensors) { + for (const auto i : c10::irange(tensors.size())) { + if (!tensors[i].sizes().equals(sizes)) { + const auto expected = toString(sizes); + const auto actual = toString(tensors[i].sizes()); + throw std::invalid_argument( + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + "mixed sizes (" + expected + " and " + actual + ")"); + } + } +} + +inline void assertSameSizeAndType(const std::vector& tensors) { + // Ensure we have at least one tensor + if (tensors.empty()) { + throw std::invalid_argument("argument is empty"); + } + + // Ensure all tensors have identical type and shape + auto options = tensors[0].options(); + auto sizes = tensors[0].sizes(); + for (const auto i : c10::irange(1, tensors.size())) { + if (!tensors[i].options().type_equal(options)) { + const auto expected = toString(options); + const auto actual = toString(tensors[i].options()); + throw std::invalid_argument( + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + "argument contains mixed types (" + expected + " and " + actual + + ")"); + } + if (!tensors[i].sizes().equals(sizes)) { + const auto expected = toString(sizes); + const auto actual = toString(tensors[i].sizes()); + throw std::invalid_argument( + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + "argument contains mixed types (" + expected + " and " + actual + + ")"); + } + } +} + +inline void assertTypeMatch( + const std::function& fn, + const at::DeprecatedTypeProperties& type, + const at::ArrayRef tensors, + size_t index) { + if (!tensors[index].options().type_equal(type.options())) { + fn("invalid tensor type at index " + std::to_string(index) + " (expected " + + type.toString() + ", got " + tensors[index].toString() + ")"); + } +} + +inline void assertTypeMatch( + const std::function& fn, + const at::TensorOptions& options, + const at::ArrayRef tensors, + size_t index) { + if (!tensors[index].options().type_equal(options)) { + fn("invalid tensor type at index " + std::to_string(index) + " (expected " + + toString(options) + ", got " + toString(tensors[index].options()) + ")"); + } +} + +inline void assertSizesMatch( + const std::function& fn, + const at::IntArrayRef& sizes, + const at::ArrayRef tensors, + size_t index) { + if (tensors[index].sizes() != sizes) { + fn("invalid tensor size at index " + std::to_string(index) + " (expected " + + toString(sizes) + ", got " + toString(tensors[index].sizes()) + ")"); + } +} + +inline void assertLayoutMatch( + const std::function& fn, + const c10::Layout& expected, + const at::ArrayRef tensors, + size_t index) { + const auto& actual = tensors[index].layout(); + if (actual != expected) { + fn("invalid tensor layout at index " + std::to_string(index) + + " (expected " + toString(expected) + ", got " + toString(actual) + ")"); + } +} + +inline void assertLayoutMatch( + const std::function& fn, + const at::ArrayRef tensors) { + const auto& layout = tensors[0].layout(); + for (const auto i : c10::irange(1, tensors.size())) { + assertLayoutMatch(fn, layout, tensors, i); + } +} + +inline void assertNonEmpty( + const std::function& fn, + const at::ArrayRef tensors) { + if (tensors.empty()) { + fn("requires non-empty tensor list"); + } +} + +inline void assertSingleElement( + const std::function& fn, + const at::ArrayRef tensors) { + if (tensors.size() != 1) { + fn("requires a single-element tensor list"); + } +} + +inline void assertSingleElementInput( + const std::function& fn, + const at::ArrayRef tensors) { + if (tensors.size() != 1) { + fn("requires a single-element input tensor list"); + } +} + +inline void assertSingleElementOutput( + const std::function& fn, + const at::ArrayRef tensors) { + if (tensors.size() != 1) { + fn("requires a single-element output tensor list"); + } +} + +inline void assertRootRank( + const std::function& fn, + int64_t rank, + int64_t size) { + if (rank < 0 || rank >= size) { + fn("invalid root rank: " + std::to_string(rank)); + } +} + +inline void assertRootTensor( + const std::function& fn, + int64_t rank, + int64_t size) { + if (rank < 0 || rank >= size) { + fn("invalid root tensor: " + std::to_string(rank)); + } +} + +inline void assertDense( + const std::function& fn, + const at::ArrayRef tensors) { + const auto& layout = tensors[0].layout(); + if (layout != at::kStrided) { + fn("only supports dense tensors"); + } +} + +inline void assertCPU( + const std::function& fn, + const at::ArrayRef tensors) { + const auto& device = tensors[0].device(); + if (device.type() != at::kCPU) { + fn("only supports CPU tensors"); + } +} + +inline void assertSameDevice( + const std::function& fn, + const at::ArrayRef tensors) { + if (tensors.size() < 2) { + return; + } + const auto& device = tensors[0].device(); + for (const auto i : c10::irange(1, tensors.size())) { + if (tensors[i].device() != device) { + fn("tensors should be on the same device"); + } + } +} + +inline void assertTypeAndSizesMatch( + const std::function& fn, + const at::ArrayRef tensors, + const at::DeprecatedTypeProperties& type, + const at::IntArrayRef& sizes) { + for (const auto i : c10::irange(tensors.size())) { + assertTypeMatch(fn, type, tensors, i); + assertSizesMatch(fn, sizes, tensors, i); + } +} + +inline void assertTypeAndSizesMatch( + const std::function& fn, + const at::ArrayRef tensors, + const at::TensorOptions& options, + const at::IntArrayRef& sizes) { + for (const auto i : c10::irange(tensors.size())) { + assertTypeMatch(fn, options, tensors, i); + assertSizesMatch(fn, sizes, tensors, i); + } +} + +inline void assertTypeAndSizesMatch( + const std::function& fn, + const at::ArrayRef tensors) { + const auto& options = tensors[0].options(); + const auto sizes = tensors[0].sizes(); + assertTypeAndSizesMatch(fn, tensors.slice(1), options, sizes); +} + +// Copied from ATen/core/functional.h. +template +inline auto fmap(T& inputs, const F& fn) + -> std::vector { + std::vector r; + r.reserve(inputs.size()); + for (auto& input : inputs) { + r.push_back(fn(input)); + } + return r; +} + +// Copied from torch/csrc/utils/tensor_flatten.h. +inline at::Tensor flattenDenseTensors(at::TensorList tensors) { + static const auto flatten = [](const at::Tensor& t) { + return t.contiguous().view({-1}); + }; + if (tensors.size() == 1) { + return flatten(tensors[0]); + } + return at::cat(::c10d::fmap(tensors, flatten)); +} + +inline at::Tensor newLikeFlat( + std::vector>& tensors, + size_t deviceIdx) { + if (tensors.empty() || tensors[0].empty()) { + TORCH_CHECK(false, "Received an empty list"); + } + if (deviceIdx >= tensors.size()) { + TORCH_CHECK(false, "Invalid device index"); + } + auto& t = tensors[deviceIdx][0]; + auto device = t.device(); + for (const auto i : c10::irange(1, tensors[deviceIdx].size())) { + if (tensors[deviceIdx][i].device() != device) { + TORCH_CHECK(false, "Expecting all tensors on the same device"); + } + } + at::DeviceGuard gpuGuard(device); + std::vector sizes{static_cast(tensors[deviceIdx].size())}; + std::vector strides{t.numel()}; + sizes.insert(sizes.end(), t.sizes().begin(), t.sizes().end()); + strides.insert(strides.end(), t.strides().begin(), t.strides().end()); + return at::empty_strided( + sizes, strides, t.options().memory_format(std::nullopt)); +} + +inline at::Tensor newLikeFlat(std::vector& tensors) { + if (tensors.empty()) { + TORCH_CHECK(false, "Received an empty list"); + } + auto& t = tensors[0]; + at::DeviceGuard gpuGuard(t.device()); + std::vector sizes{static_cast(tensors.size())}; + sizes.insert(sizes.end(), t.sizes().begin(), t.sizes().end()); + return at::empty(sizes, t.options()); +} + +inline std::vector> getSizes( + const std::vector& tensors) { + std::vector> sizes(tensors.size()); + for (const auto i : c10::irange(tensors.size())) { + sizes[i] = tensors[i].sizes().vec(); + } + return sizes; +} + +inline std::vector getDevices(const std::vector& tensors) { + std::vector devices(tensors.size(), -1); + if (tensors[0].device().is_cuda()) { + for (const auto i : c10::irange(tensors.size())) { + // NOLINTNEXTLINE(bugprone-signed-char-misuse) + devices[i] = tensors[i].storage().device().index(); + } + } + return devices; +} + +template +inline T* getDataPointer(const at::Tensor& tensor) { + // This method is only used in ProcessGroupGloo for now. Call sites must make + // sure that the input tensor is contiguous. It is OK if the tensor does not + // start from the beginning of the storage. For example, it could come from + // chunk(..., dim=0)[1]. Hence, we need to use data_ptr() instead of + // tensor.storage().data() + // NB: not using tensor.data() because tensor is not aware of gloo::TYPE + return static_cast(tensor.data_ptr()); +} + +template +std::vector getDataPointers(const std::vector& tensors) { + std::vector ptrs(tensors.size()); + for (const auto i : c10::irange(tensors.size())) { + ptrs[i] = getDataPointer(tensors[i]); + } + return ptrs; +} + +// For alltoall split size sanity check +inline void checkSplitSizes( + const std::vector& split_sizes, + const at::Tensor& tensor, + int group_size) { + if (split_sizes.empty()) { + TORCH_CHECK( + tensor.size(0) % group_size == 0, + "Tensor's dim 0 does not divide equally across group size"); + } else { + TORCH_CHECK( + split_sizes.size() == static_cast(group_size), + "Number of tensor splits not equal to group size"); + const auto sum = c10::sum_integers(split_sizes); + TORCH_CHECK( + sum == tensor.size(0), "Split sizes doesn't match total dim 0 size"); + } +} + +// Compute alltoall lengths and offsets, handling multi-dimension tensors +template +size_t computeLengthsAndOffsets( + const std::vector& split_sizes, + const at::Tensor& tensor, + std::vector* lengths, + std::vector* offsets) { + size_t group_size = lengths->size(); + bool equal_splits = false; + size_t dim0_size = tensor.size(0); + size_t row_size = (dim0_size ? tensor.numel() / dim0_size : 1); + size_t split_size = 0; + size_t offset = 0; + + if (split_sizes.empty()) { + equal_splits = true; + split_size = tensor.size(0) / group_size; + } + for (const auto i : c10::irange(group_size)) { + size_t length = row_size * (equal_splits ? split_size : split_sizes[i]); + (*lengths)[i] = length; + (*offsets)[i] = offset; + // TODO: see if we should add overflow protection for offset + offset += length; + } + return offset; +} + +template +size_t computeLengthsAndOffsets( + const std::vector& tensors, + std::vector* lengths, + std::vector* offsets) { + size_t group_size = lengths->size(); + size_t offset = 0; + for (const auto i : c10::irange(group_size)) { + size_t length = tensors[i].numel(); + (*lengths)[i] = length; + (*offsets)[i] = offset; + offset += length; + } + return offset; +} + +// Get the start and stride of the global rank from a list of global ranks +// If the global ranks do not follow the consecutive rule, the stride will be -1 +void TORCH_API getGlobalRankStartAndStride( + const std::vector& globalRanksInGroup, + int& globalRankStart, + int& globalRankStride); + +using RankType = uint32_t; +using SizeType = uint64_t; + +// `errno` is only meaningful when it fails. E.g., a successful `fork()` sets +// `errno` to `EINVAL` in child process on some macos +// (https://stackoverflow.com/a/20295079), and thus `errno` should really only +// be inspected if an error occurred. +// +// `success_cond` is an expression used to check if an error has happened. So +// for `fork()`, we can use `SYSCHECK(pid = fork(), pid != -1)`. The function +// output is stored in variable `__output` and may be used in `success_cond`. +#ifdef _WIN32 +#define SYSCHECK(expr, success_cond) \ + while (true) { \ + auto __output = (expr); \ + auto errno_local = WSAGetLastError(); \ + (void)__output; \ + if (!(success_cond)) { \ + if (errno == EINTR) { \ + continue; \ + } else if ( \ + errno_local == WSAETIMEDOUT || errno_local == WSAEWOULDBLOCK) { \ + C10_THROW_ERROR(DistNetworkError, "Socket Timeout"); \ + } else { \ + C10_THROW_ERROR(DistNetworkError, c10::utils::str_error(errno_local)); \ + } \ + } else { \ + break; \ + } \ + } +#else +#define SYSCHECK(expr, success_cond) \ + while (true) { \ + auto __output = (expr); \ + (void)__output; \ + if (!(success_cond)) { \ + if (errno == EINTR) { \ + continue; \ + } else if (errno == EAGAIN || errno == EWOULDBLOCK) { \ + C10_THROW_ERROR(DistNetworkError, "Socket Timeout"); \ + } else { \ + C10_THROW_ERROR(DistNetworkError, c10::utils::str_error(errno)); \ + } \ + } else { \ + break; \ + } \ + } +#endif + +// Most functions indicate error by returning `-1`. This is a helper macro for +// this common case with `SYSCHECK`. +// Since SOCKET_ERROR = -1 in MSVC, so also leverage SYSCHECK_ERR_RETURN_NEG1 +#define SYSCHECK_ERR_RETURN_NEG1(expr) SYSCHECK(expr, __output != -1) + +namespace tcputil { + +// Send and receive +template +void sendBytes( + int socket, + const T* buffer, + size_t length, + bool moreData = false) { + size_t bytesToSend = sizeof(T) * length; + if (bytesToSend == 0) { + return; + } + + auto currentBytes = reinterpret_cast(buffer); + + int flags = 0; + +#ifdef MSG_MORE + if (moreData) { // there is more data to send + flags |= MSG_MORE; + } +#endif + +// Ignore SIGPIPE as the send() return value is always checked for error +#ifdef MSG_NOSIGNAL + flags |= MSG_NOSIGNAL; +#endif + + while (bytesToSend > 0) { + ssize_t bytesSent = 0; + SYSCHECK_ERR_RETURN_NEG1( + bytesSent = ::send(socket, currentBytes, bytesToSend, flags)) + if (bytesSent == 0) { + C10_THROW_ERROR( + DistNetworkError, + "Failed to send, sent 0 bytes. " + "Connection was likely closed. " + "Did the remote server shutdown or crash?"); + } + + bytesToSend -= bytesSent; + currentBytes += bytesSent; + } +} + +template +void recvBytes(int socket, T* buffer, size_t length) { + size_t bytesToReceive = sizeof(T) * length; + if (bytesToReceive == 0) { + return; + } + + auto currentBytes = reinterpret_cast(buffer); + + while (bytesToReceive > 0) { + ssize_t bytesReceived = 0; + SYSCHECK_ERR_RETURN_NEG1( + bytesReceived = recv(socket, currentBytes, bytesToReceive, 0)) + if (bytesReceived == 0) { + C10_THROW_ERROR( + DistNetworkError, + "Failed to recv, got 0 bytes. " + "Connection was likely closed. " + "Did the remote server shutdown or crash?"); + } + + bytesToReceive -= bytesReceived; + currentBytes += bytesReceived; + } +} + +// send a vector's length and data +template +void sendVector(int socket, const std::vector& vec, bool moreData = false) { + SizeType size = vec.size(); + sendBytes(socket, &size, 1, true); + sendBytes(socket, vec.data(), size, moreData); +} + +// receive a vector as sent in sendVector +template +std::vector recvVector(int socket) { + SizeType valueSize = 0; + recvBytes(socket, &valueSize, 1); + std::vector value(valueSize); + recvBytes(socket, value.data(), value.size()); + return value; +} + +// this is only for convenience when sending rvalues +template +void sendValue(int socket, const T& value, bool moreData = false) { + sendBytes(socket, &value, 1, moreData); +} + +template +T recvValue(int socket) { + T value; + recvBytes(socket, &value, 1); + return value; +} + +// send a string's length and data +inline void sendString( + int socket, + const std::string& str, + bool moreData = false) { + SizeType size = str.size(); + sendBytes(socket, &size, 1, true); + sendBytes(socket, str.data(), size, moreData); +} + +// receive a string as sent in sendString +inline std::string recvString(int socket) { + SizeType valueSize = 0; + recvBytes(socket, &valueSize, 1); + std::vector value(valueSize); + recvBytes(socket, value.data(), value.size()); + return std::string(value.data(), value.size()); +} + +} // namespace tcputil +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4e94641b9b8ed2ce362b092398a6af0243aa4a81 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace c10d::tcputil { + +#define CONNECT_SOCKET_OFFSET 1 + +inline int poll(struct pollfd* fdArray, unsigned long fds, int timeout) { + return WSAPoll(fdArray, fds, timeout); +} + +inline void addPollfd( + std::vector& fds, + int socket, + short events) { + fds.push_back({(SOCKET)socket, events}); +} + +inline struct ::pollfd getPollfd(int socket, short events) { + struct ::pollfd res = {(SOCKET)socket, events}; + return res; +} + +} // namespace c10d::tcputil + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a109527dd40efdc364cc899e96d482dea336b262 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp @@ -0,0 +1,190 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +constexpr auto kNoTimeout = std::chrono::milliseconds(0); + +namespace c10d { + +constexpr const char* const kSeqNumStoreKey = "SEQ_NUM_STORE_KEY"; + +enum class OpType : std::uint8_t { + BROADCAST = 0, + ALLREDUCE = 1, + ALLREDUCE_COALESCED = 2, + REDUCE = 3, + ALLGATHER = 4, + _ALLGATHER_BASE = 5, + ALLGATHER_COALESCED = 6, + GATHER = 7, + SCATTER = 8, + REDUCE_SCATTER = 9, + ALLTOALL_BASE = 10, + ALLTOALL = 11, + SEND = 12, + RECV = 13, + RECVANYSOURCE = 14, + BARRIER = 15, + _REDUCE_SCATTER_BASE = 16, + COALESCED = 17, + _ALLREDUCE_SPARSE = 18, + UNKNOWN = 100, +}; + +// TODO: support different types of failures/errors +enum class WorkResult : std::uint8_t { + SUCCESS = 0, + TIMEOUT = 1, + COMM_ERROR = 2, + UNKNOWN = 100, +}; + +// Converts OpType to human readable string. +TORCH_API std::string opTypeToString(OpType opType); + +// Whether or not an OP is an p2p op (SEND, RECV, RECVANYSOURCE) +TORCH_API bool isP2POp(OpType opType, bool batchP2P = false); + +// Please do not use Work API, it is going away, to be +// replaced by ivalue::Future. +// Python binding for this class might change, please do not assume +// this will be bound using pybind. +class TORCH_API Work : public torch::CustomClassHolder { + public: + Work( + int rank = -1, + OpType opType = OpType::UNKNOWN, + const char* profilingTitle = nullptr, + const std::optional>& inputTensors = + std::nullopt); + + ~Work() override; + + // Checks if request has completed. Non-blocking operation. + virtual bool isCompleted(); + + // Returns if the work completed successfully. + // If false, the exception function can be called to get details. + virtual bool isSuccess() const; + + // Returns exception if isSuccess() returned false. + virtual std::exception_ptr exception() const; + + // Returns source rank if this objects represents a recv-from-any. + virtual int sourceRank() const; + + // Returns result tensors, if applicable. + // If work is not supposed to have result, we return empty list. + virtual std::vector result(); + + // Ensures that operations on the output tensors that are invoked + // after this function returns are correctly sequenced after the + // asynchronous completion of this work. + // + // For CUDA tensors, it inserts stream synchronization such that + // the streams of the caller wait for completion of the + // asynchronous operations on the destination tensors. + // + // For CPU tensors, it is currently a nop. + // + // This function should only be used if the caller polls for + // completion through the `isCompleted` function, it has returned + // true, and the `isSuccess` function also has returned true. + // + virtual void synchronize(); + + // Waits until request completes. Blocking operation. + // Throws if the work completed with an exception. + // Returns false if the work is aborted. + // Otherwise, it always returns true, indicating the work is completed. + // + // Functionally equivalent to: + // + // while (!isCompleted()) { /* nop */ } + // auto success = isSuccess(); + // if (!success) { std::rethrow_exception(exception()); } + // return success; + // + virtual bool wait(std::chrono::milliseconds timeout = kNoTimeout); + + // Blocks the current stream until the work is completed. + // This is equivalent to synchronize for CUDA tensors but works for both CPU + // tensors and CUDA tensors by using a spinlock CUDA kernel. + // This will immediately return. + // If no stream is active it will throw an error. + virtual void blockCurrentStream(); + + virtual void abort(); + + // Returns a Future object that will be associated with the completion of + // work. Only NCCL backend is currently supported. + virtual c10::intrusive_ptr getFuture(); + + // Get a Future object that would be marked as either success or failure + // This API can be used by the user to track the completion of the work + // and handle the exception if any. + virtual c10::intrusive_ptr getFutureResult(); + + virtual float getDuration() const; + + virtual uint64_t getSequencenumber() const; + + OpType retrieveOpType() const; + + static c10::intrusive_ptr create_from_future( + const c10::intrusive_ptr& /*future*/); + + protected: + // Completes the work object and optionally sets the exception in a + // thread-safe manner. Notifies all waiting condition variables as well. + void finish(std::exception_ptr exception = nullptr); + + // Similar to finish, but throws an exception if one is already set or + // provided by the user. + void finishAndThrow(std::exception_ptr exception); + + mutable std::mutex mutex_; + std::condition_variable cv_; + bool completed_ = false; + std::exception_ptr exception_; + + // Current rank of the node. + const int rank_; + + // Operation type that this work object refers to. + OpType opType_; + + // When profiling, the callback to record end of operation event. This + // callback needs to be called when collective operation is complete. + std::function recordFunctionEndCallback_; +}; + +struct TORCH_API WorkInfo { + WorkInfo( + const OpType& opType, + const uint64_t seq, + const std::chrono::time_point& timeStarted, + const std::chrono::time_point& timeFinished, + const std::chrono::duration& activeDuration) + : opType(opType), + seq(seq), + timeStarted(timeStarted), + timeFinished(timeFinished), + activeDuration(activeDuration) {} + + OpType opType; + uint64_t seq; + std::chrono::time_point timeStarted; + std::chrono::time_point timeFinished; + std::chrono::duration activeDuration; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h new file mode 100644 index 0000000000000000000000000000000000000000..45daf59b55ab849b2e72bdf275a6c09315413ef0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::c10d { + +PyMethodDef* python_functions(); + +} // namespace torch::distributed::c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e5099eb2980e5d3f38ab7aa723f5f92880b73d91 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp @@ -0,0 +1,147 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace c10d { + +// Broadcast many tensors to all processes in the process group. +TORCH_API void broadcast_coalesced( + const c10::intrusive_ptr& process_group, + at::TensorList tensors, + size_t buffer_size, + int rank = 0); + +// This class passes bucket contents tensor to DDP communication hook. +class TORCH_API GradBucket { + public: + explicit GradBucket( + size_t index, + size_t bucket_count, + at::Tensor tensor, + std::vector offsets, + std::vector lengths, + std::vector sizes_vec, + std::vector parameters, + std::optional sparse_grad_indices) + : index_(index), + bucket_count_(bucket_count), + buffer_(std::move(tensor)), + offsets_(std::move(offsets)), + lengths_(std::move(lengths)), + sizes_vec_(std::move(sizes_vec)), + parameters_(std::move(parameters)), + sparse_grad_indices_(std::move(sparse_grad_indices)) {} + + // Returns the index of the bucket, which is unique across all the buckets. + size_t getIndex() const { + return index_; + } + + const at::Tensor& getBuffer() const { + return buffer_; + } + + // Returns a mutable buffer compared with the above method. + at::Tensor& getBufferRef() { + return buffer_; + } + + // Overwrites the buffer at a specific index. + void setBuffer(at::Tensor& buffer) { + buffer_ = buffer; + } + + // Each tensor in the list that getGradients corresponds to a + // parameter. + std::vector getGradients() const; + + // Returns model parameters belonging to this bucket. They are returned in the + // same order as gradient tensors via getGradients(). For example, + // getParameters[i] will have its gradient stored in + // getGradients[i] + const std::vector getParameters() const { + return parameters_; + } + + // Returns whether this bucket is the last bucket to allreduce in an + // iteration. + bool isLast() const { + return index_ == bucket_count_ - 1; + } + + std::optional& getSparseGradIndices() { + return sparse_grad_indices_; + } + + private: + size_t index_; + size_t bucket_count_; + at::Tensor buffer_; + + // Per-variable info in buffer_. + std::vector offsets_; + std::vector lengths_; + std::vector sizes_vec_; + + // Model parameters for this bucket. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::vector parameters_; + + // Predefined sparse indices for this bucket (only used for sparse tensors). + // The gradients will be updated to have indices with these tensor values + std::optional sparse_grad_indices_; +}; + +// Base class of both `PythonCommHook` and `CppCommHook`. +// Requires implementing 1) `runHook` method that communicates gradients +// asynchronously, and 2) `parseHookResult` method that converts the hook +// result into a tensor. +class TORCH_API CommHookInterface { + public: + virtual ~CommHookInterface() = default; + + // Passes the input grad bucket to the registered communication hook. + // Once the tensor in the bucket are ready, kicks off the hook asynchronously + // and returns a future that holds the communication results. + virtual c10::intrusive_ptr runHook( + GradBucket& bucket) = 0; + + // Returns the resulting tensor once the communication hook result is + // ready. The resulting tensor will then be copied to the grads of + // individual parameters. + virtual at::Tensor parseHookResult(const c10::IValue& result) = 0; +}; + +namespace detail { +// This helper function is called both by CppCommHookInterface below and inside +// reducer. +TORCH_API at::Tensor parseCppCommHookResult(const c10::IValue& result); +} // namespace detail + +// This CppCommHook interface only requires implementing runHook method that +// potentially uses a state. +template +class CppCommHookInterface : public CommHookInterface { + public: + explicit CppCommHookInterface(T state) : state_(std::move(state)) {} + + ~CppCommHookInterface() override = default; + + at::Tensor parseHookResult(const c10::IValue& result) override { + return detail::parseCppCommHookResult(result); + } + + protected: + T state_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_collectives/ControlCollectives.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_collectives/ControlCollectives.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5beaa289331f4c3b81d3a279dddb8a3be6b51b38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_collectives/ControlCollectives.hpp @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace c10d { + +using namespace std::chrono_literals; + +class TORCH_API ControlCollectives : public torch::CustomClassHolder { + public: + virtual void barrier( + const std::string& key, + std::chrono::milliseconds timeout = 5min, + bool block = true) = 0; + + virtual void broadcastSend( + const std::string& key, + const std::vector& data, + std::chrono::milliseconds timeout = 5min) = 0; + virtual std::vector broadcastRecv( + const std::string& key, + std::chrono::milliseconds timeout = 5min) = 0; + + virtual void gatherSend( + const std::string& key, + const std::vector& data, + std::chrono::milliseconds timeout = 5min) = 0; + virtual std::vector> gatherRecv( + const std::string& key, + const std::vector& data, + std::chrono::milliseconds timeout = 5min) = 0; + + virtual std::vector scatterSend( + const std::string& key, + const std::vector>& data, + std::chrono::milliseconds timeout = 5min) = 0; + virtual std::vector scatterRecv( + const std::string& key, + std::chrono::milliseconds timeout = 5min) = 0; + + virtual std::vector> allGather( + const std::string& key, + const std::vector& data, + std::chrono::milliseconds timeout = 5min) = 0; + + virtual int64_t allSum( + const std::string& key, + int64_t data, + std::chrono::milliseconds timeout = 5min) = 0; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_collectives/StoreCollectives.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_collectives/StoreCollectives.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5782eb49f5755c1f2270428dd171260ad1d28a02 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_collectives/StoreCollectives.hpp @@ -0,0 +1,73 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace c10d { + +class TORCH_API StoreCollectives : public ControlCollectives { + public: + explicit StoreCollectives( + c10::intrusive_ptr store, + int rank, + int worldSize); + + void barrier( + const std::string& key, + std::chrono::milliseconds timeout = 5min, + bool block = true) override; + + void broadcastSend( + const std::string& key, + const std::vector& data, + std::chrono::milliseconds timeout = 5min) override; + std::vector broadcastRecv( + const std::string& key, + std::chrono::milliseconds timeout = 5min) override; + + void gatherSend( + const std::string& key, + const std::vector& data, + std::chrono::milliseconds timeout = 5min) override; + std::vector> gatherRecv( + const std::string& key, + const std::vector& data, + std::chrono::milliseconds timeout = 5min) override; + + std::vector scatterSend( + const std::string& key, + const std::vector>& data, + std::chrono::milliseconds timeout = 5min) override; + std::vector scatterRecv( + const std::string& key, + std::chrono::milliseconds timeout = 5min) override; + + std::vector> allGather( + const std::string& key, + const std::vector& data, + std::chrono::milliseconds timeout = 5min) override; + + int64_t allSum( + const std::string& key, + int64_t data, + std::chrono::milliseconds timeout = 5min) override; + + private: + void enforceUnique(const std::string& key); + + private: + c10::intrusive_ptr store_; + int rank_; + int worldSize_; + + c10::FastSet seenKeys_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/Handlers.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/Handlers.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bf79294f23d5515edbe5c98dc20b6b1ae16fdb5a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/Handlers.hpp @@ -0,0 +1,82 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace c10d::control_plane { + +// Request represents a request to the handler. This conceptually maps to an +// HTTP request but could be called via other transports. +class TORCH_API Request { + public: + virtual ~Request() = default; + + virtual const std::string& body() const = 0; + + virtual const std::multimap& params() const = 0; + + std::string getParam(const std::string& key) const { + auto it = params().find(key); + if (it != params().end()) { + return it->second; + } + return ""; + } +}; + +// Response represents a response to the handler. This conceptually maps to an +// HTTP response but could be called via other transports. +class TORCH_API Response { + public: + virtual ~Response() = default; + + // Set the response body to the provided string. + // TODO: add support for chunked responses + virtual void setContent( + std::string&& content, + const std::string& content_type) = 0; + + // Set the response status code. + // These should match standard HTTP status codes. + virtual void setStatus(int status) = 0; +}; + +using HandlerFunc = std::function; + +// Registers a handler. The name needs to be unique and can be called by using +// getHandler directly or via WorkerServer for remote requests. +// These handlers are called from a background C++ thread concurrently with the +// main thread. These handlers need to be thread safe and not cause issues +// during Python training. +TORCH_API void registerHandler(const std::string& name, HandlerFunc f); + +// Fetches a handler by name. +TORCH_API HandlerFunc getHandler(const std::string& name); + +TORCH_API std::vector getHandlerNames(); + +// Registers a handler statically. +// See registerHandler for more details. +class TORCH_API RegisterHandler { + public: + RegisterHandler(const std::string& name, HandlerFunc f) { + registerHandler(name, std::move(f)); + } + + // disable move, copy + RegisterHandler(const RegisterHandler&) = delete; + RegisterHandler(RegisterHandler&&) = delete; + RegisterHandler& operator=(const RegisterHandler&) = delete; + RegisterHandler& operator=(RegisterHandler&&) = delete; +}; + +} // namespace c10d::control_plane + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/WaitCounterHandler.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/WaitCounterHandler.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b6e73ec065fe5b1b094f4fabd97ad887a9b94b68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/WaitCounterHandler.hpp @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace c10d { +namespace control_plane { + +// Returns all wait counter values as a JSON string +std::string getWaitCounterValuesJson(); + +// Ensures the wait counter backend is registered +void ensureWaitCounterBackendRegistered(); + +} // namespace control_plane +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/WorkerServer.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/WorkerServer.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9ffaa77726734d694015d8900ae759b762deff6b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/WorkerServer.hpp @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wdeprecated-literal-operator") +#include +C10_DIAGNOSTIC_POP() + +namespace c10d::control_plane { + +class TORCH_API WorkerServer : public c10::intrusive_ptr_target { + public: + WorkerServer(const std::string& hostOrFile, int port = -1); + ~WorkerServer() override; + + void shutdown(); + + int port() { + return port_; + } + + private: + httplib::Server server_; + std::thread serverThread_; + int port_; +}; + +} // namespace c10d::control_plane + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/CUDAEventCache.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/CUDAEventCache.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e289e3d0aff7561ab197ce8c3e18ccf33d2c9ff9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/CUDAEventCache.hpp @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace c10d { + +class TORCH_API CUDAEventCache + : public std::enable_shared_from_this { + public: + CUDAEventCache(); + std::shared_ptr create(bool timing); + static std::shared_ptr get(at::DeviceIndex device); + + private: + std::mutex cacheMutex_; + // NOTE: We intentionally store raw pointers so that + // we do not attempt to destroy the event objects on process exit, + // because cuda may be gone. + std::array, 2> + eventsArray_; // 0 for timing=false, 1 for timing=true +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/StreamBlock.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/StreamBlock.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8195a6faa33d4f86c771ff08b254022e43b3cacd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/StreamBlock.hpp @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace c10d::cuda { + +enum StreamBlockStatus : int32_t { + UNKNOWN = 0, + RUNNING = 1, + TIMED_OUT = 2, + ABORTED = 3, +}; + +/* +StreamBlock implements a baton that will block a the active CUDA stream +until aborted by the main process. +*/ +class TORCH_API StreamBlock { + public: + virtual ~StreamBlock() = default; + virtual void abort() = 0; + virtual StreamBlockStatus status() = 0; +}; + +std::unique_ptr block_stream(std::chrono::milliseconds timeout); + +// Declare a registry so we can call the CUDA StreamBlock API from CPU only code +// (i.e. ProcessGroup/Work objects in libtorch_cpu). +// The implementation lives defined in StreamBlock.cu. +TORCH_DECLARE_REGISTRY( + StreamBlockRegistry, + StreamBlock, + std::chrono::milliseconds); + +} // namespace c10d::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/utils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/utils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d8a2520f4fd00d62e506f65e8645c1b035fee2c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/utils.hpp @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// This file contains utility functions common for CUDA, which can be used by +// ProcessGroupNCCL or SymmetricMemory. + +namespace c10d::cuda { + +bool deviceSupportsMulticast(int device_idx); + +} // namespace c10d::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/debug.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..cf343d0eef5a8b1a06ab96d0fbf0a19aaa61f87f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/debug.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and its 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 + +namespace c10d { + +enum class DebugLevel { Off = 0, Info = 1, Detail = 2 }; + +TORCH_API void setDebugLevel(DebugLevel level); + +// Sets the debug level based on the value of the `TORCH_DISTRIBUTED_DEBUG` +// environment variable. +TORCH_API void setDebugLevelFromEnvironment(); + +TORCH_API DebugLevel debug_level() noexcept; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/default_comm_hooks.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/default_comm_hooks.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c56d6097a4d48dfe170ebab6b5e49d7f8504e83e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/default_comm_hooks.hpp @@ -0,0 +1,57 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace c10d { + +enum class BuiltinCommHookType : uint8_t { + ALLREDUCE = 1, + FP16_COMPRESS = 2, +}; + +class AllReduceCommHook + : public CppCommHookInterface> { + public: + explicit AllReduceCommHook(const c10::intrusive_ptr& state) + : CppCommHookInterface>(state) {} + + ~AllReduceCommHook() override = default; + + c10::intrusive_ptr runHook(GradBucket& bucket) override; +}; + +class FP16CompressCommHook + : public CppCommHookInterface> { + public: + explicit FP16CompressCommHook(const c10::intrusive_ptr& state) + : CppCommHookInterface>(state) {} + + ~FP16CompressCommHook() override = default; + + c10::intrusive_ptr runHook(GradBucket& bucket) override; +}; + +// Almost same as AllReduceCommHook, but without division inside the hook. +// This enables the optimization of fusing copy and division and saves one scan +// over all the input parameters, when no communication hook is provided by the +// user. Only used internally and not released as a public built-in +// communication hook. +class _AllReduceBySumCommHook + : public CppCommHookInterface> { + public: + explicit _AllReduceBySumCommHook( + const c10::intrusive_ptr& state) + : CppCommHookInterface>(state) {} + + ~_AllReduceBySumCommHook() override = default; + + c10::intrusive_ptr runHook(GradBucket& bucket) override; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/error.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/error.h new file mode 100644 index 0000000000000000000000000000000000000000..e4e1a3e2d2be49904528720168ffc383b4332f9e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/error.h @@ -0,0 +1,58 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Facebook, Inc. and its 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 + +namespace fmt { + +template <> +struct formatter { + constexpr auto parse(format_parse_context& ctx) const { + return ctx.begin(); + } + + template + auto format(const std::error_category& cat, FormatContext& ctx) const { + if (std::strcmp(cat.name(), "generic") == 0) { + return fmt::format_to(ctx.out(), "errno"); + } else { + return fmt::format_to(ctx.out(), "{} error", cat.name()); + } + } +}; + +template <> +struct formatter { + constexpr auto parse(format_parse_context& ctx) const { + return ctx.begin(); + } + + template + auto format(const std::error_code& err, FormatContext& ctx) const { + return fmt::format_to( + ctx.out(), "({}: {} - {})", err.category(), err.value(), err.message()); + } +}; + +} // namespace fmt + +namespace c10d::detail { + +inline std::error_code lastError() noexcept { + return std::error_code{errno, std::generic_category()}; +} + +} // namespace c10d::detail + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h new file mode 100644 index 0000000000000000000000000000000000000000..b5e5c995331893cfd6f1f5a5666deeb2dd316bd3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Facebook, Inc. and its 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 + +// Utility macro similar to C10_THROW_ERROR, the major difference is that this +// macro handles exception types defined in the c10d namespace, whereas +// C10_THROW_ERROR requires an exception to be defined in the c10 namespace. +#define C10D_THROW_ERROR(err_type, ...) \ + throw ::c10d::err_type( \ + {__func__, __FILE__, static_cast(__LINE__)}, \ + c10::str(__VA_ARGS__)) + +#define C10D_CHECK_WITH(error_t, cond, ...) \ + if (C10_UNLIKELY_OR_CONST(!(cond))) { \ + C10D_THROW_ERROR( \ + error_t, TORCH_CHECK_MSG(cond, "", c10::str(__VA_ARGS__))); \ + } + +namespace c10d { + +using c10::DistNetworkError; +using c10::DistStoreError; + +class TORCH_API SocketError : public DistNetworkError { + using DistNetworkError::DistNetworkError; +}; + +class TORCH_API TimeoutError : public DistNetworkError { + using DistNetworkError::DistNetworkError; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/logger.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/logger.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9cb5cf16044d0e6fc6b6a8fdd8774a17c7cfcaf4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/logger.hpp @@ -0,0 +1,176 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace c10d { + +// A struct to hold the latest status of the process group. +struct ProcessGroupStatus { + // the sequential number of the last collective enqueued into workMetaList_ + // This is useful for identifying a rank that has not join a collective + // initialized to be -1 to indicate no collective has been enqueued + int64_t lastEnqueuedSeq{-1}; + // the sequential number of the last collective started as the kernel + int64_t lastStartedSeq{-1}; + // the sequential number of the last collective completed marked by + // the watchdog thread + // initialized to be -1 to indicate no collective has been completed + int64_t lastCompletedSeq{-1}; + + // the name of the last collective enqueued into workMetaList_ + std::string lastEnqueuedWorkName; + // the name of the last collective started as the kernel + std::string lastStartedWorkName; + // the name of the last collective completed + std::string lastCompletedWorkName; + + // the sizes of the last work enqueued + size_t lastEnqueuedNumelIn; + size_t lastEnqueuedNumelOut; + // the sizes of the last work completed + size_t lastCompletedNumelIn; + size_t lastCompletedNumelOut; + // the sizes of the last work started + size_t lastStartedNumelIn; + size_t lastStartedNumelOut; +}; + +class TORCH_API Logger { + public: + explicit Logger(std::shared_ptr reducer); + // Set logging data that can be got during DistributedDataParallel + // construction time. + void set_construction_data_and_log( + const std::string& module_name, + const std::vector& device_ids, + int output_device, + bool broadcast_buffers, + bool has_sync_bn, + bool static_graph); + + void set_static_graph(); + + // An interface for users to get DDPLoggingData and log them + // in the applications. Explanation of logging fields are in + // "struct DDPLoggingData" of "torch/c10/util/Logging.h". + at::DDPLoggingData get_ddp_logging_data(); + + // Stream insertion operator for logging data to stream under + // TORCH_DISTRIBUTED_DEBUG. + friend std::ostream& operator<<(std::ostream& output, const Logger& logger); + + ~Logger() noexcept(false) { + // Log if DDP graph is static in Logger dtor instead of Reducer dtor since + // Logger is deleted before Reducer. + log_if_graph_static(reducer_->ddp_graph_static()); + } + + // Set environment variables. + void set_env_variables(); + // Set parameters stats. + void set_parameter_stats(); + // Get size of each bucket (Bytes). + std::vector get_bucket_sizes(); + // Get variable indices for each bucket. + std::vector> get_per_bucket_variable_indices(); + // Set comm. hook, if used + void set_comm_hook(const std::string& hook); + // Set running with uneven input detection (model.join() context manager) + void set_uneven_input_join(); + + // Reset performance stats at current iteration + void reset_performance_stats(); + + // Calculate avg stats using cpu timer and gpu timer + // that has been recorded in reducer. + void calculate_avg_time( + int64_t& avg_time, + int64_t& time_duration, + Timer& timer, + Timer::Event start_event, + Timer::Event end_event); + + // Set the absolute time of the event that has been recorded in reducer. + void set_event_time(int64_t& event_time, Timer& timer, Timer::Event event); + // Set stats that can be collected only during + // training loop. It is called at the beginning of forward call + // to record the run time stats of sampled iterations that previously ran. + // GPU performance stats are collected only for single process + // single device program and single device module right now. + // TODO to support single process multiple devices and multi device modules, + // events need to be created and recorded on multiple devices. + void set_runtime_stats_and_log(); + + // Called when DDP/reducer is failing with an error. The + // logging data structure will have two fields filled: "has_error" indicating + // that this iteration encountered an error and other fields are not valid, + // and "error", a string which contains the error message that DDP failed + // with. + template + void set_error_and_log(const std::string& ddp_error, const Args&... args) { + ddp_logging_data_->ints_map["has_error"] = 1; + auto err = c10::str(ddp_error, args...); + ddp_logging_data_->strs_map["error"] = err; + // Report the iteration we are erroring at so user knows how many examples + // successfully processed before this error was hit. + ddp_logging_data_->ints_map["iteration"] = reducer_->num_iterations_; + at::LogPyTorchDDPUsage(*ddp_logging_data_); + } + + // When running without static graph, called when reducer is destroyed to log + // if graph was actually static and is a candidate for static graph + // optimization. + void log_if_graph_static(bool is_static); + + private: + // ddp_logging_data_ is used to hold all the ddp related logging + // data fields. + std::unique_ptr ddp_logging_data_; + std::shared_ptr reducer_; + // track the number of iterations when runtime stats are collected so far. + long num_iterations_stats_recorded_ = 0; +}; + +// a generic logging data struct that holds different types of logging data. +// starting with key value pairs of strings and integers, +// It can be extended to more types as needed. +struct C10dLoggingData { + // logging fields that are string types. + std::map strings; + // logging fields that are int64_t types. + std::map integers; +}; + +class TORCH_API C10dLogger { + public: + C10dLogger(const C10dLogger&) = default; + C10dLogger(C10dLogger&&) = delete; + C10dLogger& operator=(const C10dLogger&) = default; + C10dLogger& operator=(C10dLogger&&) = delete; + virtual ~C10dLogger() = default; + virtual void log(const C10dLoggingData& data); + static C10dLogger* getLogger(); + static void registerLogger(std::unique_ptr /*logger*/); + + protected: + // singletion, hide constructor from the public + C10dLogger(std::string logDestination) + : logDestination_(std::move(logDestination)) {} + + // the name of the destination this logger should log to + std::string logDestination_; + + private: + static std::unique_ptr logger_; + static std::atomic registered_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/logging.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/logging.h new file mode 100644 index 0000000000000000000000000000000000000000..596e4686212800c6ac419ac9fd77519d90257160 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/logging.h @@ -0,0 +1,52 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and its 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 + +namespace c10d::detail { + +enum class LogLevel { Trace, Debug, Info, Warning, Error }; + +TORCH_API bool isLogLevelEnabled(LogLevel level) noexcept; + +template +// NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) +std::string formatLogMessage(fmt::string_view fmt, T&&... args) { + return fmt::vformat(fmt, fmt::make_format_args(args...)); +} + +} // namespace c10d::detail + +#define C10D_ERROR(...) \ + if (c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Error)) \ + LOG(ERROR) << "[c10d] " << c10d::detail::formatLogMessage(__VA_ARGS__) + +#define C10D_WARNING(...) \ + if (c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Warning)) \ + LOG(WARNING) << "[c10d] " << c10d::detail::formatLogMessage(__VA_ARGS__) + +#define C10D_INFO(...) \ + if (c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Info)) \ + LOG(INFO) << "[c10d] " << c10d::detail::formatLogMessage(__VA_ARGS__) + +#define C10D_DEBUG(...) \ + if (c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Debug)) \ + LOG(INFO) << "[c10d - debug] " << c10d::detail::formatLogMessage(__VA_ARGS__) + +#define C10D_TRACE(...) \ + if (c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Trace)) \ + LOG(INFO) << "[c10d - trace] " << c10d::detail::formatLogMessage(__VA_ARGS__) + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/python_callback_work.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/python_callback_work.hpp new file mode 100644 index 0000000000000000000000000000000000000000..27c25dc8235c65258a8fa05d88eca27ceb87416a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/python_callback_work.hpp @@ -0,0 +1,33 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace c10d { + +// PythonCallbackWork is a subclass of Work that wraps a Python callback +// function that implements wait(). This allows asynchronous work to +// be integrated with Python code, enabling custom completion logic or +// post-processing in Python. +class PythonCallbackWork : public Work { + public: + explicit PythonCallbackWork(py::function callback); + + ~PythonCallbackWork() override; + + bool wait(std::chrono::milliseconds timeout) override; + + c10::intrusive_ptr getFuture() override; + + private: + py::function callback_; + c10::intrusive_ptr future_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/python_comm_hook.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/python_comm_hook.h new file mode 100644 index 0000000000000000000000000000000000000000..e6e985f87ced478c67147c8405303e682aac7403 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/python_comm_hook.h @@ -0,0 +1,39 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include + +namespace c10d { + +class TORCH_PYTHON_API PythonCommHook : public CommHookInterface { + public: + // Takes a state and a callable hook. The inputs are Python objects. + // The state is passed to the hook in runHook method, and it can be used to + // maintain and update any state information during the execution of the hook. + // The hook performs user-specified processing and returns a future indicating + // asynchronous communication of gradients. + PythonCommHook(py::object state, py::object hook) + : state_(std::move(state)), hook_(std::move(hook)) {} + + ~PythonCommHook() override; + + c10::intrusive_ptr runHook(GradBucket& bucket) override; + + at::Tensor parseHookResult(const c10::IValue& result) override; + + private: + // Only needed for stateful communication. + py::object state_; + py::object hook_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization.h new file mode 100644 index 0000000000000000000000000000000000000000..08e8f2948af7ec89093fb8c7701bf7e2fe21a696 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// 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 + +namespace torch::distributed::c10d::quantization { + +at::Tensor _float_to_bfloat16_cpu(const at::Tensor& input); +at::Tensor _bfloat16_to_float_cpu(const at::Tensor& input); + +} // namespace torch::distributed::c10d::quantization + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization_gpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization_gpu.h new file mode 100644 index 0000000000000000000000000000000000000000..9c21a8f5a07cfab89ce47f08d201abb1f7e1bb32 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization_gpu.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// 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 + +namespace torch::distributed::c10d::quantization { + +at::Tensor _float_to_bfloat16_cuda(const at::Tensor& input); +at::Tensor _bfloat16_to_float_cuda(const at::Tensor& input); + +} // namespace torch::distributed::c10d::quantization + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a2a6a171ba92a0741a7cc6f1990987917ff1b657 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization_utils.h @@ -0,0 +1,39 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// 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 + +inline std::string torch_tensor_device_name(const at::Tensor& ten) { + return c10::DeviceTypeName(ten.device().type()); +} + +#define TENSOR_NDIM_EQUALS(ten, dims) \ + TORCH_CHECK( \ + (ten).ndimension() == (dims), \ + "Tensor '" #ten "' must have " #dims \ + " dimension(s). " \ + "Found ", \ + (ten).ndimension()) + +#define TENSOR_ON_CPU(x) \ + TORCH_CHECK( \ + !x.is_cuda(), \ + #x " must be a CPU tensor; it is currently on device ", \ + torch_tensor_device_name(x)) + +#define TENSOR_ON_CUDA_GPU(x) \ + TORCH_CHECK( \ + x.is_cuda(), \ + #x " must be a CUDA tensor; it is currently on device ", \ + torch_tensor_device_name(x)) + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/reducer.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/reducer.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a8a5b08a4d2166a883ff047149a35abe0840a118 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/reducer.hpp @@ -0,0 +1,607 @@ +#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 +#ifndef _WIN32 +#include +#endif + +namespace c10d { + +constexpr int kDefaultFirstBucketBytes = 1024 * 1024; +constexpr int kDefaultBucketBytesCap = 25 * 1024 * 1024; +// Collect runtime stats once for every kDDPRuntimeLoggingSampleRate iterations. +constexpr int kDDPRuntimeLoggingSampleRate = 100; + +// Forward declaration +class Logger; + +// Local accumulator type for a single bucket. +struct BucketAccumulator { + std::vector indices; + size_t size = 0; + size_t size_limit = 0; +}; + +class TORCH_API Reducer { + public: + // The constructor takes a list of variables (i.e. parameters) for this + // process's single model replica (as DDP assumes single-process + // single-device). The bucket assignment for this reducer, `bucket_indices`, + // is specified as a list of buckets, each of which is specified as a list of + // indices into the bucket's `variables` list. + explicit Reducer( + std::vector params, + std::vector> bucket_indices, + c10::intrusive_ptr process_group, + std::vector expect_sparse_gradients, + int64_t bucket_bytes_cap, + bool find_unused_parameters, + bool gradient_as_bucket_view, + std::unordered_map param_names, + int64_t first_bucket_bytes_cap, + bool skip_all_reduce_unused_params, + bool use_python_reducer); + + ~Reducer() noexcept(false); + + // To (re-)initialize bucket assignment, pass a list of buckets, each of + // which is specified by a list of indices in the bucket's `variables` list. + // This function performs validation that the variables within a bucket + // all live on the same device and have the same dimensionality. + void initialize_buckets(std::vector> bucket_indices); + + void autograd_hook(size_t index); + + // This function is called when the forward function has produced an output, + // and the user wishes to reduce gradients in the backwards pass. + // If they don't, and wish to accumulate gradients before reducing them, + // a call to this function can simply be omitted. + void prepare_for_backward(const std::vector& outputs); + + // Called at the beginning of forward() inside DistributedDataParallel, + // right now it captures the starting time of forward in each iteration. + void prepare_for_forward(); + + // Returns the relative time in nanoseconds when gradients were ready, + // with respect to the time `prepare_for_backward` was called. The + // vector is for parameters for a single model replica. + std::vector get_backward_stats() const { + return backward_stats_; + } + + // Registers a hook to the reducer. The hook is `CommHookInterface` + // type to allow both Python and CPP hooks. This function can only + // be called once before calling backward. + // Cannot combine with the call of `register_builtin_comm_hook`. + void register_comm_hook(std::unique_ptr iface); + + // Registers a built-in C++ comm hook to the reducer. This function can only + // be called once before calling backward. + // Cannot combine with the call of `register_comm_hook`. + void register_builtin_comm_hook(c10d::BuiltinCommHookType comm_hook_type); + + // Informs reducer that optimizer is running in backward, so gradients + // don't need to be copied from buckets as the optimizer would've already + // been applied. + void set_optimizer_in_backward() { + optim_in_backward_ = true; + } + + // Runs allreduce or installed communication hook given GradBucket instance. + c10::intrusive_ptr run_comm_hook( + GradBucket& grad_bucket); + + // Runs default allreduce hook. + c10::intrusive_ptr run_allreduce_hook( + GradBucket& grad_bucket); + + // Returns gradient buckets in sequential order of buckets_. This is the order + // in which buckets are reduced across processes. If return_zero_tensors=true, + // will return zero tensors of the same shape instead of the true tensors. + std::vector get_grad_buckets( + bool return_zero_tensors = true) const; + + // Rebuild buckets based on rebuilt_params_ and rebuilt_param_indices_ + // according to when tensors received grads in the backward pass. + // TODO this function makes broadcast communication call and + // could be overlapped with next forward() call, thus + // it could be async. Will make it async when rebuilding buckets for + // find_unused_parameters = true case, as we could rebuild buckets more than + // once for find_unused_parameters = true case, where subgraphs are trained + // and parameter indices order may change more frequently. + // For find_unused_parameters = false case, buckets are only rebuilt once, + // the performance cost is negligible. Returns true if the buckets were + // rebuilt. + bool rebuild_buckets(); + + void setSparseMetadata(std::map& metadata); + + // Install futures that should be awaited at end of backwards. Currently these + // are only used by user-defined custom buffer reduction hooks, but can be + // generalized to any user-originating futures that need to be awaited. + void install_futures( + const c10::List>& futs); + + // Returns true if we should rebuild buckets, else false. We only rebuild + // buckets once after the first iteration and never rebuild them if + // find_unused_parameters_. + inline bool should_rebuild_buckets() const { + return (static_graph_ || !find_unused_parameters_) && !has_rebuilt_bucket_; + } + + // Pushes all parameters to be rebuilt. + void push_rebuilt_params_for_all_indices(); + + // Creates and sets ForwardPassWorkHandle given a Work and the + // corresponding tensor being reduced. + void set_forward_pass_work_handle( + c10::intrusive_ptr forwardPassWorkHandle, + bool useStaticWorldSize); + + // Retrieve on-device tensors used to track locally unused parameters. It is + // a tensor where index i = 1 if the Variable with that index has been used. + at::Tensor get_local_used_map_on_device() const; + + // An function for users to set sample_rate of collecting + // runtime stats. The time stats will be recorded for the + // first 10 iterations, after 10 iterations time stats will be + // recorded once every "sample_rate" training iterations. + void set_ddp_runtime_logging_sample_rate(int sample_rate); + + // Specify the training graph is static. + void set_static_graph(); + + // Delay all reduce to be after all gradients' calculation is complete. + void delay_all_reduce(); + + void set_mixed_precision_param_dtype(c10::ScalarType dtype); + + // Weak reference to associated DDP logger. The reference is weak to avoid + // refcycle between reducer and logger. + void set_logger(std::weak_ptr logger); + + // When graph is not explicitly set by user as static and has unused + // parameters, this will return whether the graph has been static until the + // current iteration, which means unused params set has not changed. + bool ddp_graph_static(); + + // Removes autograd hooks registered by the Reducer on the model parameters. + void remove_autograd_hooks(); + + // Checks whether or not the reducer has finalized the current backward + // iteration. + void check_finalized(); + + // Updates the underlying process group used by DDP with the new process + // group. + void update_process_group( + c10::intrusive_ptr new_process_group); + + // Resets reducer state. + void reset_state(); + + protected: + // Forward declaration. + struct Bucket; + + void push_rebuilt_params(const size_t& index); + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + mutable std::mutex mutex_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector params_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + c10::intrusive_ptr<::c10d::ProcessGroup> process_group_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::vector expect_sparse_gradients_; + + std::vector> + grad_accumulators_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::unordered_map gradAccToVariableMap_; + std::vector>> + hooks_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool expect_autograd_hooks_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool require_finalize_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + size_t next_bucket_; + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool has_marked_unused_parameters_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const bool find_unused_parameters_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const bool gradient_as_bucket_view_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::vector unused_parameters_; + // Previous iteration's unused params, used for checking if unused parameters + // change between iterations. Only filled during the first backwards call. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::vector prev_iteration_unused_parameters_; + // Whether graph is static or not. When user does not explicitly set static + // graph, the only possible dynamism is set of unused parameters changing + // between iterations which is tracked by this flag. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool ddp_graph_static_{true}; + // Locally used parameter maps indicating if parameters are used locally + // during the current iteration or no_sync session if no_sync is on. + // Each map is a one-dim int32 tensor of number of parameters. These tensors + // are marked in autograd_hook to indicate the corresponding param has been + // used, and get allreduced in the end of backward step of current iteration + // or no_sync session for figuring out the globally unused parameters. + // + // local_used_map_: CPU tensor for bookkeeping locally used params + // local_used_map_dev_: dev tensor for reducing globally unused params + at::Tensor local_used_map_; + at::Tensor local_used_map_dev_; + // Indicate that reduction is done and D2H copy is done as well. + bool local_used_map_reduced_; + + // Weak pointer to associated DDP logger. + std::weak_ptr logger_; + // List of futures installed by Reducer::install_futures that should be + // awaited at the end of backwards pass. + std::optional>> + installed_futures_{std::nullopt}; + // Mixed precision parameter dtype for bucket type checking. + std::optional mixed_precision_param_dtype_{std::nullopt}; + + // Work handle for allreduce on local_used_map_ + c10::intrusive_ptr local_used_work_; + + void mark_variable_ready_dense(size_t variable_index); + + void mark_variable_ready_sparse(size_t variable_index); + + void mark_variable_ready(size_t variable_index); + + void mark_bucket_ready(size_t bucket_index); + + void finalize_bucket_dense(Bucket& bucket); + + void finalize_backward(); + + // Returns list of model parameters corresponding to the given bucket. + // bucket_index is a key to cache after buckets are rebuilt, after which this + // mapping never changes. + std::vector get_variables_for_bucket( + size_t bucket_index, + const Bucket& bucket) const; + + // Asserts that the reduction for the previous iteration has finished before + // rebuilding buckets or kicking off the next one. + void ensure_prior_reduction_finished(); + + // Broadcast rebuilt buckets from rank 0 to other ranks before initializing + // the buckets + void sync_bucket_indices(std::vector>& bucket_indices); + + // We'd like to use DistAutogradContext::GradCallback here but dist autograd + // doesn't exist under Windows. So we just directly use the concrete type but + // to preserve and enforce our original intent we do a static assert when dist + // autograd is available. + using GradCallback = std::function; +#ifndef _WIN32 + static_assert( + std::is_same_v< + GradCallback, + torch::distributed::autograd::DistAutogradContext::GradCallback>); +#endif + void runGradCallbackForVariable(at::Tensor& variable, const GradCallback& cb); + + // This function is called inside `initialize_buckets()`. It initializes both + // `bucket_views_in` and `bucket_views_out` with views for each variable's + // gradient into the bucket's flattened `gradients` tensor. Views serve as + // entry points to `copy_()` each grad's data in/out of the flattened + // `gradients` tensor. + void initialize_bucket_views(Bucket& bucket); + + // This function is called inside `finalize_backward`, it happens only if + // DDP communication hook was registered to recreate just bucket_views_out + // with the result of `future_work`. + void populate_bucket_views_out(Bucket& bucket, at::Tensor& tensor); + + // If gradient_as_bucket_view_ is false, after allreduce buckets, + // copy bucket results back to grads. + void copy_bucket_to_grad( + at::Tensor& variable, + Reducer::Bucket& bucket, + size_t intra_bucket_index, + bool global_unused); + // Check layout of grad and bucket_view before copying the grad to bucket. + void check_grad_layout(const at::Tensor& grad, const at::Tensor& bucket_view); + + // A bucket contains [1..N] gradients to be reduced, where the gradients + // have the same dtype and device. + // Coalescing gradients together before reducing can result in lower overhead + // and/or faster time to completion. Coalescing requires the constituent + // gradients to have the same dtype and device, and the resulting flattened + // tensor uses that common dtype and device. The flattened tensor is filled + // as the corresponding gradients are computed (triggered by autograd hooks), + // and the buckets are reduced in a predetermined order consistent across + // processes. + struct Bucket { + // Gradients of the bucket flattened into a 1-dimensional tensor + at::Tensor gradients; + + // Views into the `gradients` tensor for each individual gradient + // Each view is created with layout (size and stride) matching the + // gradient's expected layout (see the "Gradient Layout Contract" in + // torch/csrc/autograd/functions/accumulate_grad.h). + // `bucket_views_in[i].copy_(grad)` and `grad.copy_(bucket_views_out[i])` + // provide convenient ways to copy gradient data in/out of `gradients`, + // respectively. + // We keep both `bucket_views_in` and `bucket_views_out` because + // registering a DDP communication hook may re-initialize + // `bucket_views_out` with the value of the hook's `future_work` but we + // still need separate views into the bucket's original flattened gradient + // to copy in gradient data. + std::vector bucket_views_in; + std::vector bucket_views_out; + + // Variables whose gradients are held in this bucket + // We use refcounted tensors here so that we can easily unflatten the + // bucket's flattened `gradients` tensor into the participating variables + // after reduction has completed. + std::vector variables; + + // Per-variable offset/length into the flattened `gradients` tensor and + // the corresponding `GradBucket` instance for communication hooks + std::vector offsets; + std::vector lengths; + + // Per-variable sizes slicing into the bucket's `gradients` tensor + std::vector sizes_vec; + + // Number of gradients left to be computed before the bucket is ready to + // be reduced + size_t pending; + + // Global indices of participating variables in the bucket + std::vector variable_indices; + + // Future work handle for DDP communication hook + // If no hook is registered, a temporary vanilla allreduce hook is used. + c10::intrusive_ptr future_work; + + // if this bucket contains complex parameters + bool is_complex_bucket = false; + + // If this bucket should expect a single sparse gradient + // If `true`, then this implies that `bucket.variables.size() == 1`. + bool expect_sparse_gradient = false; + + // Sparse indices tensor + std::optional sparse_tensor_indices = std::nullopt; + + // TODO(@pietern) + // Memory copies from gradient tensors into the bucket are potentially + // done on different CUDA streams. We record an event for every copy + // so that we can synchronize with them prior to kicking off the reduction. + // std::vector events; + }; + + std::vector buckets_; + + // A variable locator locates a particular variable in the reducer's buckets + struct VariableLocator { + // Index of the bucket containing the variable in the `buckets_` vector + size_t bucket_index; + // Index of the variable in the bucket, which may be used consistently + // across `bucket_views_in`, `bucket_views_out`, `variables`, `offsets`, + // `lengths`, `sizes_vec`, and `variable_indices` in `Bucket` + size_t intra_bucket_index; + + VariableLocator() = default; + + VariableLocator(size_t bucket_index_, size_t intra_bucket_index_) + : bucket_index(bucket_index_), + intra_bucket_index(intra_bucket_index_) {} + }; + + // Map the index of a variable to its location in the bucket structure. + std::vector variable_locators_; + + // track the number of iterations to synchronize grads in training so far. + long num_iterations_; + // track distinct iteration of backward call. This is distinct from + // num_iterations_, for example in the case of multiple forward before + // backward. + long num_bwd_calls_; + // whether the first autograd hook for a distinct backward pass has been + // called. + bool first_autograd_hook_called_; + // track the number of buckets that have been ready for + // communication calls like allReduce or communication hooks. + int num_buckets_ready_; + // track the number of buckets that have been reduced. + int num_buckets_reduced_; + + // Timing information. + int64_t backward_compute_start_time_ = -1; + std::unique_ptr timer_; + + // We collect the relative timestamp of every gradient being ready + // when executing autograd. This can be used to derive a timeline of + // the point in time buckets were ready, or ideal bucket assignment/ordering. + std::vector backward_stats_; + + bool should_collect_runtime_stats(); + void record_forward_compute_start_time(); + void record_backward_compute_start_time(); + void record_backward_compute_end_time(); + void record_backward_comm_start_time(); + void record_backward_comm_end_time(); + + int get_ddp_runtime_logging_sample_rate(); + int ddp_runtime_logging_sample_rate_ = kDDPRuntimeLoggingSampleRate; + + bool is_multi_device_module_ = false; + + // Following variables are to help build dynamic bucket order + bool has_rebuilt_bucket_; + std::vector rebuilt_params_; + std::vector rebuilt_param_indices_; + const int64_t bucket_bytes_cap_; + +#ifndef _WIN32 + struct RpcContext { + using ContextPtr = torch::distributed::autograd::ContextPtr; + // The shared_ptr is to hold the context instance. + ContextPtr context_ptr_holder; + std::atomic context_ptr{nullptr}; + + void set(ContextPtr&& new_context_ptr); + }; + RpcContext rpc_context_; +#endif + + // A struct containing work handle and tensor for allreduce scheduled in + // forward pass, if applicable. + struct ForwardPassAllreduceWork { + c10::intrusive_ptr workHandle; + at::Tensor resultTensor; + // whether we should divide by the initial world_size or the no. of + // remaining DDP ranks. + bool useStaticWorldSize; + }; + + // Handle for the currently scheduled allreduce in the forward pass, if + // applicable. + ForwardPassAllreduceWork forwardPassWorkHandle_; + + // Division factor for reduction of gradients. + // Equal to the process group size, with an exception of handling uneven + // input. + int div_factor_; + + bool static_graph_; + + bool skip_all_reduce_unused_params_; + + // Key: size_t (index), Value: the number of times that a variable's + // autograd_hook() should be triggered before marking this variable's grad as + // ready for communication. Map will not change after 1st iteration. + std::unordered_map numGradHooksTriggeredMap_; + // Key: size_t (index), Value: the number of times that a variable's + // autograd_hook() are left to be triggered before marking this variable's + // grad as ready for communication. Map will change after 1st iteration to + // track a grad is ready for communication or not. + std::unordered_map numGradHooksTriggeredMapPerIteration_; + + private: + // reset counting for buckets before backward starts + void reset_bucket_counting(); + // search unused parameters beore backward starts + void search_unused_parameters( + const std::vector& outputs); + void set_divide_factor(); + // kick off all reduce for the ready bucket + void all_reduce_bucket(Bucket& bucket); + // kick off all reduce to local used map, it can help find global unused + // parameters + void all_reduce_local_used_map(); + // initialize locally used parameter maps + void initialize_local_used_map(); + // get current cuda stream + const c10::Stream get_current_stream(); + bool dynamic_graph_find_unused(); + bool static_graph_first_iteration(); + bool static_graph_after_first_iteration(); + + bool is_unused_bucket(Bucket& bucket); + bool should_skip_all_reduce_bucket(Bucket& bucket); + + // comm_hook_ is used to access the DDP communication hook if registered. + std::unique_ptr comm_hook_; + + // Sparse metadata contains the indices that will be used + // when calling into sparse allreduce. + // This is only used in the sparse allreduce collective calls + std::unique_ptr> sparse_metadata_; + + // Debug level setting. It is parsed once when Reducer is constructed, and + // remains the same across a single invocation of DDP training. + DebugLevel ddp_debug_level_; + // Mapping of variable index to fully qualified name of model to notify users + // about errors when certain parameters do not get gradient. + std::unordered_map param_names_; + // Variable indices stored sequentially in order of when the gradient is ready + // for the current backwards pass. + std::vector grad_ready_order_indices_; + // Bytes capacity of first bucket, can be configured by user + int64_t first_bucket_bytes_cap_; + // Per iteration set of parameter indices that have been marked ready. + std::unordered_set perIterationReadyParams_; + // Retrieves parameter names that have not been marked as ready as part of + // previous iteration. + std::vector getUnmarkedParamsForIteration(); + // Retrieves parameter indices that have not been marked as ready as part of + // previous iteration. + std::vector getUnmarkedParamIndicesForIteration(); + // Raises appropriate error if mark_variable_ready is called on the same + // variable twice, which is unexpected. + void checkAndRaiseMarkedTwiceError(size_t curVariableIndex); + // Retrieves parameter corresponding to the given VariableIndex. + at::Tensor& get_param_from_index(size_t index); + // Python reducer keeps C++ reducer initialized. To remove this flag, + // we need to refactor the DDP wrapper's initialization. + bool use_python_reducer_; + + // Cached bucket index to model parameter mapping. Populated after buckets + // are rebuilt after which this mapping is static. + mutable std::unordered_map> + cached_variables_for_bucket_; + + bool optim_in_backward_{false}; + friend class Logger; +}; + +// This is equivalent to take_tensors but returns indices into the +// tensor list argument for bucket assignment. Also, it is aware +// of device placement and will not allow buckets to span devices. +// The index of tensors[i] assigned to bucket is tensor_indices[i], +// when tensor_indices is empty, the index of tensors[i] assigned to +// bucket is i. +TORCH_API std::tuple>, std::vector> +compute_bucket_assignment_by_size( + const std::vector& tensors, + const std::vector& bucket_size, + const std::vector& expect_sparse_gradient = {}, + const std::vector& tensor_indices = {}, + const std::optional>& logger = {}); + +// Verify models across all processes are the same as model on rank 0 with +// respect to no. of params and matching dtype/size/layout. +TORCH_API void verify_params_across_processes( + const c10::intrusive_ptr& process_group, + const std::vector& params, + const std::optional>& logger); +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/reducer_timer.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/reducer_timer.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7b4320325c5ef027f4ad47a789b67e5168ee7dd7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/reducer_timer.hpp @@ -0,0 +1,86 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +namespace c10d { +constexpr int kUnsetTime = -1; + +inline int64_t current_time_in_nanos() { + return c10::getTime(); +} + +class TORCH_API Timer { + private: + // The timestamp of forward call start time in each iteration. + int64_t forward_start_time = kUnsetTime; + // The timestamp of backward computation start and end time in each + // iteration. + int64_t backward_compute_start_time = kUnsetTime; + int64_t backward_compute_end_time = kUnsetTime; + // The timestamp of first communication call start time in each iteration. + int64_t backward_comm_start_time = kUnsetTime; + // The timestamp of last communication call end time in each iteration. + int64_t backward_comm_end_time = kUnsetTime; + + public: + enum class Event : uint8_t { + kForwardStart, + kBackwardComputeStart, + kBackwardComputeEnd, + kBackwardCommStart, + kBackwardCommEnd, + }; + + // Record the current event, i.e., mark it as having occurred now. Default + // CPU implementation. + virtual void record(Event event) { + getTimeRef(event) = current_time_in_nanos(); + } + + // Return the difference between when two events occurred, in nanoseconds. + // Or nullopt if one of them hasn't been recorded. + virtual std::optional measureDifference(Event start, Event end) = 0; + + virtual ~Timer() = default; + + // Return host-side timestamp, or nullopt if it has not yet been recorded. + std::optional getTimestamp(Event event) { + auto time = getTimeRef(event); + if (time == kUnsetTime) { + return std::nullopt; + } else { + return time; + } + } + + // Return host-side time member variable corresponding to the given event. + int64_t& getTimeRef(Event event) { + switch (event) { + case Event::kForwardStart: + return forward_start_time; + case Event::kBackwardComputeStart: + return backward_compute_start_time; + case Event::kBackwardComputeEnd: + return backward_compute_end_time; + case Event::kBackwardCommStart: + return backward_comm_start_time; + case Event::kBackwardCommEnd: + return backward_comm_end_time; + default: + TORCH_INTERNAL_ASSERT(false); + } + } +}; + +TORCH_DECLARE_TYPED_REGISTRY( + TimerRegistry, + c10::DeviceType, + Timer, + std::unique_ptr, + c10::Device); +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fa88322a6fa02adc0285afecf0fa128048f310f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp @@ -0,0 +1,71 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace c10d { +constexpr int kUnsetSeqNum = 0; + +namespace { +constexpr int kByteOffset = 8; +} // namespace + +// Converts from int to char vec to write in store +template +inline std::vector toVec(uint64_t num, int numBytes) { + std::vector values; + // Read off bytes from right to left, pushing them into + // char array. + for (const auto i : c10::irange(numBytes)) { + uint8_t x = (num >> (kByteOffset * i)) & 0xff; + values.push_back(static_cast(x)); + } + return values; +} + +// Converts from char vec (such as from store read) to int. +template +inline uint64_t fromVec(const std::vector& values) { + uint64_t num = 0; + // Set each byte at the correct location on num + for (const auto i : c10::irange(values.size())) { + uint8_t x = static_cast(values[i]); + num |= (static_cast(x) << (kByteOffset * i)); + } + return num; +} + +class TORCH_API SequenceNum { + public: + SequenceNum(); + explicit SequenceNum(const uint64_t num); + // Retrieve num_. Will throw if not set. + uint64_t get() const; + // Increment num_. Will throw if not set. + void increment(); + // Increment num_ and return the old value. Will throw if not set. + uint64_t getAndIncrement(); + // Sets num_ + void set(const uint64_t num); + // Returns true if this SequenceNum is properly initialized with a value, else + // false. + bool isSet() const; + + SequenceNum& operator=(const SequenceNum& other); + + SequenceNum(const SequenceNum& other); + + private: + std::optional num_; + mutable std::mutex lock_; +}; + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h new file mode 100644 index 0000000000000000000000000000000000000000..8d2ec93016c028f4d7c79410ab5c3a11cfa5264f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h @@ -0,0 +1,110 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and its 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 + +namespace c10d::detail { + +class SocketOptions { + public: + SocketOptions& prefer_ipv6(bool value) noexcept { + prefer_ipv6_ = value; + + return *this; + } + + bool prefer_ipv6() const noexcept { + return prefer_ipv6_; + } + + SocketOptions& connect_timeout(std::chrono::milliseconds value) noexcept { + connect_timeout_ = value; + + return *this; + } + + std::chrono::milliseconds connect_timeout() const noexcept { + return connect_timeout_; + } + + // Sets the backoff policy to use for socket connect ops. + SocketOptions& connect_backoff(std::shared_ptr value) noexcept { + connect_backoff_ = std::move(value); + + return *this; + } + + const std::shared_ptr& connect_backoff() const noexcept { + return connect_backoff_; + } + + private: + bool prefer_ipv6_ = true; + std::chrono::milliseconds connect_timeout_{std::chrono::seconds{30}}; + std::shared_ptr connect_backoff_{ + std::make_shared(std::chrono::milliseconds(1000))}; +}; + +class SocketImpl; + +class Socket { + public: + // This function initializes the underlying socket library and must be called + // before any other socket function. + static void initialize(); + + static Socket listen(std::uint16_t port, const SocketOptions& opts = {}); + + static Socket listenFromFd(int fd, std::uint16_t expected_port); + + static Socket connect( + const std::string& host, + std::uint16_t port, + const SocketOptions& opts = {}); + + Socket() noexcept = default; + + Socket(const Socket& other) = delete; + + Socket& operator=(const Socket& other) = delete; + + Socket(Socket&& other) noexcept; + + Socket& operator=(Socket&& other) noexcept; + + ~Socket(); + + Socket accept() const; + + int handle() const noexcept; + + std::uint16_t port() const; + + bool waitForInput(std::chrono::milliseconds timeout); + + std::string repr() const; + + private: + explicit Socket(std::unique_ptr&& impl) noexcept; + + std::unique_ptr impl_; +}; +} // namespace c10d::detail + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket_fmt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket_fmt.h new file mode 100644 index 0000000000000000000000000000000000000000..f333c8fa12d8ad4f321072b9379c24529c7d3507 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket_fmt.h @@ -0,0 +1,35 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// (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 + +/* +This file should not be included from other .h files and only used in cpp files +as it exposes the underlying platform specific socket headers. +*/ + +#include + +#ifdef _WIN32 +#include + +#include +#include +#else +#include +#endif + +namespace c10d::detail { + +// Returns a human-readable representation of the given socket address. +std::string formatSockAddr(const struct ::sockaddr* addr, socklen_t len); + +} // namespace c10d::detail + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory-inl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..480803752d9f3026d6b73a09cb1700a7c1678e5c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory-inl.h @@ -0,0 +1,363 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) && CUDART_VERSION >= 12010 +#define NVCC_SUPPORTS_MULTICAST 1 +#endif + +#include +#if defined(USE_ROCM) +#include +#endif +#if !defined(USE_ROCM) +#include +#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 600) +#include +#endif +#endif +#include + +namespace c10d::symmetric_memory { + +template +using Vec = at::native::memory::Vec; + +template +inline constexpr bool dependent_false = + at::native::memory::dependent_false; + +using at::native::memory::get_alignment; + +template +__device__ __forceinline__ uint32_t +cas(uint32_t* addr, uint32_t compare, uint32_t val) { +#if !defined(USE_ROCM) && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 600) + ::cuda::atomic_ref ref(*addr); + ref.compare_exchange_strong(compare, val, ::cuda::std::memory_order(Sem)); + return compare; +#elif defined(USE_ROCM) + __atomic_compare_exchange_n( + addr, &compare, val, false, static_cast(Sem), __ATOMIC_RELAXED); + return compare; +#else + CUDA_KERNEL_ASSERT(false); + return 0; +#endif +} + +__device__ __forceinline__ void trap() { +#if defined(USE_ROCM) + // abort() calls trap() under the covers. However, on ROCm, the trap is + // handled differently inside hip runtime. It collects a gpu core dump and + // causes linux kernel to create a core dump of the host application. + abort(); +#else + __trap(); +#endif +} + +__device__ __forceinline__ size_t global_timer_ns() { +#if defined(USE_ROCM) + static constexpr double MI300_FREQ_GHZ = 2.1; + return clock64() / MI300_FREQ_GHZ; +#else + size_t val; + asm volatile("mov.u64 %0, %globaltimer;" : "=l"(val) : : "memory"); + return val; +#endif +} + +constexpr size_t ns_per_ms = 1e6; + +template +__device__ __forceinline__ bool try_put_signal( + uint32_t* addr, + size_t timeout_ms) { + size_t deadline = global_timer_ns() + timeout_ms * ns_per_ms; + while (cas(addr, 0, 1) != 0) { + if (timeout_ms != 0 && global_timer_ns() > deadline) { + return false; + } + } + return true; +} + +template +__device__ __forceinline__ bool try_wait_signal( + uint32_t* addr, + size_t timeout_ms) { + size_t deadline = global_timer_ns() + timeout_ms * ns_per_ms; + while (cas(addr, 1, 0) != 1) { + if (timeout_ms != 0 && global_timer_ns() > deadline) { + return false; + } + } + return true; +} + +template +__device__ __forceinline__ void put_signal(uint32_t* addr) { + while (cas(addr, 0, 1) != 0) + ; +} + +template +__device__ __forceinline__ void wait_signal(uint32_t* addr) { + while (cas(addr, 1, 0) != 1) + ; +} + +// Synchronizes blocks with matching blockIdx across participating devices. +// Note: sync_remote_block itself is not a system level barrier/fence. It is a +// building block for expressing different synchronization patterns. +// +// Pattern 0: Ensures that all writes to symm_mem buffers from previous +// kernels across all devices are visible to the current kernel: +// +// sync_remote_blocks(...); +// __syncthreads(); +// +// Pattern 1: Ensures that all writes to symm_mem buffers from the current +// block are visible to all remote blocks with matching blockIdx: +// +// __syncthreads(); +// sync_remote_blocks(...); +// __syncthreads(); +// +// Pattern 2: Ensures that symm_mem buffers read by the current kernel are safe +// for writing by subsequent kernels across all devices. +// +// __syncthreads(); +// sync_remote_blocks(...); +template +__device__ __forceinline__ void sync_remote_blocks( + uint32_t** signal_pads, + size_t rank, + size_t world_size) { + if (threadIdx.x < world_size) { + auto target_rank = threadIdx.x; + if constexpr (hasPrevMemAccess) { + put_signal( + signal_pads[target_rank] + blockIdx.x * world_size + rank); + } else { + put_signal( + signal_pads[target_rank] + blockIdx.x * world_size + rank); + } + if constexpr (hasSubsequentMemAccess) { + wait_signal( + signal_pads[rank] + blockIdx.x * world_size + target_rank); + } else { + wait_signal( + signal_pads[rank] + blockIdx.x * world_size + target_rank); + } + } +}; + +template +struct MultimemLdReduce { + template + __device__ __inline__ Vec operator()(T* mc_ptr) { + static_assert(dependent_false); + } +}; + +template +__device__ __inline__ Vec multimem_ld_reduce_add(T* mc_ptr) { + MultimemLdReduce functor; + return functor.template operator()(mc_ptr); +} + +#if defined(USE_ROCM) || !defined(NVCC_SUPPORTS_MULTICAST) +#define SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(type, asm_type, acc_prec) \ + template <> \ + struct MultimemLdReduce { \ + template \ + __device__ __inline__ Vec operator()(type* mc_ptr) { \ + CUDA_KERNEL_ASSERT(false); \ + } \ + }; +#else +#define SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(type, asm_type, acc_prec) \ + template <> \ + struct MultimemLdReduce { \ + template \ + __device__ __inline__ Vec operator()(type* mc_ptr) { \ + Vec vec; \ + if constexpr (Alignment == 16) { \ + asm("multimem.ld_reduce.relaxed.sys.global.add" acc_prec \ + ".v4" asm_type " {%0,%1,%2,%3}, [%4];" \ + : "=r"(vec.u32[0]), \ + "=r"(vec.u32[1]), \ + "=r"(vec.u32[2]), \ + "=r"(vec.u32[3]) \ + : "l"(mc_ptr) \ + : "memory"); \ + } else if constexpr (Alignment == 8) { \ + asm("multimem.ld_reduce.relaxed.sys.global.add" acc_prec \ + ".v2" asm_type " {%0,%1}, [%2];" \ + : "=r"(vec.u32[0]), "=r"(vec.u32[1]) \ + : "l"(mc_ptr) \ + : "memory"); \ + } else if constexpr (Alignment == 4) { \ + asm("multimem.ld_reduce.relaxed.sys.global.add" acc_prec asm_type \ + " %0, [%1];" \ + : "=r"(vec.u32) \ + : "l"(mc_ptr) \ + : "memory"); \ + } \ + return vec; \ + } \ + }; +#endif + +SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(at::BFloat16, ".bf16x2", ".acc::f32"); +SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(float, ".f32", ""); + +template +__device__ __inline__ void multimem_st(T* mc_ptr, Vec& vec) { +#if defined(USE_ROCM) || !defined(NVCC_SUPPORTS_MULTICAST) + CUDA_KERNEL_ASSERT(false); +#else + if constexpr (Alignment == 16) { + asm("multimem.st.relaxed.sys.global.v4.f32 [%0], {%1,%2,%3,%4};" + : + : "l"(mc_ptr), + "r"(vec.u32[0]), + "r"(vec.u32[1]), + "r"(vec.u32[2]), + "r"(vec.u32[3]) + : "memory"); + } else if constexpr (Alignment == 8) { + asm("multimem.st.relaxed.sys.global.v2.f32 [%0], {%1,%2};" + : + : "l"(mc_ptr), "r"(vec.u32[0]), "r"(vec.u32[1]) + : "memory"); + } else if constexpr (Alignment == 4) { + asm("multimem.st.relaxed.sys.global.f32 [%0], %1;" + : + : "l"(mc_ptr), "r"(vec.u32) + : "memory"); + } else { + static_assert(dependent_false); + } +#endif +} + +template +__device__ __inline__ T add_bf16x2(T a, T b) { + static_assert(sizeof(T) == 4); +#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800)) + CUDA_KERNEL_ASSERT(false); + return T{}; +#elif defined(USE_ROCM) + union bf2f { + float f; + __hip_bfloat16 bf[2]; + } _bf2f_a = {.f = 0}, _bf2f_b = {.f = 0}; + + //__hip_bfloat162 is a struct with two __hip_bfloat16 elements called x and y + // This typecasts input a and b as bfloat16 and maps to low bits of a float + // and does the addition in float + _bf2f_a.bf[1] = reinterpret_cast<__hip_bfloat162*>(&a)->x; + _bf2f_b.bf[1] = reinterpret_cast<__hip_bfloat162*>(&b)->x; + union f2bf { + float f; + __hip_bfloat16 bf[2]; + } _f2bf_res0, _f2bf_res1; + _f2bf_res0.f = _bf2f_a.f + _bf2f_b.f; + + // Same thing for y elements of __hip_bfloat162 + _bf2f_a.bf[1] = reinterpret_cast<__hip_bfloat162*>(&a)->y; + _bf2f_b.bf[1] = reinterpret_cast<__hip_bfloat162*>(&b)->y; + _f2bf_res1.f = _bf2f_a.f + _bf2f_b.f; + + // Put the two results together + __hip_bfloat162 rtn(_f2bf_res0.bf[1], _f2bf_res1.bf[1]); + return *reinterpret_cast(&rtn); +#else + auto res = __hadd2( + *reinterpret_cast<__nv_bfloat162*>(&a), + *reinterpret_cast<__nv_bfloat162*>(&b)); + return *reinterpret_cast(&res); +#endif +} + +template +__device__ __inline__ Vec add_vec( + const Vec& a, + const Vec& b) { + Vec c{}; + if constexpr (std::is_same_v) { + if constexpr (Alignment == 16) { + c.f32[0] = a.f32[0] + b.f32[0]; + c.f32[1] = a.f32[1] + b.f32[1]; + c.f32[2] = a.f32[2] + b.f32[2]; + c.f32[3] = a.f32[3] + b.f32[3]; + } else if constexpr (Alignment == 8) { + c.f32[0] = a.f32[0] + b.f32[0]; + c.f32[1] = a.f32[1] + b.f32[1]; + } else if constexpr (Alignment == 4) { + c.f32 = a.f32 + b.f32; + } else { + static_assert(dependent_false); + } + } else if constexpr (std::is_same_v) { + if constexpr (Alignment == 16) { + c.u32[0] = add_bf16x2(a.u32[0], b.u32[0]); + c.u32[1] = add_bf16x2(a.u32[1], b.u32[1]); + c.u32[2] = add_bf16x2(a.u32[2], b.u32[2]); + c.u32[3] = add_bf16x2(a.u32[3], b.u32[3]); + } else if constexpr (Alignment == 8) { + c.u32[0] = add_bf16x2(a.u32[0], b.u32[0]); + c.u32[1] = add_bf16x2(a.u32[1], b.u32[1]); + } else if constexpr (Alignment == 4) { + c.u32 = add_bf16x2(a.u32, b.u32); + } else { + static_assert(dependent_false); + } + } else { + static_assert(dependent_false); + } + return c; +} + +// With world_size specialization: perform balanced load from all peers before +// performing reduction. +template +__device__ inline std::enable_if_t<(k_world_size > 0), Vec> +load_and_reduce(T** ptrs, size_t rank, size_t world_size, size_t offset) { + Vec vecs[k_world_size]; +#pragma unroll k_world_size + for (size_t step = 0; step < k_world_size; ++step) { + size_t remote_rank = (rank + step) % k_world_size; + vecs[remote_rank] = + at::native::memory::ld_vec(ptrs[remote_rank] + offset); + } + auto acc = vecs[0]; +#pragma unroll k_world_size - 1 + for (size_t r = 1; r < world_size; ++r) { + acc = add_vec(acc, vecs[r]); + } + return acc; +} + +// Without world_size specialization: perform ordered (unbalanced) load and +// accumulate on each load. +template +__device__ inline std::enable_if_t<(k_world_size <= 0), Vec> +load_and_reduce(T** ptrs, size_t rank, size_t world_size, size_t offset) { + Vec acc{}; + for (size_t step = 0; step < world_size; ++step) { + auto vec = at::native::memory::ld_vec(ptrs[step] + offset); + acc = add_vec(acc, vec); + } + return acc; +} + +} // namespace c10d::symmetric_memory + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory.hpp new file mode 100644 index 0000000000000000000000000000000000000000..caaa52d32408bffd084a772282c94e23af9d0a6b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory.hpp @@ -0,0 +1,157 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace c10d::symmetric_memory { + +// Resource wrapper that owns a (vaddr, allocation handle) pair. Upon +// destruction, it unmaps the vaddr and releases the allocation handle. +struct AllocationRef : public c10::intrusive_ptr_target { + void* ptr; + HandleType handle; + size_t block_size; + int device_idx; + bool is_multicast; + + AllocationRef( + void* ptr, + HandleType handle, + size_t block_size, + int device_idx, + bool is_multicast = false); + + ~AllocationRef(); +}; + +// Forward declaration of CUDAPeerAllocInfo +class CUDAPeerAllocInfo; + +class CUDASymmetricMemory : public SymmetricMemory { + public: + // This is mostly a shallow copy that shares the pointer to + // `CUDAPeerAllocInfo` which corresponds to the base Block. The + // CUDASymmetricMemory handle is specified by the offset to the base ptr. + CUDASymmetricMemory( + const c10::intrusive_ptr& pai, + size_t offset); + + ~CUDASymmetricMemory() override {}; + + std::vector get_buffer_ptrs() override; + std::vector get_signal_pad_ptrs() override; + void** get_buffer_ptrs_dev() override; + void** get_signal_pad_ptrs_dev() override; + size_t get_buffer_size() override; + size_t get_offset() override; + + bool has_multicast_support() override; + void* get_multicast_ptr() override; + + void barrier(int channel, size_t timeout_ms) override; + void put_signal(int dst_rank, int channel, size_t timeout_ms) override; + void wait_signal(int src_rank, int channel, size_t timeout_ms) override; + + int get_rank() override; + int get_world_size() override; + c10::Device get_device() override; + bool world_within_direct_access() override; + + private: + int local_device_idx_; + int rank_; + int world_size_; + c10::intrusive_ptr pai_; + size_t offset_{0}; // in byte +}; + +// A class to hold the base pointers and signal pad pointers for a group of +// peers. One `CUDAPeerAllocInfo` object can be shared by multiple +// `CUDASymmetricMemory` objects when latter reside on the same allocation +// and rendezvous over the same group. (The `CUDASymmetricMemory` objects may +// have different offsets compared to the base address.) +class CUDAPeerAllocInfo : public c10::intrusive_ptr_target { + public: + CUDAPeerAllocInfo( + std::vector> alloc_refs, + std::vector buffers, + std::vector signal_pads, + HandleType mc_handle, + void* mc_addr, + size_t buffer_size, + int local_device_idx, + int rank, + int world_size); + + private: + std::vector> alloc_refs_; + std::vector buffers_; + std::vector signal_pads_; + HandleType mc_handle_; + void* mc_addr_; + size_t buffer_size_; + int local_device_idx_; + int rank_; + int world_size_; + void** buffers_dev_; + void** signal_pads_dev_; + + friend class CUDASymmetricMemory; +}; + +// Metadata associated with each allocation performed by +// `CUDASymmetricMemoryAllocator`. +struct Block : public c10::intrusive_ptr_target { + c10::intrusive_ptr alloc_ref; + int device_idx; + size_t block_size; + size_t buffer_size; + size_t signal_pad_offset; + std::optional default_group_name; + std::map> symm_mems; + + Block( + c10::intrusive_ptr alloc_ref, + int device_idx, + size_t block_size, + size_t buffer_size, + size_t signal_pad_offset, + const std::optional& group_name); +}; + +class CUDASymmetricMemoryAllocator : public SymmetricMemoryAllocator { + public: + void* alloc( + size_t size, + int device_idx, + const std::optional& group_name) override; + + void free(void* ptr) override; + size_t get_alloc_size(void* ptr) override; + c10::intrusive_ptr rendezvous( + void* ptr, + const std::optional& group_name) override; + bool has_multicast_support(int device_idx) override; + c10::DeviceType supported_device_type() override; + std::string name() override; + + private: + c10::intrusive_ptr find_block(void* ptr); + c10::intrusive_ptr find_block_covering(void* ptr, size_t& offset); + + std::shared_mutex mutex_; + std::unordered_map> ptr_to_block_; + c10::cuda::CUDACachingAllocator::Expandable_Segments_Handle_Type + handle_type_ = c10::cuda::CUDACachingAllocator:: + Expandable_Segments_Handle_Type::UNSPECIFIED; +}; + +} // namespace c10d::symmetric_memory + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryTypes.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryTypes.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2822011bdb192125ec44e3825ffff1f74aa18e55 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryTypes.hpp @@ -0,0 +1,36 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#if defined(USE_ROCM) +#include +#endif + +namespace c10d::symmetric_memory { + +// Covers NVL72 +constexpr int max_cuda_p2p_domain_size = 72; +// Maximum number of channels +constexpr int symm_max_nblocks = 32; + +// Maximally, a rank will need to sync with all other ranks, over all +// channels. Each signal is 32 bits, which is the minimum unit for atomic cas. +// Default signal pad size, can be overridden via set_signal_pad_size(). +constexpr size_t default_signal_pad_size = + symm_max_nblocks * max_cuda_p2p_domain_size * sizeof(uint32_t); + +#if !defined(USE_ROCM) && defined(PYTORCH_C10_DRIVER_API_SUPPORTED) +using HandleType = CUmemGenericAllocationHandle; +#elif defined(USE_ROCM) +using HandleType = hipMemGenericAllocationHandle_t; +#else +using HandleType = void*; +#endif + +} // namespace c10d::symmetric_memory + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryUtils.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryUtils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0c6f8e725fdaea39eba18fcb303469cf9db1e643 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryUtils.hpp @@ -0,0 +1,120 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace c10d { +namespace symmetric_memory { + +bool device_has_multicast_support(int device_idx); + +bool allow_overlapping_devices(); + +// Query environment variable to get the backend used for CUDA Symmetric Memory. +std::string getSymmMemBackendCUDA(); + +class IpcChannel { + public: + IpcChannel(); + ~IpcChannel(); + + void send_fd(int dst_pid, int fd); + int recv_fd(); + + std::vector all_gather_fds( + int rank, + const std::vector& pids, + int fd); + + int broadcast_fds( + int rank, + int src_rank, + const std::vector& pids, + int fd); + + private: + static std::string get_socket_name(int pid); + + std::string socket_name_; + int socket_; +}; + +// A set of store-based exchange methods with a preset prefix typically type of +// the SymmetricMemory. Most used as static instances at respective +// SymmetricMemory implementation files. +class StoreExchange { + public: + StoreExchange(const std::string& store_prefix) + : store_prefix_(store_prefix) {} + + // Put template function in header file so that compiler can easily access it. + template + std::vector all_gather( + const c10::intrusive_ptr& store, + int rank, + int world_size, + T val) { + static_assert(std::is_trivially_copyable_v); + + std::vector peer_keys; + peer_keys.reserve(world_size); + for (int r = 0; r < world_size; ++r) { + std::ostringstream oss; + oss << store_prefix_ << '/' << seq_id_ << '/' << r; + peer_keys.push_back(oss.str()); + } + ++seq_id_; + + { + std::vector payload( + reinterpret_cast(&val), + reinterpret_cast(&val) + sizeof(T)); + store->set(peer_keys[rank], payload); + } + + std::vector peer_vals; + peer_vals.reserve(world_size); + for (int r = 0; r < world_size; ++r) { + if (r == rank) { + peer_vals.push_back(val); + continue; + } + store->wait({peer_keys[r]}); + auto payload = store->get(peer_keys[r]); + TORCH_CHECK(payload.size() == sizeof(T)); + T peer_val{}; + std::memcpy(&peer_val, payload.data(), sizeof(T)); + peer_vals.push_back(peer_val); + } + return peer_vals; + } + + void barrier( + const c10::intrusive_ptr& store, + int rank, + int world_size) { + // TODO: implement an efficient one? + all_gather(store, rank, world_size, 0); + } + + private: + const std::string store_prefix_; + size_t seq_id_ = 0; +}; + +// Returns a pointer of virtual address that is mapped to the physical memory +// held by the handle. +void map_block( + void** ptr, + c10d::symmetric_memory::HandleType handle, + size_t size, + int device_idx); + +} // namespace symmetric_memory +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/DMAConnectivity.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/DMAConnectivity.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1fbf2d774c5543fcf496bb87f2599fbace5c46b7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/DMAConnectivity.hpp @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace c10d { + +struct TORCH_API DMAConnectivity : c10::intrusive_ptr_target { + c10::DeviceType device_type; + std::string connection_type; + + // This is an NxN matrix representing the connectivity between N devices, + // where each element matrix[i][j] indicates the connectivity between device + // i and device j. A value of 0 denotes that there is no connection between + // device i and j. The meaning of non-zero values are specific to the + // connection type (e.g., for NVLink it represents the number of NVLinks). + std::vector> matrix; + + explicit DMAConnectivity( + c10::DeviceType device_type, + std::string connection_type, + std::vector> matrix); +}; + +struct DMAConnectivityDetector : c10::intrusive_ptr_target { + virtual c10::intrusive_ptr detect() = 0; + ~DMAConnectivityDetector() override = default; +}; + +C10_EXPORT void register_dma_connectivity_detector( + c10::DeviceType device_type, + const std::string& connection_type, + c10::intrusive_ptr detector); + +TORCH_API c10::intrusive_ptr detect_dma_connectivity( + c10::DeviceType device_type, + const std::string& connection_type); + +} // namespace c10d + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/SymmetricMemory.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/SymmetricMemory.hpp new file mode 100644 index 0000000000000000000000000000000000000000..35c12d238f4817ffc6bcf1b52a4be4012ec27c95 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/SymmetricMemory.hpp @@ -0,0 +1,225 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace c10d::symmetric_memory { + +// SymmetricMemory represents symmetric allocations across a group of devices. +// The allocations represented by a SymmetricMemory object are accessible by +// all devices in the group. The class can be used for op-level custom +// communication patterns (via the get_buffer APIs and the synchronization +// primitives), as well as custom communication kernels (via the buffer and +// signal_pad device pointers). +// +// To acquire a SymmetricMemory object, each rank first allocates +// identical-sized memory via SymmetricMemoryAllocator::alloc(), then invokes +// SymmetricMemoryAllocator::rendezvous() on the memory to establish the +// association across peer buffers. The rendezvous is a one-time process, and +// the mapping between a local memory memory and the associated SymmetricMemory +// object is unique. +// +// NOTE [symmetric memory signal pad] +// Signal pads are P2P-accessible memory regions designated for +// synchronization. SymmetricMemory offers built-in synchronization primitives +// such as barriers, put_signal, and wait_signal, which are all based on signal +// pads. Users may utilize signal pads for their own synchronization logic, +// provided that the signal pads remain zero-filled following successful +// synchronization. +// +// NOTE [symmetric memory synchronization channel] +// Synchronization channels allow users to use a single SymmetricMemory object +// to perform isolated synchronizations on different streams. For example, +// consider the case in which two barriers are issued on two streams for +// different purposes. Without the concept of channels, we cannot guarantee the +// correctness of the barriers since signals issued from barrier on stream A +// can be received by the barrier on stream B. By specifying different channels +// for these two barriers, they can operate correctly in parallel. +class TORCH_API SymmetricMemory : public c10::intrusive_ptr_target { + public: + ~SymmetricMemory() override = default; + + virtual std::vector get_buffer_ptrs() = 0; + virtual std::vector get_signal_pad_ptrs() = 0; + + // get_buffer_ptrs_dev() and get_signal_pad_ptrs_dev() each return a pointer + // to a device array of size world_size, containing buffer pointers and + // signal pad pointers, respectively. + virtual void** get_buffer_ptrs_dev() = 0; + virtual void** get_signal_pad_ptrs_dev() = 0; + virtual size_t get_buffer_size() = 0; + size_t get_signal_pad_size(); + + virtual size_t get_offset() { + TORCH_CHECK(false, "NYI"); + } + + virtual bool has_multicast_support() = 0; + virtual void* get_multicast_ptr() = 0; + + at::Tensor get_buffer( + int rank, + c10::IntArrayRef sizes, + c10::ScalarType dtype, + int64_t storage_offset); + + at::Tensor get_signal_pad( + int rank, + c10::IntArrayRef sizes, + std::optional dtype = std::nullopt, + int64_t storage_offset = 0); + + at::Tensor get_remote_tensor( + int peer, + c10::IntArrayRef sizes, + c10::ScalarType dtype); + + virtual void barrier(int channel, size_t timeout_ms) = 0; + virtual void put_signal(int dst_rank, int channel, size_t timeout_ms) = 0; + virtual void wait_signal(int src_rank, int channel, size_t timeout_ms) = 0; + + virtual int get_rank() = 0; + virtual int get_world_size() = 0; + virtual c10::Device get_device() = 0; + + virtual const std::vector& get_rank_to_global_rank() { + TORCH_CHECK(false, "NYI"); + } + + virtual int* get_rank_to_global_rank_dev() { + TORCH_CHECK(false, "NYI"); + } + + // Returns true if *all* peers within the group are accessible via direct + // memory load and store. + virtual bool world_within_direct_access() { + TORCH_CHECK(false, "NYI"); + } +}; + +class SymmetricMemoryAllocator : public c10::intrusive_ptr_target { + public: + ~SymmetricMemoryAllocator() override = default; + + virtual void* alloc( + size_t size, + int device_idx, + const std::optional& group_name) = 0; + + virtual void free(void* ptr) = 0; + virtual size_t get_alloc_size(void* ptr) = 0; + virtual c10::intrusive_ptr rendezvous( + void* ptr, + const std::optional& group_name) = 0; + virtual bool has_multicast_support(int device_idx) = 0; + virtual c10::DeviceType supported_device_type() = 0; + virtual std::string name() = 0; +}; + +C10_EXPORT bool is_finalizing(); + +C10_EXPORT void register_allocator( + c10::DeviceType device_type, + c10::intrusive_ptr allocator); + +C10_EXPORT void register_availability( + const std::string& name, + c10::intrusive_ptr allocator); + +C10_EXPORT bool has_allocator(c10::DeviceType device_type); + +C10_EXPORT c10::intrusive_ptr get_allocator( + c10::DeviceType device_type); + +// Set a store for rendezvousing symmetric allocations on a group of devices +// identified by `group_name`. The concept of groups is logical; users can +// utilize predefined groups (e.g., a group of device identified by a +// ProcessGroup) or create custom ones. Note that a SymmetricMemoryAllocator +// backends might employ a more efficient communication channel for the actual +// rendezvous process and only use the store for bootstrapping purposes. +TORCH_API void set_group_info( + const std::string& group_name, + int rank, + int world_size, + c10::intrusive_ptr store); + +struct GroupInfo { + int rank; + int world_size; + c10::intrusive_ptr store; + // Note this field is not automatically populated by set_group_info(). If a + // SymmetricMemory implementation needs to use it, it must be populated by a + // call to exchange_global_ranks() first. + std::vector rank_to_global_rank; +}; + +C10_EXPORT GroupInfo& get_group_info(const std::string& group_name); + +// Identical to empty_strided, but allows symmetric memory access to be +// established for the allocated tensor via SymmetricMemory::rendezvous(). This +// function itself is not a collective operation. It invokes +// SymmetricMemoryAllocator::alloc() for the requested device under the hood. +// +// NOTE [symmetric memory persistent allocation] +// If an `alloc_id` is supplied, empty_strided_p2p will perform persistent +// allocation. This makes the function cache allocated memory and ensure that +// invocations with the same `alloc_id` receive tensors backed by the same +// memory address. For safety, if a previous persistent allocation is still +// active (i.e., the storage of the returned tensor is still alive), persistent +// allocations with the same `alloc_id` will fail. This determinism coupled +// with memory planning of communication buffers (e.g., by Inductor) allows +// communication algorithms to reliably reuse previously established remote +// memory access. +TORCH_API at::Tensor empty_strided_p2p( + c10::IntArrayRef size, + c10::IntArrayRef stride, + c10::ScalarType dtype, + c10::Device device, + const std::optional& group_name, + std::optional alloc_id); + +// Establishes symmetric memory access on tensors allocated via +// empty_strided_p2p() and empty_strided_p2p_persistent(). rendezvous() is a +// one-time process, and the mapping between a local memory region and the +// associated SymmetricMemory object is unique. Subsequent calls to +// rendezvous() with the same tensor, or tensors allocated with +// empty_strided_p2p_persistent() using the same alloc_id, will receive the +// cached SymmetricMemory object. +// +// The function has a collective semantic and must be invoked simultaneously +// from all rendezvous participants. +TORCH_API c10::intrusive_ptr rendezvous( + const at::Tensor& tensor, + const std::optional& group_name = std::nullopt); + +TORCH_API bool has_multicast_support( + c10::DeviceType device_type, + int device_idx); + +TORCH_API void set_backend(const std::string& name); + +TORCH_API std::optional get_backend(c10::Device device); + +// Get the current signal pad size for symmetric memory allocations. +// Returns the user-configured size if set, otherwise returns the default size. +TORCH_API size_t get_signal_pad_size(); + +// Set the signal pad size for future symmetric memory allocations. +// This must be called before any symmetric memory allocations are made. +// The size should be proportional to the number of blocks the user launches +// and the world size. +TORCH_API void set_signal_pad_size(size_t size); + +C10_EXPORT void register_mempool_allocator( + c10::DeviceType device_type, + std::shared_ptr allocator); + +TORCH_API std::shared_ptr get_mempool_allocator( + c10::Device device); + +} // namespace c10d::symmetric_memory + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/env.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/env.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ec10b3d7f4a84d66f1bb54ce582c56155d7f9257 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/env.hpp @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace c10d::symmetric_memory { + +static int getenv_nblocks() { + static int num_blocks = -1; // Uninitialized + if (num_blocks == -1) { + auto str = c10::utils::get_env("TORCH_SYMMMEM_NBLOCKS"); + if (str.has_value()) { + num_blocks = std::stoi(str.value()); + } else { + num_blocks = -2; // Not set + } + } + return num_blocks; +} + +} // namespace c10d::symmetric_memory +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/intra_node_comm.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/intra_node_comm.hpp new file mode 100644 index 0000000000000000000000000000000000000000..28a07ea5936325b11d5f9295d3169e68e11e284f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/intra_node_comm.hpp @@ -0,0 +1,96 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace c10d::intra_node_comm { + +using namespace c10d::symmetric_memory; + +constexpr size_t kMaxDevices = 8; +constexpr size_t kDefaultBufferSize = 10ull * 1024 * 1024; + +using NvlMesh = std::array, kMaxDevices>; + +enum class Topology : uint8_t { + UNKNOWN = 0, + FULLY_CONNECTED = 1, +}; + +enum class AllReduceAlgo : uint8_t { + NONE = 0, + ONE_SHOT = 1, + TWO_SHOT = 2, +}; + +// NOTE: this class will be be removed soon in favor of SymmetricMemory +class TORCH_API IntraNodeComm : public c10::intrusive_ptr_target { + public: + IntraNodeComm( + c10::intrusive_ptr store, + size_t rank, + size_t worldSize, + std::optional bufferSize = std::nullopt); + + ~IntraNodeComm() override; + + static bool isEnabled(); + + /** + * Performs rendezvous. + * If rendezvous fails, the IntraNodeComm object will be in an invalid + * state and it is the caller's responsibility to dispose it. + */ + bool rendezvous(); + + /** + * Selects a AllReduceAlgo that we think will outperform nccl. + * Returns AllReduceAlgo::NONE if we don't think we can outperform nccl. + */ + AllReduceAlgo selectAllReduceAlgo(const at::Tensor& input); + + at::Tensor allReduce(const at::Tensor& input, AllReduceAlgo algo); + + private: + at::Tensor oneShotAllReduce( + const at::Tensor& input, + at::cuda::CUDAStream& stream); + + at::Tensor twoShotAllReduce( + const at::Tensor& input, + at::cuda::CUDAStream& stream); + + c10::intrusive_ptr store_; + size_t rank_; + size_t worldSize_; + size_t bufferSize_; + + /** + * Members initialized after rendezvous + */ + bool isInitialized_ = false; + int deviceIdx_{0}; + Topology topology_ = Topology::UNKNOWN; + void* symmetricMemoryPtr_ = nullptr; + c10::intrusive_ptr symmetricMemory_ = nullptr; +}; + +class IntraNodeCommWork : public c10d::Work { + public: + bool wait(std::chrono::milliseconds timeout = kNoTimeout) override { + return true; + } +}; + +TORCH_API int64_t getIntraNodeCommUsageCounter(); + +bool isIntraNodeCommSupported(); +} // namespace c10d::intra_node_comm + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/nvshmem_team_manager.hpp b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/nvshmem_team_manager.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6bf1ed77235da338723478a4868a1cb7a4379ba5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/nvshmem_team_manager.hpp @@ -0,0 +1,174 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// Starting from NVSHMEM 3.3.9, nvshmem_host.h exists so that we can cleanly +// include only the nvshmem host library headers: +// #include +// It translates into the following two lines: +#include +#include +// For maximum compatibility, we use the "host/" style for now. + +namespace c10d::nvshmem_extension { + +// This corresponds to max nblocks +constexpr int MAX_N_TEAMS = 128; + +// A pool of teams for each group. These are duplicate teams. +using TeamPool = std::vector; + +// Manage all the team business. Singleton. +class TeamManager { + public: + // Constructor + explicit TeamManager(const c10::Device device) : device_(device) {} + + // Get single, global manager. + static TeamManager& get(const c10::Device device) { + static TeamManager manager(device); + TORCH_CHECK( + manager.device_ == device, + "Detected use of TeamManager on multiple devices. This is not supported."); + return manager; + } + + // Get a team for a group. + nvshmem_team_t get_team( + const std::string& group_name, + const std::vector& global_ranks) { + auto [team_pool, pool_updated] = + group_to_team_pool(group_name, global_ranks, 1); + // Return the fist available team + return team_pool[0]; + } + + // Get n teams for a group. + // The first element of the returned pair is the team pool on host side. + // The second element of the returned pair is the team pool on device side. + // This API must be call with a device guard. + std::pair get_n_teams( + const std::string& group_name, + const std::vector& global_ranks, + const int need_n) { + // A device guard is required for malloc and memcpy below + c10::cuda::CUDAGuard guard(device_); + // Get the team pool with the requested number of teams + auto [team_pool, pool_updated] = + group_to_team_pool(group_name, global_ranks, need_n); + // Check if the pool already exists in device memory + nvshmem_team_t* team_pool_dev = nullptr; + constexpr auto pool_bytes = sizeof(nvshmem_team_t) * MAX_N_TEAMS; + auto it = team_pool_devptrs_.find(group_name); + if (it == team_pool_devptrs_.end()) { + // If not, allocate a new pool in device memory + team_pool_dev = reinterpret_cast( + c10::cuda::CUDACachingAllocator::raw_alloc(pool_bytes)); + team_pool_devptrs_[group_name] = team_pool_dev; + } else { + team_pool_dev = it->second; + } + // Update the pool in device memory if host side pool is updated + if (pool_updated) { + TORCH_INTERNAL_ASSERT(team_pool.size() == MAX_N_TEAMS); + auto stream = at::cuda::getCurrentCUDAStream(); + C10_CUDA_CHECK(cudaMemcpyAsync( + team_pool_dev, + team_pool.data(), + pool_bytes, + cudaMemcpyHostToDevice, + stream)); + } + return std::make_pair(std::cref(team_pool), team_pool_dev); + } + + ~TeamManager() noexcept { + // Free the team pools in device memory + // Note that we do it in a best effort manner because the team pool is + // managed by a static TeamManager and the destruction order of static + // objects is undetermined. If the destructor is called after the CUDA + // context is destroyed, cudaFree would fail. + try { + // cudaFree generally implies a device synchronization, meaning it will + // block until all preceding CUDA operations on the device have completed + // before freeing the memory. Thus we don't need to worry about freeing + // the memory before CUDA kernels complete. + for (auto& [_, team_pool_dev] : team_pool_devptrs_) { + c10::cuda::CUDACachingAllocator::raw_delete(team_pool_dev); + } + } catch (...) { + // Ignore the error + std::cerr << "Failed to free the team pool in device memory, skipping\n"; + } + } + + private: + // Get the team pool for a group. If the pool doesn't exist, create it. If the + // pool exists but is not large enough, create more teams. + // The first element of the returned pair is the team pool on host side. + // The second element of the returned pair is a boolean indicating if the pool + // is updated. + std::pair group_to_team_pool( + const std::string& group_name, + const std::vector& global_ranks, + const int need_n) { + TORCH_CHECK(need_n < MAX_N_TEAMS, "Too many teams requested"); + // Guarding the NVSHMEM API calls below just to be safe + c10::cuda::CUDAGuard guard(device_); + + // Insert a new team pool if not exists + auto [it, inserted] = group_name_to_team_pool_.emplace( + group_name, TeamPool(MAX_N_TEAMS, NVSHMEM_TEAM_INVALID)); + auto& team_pool = it->second; + bool pool_updated = inserted; + + // Create new teams if what's requested is more than what we have + int stride = 0; // stride in globe, uninitialized + for (int i = 0; i < need_n; ++i) { + if (team_pool[i] != NVSHMEM_TEAM_INVALID) { + continue; + } + // Some checks before we create new teams + if (stride == 0) { // Check only once + TORCH_CHECK(global_ranks.size() > 1); + stride = global_ranks[1] - global_ranks[0]; + for (size_t r = 1; r < global_ranks.size(); ++r) { + TORCH_CHECK(global_ranks[r] - global_ranks[r - 1] == stride); + } + } + nvshmem_team_t team = NVSHMEM_TEAM_INVALID; + nvshmem_team_split_strided( + NVSHMEM_TEAM_WORLD, + global_ranks[0], + stride, + global_ranks.size(), + nullptr, + 0, + &team); + TORCH_CHECK(team != NVSHMEM_TEAM_INVALID, "Failed to create a new team"); + team_pool[i] = team; + pool_updated = true; + } + return std::make_pair(std::cref(team_pool), pool_updated); + } + + private: + // Device where the team manager is created + const c10::Device device_; + // A map from group name to team pool for that group. + std::unordered_map group_name_to_team_pool_; + // A map from group name to team pool array in device memory. + std::unordered_map team_pool_devptrs_; +}; + +} // namespace c10d::nvshmem_extension +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/python_placement.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/python_placement.h new file mode 100644 index 0000000000000000000000000000000000000000..a15d330768b9788f18b96b6620c750ab0abdf9da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/python_placement.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed { +void initPlacementBindings(PyObject* module); +} // namespace torch::distributed + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..25f915f21a7cc914b352ba4b8208e3ce4617d9a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h @@ -0,0 +1,47 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::rpc { + +// All RPC peers should call into this function at the same time. Each peer +// provides its own id and name, and this function uses the given Store to +// gather global name-to-id mapping on all peers. +TORCH_API std::unordered_map collectNames( + ::c10d::PrefixStore store, + const worker_id_t selfId, + const std::string& selfName, + const int worldSize); + +// Ranks in dynamic RPC groups will initially call into this to establish the +// name-to-id mapping for the current peers in the group. The current rank will +// put its own worker info in the store and discover all the ranks that came +// before it. NOTE: This needs to be called with the Dynamic RPC group +// membership management token held. +TORCH_API std::unordered_map collectCurrentNames( + ::c10d::PrefixStore store, + const worker_id_t selfId, + const std::string& selfName); + +// Remove name from Store, used in dynamic RPC groups. +// NOTE: This needs to be called with the Dynamic RPC group +// membership management token held. +TORCH_API void removeCurrentName( + ::c10d::PrefixStore store, + const worker_id_t selfId, + const std::string& selfName); + +// This performs a synchronization of all call counts by using store. +// All RPC peers wait for others to join to exit at the same time. +TORCH_API int syncCallCount( + ::c10d::PrefixStore store, + const int worldSize, + int activeCalls = 0); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/message.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/message.h new file mode 100644 index 0000000000000000000000000000000000000000..f6e71490f27f885d1a2e4e897a29fe50a1cb0ea5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/message.h @@ -0,0 +1,198 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::rpc { + +// An enum denoting common RPC errors to allow specific error handling for them. +// NOLINTNEXTLINE(performance-enum-size) +enum RPCErrorType { + UNKNOWN_ERROR = 0, /* Indicates that error type could not be parsed */ + TIMEOUT = 1, /* Indicates that the RPC has timed out */ + INTENTIONAL_FAILURE = 2 /* Deliberate failure, such as those injected by + FaultyAgent for testing */ +}; + +// The enum values are bitwise ORed with MessageType +// They are bit flags starting from 0x100 and should have +// value such as 0x100, 0x200, 0x400, 0x800, 0xF00, etc. +// NOLINTNEXTLINE(performance-enum-size) +enum MessageTypeFlags { + REQUEST_TYPE = 0x100, + RESPONSE_TYPE = 0x200, +}; + +// Message types must have values between 0x00 to 0xff +// NOLINTNEXTLINE(performance-enum-size) +enum MessageType { + // messages for dist.rpc on builtin operators + SCRIPT_CALL = 0x00 | MessageTypeFlags::REQUEST_TYPE, + SCRIPT_RET = 0x01 | MessageTypeFlags::RESPONSE_TYPE, + + // messages for dist.rpc on Python UDF + PYTHON_CALL = 0x02 | MessageTypeFlags::REQUEST_TYPE, + PYTHON_RET = 0x03 | MessageTypeFlags::RESPONSE_TYPE, + + // messages for dist.remote on builtin operators and Python UDF + SCRIPT_REMOTE_CALL = 0x04 | + MessageTypeFlags::REQUEST_TYPE, // A remote call on a builtin operator + PYTHON_REMOTE_CALL = + 0x05 | MessageTypeFlags::REQUEST_TYPE, // A remote call on a Python UDF + REMOTE_RET = + 0x06 | MessageTypeFlags::RESPONSE_TYPE, // Response for remote calls for + // UDF, builtin, or script + + // RRef related internal messages + SCRIPT_RREF_FETCH_CALL = + 0x07 | MessageTypeFlags::REQUEST_TYPE, // A UserRRef fetches value + // from owner + PYTHON_RREF_FETCH_CALL = + 0x08 | MessageTypeFlags::REQUEST_TYPE, // A UserRRef fetches + // value from owner + SCRIPT_RREF_FETCH_RET = 0x09 | + MessageTypeFlags::RESPONSE_TYPE, // An OwnerRRef sends ivalue to user + PYTHON_RREF_FETCH_RET = 0x0a | + MessageTypeFlags::RESPONSE_TYPE, // An OwnerRRef sends py::object to user + RREF_USER_DELETE = 0x0b | + MessageTypeFlags::REQUEST_TYPE, // A UserRRef tells the owner to deref + RREF_FORK_REQUEST = + 0x0c | MessageTypeFlags::REQUEST_TYPE, // A child UserRRef tells the owner + // about itself + RREF_CHILD_ACCEPT = + 0x0d | MessageTypeFlags::REQUEST_TYPE, // A child UserRRef tells parent + // that owner knows it + RREF_ACK = + 0x0e | MessageTypeFlags::RESPONSE_TYPE, // ACK to internal RRef messages + + // Messages with autograd info + FORWARD_AUTOGRAD_REQ = 0x0f | MessageTypeFlags::REQUEST_TYPE, + FORWARD_AUTOGRAD_RESP = 0x10 | MessageTypeFlags::RESPONSE_TYPE, + + // Messages to propagate gradients on the backward pass. + BACKWARD_AUTOGRAD_REQ = 0x11 | MessageTypeFlags::REQUEST_TYPE, + BACKWARD_AUTOGRAD_RESP = 0x12 | MessageTypeFlags::RESPONSE_TYPE, + + // Messages to tell workers to clean up their autograd context. + CLEANUP_AUTOGRAD_CONTEXT_REQ = 0x13 | MessageTypeFlags::REQUEST_TYPE, + CLEANUP_AUTOGRAD_CONTEXT_RESP = 0x14 | MessageTypeFlags::RESPONSE_TYPE, + + // Messages that tell workers to run requests with profiling enabled. + RUN_WITH_PROFILING_REQ = 0x15 | MessageTypeFlags::REQUEST_TYPE, + RUN_WITH_PROFILING_RESP = 0x16 | MessageTypeFlags::RESPONSE_TYPE, + + // Messages to support RRef.backward(). + RREF_BACKWARD_REQ = 0x17 | MessageTypeFlags::REQUEST_TYPE, + RREF_BACKWARD_RESP = 0x18 | MessageTypeFlags::RESPONSE_TYPE, + + // Other internal message types + EXCEPTION = 0x37 | MessageTypeFlags::RESPONSE_TYPE, + UNKNOWN = 0x3c +}; + +// A message to be sent/received by an RpcAgent. +// +// A Message object contains 4 fields: +// payload (std::vector): a binary chunk of data. +// tensors (std::vector): all tensors. Tensor data are not +// included in the payload, and it is up to the RpcAgent implementation +// to determine how to serialize them. This design is helpful for +// communicating super large tensors where serializing all the data at +// once leads to excessively large memory footprint. An implementation +// can then serialize and send tensors chunk-by-chunk, in the streaming +// fashion. +// type (MessageType): type of the message. +// id (int64_t): message id, this is used to match request and response. +// Other implementation can ignore it if they have their own +// ways to do matching. +// +// Layers above ``RpcAgent`` only converts ScriptCall, ScriptResp, PythonCall, +// and PythonResp into a Message, and it is up to the RpcAgent +// implementation to determine how to serialize a message. +class TORCH_API Message final : public torch::CustomClassHolder { + private: + // Keep these private in order to force users to go through make_intrusive and + // thus prevent creating a Message that's not held by an intrusive_ptr. + Message(); + + Message( + std::vector&& payload, + std::vector&& tensors, + MessageType type); + + Message( + std::vector&& payload, + std::vector&& tensors, + MessageType type, + int64_t id); + + friend c10::intrusive_ptr; + + public: + Message(const Message& other) = delete; + Message(Message&& other) = delete; + Message& operator=(Message const& rhs) = delete; + Message& operator=(Message&& rhs) = delete; + ~Message() override = default; + + // Destructively retrieves the payload. + std::vector&& movePayload() &&; + std::vector&& moveTensors() &&; + + std::vector& payload(); + const std::vector& payload() const; + std::vector& tensors(); + const std::vector& tensors() const; + MessageType type() const; + + bool isRequest() const; + bool isResponse() const; + bool isShutdown() const; + + // id is an optional field to match request/response. If an RpcAgent + // implementation is able to do the matching without using this id, it can be + // dropped during message serialization. + int64_t id() const; + void setId(int64_t id); + + std::vector> getStorages() const; + + private: + std::vector payload_; + std::vector tensors_; + MessageType type_ = MessageType::UNKNOWN; + int64_t id_ = -1; +}; + +// Create a response Message of type Exception. +// The exception string representation will be used as the message's payload. +// A message ID corresponding to the request that resulted in this response can +// be provided for matching requests/responses. +TORCH_API c10::intrusive_ptr createExceptionResponse( + const std::exception& e, + int64_t id); + +// Create a response Message of type Exception. +// The passed in string representation will be used as the message's payload. +// A message ID corresponding to the request that resulted in this response can +// be provided for matching requests/responses. +TORCH_API c10::intrusive_ptr createExceptionResponse( + const std::string& exceptionStr, + int64_t id); + +inline std::tuple< + c10::intrusive_ptr, + std::vector>> +withStorages(c10::intrusive_ptr message) { + auto storages = message->getStorages(); + return std::make_tuple(std::move(message), std::move(storages)); +} + +using JitFuture = c10::ivalue::Future; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h new file mode 100644 index 0000000000000000000000000000000000000000..d46a0e9be89a5957fd498fe2fbd17c7e02767e4b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h @@ -0,0 +1,45 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +namespace torch::distributed::rpc { +// All metrics are prefixed with the following key. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) +constexpr char kRpcMetricsKeyPrefix[] = "torch.distributed.rpc."; +// APIs for logging time-series metrics for RPC-based distributed +// training. Implementations of this class should provide thread safety so that +// metrics can be logged from multiple threads without the user needing to +// coordinate serialization. +class RpcMetricsHandler { + public: + // Accumulates the metric value specified by the name for purposes of + // computing aggregate statistics over time. + virtual void accumulateMetric(const std::string& name, double value) = 0; + // Increment a count for the metric given by the name. + virtual void incrementMetric(const std::string& name) = 0; + virtual ~RpcMetricsHandler() = default; +}; + +// Configuration struct for metrics handling. +struct RpcMetricsConfig { + explicit RpcMetricsConfig(std::string handlerName, bool enabled) + : handlerName_(std::move(handlerName)), enabled_(enabled) {} + + // Handler name + std::string handlerName_; + // Whether metrics exporting should be enabled or not. + bool enabled_; +}; + +// A registry for different implementations of RpcMetricsHandler. Classes +// implementing the above interface should use this to register implementations. +TORCH_DECLARE_REGISTRY( + RpcMetricsHandlerRegistry, + torch::distributed::rpc::RpcMetricsHandler); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..ba39ea8a02305f64f642b6927ee43b35459d10b8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h @@ -0,0 +1,60 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { +extern const std::string REMOTE_PROFILING_KEY_PREFIX; + +class TORCH_API RemoteProfilerManager { + public: + // Retrieves the lazily-initialized RemoteProfilerManager singleton instance. + static RemoteProfilerManager& getInstance(); + // Sets the current, thread-local profiling key. + void setCurrentKey(std::string key); + // Returns whether the current profiling key is set. + bool isCurrentKeySet() const; + // Unsets the current, thread-local profiling key to allow other RPCs to reset + // it. + void unsetCurrentKey(); + // inserts a pair (globallyUniqueId, key) to an in-memory map. The + // corresponding ID is used in RPC deserialization to prefix remotely profiled + // events with the right key. + void saveRPCKey( + ProfilingId globallyUniqueId, + const std::string& rpcProfilingKey); + // Retrieves the profiling key corresponding to the given globallyUniqueId. + // Throws if it is not found. + std::string retrieveRPCProfilingKey(const ProfilingId& globallyUniqueId); + // Generates the next globally unique ID for profiling. + ProfilingId getNextProfilerId(); + // Retrieves the currently set thread-local profiling key. Throws if it is not + // set. + std::string& getCurrentProfilingKey(); + // erases the globallyUniqueId from the map. This can help save memory in the + // case that many RPCs are being profiled. + void eraseKey(const ProfilingId& globallyUniqueId); + + RemoteProfilerManager(const RemoteProfilerManager& other) = delete; + RemoteProfilerManager operator=(const RemoteProfilerManager& other) = delete; + RemoteProfilerManager(RemoteProfilerManager&&) = delete; + RemoteProfilerManager& operator=(RemoteProfilerManager&&) = delete; + + private: + RemoteProfilerManager(); + ~RemoteProfilerManager() = default; + local_id_t getNextLocalId(); + std::unordered_map + profiledRpcKeys_; + static thread_local std::optional currentThreadLocalKey_; + std::mutex mutex_; + local_id_t currentLocalId_; +}; +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h new file mode 100644 index 0000000000000000000000000000000000000000..f86461f6f895bee8a46b54b9f57dd88b66362ad6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h @@ -0,0 +1,134 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::distributed::rpc::profiler::processglobal { + +using namespace torch::autograd::profiler; + +// Process global profiler state. +// +// This class holds information about a profiling range, from "enable" to +// "disable". +// An instance of this ``State`` will be +// pushed into a global stack, so nested profiling range is supported. +// +// It has 2 members. +// One is ``autograd::profiler::ProfilerConfig``. It's set by user and +// will be copied to thread-local profiler state of RPC threads. +// The other is a container that aggregates recorded +// ``autograd::profiler::Event``s from all thread-local profilers on RPC +// threads. +class State { + public: + explicit State(ProfilerConfig config) : config_(std::move(config)) {} + ~State() = default; + + const ProfilerConfig& config() const { + return config_; + } + + void pushResult(thread_event_lists result) { + std::unique_lock lock(resultsMutex_); + + // NB: When a thread wants to push an entry into the this container, + // main control logic might have exited the process-global profile range. + results_.emplace_back(std::move(result)); + } + + std::vector results(); + + private: + // Each result comes from a profile range. In each profile range, there is a + // "__profiler_start" marker event that all following events calculate time + // relative to it, so it's required to call + // parse_cpu_trace(result) for results of all profile range. + std::mutex resultsMutex_; + std::vector results_; + const ProfilerConfig config_ = ProfilerConfig(ProfilerState::Disabled); +}; + +class StateStackEntry; + +#if defined(__MACH__) +// Compiler error: 'shared_timed_mutex' is unavailable: introduced in +// macOS 10.12 +using mutexType = std::mutex; +// Compiler error: 'shared_lock' is unavailable: introduced in +// macOS 10.12 +using rLockType = std::unique_lock; +using wLockType = std::unique_lock; +#else +using mutexType = std::shared_timed_mutex; +using rLockType = std::shared_lock; +using wLockType = std::unique_lock; +#endif + +// This is the global stack of ``State``s. +TORCH_API extern std::shared_ptr currentStateStackEntryPtr; +TORCH_API extern mutexType currentStateStackEntryMutex; + +// This class is used to implement a stack of ``State``s. +// It has 2 members. +// One is `prevPtr`, a shared_ptr pointing to previous element in the +// stack. +// The other is ``statePtr``, a shared_ptr pointing to ``State``. +class StateStackEntry { + public: + StateStackEntry( + std::shared_ptr prevPtr, + std::shared_ptr statePtr) + : prevPtr_(std::move(prevPtr)), statePtr_(std::move(statePtr)) {} + + static void pushRange(std::shared_ptr profilerProcessGlobalStatePtr); + static std::shared_ptr popRange(); + + static std::shared_ptr current() { + rLockType rlock(currentStateStackEntryMutex); + + return currentStateStackEntryPtr; + } + + std::shared_ptr prevPtr() const { + return prevPtr_; + } + + std::shared_ptr statePtr() const { + return statePtr_; + } + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::shared_ptr prevPtr_{nullptr}; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::shared_ptr statePtr_{nullptr}; +}; + +// Push the result to ``State``s of current profile range and recursively outer +// profile ranges. +TORCH_API void pushResultRecursive( + std::shared_ptr stateStackEntryPtr, + const thread_event_lists& result); + +// User-facing API. +// +// Enter a server-side process-global profiling range. +// Profiling range can be neste, so it's ok to call this API for multiple +// times. This enables all RPC threads running server-side request callbacks. +TORCH_API void enableServer(const ProfilerConfig& new_config); +// +// Exit a server-side process-global profiling range. +// Profiling range can be neste, so it's possible that profiler is still on +// after calling this API. +// This enables all RPC threads running server-side request callbacks. +TORCH_API std::vector disableServer(); + +} // namespace torch::distributed::rpc::profiler::processglobal + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/py_rref.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/py_rref.h new file mode 100644 index 0000000000000000000000000000000000000000..c5735e844b6e1f62dbfc779a76db78857e111593 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/py_rref.h @@ -0,0 +1,86 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::distributed::rpc { + +// NOLINTNEXTLINE(performance-enum-size) +enum RRefProxyType { RPC_SYNC, RPC_ASYNC, REMOTE }; + +// Python wrapper of an RRef shared_ptr that supports Python +// pickle and unpickle. +class PYBIND11_EXPORT PyRRef { + public: + // The first ctor can only be called while holding GIL. See its implementation + // for more explanations. + explicit PyRRef(const py::object& value, const py::object& type_hint); + explicit PyRRef(c10::intrusive_ptr rref); + PyRRef(const PyRRef&) = default; + ~PyRRef(); + + bool isOwner() const; + bool confirmedByOwner() const; + WorkerInfo owner() const; + std::string ownerName() const; + py::object toHere( + const float timeoutSeconds = + torch::distributed::rpc::kUnsetRpcTimeout) const; + py::object localValue() const; + std::string str() const; + py::tuple pickle() const; + static PyRRef unpickle(const py::tuple& t); + c10::IValue toIValue() const; + // Future that is associated with the creation of this RRef on the remote end. + // This is only used to get the future corresponding to the rref for profiling + // use cases. + c10::intrusive_ptr getFuture() const; + // Keeps track of the future responsible for profiling owner creation + // acknowledgement + c10::intrusive_ptr getProfilingFuture() const; + // Sets the future responsible for profiling owner creation acknowledgement. + // This future is set from python to be a future that returns when profiling + // callbacks have been run. + void setProfilingFuture(c10::intrusive_ptr profilingFuture); + + // create a proxy on this RRef, which can be used to launch RPC on the owner + // of this RRef to run functions on the object referenced by this RRef. + py::object createRRefProxy( + const RRefProxyType& mode, + float timeoutSeconds = rpc::kUnsetRpcTimeout) const; + + // get the type of the data object referenced by this RRef. Timeout argument + // is only used in the first invocation of this function as an argument to the + // RPC to the owner node of the RRef. + py::object getRRefType( + float timeout = rpc::kUnsetRpcTimeout, + bool blocking = true); + + // Run the backward pass with the RRef as the root. + void backward(int64_t autogradContextId, bool retainGraph); + + // Helper static function to run backward on a given rref. + static void backward( + int64_t autogradContextId, + bool retainGraph, + const c10::intrusive_ptr& rref); + + // Specialization of backward if the rref is an OwnerRRef. + static void backwardOwnerRRef( + int64_t autogradContextId, + bool retainGraph, + IValue value); + + private: + c10::intrusive_ptr rref_; + std::optional> profilingFuture_; + std::optional type_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h new file mode 100644 index 0000000000000000000000000000000000000000..ea339cae11b4dedb5a2aefa2b702443bc53708a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::rpc { + +// RPC call representing calling a Python function over RPC. +class TORCH_API PythonCall final : public RpcCommandBase { + public: + PythonCall(SerializedPyObj&& serializedPyObj, bool isAsyncExecution); + + c10::intrusive_ptr toMessageImpl() && override; + + static std::unique_ptr fromMessage(const Message& message); + + const SerializedPyObj& serializedPyObj() const; + + inline bool isAsyncExecution() const { + return isAsyncExecution_; + } + + private: + SerializedPyObj serializedPyObj_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isAsyncExecution_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..ba69781bdcb0a200b52d30da80cabeb52ff8608d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h @@ -0,0 +1,71 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// Converts an internal ivalue::Future of Message into a user-facing +// ivalue::Future of py::object type by creating a new ivalue::Future and call +// its markCompleted as a callback in the given ivalue::Future. +// If hasValue is true, the Message will be converted into a py::object and then +// wrap it with an IValue. If hasValue is false, this ivalue::Future is only +// used for signaling and launching callbacks. In this case, the message will be +// discarded and then set the ivalue::Future using an empty IValue or the given +// FutureError if there is an error. +c10::intrusive_ptr toPyJitFuture( + const c10::intrusive_ptr& messageJitFuture, + bool hasValue = true); + +c10::intrusive_ptr pyRpcBuiltin( + const WorkerInfo& dst, + const std::string& opName, + const py::args& args, + const py::kwargs& kwargs, + const float rpcTimeoutSeconds); + +c10::intrusive_ptr pyRpcPythonUdf( + const WorkerInfo& dst, + std::string& pickledPythonUDF, + std::vector& tensors, + const float rpcTimeoutSeconds, + const bool isAsyncExecution); + +c10::intrusive_ptr pyRpcTorchscript( + const std::string& dstWorkerName, + const std::string& qualifiedNameStr, + const py::tuple& argsTuple, + const py::dict& kwargsDict, + const float rpcTimeoutSeconds, + const bool isAsyncExecution); + +PyRRef pyRemoteBuiltin( + const WorkerInfo& dst, + const std::string& opName, + const float rpcTimeoutSeconds, + const py::args& args, + const py::kwargs& kwargs); + +PyRRef pyRemotePythonUdf( + const WorkerInfo& dst, + std::string& pickledPythonUDF, + std::vector& tensors, + const float rpcTimeoutSeconds, + const bool isAsyncExecution); + +PyRRef pyRemoteTorchscript( + const std::string& dstWorkerName, + const std::string& qualifiedNameStr, + const float rpcTimeoutSeconds, + const bool isAsyncExecution, + const py::args& args, + const py::kwargs& kwargs); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h new file mode 100644 index 0000000000000000000000000000000000000000..b34cb40349850c4c643e9e5d899b53293f220a2b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +namespace torch::distributed::rpc { + +class TORCH_API PythonRemoteCall : public RpcCommandBase { + public: + PythonRemoteCall( + SerializedPyObj&& serializedPyObj, + at::IValue retRRefId, + at::IValue retForkId, + const bool isAsyncExecution); + + inline const SerializedPyObj& serializedPyObj() const { + return serializedPyObj_; + } + + inline const at::IValue& retRRefId() const { + return retRRefId_; + } + + inline const at::IValue& retForkId() const { + return retForkId_; + } + + inline bool isAsyncExecution() const { + return isAsyncExecution_; + } + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); + + private: + SerializedPyObj serializedPyObj_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const at::IValue retRRefId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const at::IValue retForkId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isAsyncExecution_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h new file mode 100644 index 0000000000000000000000000000000000000000..cc47fbe631a219bcd16a847d1bb849fa812068cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::rpc { + +// RPC call representing the response of a Python UDF over RPC. +class TORCH_API PythonResp final : public RpcCommandBase { + public: + explicit PythonResp(SerializedPyObj&& serializedPyObj); + + c10::intrusive_ptr toMessageImpl() && override; + + static std::unique_ptr fromMessage(const Message& message); + + const SerializedPyObj& serializedPyObj() const; + + private: + SerializedPyObj serializedPyObj_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..8de1c7d7592e448f541f2a3f03b1a0f9b9a5f2ec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h @@ -0,0 +1,134 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// Singleton class provides interface to execute python UDF remote call +// and deserialize the returned results by running python function +// in internal_rpc_utilities. +// The singleton object is constructed at first when RPC agent is +// constructed, where the python function in +// torch/distributed/internal_rpc_utils.py are imported only once. +class PYBIND11_EXPORT PythonRpcHandler { + public: + struct RRefProxyFunctions { + py::object rrefProxyCtor_; + py::object rpcSync_; + py::object rpcAsync_; + py::object remote_; + }; + + struct RRefTypeFunctions { + py::object onOwner_; + py::object onUser_; + }; + + static PythonRpcHandler& getInstance(); + + // Run a pickled Python UDF and return the result py::object + py::object runPythonUdf(const py::object& pythonUdf); + + // Serialized a py::object into a string + SerializedPyObj serialize(const py::object& obj); + + // Deserialize a string into a py::object + py::object deserialize(const SerializedPyObj& serializedObj); + + // Check if obj is RemoteException, then throw it + void handleException(const py::object& obj); + // Alternative if the caller is already holding the GIL. + void handleExceptionGILHeld(const py::object& obj); + // Check if obj is an RemoteException instance. + bool isRemoteException(const py::object& obj); + + // Explicitly clean up py::objects to avoid segment faults when + // py::objects with CPython are cleaned up later at program exit + // See similar issues reported https://github.com/pybind/pybind11/issues/1598 + // and https://github.com/pybind/pybind11/issues/1493 + // Our local tests also caught this segment faults if py::objects are cleaned + // up at program exit. The explanation is: CPython cleans up most critical + // utilities before cleaning up PythonRpcHandler singleton, so when + // PythonRpcHandler singleton cleans up py::objects and call dec_ref(), it + // will crash. + // The solution is to clean up py::objects earlier when Rpc agent join(). + // Be note that py::objects can not be cleaned up when Rpc agent is destroyed + // as well, as Rpc agent is global variable and it will have same issue as + // PythonRpcHandler. + void cleanup(); + + std::shared_ptr jitCompilationUnit(); + + // Parse the string to recover the jit_type, this is used for RRef python + // pickling/unpickling type recovery. The type string inference rule is as + // follows: + // 1. first try to parse if this is primitive types. + // i.e. TensorType, IntType, PyObjectType, etc. + // 2. if not primitive type, we query the python_cu to see if it is a + // class type or interface type registered in python + // We use a ScriptTypeParser instance with custom PythonTypeResolver + // to resolve types according to the above rules. + TypePtr parseTypeFromStr(const std::string& typeStr); + + // Return a set of Python functions for RRef helpers. + const RRefProxyFunctions& getRRefProxyFunctions() const; + + // Return a set of Python functions to retrieve the type of the object + // referenced by a given RRef. + const RRefTypeFunctions& getRRefTypeFunctions() const; + + PythonRpcHandler(const PythonRpcHandler&) = delete; + PythonRpcHandler& operator=(const PythonRpcHandler&) = delete; + PythonRpcHandler(PythonRpcHandler&&) = delete; + PythonRpcHandler& operator=(PythonRpcHandler&&) = delete; + + private: + void init(); + PythonRpcHandler(); + ~PythonRpcHandler() = default; + + // Ref to `torch.distributed.rpc.internal._run_function`. + py::object pyRunFunction_; + + // Ref to `torch.distributed.rpc.internal.serialize`. + py::object pySerialize_; + + // Ref to `torch.distributed.rpc.internal.deserialize`. + py::object pyDeserialize_; + + // Ref to 'torch.distributed.rpc.internal._handle_exception' + py::object pyHandleException_; + + // Python functions for RRef proxy + RRefProxyFunctions rrefProxyFunctions_; + + // Ref to 'torch.distributed.rpc.api._rref_typeof_on_' + RRefTypeFunctions rrefTypeFunctions_; + + // Shared ptr to python compilation unit in jit, it is constructed in python + // side (see _python_cu = torch._C.CompilationUnit() in jit/__init__.py) + // and imported in C++ (see get_python_cu() in + // csrc/jit/python/pybind_utils.h). We import the compilation unit here only + // once for less cost and thread safety. + std::shared_ptr jitCompilationUnit_; + + // jit type parser to parse type_str back to TypePtr for RRef type + // recovery when pickling and unpickling RRef + std::shared_ptr typeParser_; + + // Indicates whether or not we have properly initialized the handler. + bool initialized_; + + // Lock to protect initialization. + std::mutex init_lock_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..f0b0a52371b27e14b530df19a47491337c856d63 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::rpc { + +// Functor which is invoked to process an RPC message. This is an abstract class +// with some common functionality across all request handlers. Users need to +// implement this interface to perform the actual business logic. +class TORCH_API RequestCallback { + public: + // Invoke the callback. + c10::intrusive_ptr operator()( + Message& request, + std::vector streams) const; + + virtual ~RequestCallback() = default; + + protected: + // RpcAgent implementation should invoke ``RequestCallback`` to process + // received requests. There is no restriction on the implementation's + // threading model. This function takes an rvalue reference of the Message + // object. It is expected to return the future to a response message or + // message containing an exception. Different rpc agent implementations are + // expected to ensure delivery of the response/exception based on their + // implementation specific mechanisms. + virtual c10::intrusive_ptr processMessage( + Message& request, + std::vector streams) const = 0; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..7bea64f4b19c05dec4201eead386978cf6a32c64 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h @@ -0,0 +1,66 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +class TORCH_API RequestCallbackImpl : public RequestCallbackNoPython { + public: + std::unique_ptr deserializePythonRpcCommand( + std::unique_ptr rpc, + const MessageType& messageType) const override; + + c10::intrusive_ptr processPythonCall( + RpcCommandBase& rpc, + const std::vector& streams) const override; + + c10::intrusive_ptr processScriptCall( + RpcCommandBase& rpc, + const std::vector& streams) const override; + + c10::intrusive_ptr processScriptRemoteCall( + RpcCommandBase& rpc, + const std::vector& streams) const override; + + c10::intrusive_ptr processPythonRemoteCall( + RpcCommandBase& rpc, + const std::vector& streams) const override; + + c10::intrusive_ptr processPythonRRefFetchCall( + RpcCommandBase& rpc) const override; + + void handleRRefDelete(c10::intrusive_ptr& rref) const override; + + c10::intrusive_ptr processRpcWithErrors( + RpcCommandBase& rpc, + const MessageType& messageType, + const std::vector& streams) const override; + + bool cudaAvailable() const override; + + c10::intrusive_ptr processRRefBackward( + RpcCommandBase& rpc) const override; + + // Helpers to run user-defined functions, operators and other computations. + + c10::intrusive_ptr runJitFunction( + const c10::QualifiedName& name, + std::vector& stack, + const std::vector& streams, + bool isAsyncExecution) const; + + c10::intrusive_ptr runPythonFunction( + const py::object& function, + const std::vector& streams, + bool isAsyncExecution) const; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h new file mode 100644 index 0000000000000000000000000000000000000000..e8632437b14fefed1c3de5c8ea390059c98c87a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h @@ -0,0 +1,120 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// RequestCallback implementation with no Python dependencies. +class TORCH_API RequestCallbackNoPython : public RequestCallback { + public: + c10::intrusive_ptr processMessage( + Message& request, + std::vector streams) const override; + + protected: + virtual std::unique_ptr deserializePythonRpcCommand( + std::unique_ptr rpc, + const MessageType& messageType) const; + + virtual c10::intrusive_ptr processScriptCall( + RpcCommandBase& rpc, + const std::vector& streams) const; + + virtual c10::intrusive_ptr processPythonCall( + RpcCommandBase& rpc, + const std::vector& streams) const; + + c10::intrusive_ptr assignOwnerRRef( + const RRefId& rrefId, + const RRefId& forkId, + const c10::intrusive_ptr& valueFuture) const; + + virtual c10::intrusive_ptr processScriptRemoteCall( + RpcCommandBase& rpc, + const std::vector& streams) const; + + virtual c10::intrusive_ptr processPythonRemoteCall( + RpcCommandBase& rpc, + const std::vector& streams) const; + + c10::intrusive_ptr retrieveOwnerRRef(const RRefId& rrefId) const; + + c10::intrusive_ptr processScriptRRefFetchCall( + RpcCommandBase& rpc) const; + + virtual c10::intrusive_ptr processPythonRRefFetchCall( + RpcCommandBase& rpc) const; + + c10::intrusive_ptr processRRefUserDelete( + RpcCommandBase& rpc) const; + + c10::intrusive_ptr processRRefChildAccept( + RpcCommandBase& rpc) const; + + c10::intrusive_ptr processRRefForkRequest( + RpcCommandBase& rpc) const; + + c10::intrusive_ptr processForwardAutogradReq( + RpcCommandBase& rpc, + const std::vector& streams) const; + + c10::intrusive_ptr processBackwardAutogradReq( + RpcCommandBase& rpc, + const std::vector& streams) const; + + c10::intrusive_ptr processCleanupAutogradContextReq( + RpcCommandBase& rpc) const; + + c10::intrusive_ptr processRunWithProfilingReq( + RpcCommandBase& rpc) const; + + virtual void handleRRefDelete(c10::intrusive_ptr& rref) const; + + c10::intrusive_ptr processRpc( + RpcCommandBase& rpc, + const MessageType& messageType, + const std::vector& streams) const; + + virtual c10::intrusive_ptr processRpcWithErrors( + RpcCommandBase& rpc, + const MessageType& messageType, + const std::vector& streams) const; + + c10::intrusive_ptr handleError( + const std::exception& e, + const MessageType messageType, + int64_t messageId) const; + + virtual bool cudaAvailable() const; + + virtual c10::intrusive_ptr processRRefBackward( + RpcCommandBase& rpc) const; + + // Helpers to run user-defined functions, operators and other computations. + + c10::intrusive_ptr runJitOperator( + const jit::Operator& op, + std::vector& stack, + const std::vector& streams) const; + + // Helpers to convert various kinds of objects into already-completed futures. + + c10::intrusive_ptr asFuture(IValue value, TypePtr type) const; + + c10::intrusive_ptr asFuture( + c10::intrusive_ptr message) const; + + c10::intrusive_ptr asFuture(std::exception_ptr err) const; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h new file mode 100644 index 0000000000000000000000000000000000000000..9e0ced778117bcf6dc19a32b2a7fc90749172e88 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::rpc { + +PyMethodDef* python_functions(); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h new file mode 100644 index 0000000000000000000000000000000000000000..7ce5590994cca2b262f3015e183d36c616f69137 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h @@ -0,0 +1,345 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +using DeviceMap = std::unordered_map; + +// Default RPC timeout +constexpr float kDefaultRpcTimeoutSeconds = 60; +// Unset RPC timeout. This is the value agent::send() will have if user does not +// pass in a specific timeout, and indicates that we must use the default +// timeout for RPCs. +constexpr float kUnsetRpcTimeout = -1; +constexpr auto kDefaultInitMethod = "env://"; +constexpr float kSecToMsConversion = 1000; +constexpr auto kRpcTimeoutErrorStr = + "RPC ran for more than set timeout ({} ms) and will now be marked with an error"; +constexpr auto kDefaultNumWorkerThreads = 16; + +using steady_clock_time_point = + std::chrono::time_point; +// Input is qualified name string, output is JIT StrongTypePtr +// Same as jit::TypeResolver, did not import jit::TypeResolver to here +// because it could introduce cyclic dependencies. +using TypeResolver = + std::function; + +struct TORCH_API RpcBackendOptions { + RpcBackendOptions() + : RpcBackendOptions(kDefaultRpcTimeoutSeconds, kDefaultInitMethod) {} + + RpcBackendOptions(float rpcTimeoutSeconds, std::string initMethod) + : rpcTimeoutSeconds(rpcTimeoutSeconds), + initMethod(std::move(initMethod)) { + TORCH_CHECK(rpcTimeoutSeconds >= 0, "RPC Timeout must be non-negative"); + } + + float rpcTimeoutSeconds; + std::string initMethod; +}; + +// A globally unique ID to identify an RpcAgent +struct TORCH_API WorkerInfo : torch::CustomClassHolder { + WorkerInfo(std::string name, int64_t id); + + WorkerInfo(std::string name, worker_id_t id); + + bool operator==(const WorkerInfo& rhs) { + return (id_ == rhs.id_) && (name_ == rhs.name_); + } + + static constexpr size_t MAX_NAME_LEN = 128; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::string name_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const worker_id_t id_; +}; + +struct TORCH_API RegisterWorkerInfoOnce { + RegisterWorkerInfoOnce(); +}; + +TORCH_API std::ostream& operator<<( + std::ostream& os, + const WorkerInfo& workerInfo); + +// Struct for options to configure the RPC Retry protocol. +struct TORCH_API RpcRetryOptions { + // Using a default constructor like all other Options structs in the RPC + // codebase. TORCH_CHECKs for input validation are done in the + // sendWithRetries function. + RpcRetryOptions() = default; + // Maximum number of times we will retry the RPC + int maxRetries{5}; + // Initial duration between consecutive RPC send attempts + std::chrono::milliseconds rpcRetryDuration{std::chrono::milliseconds(1000)}; + // Constant for exponential backoff used while calculating future wait + // durations + float retryBackoff{1.5}; +}; + +// Struct that stores all the metadata needed to retry a given RPC. +struct TORCH_API RpcRetryInfo { + RpcRetryInfo( + const WorkerInfo& to, + c10::intrusive_ptr message, + c10::intrusive_ptr originalFuture, + int retryCount, + RpcRetryOptions options) + : to_(to), + message_(std::move(message)), + originalFuture_(std::move(originalFuture)), + retryCount_(retryCount), + options_(options) {} + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const WorkerInfo& to_; + c10::intrusive_ptr message_; + // Future that is returned to the caller of sendWithRetries(). + c10::intrusive_ptr originalFuture_; + // Number of send attempts completed so far. + int retryCount_; + RpcRetryOptions options_; +}; + +// ``RpcAgent`` is the base class for sending and receiving RPC messages. It +// provides a unified ``send`` API for both request and response messages, and +// will invoke the given ``RequestCallback`` to process received requests. It +// should immediately become ready to serve request and accept response after +// construction. +class TORCH_API RpcAgent { + public: + // `WorkerInfo` is the globally unique identifier for this RpcAgent instance. + // It contains a ``name_`` field and an ``id_`` field. ``name_`` is the + // globally unique name for this ``RpcAgent``. It is up to the ``RpcAgent`` + // implementation to determine how to resolve names. ``id_`` is the globally + // unique ID for this ``RpcAgent``. This should be determined by the + // ``RpcAgent`` implementation. + // The ``RequestCallback`` will be invoked to handle received requests. This + // ``RpcAgent`` base class makes no assumption on the thread-safeness of the + // ``RequestCallback``. ``RpcAgent`` implementations need to make sure that + // its threading model conform to ``RequestCallback``'s requirement. + // NB: RpcAgent implementations should not start serving requests until + // ``start()`` is called, as there could be other contexts that have not been + // initialized yet at this time. + RpcAgent( + WorkerInfo id, + std::unique_ptr cb, + std::chrono::milliseconds rpcTimeout); + + virtual ~RpcAgent(); + + // Send a message to the ``RpcAgent`` of id ``to`` and returns a + // ``JitFuture`` ptr. The implementation must be asynchronous, i.e., it + // cannot block until it receives the response. + // + // If ``message.isRequest()`` is true, the ``JitFuture`` will be + // completed when the response arrives. For other message types, the Future + // should be ignored by the caller. + virtual c10::intrusive_ptr send( + const WorkerInfo& to, + c10::intrusive_ptr message, + const float rpcTimeoutSeconds = kUnsetRpcTimeout, + const DeviceMap& deviceMap = {}) = 0; + + // Retries sending the message up to maxRetries times until an ACK is + // received. The duration between consecutive sends is increased over + // time using an exponential backoff algorithm. + // + // Sends ``message`` to the ``RpcAgent`` of id ``to`` and returns a + // ``JitFuture`` ptr, just like send(). Caller can specify the maximum + // number of retries for this RPC (default is 5), initial duration between + // sends (default is 1000ms), and backoff constant (default is 1.5) by + // passing in the RpcRetryOptions struct. This API might end up + // executing a method twice on the remote end (it does not guarantee + // exactly-once semantics). Therefore, the user must ensure their requests + // are idempotent. + c10::intrusive_ptr sendWithRetries( + const WorkerInfo& to, + c10::intrusive_ptr message, + RpcRetryOptions retryOptions = RpcRetryOptions()); + + // Return a reference to the ``WorkerInfo`` of this RpcAgent. + // NB: not using ``std::optional`` here because we might + // need to create a separate RPC API lib and avoid forcing all ``RpcAgent`` + // implementations to depend on libtorch. + const WorkerInfo& getWorkerInfo() const; + + // Return a reference to the ``WorkerInfo`` of the given ``workerName``. + virtual const WorkerInfo& getWorkerInfo( + const std::string& workerName) const = 0; + + virtual const WorkerInfo& getWorkerInfo(worker_id_t id) const = 0; + + virtual std::vector getWorkerInfos() const = 0; + + // Retrieve the timeout for all RPCs. + inline std::chrono::milliseconds getRpcTimeout() const { + return rpcTimeout_.load(); + } + + // Set the timeout for all RPCs + inline void setRpcTimeout(const std::chrono::milliseconds& rpcTimeout) { + rpcTimeout_.store(rpcTimeout); + } + + // Call sync and join all internal threads. This method should be called + // before every RPC process exits. + virtual void join(bool shutdown = false, float timeout = 0) = 0; + + // Synchronize the this process with other ``RpcAgent`` processes. Block until + // all ``RpcAgent``s reach this method and send all pending messages. + virtual void sync() = 0; + + // Sets up backend-agnostic state for accepting requests. Currently, this + // entails setting rpcAgentRunning_ to true, creating the retry thread, and + // calling the backend's startImpl. + void start(); + + // Derived classes must override this function to start accepting requests. + // This is used to initialize any backend-specific state. Users must call + // start, not startImpl, to initialize the RPC Agent. + virtual void startImpl() = 0; + + // Stop accepting requests and shutdown the RPC framework as soon as possible + // by terminating all RPC threads. + void shutdown(); + + // Derived classes must override this function to start accepting requests. + // THis is used to clean up any backend-specific state. Users must call + // shutdown, not shutdownImpl, to shutdown the RPC Agent. + virtual void shutdownImpl() = 0; + + // Check if current RPC agent is set. + static bool isCurrentRpcAgentSet(); + + // Retrieve the valid current RPC agent. + static std::shared_ptr getCurrentRpcAgent(); + + // Set the current RPC agent. + static void setCurrentRpcAgent(std::shared_ptr rpcAgent); + + // Retrieve metrics as KV map + virtual std::unordered_map getMetrics() = 0; + + // Retrieve debug info in addition to metrics as KV map + virtual std::unordered_map getDebugInfo(); + + // Flag to control whether GIL wait times + // should be profiled or not. + void enableGILProfiling(bool flag); + + // Retrieve whether we should profile GIL wait times or not. + bool isGILProfilingEnabled(); + + // Set type resolver that will be passed to JIT pickler to resolver type Ptr + // based on type str. + void setTypeResolver(std::shared_ptr typeResolver); + + // Get the type resolver + std::shared_ptr getTypeResolver(); + + // Retrieves the device map for the provided destination worker. + virtual DeviceMap getDeviceMap(const WorkerInfo& dst) const; + + // Retrieve the (non-CPU) devices that are supported by the agent. + virtual const std::vector& getDevices() const; + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const WorkerInfo workerInfo_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::unique_ptr cb_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::atomic rpcTimeout_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::atomic profilingEnabled_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr typeResolver_; + // Atomic boolean indicating whether this agent is running. It controls + // whether several background threads should be running. It is set in + // RpcAgent::start() and unset in the derived class shutdown(). + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::atomic rpcAgentRunning_; + + private: + static std::shared_ptr currentRpcAgent_; + // Add GIL wait time data point to metrics + virtual void addGilWaitTime(const std::chrono::microseconds gilWaitTime) = 0; + friend class PythonRpcHandler; + + // Map that stores metadata for RPC's that may need to be re-tried as well as + // the timepoint at which we should re-try them. + std::map< + steady_clock_time_point, + std::unordered_set>> + rpcRetryMap_; + + // Thread that checks for retryable RPC's in the rpcRetryMap_ and sleeps until + // the next unACKed RPC's timeout has expired. + std::thread rpcRetryThread_; + + // Function that rpcRetryThread_ calls in a loop as long as RpcAgent is + // running. + void retryExpiredRpcs(); + + // This is the callback attached to futures corresponding to send retries. + // This handles 3 cases: 1). send was completed, 2). send failed with an + // error and we've done maxRetries failed send attempts, and 3). send + // failed with an error and we have more retries to go. In case 1, we mark + // the original future as complete. In case 2, we mark the future with an + // error and do not retry again. In case 3, we move the RpcRetryInfo struct + // to another time point in the map to schedule the RPC for a future send. + void rpcRetryCallback( + JitFuture& message, + steady_clock_time_point newTime, + std::shared_ptr earliestRpc); + + // Function that uses the exponential backoff algorithm to compute the next + // time point to retry a given RPC. + inline steady_clock_time_point computeNewRpcRetryTime( + RpcRetryOptions& options, + int retryCount) { + // The exponential backoff algorithm being used here is: + // newTime = timeNow + (retryDuration * (backoffConstant ^ retryCount)). + std::chrono::milliseconds timedelta = + std::chrono::duration_cast( + options.rpcRetryDuration * pow(options.retryBackoff, retryCount)); + return std::chrono::time_point_cast( + std::chrono::steady_clock::now() + timedelta); + } + + // Condition Variable to signal when the rpcRetryMap_ has been populated. + std::condition_variable rpcRetryMapCV_; + + // Mutex to protect RpcRetryMap_. + std::mutex rpcRetryMutex_; +}; + +} // namespace torch::distributed::rpc + +namespace std { +template <> +struct hash { + std::size_t operator()( + const torch::distributed::rpc::WorkerInfo& worker_info) const noexcept { + return worker_info.id_; + } +}; +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h new file mode 100644 index 0000000000000000000000000000000000000000..2ea338813b121c913e1cd0d78fdf5dfe22c03bb1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::rpc { + +// Base class for all RPC request and responses. +class RpcCommandBase { + public: + // Need to override this to serialize the RPC. This should destructively + // create a message for the RPC (Hence the &&). + c10::intrusive_ptr toMessage() && { + JitRRefPickleGuard jitPickleGuard; + return std::move(*this).toMessageImpl(); + } + virtual c10::intrusive_ptr toMessageImpl() && = 0; + virtual ~RpcCommandBase() = 0; +}; + +inline RpcCommandBase::~RpcCommandBase() = default; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h new file mode 100644 index 0000000000000000000000000000000000000000..6f1703a51e6f67be61b2591e3728eda4da5d5566 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h @@ -0,0 +1,340 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::distributed::rpc { + +namespace callback { +// It's the callback for RemoteCall. +void TORCH_API +confirmPendingUser(const JitFuture& jitFuture, const ForkId& expectedForkId); + +// It's the callback for finishing creating owner rref, it returned deletedRRef, +// so that the deletedRRef can be handled under GIL in python_functions.cpp if +// deletedRRef contains python object. +c10::intrusive_ptr TORCH_API +finishCreatingOwnerRRef(const JitFuture& jitFuture, const RRefId& rrefId); +} // namespace callback + +// Manages RRef lifetime and keeps track of RRef forks. +class TORCH_API RRefContext { + public: + static RRefContext& getInstance(); + // NB: This method must be called before destructing RRefContext singleton. + // Similar to delForkOfOwner, this method returns a vector of OwnerRRefs that + // hold py::object. The call-site is also responsible for resetting those + // shared_ptr objects with a GIL. See comments at delForkOfOwner() for more + // details. + static std::vector> destroyInstance( + bool ignoreRRefLeak = true); + + static void handleException(const JitFuture& jitFuture); + + // handle exception without throw ::c10::Error again + static void handleExceptionSilent(const JitFuture& jitFuture); + + RRefContext(const RRefContext&) = delete; + RRefContext(RRefContext&& other) = delete; + void operator=(const RRefContext&) = delete; + RRefContext& operator=(RRefContext&& other) = delete; + + ~RRefContext(); + + // get the worker id of the current worker + inline worker_id_t getWorkerId() const { + return agent_->getWorkerInfo().id_; + } + + // get the worker name of the current worker + inline const std::string& getWorkerName() const { + return agent_->getWorkerInfo().name_; + } + + // generate a globally unique ID + inline GloballyUniqueId genGloballyUniqueId() { + return GloballyUniqueId(getWorkerId(), nextLocalId_++); + } + + inline const std::shared_ptr& agent() const { + return agent_; + } + + // create a ``UserRRef`` owned by the worker ``ownerId`` + c10::intrusive_ptr createUserRRef( + worker_id_t ownerId, + const TypePtr& type); + + // Convert an RRefForkData into an RRef. This RRef could be user or owner. + // This RRef could have already existed before, or could be created in this + // method, we pass type here to validate or help the rref creation. + c10::intrusive_ptr getOrCreateRRef( + const RRefForkData& rfd, + const TypePtr& type); + + // Get the ``OwnerRRef`` of id ``rrefId``. If it does not exist, create a new + // one. This function is called in two places: + // 1. when processing ``rpc.remote()``, i.e., ``SCRIPT_REMOTE_CALL`` + // ``PYTHON_REMOTE_CALL``. + // 2. when unpickling ``OwnerRRef``. + // What's common in these two cases are, 1) the RRefId is already generated + // 2) the TypePtr is presented. So it can always create the ``OwnerRRef`` if + // it is not yet available. + c10::intrusive_ptr getOrCreateOwnerRRef( + const RRefId& rrefId, + const TypePtr& type); + + // Create an empty owner rref of type. + // This method is called to first time generate an ``OwnerRRef``, e.g., + // 1) ``rpc.RRef(obj)`` + // 2) create the ``OwnerRRef`` on `rpc.remote()` caller side. + // What's common in these two cases are, 1) the RRefId hasn't been generated + // 2) the TypePtr is presented. + c10::intrusive_ptr createOwnerRRef(const TypePtr& type); + + // Returns a Future of the OwnerRRef, which will be marked completed when + // ``OwnerRRef`` is created. This method is used when the TypePtr is not + // available, e.g., when processing to_here(). The forceCreated flag can be + // used to ensure that the rref is created on the owner, otherwise throw in + // cases where the user of this API expects this to return a completed future. + // Note that the return value is a intrusive_ptr to a c10::ivalue::Future that + // holds the RRef. + c10::intrusive_ptr getOwnerRRef( + const RRefId& rrefId, + bool forceCreated = false); + + // Adding the RRefId of an OwnerRRef into the forks_ map. This is useful when + // making a remote call to self, which as for now, still goes through serde + // and invokes request callback. In this case, the OwnerRRef has already been + // created on the send side, and we need to pass it to the receive side, + // instead of creating a new OwnerRRef. This is done by adding the OwnerRRef + // into owners_. However, that alone is not enough, as it could be deleted + // when all UserRRef die, which would then remove the OwnerRRef from owners_ + // and this could happen before the self remote call finishes. To prevent + // that, this API adds the RRefId as a ForkId, which will then delete the + // ForkId when the self remote is done. + void addSelfAsFork(c10::intrusive_ptr& rref); + + // Register a fork of the ``OwnerRRef``, and inserts a intrusive_ptr of the + // ``OwnerRRef`` in a map to keep it alive. + void addForkOfOwner(const RRefId& rrefId, const ForkId& forkId); + // Performs the same function as addForkOfOwner but ignores duplicate + // requests. This idempotent function is used with RREF_FORK_REQUEST calls, + // whereas all other message types use the non-idempotent variant. + void addForkOfOwnerIfNotPresent(const RRefId& rrefId, const ForkId& forkId); + // Delete a fork of the ``OwnerRRef``. NB: this could trigger deletion on the + // IValue or py::object. For the later, this method will acquire GIL. + // NB: If this fork deletion triggered deleting OwnerRRef, this method will + // return a shared_ptr to the OwnerRRef, which is likely to be the last + // shared_ptr instance for it. Therefore, deleting this shared_ptr + // will also trigger deleting the object it points to. If OwnerRRef holds a + // py::object, deleting it require GIL. The call site should guarded it with + // a GIL and reset the shared_ptr. The GIL-guarded deletion is intentionally + // left out of this function to avoid creating dependency on pybind. + c10::intrusive_ptr delForkOfOwner( + const RRefId& rrefId, + const ForkId& forkId); + + // Invoked when pickling an RRef to setup child/fork properly + RRefForkData prepareChildFork(const c10::intrusive_ptr& rref); + // Invoked when unpickling an RRef to send RREF_FORK_REQUEST to owner and + // send RREF_CHILD_ACCEPT to the parent. + // NB: forkId is necessary here as the rref could be an OwnerRRef + void notifyOwnerAndParentOfFork( + const ForkId& forkId, + worker_id_t parent, + const c10::intrusive_ptr& rref); + + // When a UserRRef is forked to another worker (user or owner), it is added + // into pendingChildren_ to be held alive until it receives RREF_CHILD_ACCEPT + // from the child. + // NB: This is necessary for both user and owner child. As we do not have FIFO + // communication between workers, we need this strategy to make sure that all + // previously submitted rpc/remote calls are acked before sending out the + // RREF_USER_DELETE message. Otherwise, the OwnerRRef could be deleted too + // soon. + void addPendingChild( + const ForkId& forkId, + const c10::intrusive_ptr& rref); + void delPendingChild(const ForkId& forkId); + + // When a UserRRef is created, it is added into pendingUsers_ to be held alive + // until it receives RREF_USER_ACCEPT from the owner. + void addPendingUser( + const ForkId& forkId, + const c10::intrusive_ptr& rref); + void delPendingUser(const ForkId& forkId); + void addConfirmedUser( + const ForkId& forkId, + const c10::intrusive_ptr& rref); + + // Retrieve a pending user given the fork ID. Throws if the user has already + // been confirmed (i.e. is no longer in the pendingUsers_ map). + c10::intrusive_ptr getPendingUser(const ForkId& forkId); + + // Start recording new pending UserRRefs. All pending UserRRefs introduced + // after this point will be put into the thread_local userTable_, which will + // then be consumed and cleared in waitForThreadLocalPendingRRefs(). + void recordThreadLocalPendingRRefs(); + // End recording new pending UserRRefs, and clear the thread_local userTable_. + // Returns a Future which will be marked as completed when all pending + // UserRRefs in the current userTable_ are confirmed by their owners. The bool + // value in the Future is unused. + // This method is useful to make sure RRefs in user function arguments are + // confirmed before launching user code. + // NB: Callers of this method does not need to keep the returned Future alive, + // because this Future is already captured in callbacks of the + // PendingUserState. If there is no pending UserRRefs, this method returns a + // completed future. + c10::intrusive_ptr waitForThreadLocalPendingRRefs(); + // Only call this function when there are errors during a recording session, + // and it is likely that waitForThreadLocalPendingRRefs() cannot be invoked + // properly. + // TODO: make this a context guard + void clearRecordedPendingRRefsOnError(); + + void delUser( + const worker_id_t owner, + const RRefId& rrefId, + const ForkId& forkId); + void delAllUsersAndUnforkedOwners(std::chrono::milliseconds timeoutMillis); + + std::unordered_map getDebugInfo(); + + private: + struct PendingUserState { + PendingUserState(c10::intrusive_ptr rref) + : rref_(std::move(rref)), + confirmationFuture_(c10::make_intrusive(BoolType::get())) { + } + + inline void confirm() { + c10::static_intrusive_pointer_cast(rref_)->confirm(); + confirmationFuture_->markCompleted(); + } + + c10::intrusive_ptr rref_; + // Use Future.wait() and Future.markCompleted() to block and unblock user + // functions. The bool value wrapped by the future_ is not used. + c10::intrusive_ptr confirmationFuture_; + }; + + RRefContext(std::shared_ptr /*agent*/); + + c10::intrusive_ptr createUserRRef( + worker_id_t ownerId, + const RRefId& rrefId, + const ForkId& forkId, + const TypePtr& type); + + void finishForkRequest(const ForkId& forkId, worker_id_t parent); + + // If there is any leak on any RRef, this method will throw an error. + void checkRRefLeaks(bool ignoreRRefLeak); + + static std::atomic nextLocalId_; + + const std::shared_ptr agent_; + mutable std::mutex mutex_; + // Keep OwnerRRefs alive until there is no living UserRRefs. + std::unordered_map, RRefId::Hash> owners_; + // A map to track OwnerRRefs that are requested but not yet created. This can + // happen if the to_here() message is processed on the owner before the + // corresponding creator rpc.remote() message. If this happens, instead of + // to_here() RPC thread to block waiting for the OwnerRRef creation, the + // RRefContext returns a Future, so that the RPC request processing logic can + // attach subsequent code as a callback to that Future. + // NB: the OwnerRRefs in this map must be cleared when the corresponding + // OwnerRRef is created. Note that the values in this map are intrusive_ptrs + // to c10::ivalue::Future that will be marked completed with the owner RRef. + std::unordered_map, RRefId::Hash> + pendingOwners_; + // Tracks known living UserRRefs of an OwnerRRef + std::unordered_map< + RRefId, + std::unordered_set, + RRefId::Hash> + forks_; + + // This cond var is used by deleteAllUsers(), a event notification is sent if + // number of pending UserRRef or UserRRef children is reduced, or + // number of owned OwnerRRef is reduced. + std::condition_variable deleteAllUsersCV_; + // The follow 3 maps keep UserRRefs alive by holding a intrusive_ptr to the + // RRef instances. A UserRRef must be added into this map if any of the + // following two conditions is true: + // + // (1) A UserRRef has not been accepted by owner yet. + // + // It can be used or shared, but cannot be deleted, and hence kept alive + // in this map. A message of type RREF_USER_ACCEPT will move the + // corresponding RRef from pendingUsers_ map to confirmedUsers_ map. + std::unordered_map, ForkId::Hash> + pendingUsers_; + // UserRRefs are added into this map when it is confirmed by the owner. + // When destroying RRefContext this map helps to find local UserRRefs + // and send delete messages if they are still not deleted by Python + // garbage collection. + std::unordered_map, ForkId::Hash> + confirmedUsers_; + + // (2) A UserRRef has forked a child UserRRef which has not been accepted by + // the owner yet. + // + // In this case, this UserRRef cannot send out RREF_USER_DELETE message, + // as it could potentially trigger the OwnerRRef been deleted before the + // owner learns about the forked child. + std::unordered_map, ForkId::Hash> + pendingChildren_; + + // The RRef context performs its operations through async RPC requests, in + // order to not block the user code. Therefore the RRef context's state may be + // lagging a bit behind what it is intended to be, while it waits for these + // requests to complete. To allow syncing when needed, we store the count of + // these pending requests, so that users can wait for it to reach zero. + std::atomic numPendingFutures_{0}; + + std::mutex destroyedMutex_; + bool destroyed_{false}; + + // Thread local states to keep UserRRefs deserialized from user function + // arguments. + static thread_local std::vector> userTable_; + // A flag indicating whether subsequently created UserRRefs should be added to + // the thread_local userTable_. The flag is set to true before serializing + // RPC arguments and then set to false before running the corresponding + // user code. See addPendingUser and delPendingUser for more details. + // NB: The reason for having this flag is because addPendingUser are called in + // two cases, and we only want to track the 2nd case. + // (1) RRef as the return value: when calling rpc.remote, the UserRRef on the + // caller side is added to the context using addPendingUser. + // (2) RRef as an argument: When running an RPC using RRefs as arguments, the + // RRef is forwarded to the callee as new UserRRefs (if the callee is not + // the owner). In this case, we block running the user function until all + // UserRRefs are confirmed by the owner. + // This contract guarantees that no UserRRefs can be used remotely without + // confirmation. Note that, however, the UserRRef created by rpc.remote can + // still be passed to local functions as arguments and used there. This is by + // design, because this feature is especially useful when, say a master node + // creates multiple UserRRefs in a loop and then shares them with other nodes. + // Blocking every iteration in the loop until RRefs are confirmed will slow + // this down. This nuance on UserRRef can be interpreted as we only make + // exceptions for UserRRef creators. And using the UserRRef on its creator + // without confirmation is OK, because the creator would either call to_here + // or forward the UserRRef, and both would then require confirmations from the + // owner. + static thread_local bool recording_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..ae01733c5d9dab82ad33d47164120d1037ecb3f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h @@ -0,0 +1,426 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace torch::distributed::rpc { + +class RRef; +class RRefContext; +class UserRRef; + +constexpr int OWNER_IDX = 0; // index of ownerId in the tuple +constexpr int RREFID_ON_IDX = 1; // index of RRefId.createdOn_ in the tuple +constexpr int RREFID_ID_IDX = 2; // index of RRefId.localId_ in the tuple +constexpr int FORKID_ON_IDX = 3; // index of ForkId.createdOn_ in the tuple +constexpr int FORKID_ID_IDX = 4; // index of ForkId.localId_ in the tuple +constexpr int PARENT_IDX = 5; // index of parent in the tuple +constexpr int TYPE_IDX = 6; // index of parent in the tuple + +// NB: if more fields are added, make sure this field is also bumped +constexpr int RFD_TUPLE_SIZE = 7; // number of RRefForkData fields in py::tuple + +// Represents fork of an RRef to be sent over the wire. +struct TORCH_API RRefForkData { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const worker_id_t ownerId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const RRefId rrefId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const ForkId forkId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const worker_id_t parent_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::string typeStr_; + + RRefForkData( + worker_id_t ownerId, + const RRefId& rrefId, + const ForkId& forkId, + worker_id_t parent, + std::string typeStr); +}; + +// Note [RRef Protocol] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// [Background] +// +// RRef stands for Remote REFerence. Each RRef is owned by a single worker +// (i.e., owner) and can be used by multiple users. The owner stores the real +// data referenced by its RRefs. RRef needs to support fast and scalable RPC. +// Hence, in the design, we avoid using a single global master to keep RRef +// states, instead owners will keep track of the global reference counts +// for its RRefs. Every RRef can be uniquely identified by a global RRefId, +// which is assigned at the time it is first created either on a user or on the +// owner. +// +// On the owner worker, there is only one OwnerRRef instance, which contains the +// real data, while on user workers, there can be as many UserRRefs as +// necessary, and UserRRef does not hold the data. All usage on the OwnerRRef +// should retrieve the unique OwnerRRef instance using the globally unique +// RRefId. //A UserRRef will be created when it is used as an argument or return +// value in dist.rpc or dist.remote call, but RRef forking and reference +// counting (RC) are completely transparent to applications. Every UserRRef will +// also have its globally unique ForkId. +// +// [Assumptions] +// +// 1. Transient Network Failures +// +// TODO: current RRef implementation does not tolerate failures +// +// The RRef design handles transient network failures by retrying +// messages. Node crashes or permanent network partition is beyond the scope. +// When those incidents occur, the application may take down all workers, revert +// to the previous checkpoint, and resume training. +// +// 2. Non-idempotent UDFs +// +// We assume UDFs are not idempotent and therefore cannot be retried. However, +// internal RRef control messages are idempotent and retried upon message +// failure. +// +// TODO: RRef internal messages are not yet idempotent +// +// 3. Out of Order Message Delivery +// +// We do not assume message delivery order between any pair of nodes, because +// both sender and receiver are using multiple threads. There is no guarantee on +// which message will be processed first. +// +// [RRef Lifetime] +// +// The goal of the protocol is to delete an OwnerRRef at an appropriate time. +// The right time to delete an OwnerRRef is when there are no living UserRRefs +// and Python GC also agrees to delete the OwnerRRef instance on the owner. The +// tricky part is to determine if there are any living UserRRefs. +// +// A user can get a UserRRef in three situations: +// +// (1). Receiving a UserRRef from the owner. +// (2). Receiving a UserRRef from another user. +// (3). Creating a new UserRRef owned by another worker. +// +// (1) is the simplest case where the owner initiates the fork, and hence it can +// easily increment local RC. The only requirement is that any UserRRef must +// notify the owner before destruction. Hence, we need the first guarantee: +// +// G1. The owner will be notified when any UserRRef is deleted. +// +// As messages might come delayed or out-of-order, we need more one guarantee to +// make sure the delete message is not sent out too soon. Let us first introduce +// a new concept. If A sends an RPC to B that involves an RRef, we call the RRef +// on A the parent RRef and the RRef on B the child RRef. +// +// G2. Parent RRef cannot be deleted until the child RRef is confirmed by the +// owner. +// +// Under (1), where the caller is UserRRef and callee is OwnerRRef, it simply +// means that the user will not send out the delete message until all previous +// messages are ACKed. Note that ACKed does not mean the owner finishes +// executing the function, instead, it only means the owner has retrieved its +// local OwnerRRef and about to pass it to the function, which is sufficient to +// keep the OwnerRRef alive even if the delete message from the user arrives at +// the owner before the function finishes execution. +// +// With (2) and (3), it is possible that the owner only partially knows the RRef +// fork graph or not even knowing it at all. For example, the RRef could be +// constructed on a user, and before the owner receives the RPC call, the +// creator user might have already shared the RRef with other users, and those +// users could further share the RRef. One invariant is that the fork graph of +// any RRef is always a tree rooted at the owner, because forking an RRef always +// creates a new RRef instance, and hence every RRef has a single parent. One +// nasty detail is that when an RRef is created on a user, technically the owner +// is not its parent but we still consider it that way and it does not break the +// argument below. +// +// The owner's view on any node (fork) in the tree has three stages: +// +// 1) unknown -> 2) known -> 3) deleted. +// +// The owner's view on the entire tree keeps changing. The owner deletes its +// OwnerRRef instance when it thinks there are no living UserRRefs, i.e., when +// OwnerRRef is deleted, all UserRRefs could be either indeed deleted or +// unknown. The dangerous case is when some forks are unknown and others are +// deleted. +// +// G2 trivially guarantees that no parent UserRRef Y can be deleted before the +// owner knows all of Y's children UserRRefs. +// +// However, it is possible that the child UserRRef Z may be deleted before the +// owner knows its parent Y. More specifically, this can happen when all of Z's +// messages are processed by the owner before all messages from Y, including the +// delete message. Nevertheless, this does not cause any problem. Because, at +// least one of Y's ancestor will be alive, and it will prevent the owner from +// deleting the OwnerRRef. Consider the following example: (NB: this scenario +// will no longer relevant when we block UDF until all RRefs are confirmed by +// the owner) +// +// OwnerRRef -> A -> Y -> Z +// +// OwnerRRef forks to A, then A forks to Y, and Y forks to Z. Z can be deleted +// without OwnerRRef knowing Y. However, the OwnerRRef will at least know A, as +// the owner directly forks the RRef to A. A won't die before the owner knows Y. +// +// Things get a little trickier if the RRef is created on a user: +// +// OwnerRRef +// ^ +// | +// A -> Y -> Z +// +// If Z calls to_here on the UserRRef, the owner at least knows A when Z is +// deleted, because otherwise to_here wouldn't finish. If Z does not call +// to_here, it is possible that the owner receives all messages from Z before +// any message from A and Y. In this case, as the real data of the OwnerRRef has +// not been created yet, there is nothing to be deleted either. It is the same +// as Z does not exist at all Hence, it's still OK. +// +// See #26759 for more details and discussions. +// +// TODO: make RRef an IValue, and edit createStackForSchema accordingly +// TODO: make RRef system messages idempotent and retry on failures. +// +// ``RRef`` is the base type for both ``UserRRef`` and ``OwnerRRef``. +// Each ``RRef`` has a globally unique ``RRefId``. +class TORCH_API RRef : public RRefInterface { + public: + // RRef is made NOT copyable NOT movable to prevent messing up reference + // counting. + explicit RRef(const RRef& other) = delete; + explicit RRef(RRef&& other) = delete; + RRef& operator=(RRef&& other) = delete; + + ~RRef() override = default; + + // returns the worker id of the owner + inline worker_id_t owner() const override { + return ownerId_; + } + + // returns the worker name of the owner + inline std::string ownerName() const override { + return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_).name_; + } + + // returns the worker info of the owner + inline WorkerInfo ownerWorkerInfo() const { + return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_); + } + + // Returns the globally unique RRefId of this RRef + inline const RRefId& rrefId() const { + return rrefId_; + } + + inline bool isPyObj() const { + return type_ == PyObjectType::get(); + } + inline const TypePtr type() const override { + return type_; + } + + // Save the future corresponding to the creation of this RRef on a remote + // node. Note that this is only set when processing requests invoked with + // rpc.remote. This is only used to get the future corresponding to the rref + // for profiling use cases. + inline void registerOwnerCreationFuture(c10::intrusive_ptr fut) { + ownerCreationFuture_ = std::move(fut); + } + + // Get the future corresponding to the creation of this rref. + inline c10::intrusive_ptr getOwnerCreationFuture() const { + return ownerCreationFuture_; + } + + // Check if creation of this RRef on owner node has timed out. + inline bool getTimedOut() const { + return timedOut_.load(); + } + + // Dispatches an error to the correct handler based on its RPCErrorType. + void handleError(RPCErrorType errorType, const JitFuture& JitFuture); + + // Send delete UserRRef request to Owner, + // if the request hasn't been sent yet. + // There are 2 cases to call it, + // 1, Python GC decides end of UserRRef lifetime, calling destructor. + // 2, RPC module graceful shutdown calls it on all UserRRefs tracked + // in the RRefContext. + virtual void tryDel() {} + + protected: + // Indicates that the creation of this RRef on owner node has timed out. + inline void setTimedOut() { + timedOut_ = true; + } + friend class RRefContext; + + RRef(worker_id_t ownerId, const RRefId& rrefId, TypePtr type); + + virtual RRefForkData fork() const; + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const worker_id_t ownerId_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const RRefId rrefId_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::atomic timedOut_{false}; + + // type field to denote the type of the element that the RRef is holding + // it could be any TypePtr that JIT support, including PyObjectType + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const TypePtr type_; + // Future corresponding to request to create RRef on remote node. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + c10::intrusive_ptr ownerCreationFuture_; +}; + +// ``UserRRef`` represents a user of an RRef. Besides the ``RRefId``, each user +// also has a globally unique ``ForkId`` to identify this user. ``UserRRef`` +// never owns the real value, the only way to get the value of the ``RRef`` is +// to call ``to_here()`` and get a copy.. +class TORCH_API UserRRef final : public RRef { + public: + UserRRef(const UserRRef& other) = delete; + UserRRef(UserRRef&& other) = delete; + UserRRef& operator=(const UserRRef& other) = delete; + UserRRef& operator=(UserRRef&& other) = delete; + + UserRRef( + worker_id_t ownerId, + const RRefId& rrefId, + const ForkId& forkId, + TypePtr type); + + inline bool isOwner() const override { + return false; + } + + inline bool confirmedByOwner() const override { + return confirmedByOwner_; + } + + // Returns the globally unique ForkId of this RRef + const ForkId& forkId() const; + + // Get of copy of the value from the ``OwnerRRef``. If the value is not ready + // yet, this call will block. + IValue toHere( + const float timeoutSeconds = + torch::distributed::rpc::kUnsetRpcTimeout) const; + + void tryDel() override; + + // Will be called when refcount reaches 0. + // Upon destruction, this ``UserRRef`` will tell the owner to deref. + void release_resources() override; + + // Will be called when both refcount and weakcount reach 0. See + // https://github.com/pytorch/pytorch/blob/9116f02bebf3a5260feef5732d36c54ecb3b4033/c10/util/intrusive_ptr.h#L204 + // This is called on destructing the wrapping intrusive_ptr_target instance + // and it's data members. + ~UserRRef() override; + + private: + friend class RRefContext; + + RRefForkData fork() const override; + inline void confirm() { + confirmedByOwner_ = true; + } + + const ForkId forkId_; + + // Indicates if this user has sent delete message to it's owner. + // Note, thread safety is needed because delete message could be sent by + // either the destructor called by Python garbage collection or RRefContext + // proactive cleanup on RPC graceful shutdown. + std::mutex deletedOnOwnerMutex_; + bool deletedOnOwner_{false}; + // Indicating whether this UserRRef has been confirmed by its owner. + std::atomic confirmedByOwner_; +}; + +// Keep the template only on the derived class because ``RRefContext`` needs to +// erase the type on ``RRef`` and keep them in one map. +class TORCH_API OwnerRRef final : public RRef { + public: + OwnerRRef(const OwnerRRef& other) = delete; + OwnerRRef(OwnerRRef&& other) = delete; + OwnerRRef& operator=(const OwnerRRef& other) = delete; + OwnerRRef& operator=(OwnerRRef&& other) = delete; + + OwnerRRef( + worker_id_t ownerId, + const RRefId& rrefId, + TypePtr type, + std::vector devices); + + OwnerRRef( + worker_id_t ownerId, + const RRefId& rrefId, + TypePtr type, + std::optional value, + std::vector devices); + + inline bool isOwner() const override { + return true; + } + + // OwnerRRef is always confirmed, while UserRRef is only confirmed when the + // owner knows about it. + inline bool confirmedByOwner() const override { + return true; + } + + // Get a constant reference of the real value. This method will block if the + // value is not ready. This method does not need GIL as it does not create + // any new py::object. It will throw if there is an error. + const IValue& getValue() const; + + // Set the value of this ``OwnerRRef``. This method does not need GIL as it + // does not create any new py::object. + void setValue(IValue&& value); + // Sets the value of this ``OwnerRRef`` to contain an exception. + void setError(std::exception_ptr eptr); + + // Has a value or error been set? + bool hasValue() const; + // Gets a future that is satisfied when the value or error is set. + c10::intrusive_ptr getFuture(); + + private: + friend class RRefContext; + + c10::intrusive_ptr future_; +}; + +TORCH_API std::ostream& operator<<(std::ostream& os, const RRef& rref); + +// Helper function that casts from c10::RRefInterface to OwnerRRef +inline TORCH_API c10::intrusive_ptr fromRRefInterface( + const c10::intrusive_ptr& rrefInterface) { + return c10::static_intrusive_pointer_cast(rrefInterface); +} + +// Helper function that casts from OwnerRRef to c10::RRefInterface +inline TORCH_API c10::intrusive_ptr fromOwnerRRef( + const c10::intrusive_ptr& ownerRRef) { + return c10::static_intrusive_pointer_cast(ownerRRef); +} + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h new file mode 100644 index 0000000000000000000000000000000000000000..b96713516e679436aee835898be9d554283e0a3e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h @@ -0,0 +1,168 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// Temporary solution of RRef operations. +// TODO: Remove all these messages and use rpc + registered functions instead. +class TORCH_API RRefMessageBase : public RpcCommandBase { + public: + RRefMessageBase(const RRefId& rrefId, MessageType type) + : rrefId_(rrefId), type_(type) {} + + const RRefId& rrefId(); + + protected: + // NOLINTNEXTLINE(cppcoreguidelines*) + const RRefId rrefId_; + // NOLINTNEXTLINE(cppcoreguidelines*) + const MessageType type_; +}; + +class TORCH_API ForkMessageBase : public RRefMessageBase { + public: + ForkMessageBase(const RRefId& rrefId, const ForkId& forkId, MessageType type) + : RRefMessageBase(rrefId, type), forkId_(forkId) {} + + const ForkId& forkId(); + + c10::intrusive_ptr toMessageImpl() && override; + static std::pair fromMessage( + const Message& message, + MessageType type); + + protected: + // NOLINTNEXTLINE(cppcoreguidelines*) + const ForkId forkId_; +}; + +// UserRRef uses this message to fetch the remote RRef value from the owner. +class TORCH_API ScriptRRefFetchCall final : public RRefMessageBase { + public: + ScriptRRefFetchCall(worker_id_t fromWorkerId, const RRefId& rrefId) + : RRefMessageBase(rrefId, MessageType::SCRIPT_RREF_FETCH_CALL), + fromWorkerId_(fromWorkerId) {} + + inline worker_id_t fromWorkerId() const { + return fromWorkerId_; + } + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const Message& message); + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const worker_id_t fromWorkerId_; +}; + +class TORCH_API PythonRRefFetchCall final : public RRefMessageBase { + public: + PythonRRefFetchCall(worker_id_t fromWorkerId, const RRefId& rrefId) + : RRefMessageBase(rrefId, MessageType::PYTHON_RREF_FETCH_CALL), + fromWorkerId_(fromWorkerId) {} + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage( + const Message& message); + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const worker_id_t fromWorkerId_; +}; + +// OwnerRRef uses this message to send the RRef value to a remote UserRRef +class TORCH_API RRefFetchRet : public RpcCommandBase { + public: + RRefFetchRet(std::vector values, MessageType type) + : values_(std::move(values)), type_(type) {} + + const std::vector& values(); + c10::intrusive_ptr toMessageImpl() && override; + + private: + std::vector values_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const MessageType type_; +}; + +class TORCH_API ScriptRRefFetchRet final : public RRefFetchRet { + public: + explicit ScriptRRefFetchRet(std::vector values) + : RRefFetchRet(std::move(values), MessageType::SCRIPT_RREF_FETCH_RET) {} + + static std::unique_ptr fromMessage( + const Message& message); +}; + +class TORCH_API PythonRRefFetchRet final : public RRefFetchRet { + public: + explicit PythonRRefFetchRet(std::vector values) + : RRefFetchRet(std::move(values), MessageType::PYTHON_RREF_FETCH_RET) {} + + static std::unique_ptr fromMessage( + const Message& message); +}; + +// UserRRef (regardless it's the creator or not) uses this message to notify +// OwnerRRef on delete. +class TORCH_API RRefUserDelete final : public ForkMessageBase { + public: + RRefUserDelete(const RRefId& rrefId, const ForkId& forkId) + : ForkMessageBase(rrefId, forkId, MessageType::RREF_USER_DELETE) {} + + static std::unique_ptr fromMessage(const Message& message); +}; + +class TORCH_API RemoteRet final : public ForkMessageBase { + public: + RemoteRet(const RRefId& rrefId, const ForkId& forkId) + : ForkMessageBase(rrefId, forkId, MessageType::REMOTE_RET) {} + + static std::unique_ptr fromMessage(const Message& message); +}; + +// A child RRef uses this message to notify its parent that the child has been +// confirmed by the owner. +class TORCH_API RRefChildAccept final : public RpcCommandBase { + public: + explicit RRefChildAccept(const ForkId& forkId) : forkId_(forkId) {} + + const ForkId& forkId() const; + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const ForkId forkId_; +}; + +// A child RRef uses this message to send a fork request to the owner. +class TORCH_API RRefForkRequest final : public ForkMessageBase { + public: + RRefForkRequest(const RRefId& rrefId, const ForkId& forkId) + : ForkMessageBase(rrefId, forkId, MessageType::RREF_FORK_REQUEST) {} + + static std::unique_ptr fromMessage(const Message& message); +}; + +class TORCH_API RRefAck final : public RpcCommandBase { + public: + RRefAck() = default; + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h new file mode 100644 index 0000000000000000000000000000000000000000..b4073693ec762921a3816b558a8c76913b940357 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h @@ -0,0 +1,72 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +using torch::jit::Operator; + +// A ScriptCall instance represents an invocation of a builtin operator for a +// TorchScript function. If it is a builtin operator, it +// contains a shared ptr to the `Operator` and a list of arguments. +// If it is a TorchScript function, it contains a non empty qualifiedName string +// to the TorchScript function schema name and a list of arguments. +class TORCH_API ScriptCall : public RpcCommandBase { + public: + // Constructor for builtin operator call. + ScriptCall(std::shared_ptr op, std::vector&& stack); + // Constructor for TorchScript function call. + ScriptCall( + const c10::QualifiedName& qualifiedName, + std::vector&& stack, + const bool isAsyncExecution = false); + + bool hasOp() const; + std::shared_ptr op() const; + bool hasQualifiedName() const; + const c10::QualifiedName& qualifiedName() const; + // return the argument stack of this builtin operator + const std::vector& stack() const; + std::vector& stackRef(); + inline bool isAsyncExecution() const { + return isAsyncExecution_; + } + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); + + ~ScriptCall() override = default; + + protected: + virtual void toIValues(std::vector& ivalues) const; + static std::unique_ptr fromIValues( + std::vector& ivalues); + + private: + // Given an operator symbol and a string schema, return the matched operator. + static std::shared_ptr matchOperator(const std::string& str_schema); + + static const std::string BUILTIN_OP_NAMESPACE_; + static const std::string ATEN_PREFIX_; + + // This field has value if this ScriptCall represents invocation of a builtin + // operator. + std::optional> op_; + // This field has non empty string if this ScriptCall represents invocation of + // an annotated torchscript function defined by users. + std::optional qualifiedName_; + std::vector stack_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isAsyncExecution_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h new file mode 100644 index 0000000000000000000000000000000000000000..6ae72a328d457a150ae78f30c8c4c1d18c4b2664 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h @@ -0,0 +1,59 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +using torch::jit::Operator; + +// A ScriptRemoteCall instance represents an invocation of `dist.remote` on a +// builtin operator. Currently, it does not support using RRef as arguments yet. +// Besides the operator and a vector of arguments, ScriptRemoteCall also +// contains the RRefId and the ForkId of the return value RRef. +class TORCH_API ScriptRemoteCall final : public ScriptCall { + public: + // Constructor for builtin operator call. + ScriptRemoteCall( + std::shared_ptr op, + std::vector&& stack, + const RRefId& retRRefId, + const ForkId& retForkId); + + // Constructor for TorchScript function call. + ScriptRemoteCall( + const c10::QualifiedName& qualifiedName, + std::vector&& stack, + const RRefId& retRRefId, + const ForkId& retForkId, + const bool isAsyncExecution); + + inline const RRefId& retRRefId() const { + return retRRefId_; + } + + inline const ForkId& retForkId() const { + return retForkId_; + } + + static std::unique_ptr fromIValues( + std::vector& ivalues); + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const RRefId retRRefId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const ForkId retForkId_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h new file mode 100644 index 0000000000000000000000000000000000000000..e4fb8e7ca92d1389f1501908ad7062b0a223a204 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::rpc { + +// Return value of a builtin operator or a TorchScript function. +class TORCH_API ScriptResp final : public RpcCommandBase { + public: + explicit ScriptResp(at::IValue&& values); + + const at::IValue& value(); + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const at::IValue value_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h new file mode 100644 index 0000000000000000000000000000000000000000..b5f3a788d0cb86657effd94171062c84f0efc0e9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h @@ -0,0 +1,498 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_TENSORPIPE + +#include +#include + +#include +#include +#include +#include +#include + +// Forward-declare the TensorPipe classes we need, to avoid including its +// headers in PyTorch's ones and thus have it become a public dependency. + +namespace tensorpipe { + +class Context; +class Error; +class Listener; +class Message; +class Pipe; + +namespace transport { +class Context; +} // namespace transport + +namespace channel { +class Context; +} // namespace channel + +} // namespace tensorpipe + +namespace torch::distributed::rpc { + +// These priorities instruct TensorPipe on which transport/channel to pick +// during handshake. Higher priorities will take precedence over lower ones. +// The transport with lowest priority will be the one used to bootstrap pipes. + +constexpr int64_t kShmTransportPriority = 200; +constexpr int64_t kIbvTransportPriority = 100; +// The UV transport just uses TCP and should work everywhere, thus keep it last. +constexpr int64_t kUvTransportPriority = 0; + +constexpr int64_t kCmaChannelPriority = 1200; +constexpr int64_t kMultiplexedUvChannelPriority = 1100; +// The basic channel reuses a transport as a channel, and is thus our fallback. +constexpr int64_t kBasicChannelPriority = 1000; + +// CPU channel have higher priority than CUDA channels, since the latter might +// handle CPU-to-CPU transfers, but will always be less efficient than their +// CPU-only counterparts. +constexpr int64_t kCudaIpcChannelPriority = 300; +constexpr int64_t kCudaGdrChannelPriority = 200; +constexpr int64_t kCudaXthChannelPriority = 400; +constexpr int64_t kCudaBasicChannelPriority = 0; + +using steady_clock_time_point = + std::chrono::time_point; + +struct TORCH_API TransportRegistration { + std::shared_ptr transport; + int64_t priority; + std::string address; +}; + +TORCH_DECLARE_REGISTRY(TensorPipeTransportRegistry, TransportRegistration); + +struct TORCH_API ChannelRegistration { + std::shared_ptr channel; + int64_t priority; +}; + +TORCH_DECLARE_REGISTRY(TensorPipeChannelRegistry, ChannelRegistration); + +struct TORCH_API TensorPipeRpcBackendOptions : public RpcBackendOptions { + TensorPipeRpcBackendOptions( + int numWorkerThreads, + std::optional> transports, + std::optional> channels, + float rpc_timeout, + std::string init_method, + std::unordered_map device_maps = {}, + std::vector devices = {}) + : RpcBackendOptions(rpc_timeout, std::move(init_method)), + numWorkerThreads(numWorkerThreads), + transports(std::move(transports)), + channels(std::move(channels)), + deviceMaps(std::move(device_maps)), + devices(std::move(devices)) { + TORCH_CHECK( + numWorkerThreads > 0, + "num_worker_threads must be positive, got ", + numWorkerThreads); + + if (this->transports.has_value()) { + for (const std::string& transportName : this->transports.value()) { + TORCH_CHECK( + TensorPipeTransportRegistry()->Has(transportName), + "Unknown transport: ", + transportName); + } + } + + if (this->channels.has_value()) { + for (const std::string& channelName : this->channels.value()) { + TORCH_CHECK( + TensorPipeChannelRegistry()->Has(channelName), + "Unknown channel: ", + channelName); + } + } + } + + void setDeviceMap(const std::string& workerName, const DeviceMap& deviceMap) { + auto iter = deviceMaps.find(workerName); + if (iter == deviceMaps.end()) { + deviceMaps[workerName] = deviceMap; + } else { + for (auto& entry : deviceMap) { + // c10::Device has no default constructor, hence map[device] doesn't + // work In C++-17 we can use insert_or_assign. + auto entryIter = iter->second.find(entry.first); + if (entryIter == iter->second.end()) { + iter->second.emplace(entry.first, entry.second); + } else { + entryIter->second = entry.second; + } + } + } + } + + int numWorkerThreads; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional> transports; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional> channels; + std::unordered_map deviceMaps; + std::vector devices; +}; + +// Struct to track the network source metrics +struct TORCH_API NetworkSourceInfo { + worker_id_t srcRank; + std::vector srcMachineAddr; +}; + +// Struct to track aggregated network metrics +struct TORCH_API AggregatedNetworkData { + uint64_t numCalls{0}; + uint64_t totalSentBytes{0}; + uint64_t totalRecvBytes{0}; + uint64_t totalErrors{0}; +}; + +// TensorPipeAgent leverages TensorPipe (https://github.com/pytorch/tensorpipe) +// to transparently move tensors and payloads through the fastest available +// transport or channel. It acts like a hybrid RPC transport, providing shared +// memory (linux) and TCP (linux & mac) support. CUDA support is in progress. +class TORCH_API TensorPipeAgent : public RpcAgent { + public: + TensorPipeAgent( + const c10::intrusive_ptr<::c10d::Store>& store, + std::string selfName, + worker_id_t selfId, + std::optional worldSize, + TensorPipeRpcBackendOptions opts, + std::unordered_map reverseDeviceMaps, + std::vector devices, + std::unique_ptr cb); + + TensorPipeAgent(const TensorPipeAgent&) = delete; + TensorPipeAgent& operator=(const TensorPipeAgent&) = delete; + + c10::intrusive_ptr send( + const WorkerInfo& to, + c10::intrusive_ptr message, + const float rpcTimeoutSeconds = kUnsetRpcTimeout, + const DeviceMap& deviceMap = {}) override; + + // join() and sync() would be deprecated - + // https://github.com/pytorch/pytorch/issues/27647 + void join(bool shutdown = false, float timeout = 0) override; + void sync() override {} + void startImpl() override; + void shutdownImpl() override; + + ~TensorPipeAgent() override; + + const WorkerInfo& getWorkerInfo(const std::string& workerName) const override; + const WorkerInfo& getWorkerInfo(worker_id_t workerId) const override; + std::vector getWorkerInfos() const override; + void updateGroupMembership( + const WorkerInfo& workerInfo, + const std::vector& devices, + const std::unordered_map& reverseDeviceMaps, + bool isJoin); + + std::unordered_map getMetrics() override; + + void addGilWaitTime(const std::chrono::microseconds gilWaitTime) override; + + TensorPipeRpcBackendOptions getBackendOptions() const; + + const c10::intrusive_ptr<::c10d::Store> getStore() const; + + DeviceMap getDeviceMap(const WorkerInfo& dest) const override; + + const std::vector& getDevices() const override; + + using NetworkDataDict = + std::unordered_map; + + // Returns metrics tracked by the NetworkDataDict + NetworkDataDict getNetworkData(); + // Returns NetworkSourceInfo struct + NetworkSourceInfo getNetworkSourceInfo(); + + static const std::string& guessAddress(); + + // For testing purposes. + size_t timeoutMapSize(); + size_t numPendingResponses(); + size_t messageIdToTimeoutMapSize(); + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isStaticGroup_; + + protected: + // TensorPipe write function that could be used to write response + // messages by server, and write request messages by client. This + // is a protected method since it is overwritten by FaultyTensorPipeAgent + virtual void pipeWrite( + const std::shared_ptr& /*pipe*/, + const c10::intrusive_ptr& message, + std::vector&& devices, + std::vector streams, + std::function /*fn*/) noexcept; + + private: + // Removes the given messageId with the given expirationTime from the + // timeoutMap_. + void removeFromTimeoutMap(uint64_t messageId); + + // Populates workerIdToInfo_ and workerNameToInfo_ using addressStore_ + void prepareNames(bool isStaticGroup); + + // Check the static group attribute with the value set in store + void checkAndSetStaticGroup(const c10::intrusive_ptr<::c10d::Store>& store); + + const std::string& findWorkerURL(const WorkerInfo& worker) const; + + // Only use for Dynamic RPC groups, method to have worker leave group + void leaveGroup(); + + // TensorPipe read function that could be used to read response messages + // by client, and read request messages by server. + void pipeRead( + const std::shared_ptr& /*pipe*/, + std::function, + std::vector)> /*fn*/) noexcept; + + // Callback of listener accept() + void onListenerAccepted( + const tensorpipe::Error& error, + std::shared_ptr& pipe); + + // Respond to a call from a peer + void respond(std::shared_ptr& pipe); + + void sendCompletedResponseMessage( + std::shared_ptr& pipe, + JitFuture& futureResponseMessage, + uint64_t messageId, + std::vector stream); + + // Collects metrics from successful RPC calls + void trackNetworkData( + uint64_t requestSize, + uint64_t responseSize, + const std::string& destWorkerName); + + // Collects metrics from failed RPC calls + void trackNetworkError( + uint64_t requestSize, + const std::string& destWorkerName); + + inline std::vector getDevicesForRemote( + const std::string& remoteName, + const Message& message) const; + + // When a request+response completes, we need to mark the future message as + // complete. However, if its timeout has already expired, it already has an + // error set. There is no atomic "test-and-set" way to mark a future complete + // only if it isn't yet. It does exist for errors (setErrorIfNeeded) but, even + // then, it ends up printing a log message, which may worry the user. To solve + // both issues we use a separate atomic flag to know the status of the future. + struct AtomicJitFuture { + explicit AtomicJitFuture(const std::vector& devices) { + jitFuture = c10::make_intrusive( + at::AnyClassType::get(), devices); + } + + std::atomic_flag isComplete = ATOMIC_FLAG_INIT; + c10::intrusive_ptr jitFuture; + }; + + // Maintains state per client pipe to track pending response messages and + // error states. pendingResponseMessage_ should be protected by a mutex since + // it can be raced with user send() call. + // TODO: To achieve better performance we can have a pipe pool per + // client that can be configured using RpcBackendOptions. + struct ClientPipe { + explicit ClientPipe(std::shared_ptr pipe) + : pipe_(std::move(pipe)) {} + std::shared_ptr pipe_; + mutable std::mutex mutex_; + bool inError_{false}; + // Map from Message Request ID's to corresponding futures. + std::unordered_map> + pendingResponseMessage_; + }; + + const c10::intrusive_ptr<::c10d::Store> store_; + + const TensorPipeRpcBackendOptions opts_; + // For dynamic RPC, the reverse device maps are updated whenever a new rank + // joins or leaves the group + std::unordered_map reverseDeviceMaps_; + // Local devices used by this agent. If application didn't specify this + // field, it will be initialized using corresponding local devices in + // opts_.deviceMaps and reverseDeviceMaps_; + std::vector devices_; + + ThreadPool threadPool_; + std::shared_ptr context_; + std::shared_ptr listener_; + + mutable std::mutex connectedPipesMutex_; + std::unordered_map connectedPipes_; + + // Maps keyed on name and id for easy WorkerInfo lookup. + std::unordered_map workerIdToInfo_; + std::unordered_map workerNameToInfo_; + std::unordered_map workerNameToURL_; + + ::c10d::PrefixStore rankToNameStore_; + ::c10d::PrefixStore nameToAddressStore_; + // Store keys that will used to count joined processes and active calls during + // the shutdown process + ::c10d::PrefixStore shutdownStore_; + int worldSize_ = 0; + std::atomic nextMessageID_{0}; + + // Metadata used for tracking of whether certain RPCs have timed out or not. + struct TimeoutMessageMetadata { + TimeoutMessageMetadata( + uint64_t messageId_, + std::shared_ptr responseFuture_, + std::chrono::milliseconds timeout_) + : messageId(messageId_), + responseFuture(std::move(responseFuture_)), + timeout(timeout_) {} + uint64_t messageId; + std::shared_ptr responseFuture; + std::chrono::milliseconds timeout; + }; + + // Map to store the expiration times for each message. + std::map> + timeoutMap_; + + // Map to store the messageId to expiry time. + std::unordered_map messageIdToTimeout_; + + // Thread that will poll the timeoutMap_ for timed out messages and mark them + // with an error accordingly + std::thread timeoutThread_; + + // Function run by the timeoutThread_ to check for timed out RPCs + void pollTimeoutRpcs(); + + // Mutex to guard the timeoutMap_ + std::mutex timeoutMapMutex_; + + // Condition Variable to signal population of the timeoutMap_ + std::condition_variable timeoutThreadCV_; + + // Returns the expiration time for an RPC by adding the current time to the + // passed in timeout. + inline steady_clock_time_point computeRpcMessageExpiryTime( + std::chrono::milliseconds timeout) const { + return std::chrono::time_point_cast( + std::chrono::steady_clock::now() + timeout); + } + + // Handle error on an outgoing pipe + void handleClientError( + ClientPipe& clientPipe, + const tensorpipe::Error& error); + + // This is a generic struct for capturing Time-Series Metrics. It keeps a + // running sum and count of data points (observations), and can return an + // average of the data points seen so far. This is currently only used for + // tracking the GIL Wait Time in RPC Agents, but can be used for other metrics + // as well. + struct TimeSeriesMetricsTracker { + // Running sum of the data points seen so far + uint64_t currentSum_; + // Running count of the data points seen so far + uint64_t currentCount_; + + explicit TimeSeriesMetricsTracker( + uint64_t currentSum = 0, + uint64_t currentCount = 0); + + // Adds a data point (which is basically one observation for the metric + // being tracked) to the running sum and count. + void addData(uint64_t dataPoint); + // Returns the average of all the data points seen so far. + float computeAverage() const; + }; + + // Map of Time-Series metrics tracked by the RPC Agent + std::unordered_map timeSeriesMetrics_; + // Mutex to guard timeSeriesMetrics_ + std::mutex metricsMutex_; + + // Custom lock guard used to check if the RPC group is dynamic and lock the + // mutex if so + struct GroupMembershipLockGuard { + GroupMembershipLockGuard(std::mutex& mutex, bool isStaticGroup) + : ref_(mutex), isStaticGroup_(isStaticGroup) { + if (isStaticGroup_) { + ref_.lock(); + } + } + + ~GroupMembershipLockGuard() { + if (isStaticGroup_) { + ref_.unlock(); + } + } + + GroupMembershipLockGuard(const GroupMembershipLockGuard&) = delete; + + private: + std::mutex& ref_; + bool isStaticGroup_; + }; + // Mutex to guard access to group membership data + // e.g. updates to (workerIdToInfo_, workerNameToInfo_, workerNameToURL_) + mutable std::mutex groupMembershipMutex_; + + // Map to Track Network Data + NetworkDataDict networkData_; + // Mutex to guard networkData_ + std::mutex networkDataMutex_; + + // A mutex and a cv to guard access to the call counts and watch for changes. + std::mutex callCountMutex_; + std::condition_variable callCountCV_; + // Running total of un-processed, un-errored RPC calls sent + int32_t clientActiveCalls_{0}; + // Running total of un-processed RPC requests received + int32_t serverActiveCalls_{0}; + // Running total of RPC requests that will be completed asynchronously + int32_t serverActiveAsyncCalls_{0}; + + // Whether a global graceful shutdown has begun, in which case we'll silence + // error messages due to remote workers closing their pipes. + std::atomic shuttingDown_{false}; + + // Helpers to modify the counts while correctly dealing with the mutex and cv. + void increaseCallCount(int32_t& count); + void decreaseCallCount(int32_t& count); + + // Helpers to set the state of the requests. + void markFutureAsComplete( + std::shared_ptr atomicFuture, + c10::intrusive_ptr message, + std::vector streams); + void markFutureWithError( + std::shared_ptr atomicFuture, + std::string errorMsg); +}; + +} // namespace torch::distributed::rpc + +#endif // USE_TENSORPIPE + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..025e143190c2df7c2898f03187e70064619bbf3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h @@ -0,0 +1,124 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_TENSORPIPE + +#include + +namespace tensorpipe { +class Message; +class Allocation; +class Descriptor; +} // namespace tensorpipe + +namespace torch::distributed::rpc { + +TORCH_API const c10::Stream& getStreamForDevice( + const std::vector& streams, + const c10::Device& device); + +// Inspired by c10/core/impl/DeviceGuardImplInterface.h. + +class TensorpipeDeviceTypeConverter { + public: + // Ideally we'd want this to also return a tensorpipe::Message::Tensor object + // but we cannot forward-declare that class (because it's nested), and we + // cannot include the TensorPipe headers because it's a private dependency. + // Thus we bend over backwards and entrust this method with appending that + // object to the `tensors` field of the tensorpipe::Message object we pass. + virtual std::optional> prepareTensorForSending( + const c10::Storage& storage, + const std::vector& streams, + tensorpipe::Message& message) const = 0; + + // Same as above: this method cannot return a tensorpipe::Allocation::Tensor, + // thus it appends it to the `tensors` field of the tensorpipe::Allocation. + virtual at::DataPtr allocateTensorForReceiving( + c10::DeviceIndex deviceIndex, + size_t length, + const std::vector& streams, + tensorpipe::Allocation& allocation) const = 0; + + virtual ~TensorpipeDeviceTypeConverter() = default; +}; + +extern TORCH_API std::array< + std::atomic, + static_cast(DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES)> + device_type_converter_registry; + +class TORCH_API TensorpipeDeviceTypeConverterRegistrar { + public: + TensorpipeDeviceTypeConverterRegistrar( + DeviceType /*type*/, + const TensorpipeDeviceTypeConverter* /*impl*/); +}; + +#define C10_REGISTER_TENSORPIPE_DEVICE_TYPE_CONVERTER( \ + DevType, TensorpipeDeviceTypeConverter) \ + static ::torch::distributed::rpc::TensorpipeDeviceTypeConverterRegistrar \ + C10_ANONYMOUS_VARIABLE(g_##DeviceType)( \ + ::c10::DeviceType::DevType, new TensorpipeDeviceTypeConverter()); + +inline const TensorpipeDeviceTypeConverter* getDeviceTypeConverter( + DeviceType type) { + return device_type_converter_registry[static_cast(type)].load(); +} + +// A struct that holds pointers that keep alive all the memory that will be +// accessed by TensorPipe during a write operation. +struct TensorpipeWriteBuffers { + // Allocate on heap so pointers stay valid as we move the holder. + std::unique_ptr type; + std::unique_ptr id; + std::vector payload; + std::vector pickle; + // This contains the original tensors and the clones of the sparse tensors. + std::vector tensors; + // This contains the copies of the data of the tensors that didn't own their + // memory, e.g., the ones created from torch::from_blob() with no deleter. + std::vector> copiedTensors; +}; + +// A struct that holds pointers that keep alive all the memory that will be +// accessed by TensorPipe during a read operation. +struct TensorpipeReadBuffers { + // Allocate on heap so pointers stay valid as we move the holder. + std::unique_ptr type; + std::unique_ptr id; + std::vector payload; + std::vector pickle; + std::vector tensors; +}; + +// Convert an RPC message into a TensorPipe message, plus a holder to all the +// data that must be kept alive while the write is performed asynchronously. +TORCH_API std::tuple +tensorpipeSerialize( + const c10::intrusive_ptr& rpcMessage, + std::vector devices, + const std::vector& streams); + +// Allocate the buffers that will hold the incoming data. They will be managed +// by the returned holder, which must be kept alive until the asynchronous read +// has finished. Pointers to these buffers will be stored in the returned +// tensorpipe::Allocation struct. +TORCH_API std::pair +tensorpipeAllocate( + const tensorpipe::Descriptor& tpDescriptor, + const std::vector& streams); + +// Convert a TensorPipe message back into an RPC message. This requires the data +// to be available and can thus only be performed once the asynchronous read has +// completed. The holder can be destroyed once this function returns. +TORCH_API c10::intrusive_ptr tensorpipeDeserialize( + const tensorpipe::Descriptor& tpDescriptor, + TensorpipeReadBuffers&& holder); + +} // namespace torch::distributed::rpc + +#endif // USE_TENSORPIPE + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h new file mode 100644 index 0000000000000000000000000000000000000000..c0adb349f2095a721970b5bfdd9acd7141abe827 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h @@ -0,0 +1,109 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_TENSORPIPE + +#include +#include + +namespace torch::distributed::rpc { + +struct TORCH_API FaultyTensorPipeRpcBackendOptions + : public TensorPipeRpcBackendOptions { + FaultyTensorPipeRpcBackendOptions( + int num_worker_threads, + float rpc_timeout, + std::string init_method, + std::vector messages_to_fail, + std::unordered_map messages_to_delay, + int num_fail_sends = 0) + : TensorPipeRpcBackendOptions( + num_worker_threads, + std::optional>(), + std::optional>(), + rpc_timeout, + std::move(init_method)), + messagesToFail(std::move(messages_to_fail)), + messagesToDelay(std::move(messages_to_delay)), + numFailSends(num_fail_sends) { + TORCH_CHECK(numFailSends >= 0, "numFailSends should be non-negative"); + } + + std::vector messagesToFail; + std::unordered_map messagesToDelay; + int numFailSends; +}; + +class TORCH_API FaultyTensorPipeAgent : public TensorPipeAgent { + public: + FaultyTensorPipeAgent( + const c10::intrusive_ptr<::c10d::Store>& store, + std::string selfName, + worker_id_t selfId, + int worldSize, + FaultyTensorPipeRpcBackendOptions opts, + std::unordered_map reverseDeviceMaps, + std::vector devices, + std::unique_ptr callback); + + // Faulty send function for this class. + c10::intrusive_ptr send( + const WorkerInfo& to, + c10::intrusive_ptr message, + const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout, + const DeviceMap& deviceMap = {}) override; + + // Add delay to writes + void pipeWrite( + const std::shared_ptr& pipe, + const c10::intrusive_ptr& rpcMessage, + std::vector&& devices, + std::vector streams, + std::function fn) noexcept override; + + protected: + // This function checks the messageTypesToFail_ to determine whether to use + // the faulty send or not. + bool shouldFailMessage(MessageType type) const; + + private: + // This function parses the list of strings passed in by the python tests and + // resolves the Message Types that must use the faulty send. + std::vector parseMessagesToFailInput( + const std::vector& messagesToFail) const; + + // Returns amount of time in seconds to delay sending of the given message + // type. + float getDelayForMessage(MessageType type) const; + + // Parse message types that we should inject arbitrary delays for. + std::unordered_map> parseMessagesToDelay( + const std::unordered_map& messageTypesToDelay) const; + + // Number of sends to intentionally fail before allowing one to succeed. + const int numFailSends_; + + // Vector of the MessageTypes that we must use the faulty send for. This is + // parsed based on a list of strings passed in by the python tests. + const std::vector messageTypesToFail_; + + // Mapping of message types to amount we should delay send for in the ::send() + // function. + std::unordered_map> messageTypesToDelay_; + + // Map to track the number of sends we've failed for each RPC. + std::unordered_map failMessageCountMap_; + + // Mutex to guard failMessageCountMap_ + std::mutex failMapMutex_; + + MessageType messageStringToType(const std::string& messageString) const; +}; + +} // namespace torch::distributed::rpc + +#endif // USE_TENSORPIPE + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/testing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/testing.h new file mode 100644 index 0000000000000000000000000000000000000000..baf94a5397fe21394cf9ab024800a29cbc4fe9d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/testing.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::rpc::testing { + +PyMethodDef* python_functions(); + +} // namespace torch::distributed::rpc::testing + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..37c6975d05559d13de07463d279ea11cab121f79 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h @@ -0,0 +1,42 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// This function sends an rpc call to run torchscript function, currently the +// torchscript function could only be a user defined python function with +// "@torch.jit.script" annotation. The torchscript function could not be +// a class constructor, class method, instance method or a script module. +// dst: destination worker name +// qualifiedName: torchscript function qualified name string like +// "moduleName::torchscriptFunctionName", e.g, +// "dist_autograd_test::my_py_add" +// stack: a bag of IValue args passed to torchscriptFunctionName +// It returns c10::intrusive_ptr +c10::intrusive_ptr TORCH_API rpcTorchscript( + const std::string& dstWorkerName, + const c10::QualifiedName& qualifiedName, + const c10::FunctionSchema& functionSchema, + std::vector stack, + const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout, + const bool isAsyncExecution = false); + +c10::intrusive_ptr TORCH_API remoteTorchscript( + const std::string& dstWorkerName, + const c10::QualifiedName& qualifiedName, + const c10::FunctionSchema& functionSchema, + std::vector& stack, + const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout, + const bool isAsyncExecution = false); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/types.h new file mode 100644 index 0000000000000000000000000000000000000000..f8ec54b86e986a64fd2f55d2c35e1d5c594f30f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/types.h @@ -0,0 +1,75 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::rpc { + +using worker_id_t = int16_t; +using local_id_t = int64_t; + +bool getAllowJitRRefPickle(); +TORCH_API void enableJitRRefPickle(); +TORCH_API void disableJitRRefPickle(); + +struct TORCH_API JitRRefPickleGuard { + JitRRefPickleGuard(); + JitRRefPickleGuard(JitRRefPickleGuard&& other) = delete; + JitRRefPickleGuard(const JitRRefPickleGuard&) = delete; + JitRRefPickleGuard& operator=(const JitRRefPickleGuard&) = delete; + JitRRefPickleGuard& operator=(JitRRefPickleGuard&&) = delete; + ~JitRRefPickleGuard(); +}; + +struct TORCH_API GloballyUniqueId final { + GloballyUniqueId(worker_id_t createdOn, local_id_t localId); + GloballyUniqueId(const GloballyUniqueId& other) = default; + GloballyUniqueId& operator=(const GloballyUniqueId& other) = delete; + GloballyUniqueId(GloballyUniqueId&& other) = default; + GloballyUniqueId& operator=(GloballyUniqueId&& other) = delete; + ~GloballyUniqueId() = default; + + bool operator==(const GloballyUniqueId& other) const; + bool operator!=(const GloballyUniqueId& other) const; + + at::IValue toIValue() const; + static GloballyUniqueId fromIValue(const at::IValue& /*ivalue*/); + + struct Hash { + size_t operator()(const GloballyUniqueId& key) const { + return (uint64_t(key.createdOn_) << kLocalIdBits) | key.localId_; + } + }; + + static constexpr int kLocalIdBits = 48; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const worker_id_t createdOn_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const local_id_t localId_; +}; + +TORCH_API std::ostream& operator<<( + std::ostream& os, + const GloballyUniqueId& globalId); + +using RRefId = GloballyUniqueId; +using ForkId = GloballyUniqueId; +using ProfilingId = GloballyUniqueId; + +struct TORCH_API SerializedPyObj final { + SerializedPyObj(std::string&& payload, std::vector&& tensors) + : payload_(std::move(payload)), tensors_(std::move(tensors)) {} + + std::vector toIValues() &&; + static SerializedPyObj fromIValues(std::vector value); + + std::string payload_; + std::vector tensors_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h new file mode 100644 index 0000000000000000000000000000000000000000..da76292342019059afd7d1c868c7cac1e375fd88 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::distributed::rpc { + +// This class converts the content in a PythonCall into py::object. This is a +// helper class to make sure that all arguments deserialization is done before +// entering RequestCallbackImpl::processRpc(...), so that the deserialization +// related logic can be carried out in one spot instead of scattered in multiple +// places for different message types. +// NB: The reason for not consolidating class into PythonCall is because +// PythonCall is a libtorch type which should not depend on Python types. +class TORCH_API UnpickledPythonCall : public RpcCommandBase { + public: + UnpickledPythonCall( + const SerializedPyObj& serializedPyObj, + bool isAsyncExecution); + ~UnpickledPythonCall() override; + + // toMessage() method is not implemented, as objects of this class should + // never be directly converted into a Message object. + c10::intrusive_ptr toMessageImpl() && override; + const py::object& pythonUdf() const; + + inline bool isAsyncExecution() const { + return isAsyncExecution_; + } + + private: + py::object pythonUdf_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isAsyncExecution_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h new file mode 100644 index 0000000000000000000000000000000000000000..afe8a977a615e59b2f77e180275e9fc0e6adc92b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h @@ -0,0 +1,38 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// This class converts the content in a PythonRemoteCall into py::object. This +// is a helper class to make sure that all arguments deserialization is done +// before entering RequestCallbackImpl::processRpc(...), so that the +// deserialization related logic can be carried out in one spot instead of +// scattered in multiple places for different message types. +// NB: The reason for not consolidating class into PythonRemoteCall is because +// PythonRemoteCall is a libtorch type which should not depend on Python types. +class TORCH_API UnpickledPythonRemoteCall final : public UnpickledPythonCall { + public: + explicit UnpickledPythonRemoteCall( + const SerializedPyObj& serializedPyObj, + const at::IValue& retRRefId, + const at::IValue& retForkId, + const bool isAsyncExecution); + + const RRefId& rrefId() const; + const ForkId& forkId() const; + + private: + RRefId rrefId_; + ForkId forkId_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..324d76b2e4dc48b6b12b593fa58c198daa723ad9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h @@ -0,0 +1,91 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// Parse error message and return RPCErrorType based on the message. +TORCH_API RPCErrorType getRPCErrorType(const JitFuture& jitFuture); +// Create an error string given the error description and error type +TORCH_API std::string makeRPCError( + const std::string& rpcErrorStr, + RPCErrorType errorType); + +// Given an RPC message received as a request over the wire, deserialize it into +// the appropriate 'RpcCommandBase' type. +TORCH_API std::unique_ptr deserializeRequest( + const Message& request); + +// Given an RPC message received as a response over the wire, deserialize it +// into the appropriate 'RpcCommandBase' type, if the response is +// FORWARD_AUTOGRAD_RESP type, unwrap it, attach recvBackward() functions +// to received tensors and set the wrappedMsgType to its wrapped message type. +TORCH_API std::unique_ptr deserializeResponse( + const Message& response, + MessageType& wrappedMsgType); + +// Given an RPC message received as a response over the wire, deserialize it +// into the valid IValue if the message is for a script rpc result, +// otherwise deserialize it into dummy none ivalue that will never be used. +// In this deserialization, we also attach recv rpc backward functions if +// needed. +IValue deserializeResptoIValueInternal( + RpcCommandBase& rpc, + MessageType messageType); +TORCH_API IValue deserializeRespToIValue(const Message& message); + +// Note: format is subject to change and intended for RPCs. +// For saving persistently to disk, use torch::save(). +TORCH_API std::string wireSerialize( + const std::vector& payload, + const std::vector& tensors); + +TORCH_API std::pair, std::vector> wireDeserialize( + const void* data, + size_t data_size); + +// We use vector as the type of blobs because it's what rpc::Message uses +// for its payload, even though it has the disadvantage that it cannot be +// allocated with uninitialized memory: it is always zeroed out. + +// Some Tensors are effectively views of larger Tensors, where only a small +// subset of the Storage data is referenced. This normally is good and avoids +// copies when kept locally, but if we naively push the whole Storage over the +// wire, we'll end up with excess network traffic. This change clones tensors if +// we'd save at least half the data, and over a minimum hurdle. +TORCH_API c10::List cloneSparseTensors( + const std::vector& tensors); + +// Combines an original payload and wrapped payload into the original payload. +// Used to generate the overall payload for the wrapped RPC. +TORCH_API void writeWrappedPayload( + std::vector& originalPayload, + std::vector& additionalPayload); + +// Reads the additional, wrapped payload from a wrapped RPC off of the input +// payload. After this, payload will contain the payload of the original, +// un-wrapped RPC. +TORCH_API std::vector readWrappedPayload( + std::vector& payload, + const rpc::Message& message); + +// Takes a list of events from autograd profiler and populates them into +// profiledEvents to be carried over RPC. +TORCH_API void populateRemoteProfiledEvents( + std::vector& profiledEvents, + const torch::autograd::profiler::ProfilerConfig& profilerConfig, + const std::vector>& + eventLists); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cache_entry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cache_entry.h new file mode 100644 index 0000000000000000000000000000000000000000..c178ce57cf456cbd3e7bc3913364e37d80b5c592 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cache_entry.h @@ -0,0 +1,100 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#ifdef __cplusplus + +#include +#include +#include + +extern "C" { + +#endif + +/* +Our cache resides on the extra scratch space of the code object. The structure +of the cache is as follows: + +-> ExtraState + -> CacheEntry (list) + -> guard_manager (a wrapper that contains the actual guard manager at its +attr named root) + -> code + -> FrameState + +CacheEntry is a linked list node containing the guard_manager for guards +and the optimized code. + +The FrameState is a PyDict that enables sharing between different frames. This +is used to detect dynamism in automatic dynamic shapes. + +These two are encapsulated into a ExtraState. +*/ + +typedef struct CacheEntry CacheEntry; +typedef struct ExtraState ExtraState; + +#ifdef __cplusplus + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED( + "-Wdeprecated-copy-with-user-provided-dtor") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wdeprecated-copy-dtor") +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) +typedef struct VISIBILITY_HIDDEN CacheEntry { + // check the guards: lambda: : bool + py::object guard_manager; + // modified user bytecode (protected by guard_manager's guards) + py::object code; + // CompileId corresponding to this compilation + py::object compile_id; + // root guard manager if exists + void* root_mgr{nullptr}; + // diff guard root guard manager if exists + void* diff_guard_root_mgr{nullptr}; + // backend used to create this cache entry + py::object backend; + // Reference to owning ExtraState + ExtraState* _owner{nullptr}; + // Reference to this CacheEntry's location in owner's linked list + std::list::iterator _owner_loc; + // Reference to string representation of the CompileContext + std::string trace_annotation; + + CacheEntry(const py::handle& guarded_code, PyObject* backend); + CacheEntry(const CacheEntry&) = default; + CacheEntry(CacheEntry&&) = default; + CacheEntry& operator=(const CacheEntry&) = default; + CacheEntry& operator=(CacheEntry&&) = default; + ~CacheEntry(); + + // Warning: returns a reference whose lifetime is controlled by C++ + py::object next(); + + void invalidate(py::object deleted_guard_manager); + // Called from the python side to update the diff guard root manager + void update_diff_guard_root_manager(); +} CacheEntry; +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() + +#endif + +// Returns borrowed reference +PyCodeObject* CacheEntry_get_code(CacheEntry* e); + +// Returns borrowed string representation of CompileContext +const char* CacheEntry_get_trace_annotation(CacheEntry* e); + +// Returns a borrowed reference to CacheEntry as a PyObject +// Warning: lifetime is controlled by C++ +PyObject* CacheEntry_to_obj(CacheEntry* e); + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/compiled_autograd.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/compiled_autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..294641783728f9968e9e10beb5b872e11f6cf879 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/compiled_autograd.h @@ -0,0 +1,1566 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// see [Note: Compiled Autograd] + +namespace torch::dynamo::autograd { +using namespace torch::autograd; + +// This is a layer of indirection for calling methods on the Python +// AutogradCompilerInstance (referred to as the "py_compiler") from +// libtorch_cpu (where Python is not available). +// A PyCompilerInterfaceImpl in libtorch_python subclasses it and +// overrides the methods to do the actual calls back to Python. +struct TORCH_API PyCompilerInterface { + PyCompilerInterface() = default; + PyCompilerInterface(const PyCompilerInterface&) = delete; + PyCompilerInterface& operator=(const PyCompilerInterface&) = delete; + PyCompilerInterface(PyCompilerInterface&&) = delete; + PyCompilerInterface& operator=(PyCompilerInterface&&) = delete; + virtual ~PyCompilerInterface() = default; + + // Invokes py_compiler.bind_function + virtual std::string bind_function( + PyObject* py_compiler, + const std::string& fn_name, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + functional_apply_t fn, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::vector packed_args_schema, + bool is_custom_function = false, + bool is_traceable = true) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + + // Invokes py_compiler.method_name(fn_name, inputs, packed_args, + // output_metadata) + virtual variable_list call_function( + PyObject* py_compiler, + const char* method_name, + const std::string& fn_name, + const variable_list& inputs, + const ivalue_list& packed_args, + const c10::IValue& output_metadata) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + virtual variable_list call_copy_slices_prologue( + PyObject* py_compiler, + const variable_list& inputs, + const at::TensorGeometry& base, + const at::TensorGeometry& view) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + virtual variable_list call_copy_slices_epilogue( + PyObject* py_compiler, + const std::vector& needs_input_grad, + const at::Tensor& result, + const variable_list& res, + const at::Tensor& grad_slice) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + virtual at::Tensor call_unpack( + PyObject* py_compiler, + std::optional hook_id, + size_t hook_input_id) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + virtual void call_accumulate_grad( + PyObject* py_compiler, + const at::Tensor& variable, + const at::Tensor& grad, + bool has_post_hooks) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } +}; + +TORCH_API const std::unique_ptr& getPyCompilerInterface(); +struct TORCH_API PyCompilerGuard { + explicit PyCompilerGuard(std::unique_ptr&& impl); + PyCompilerGuard(const PyCompilerGuard&) = delete; + PyCompilerGuard& operator=(const PyCompilerGuard&) = delete; + PyCompilerGuard(PyCompilerGuard&&) = delete; + PyCompilerGuard& operator=(PyCompilerGuard&&) = delete; + + ~PyCompilerGuard(); +}; + +// including torch/csrc/autograd/engine.h breaks BC by somehow introducing +// symbol resolution issues. Instead requiring downstream users to include +// engine.h to access collect_input_metadata, we provide it here (with a +// different name to avoid ambiguous symbols...) +TORCH_API std::vector> get_input_metadata( + const edge_list& edges); + +struct SizeInput { + // Note: int value is still needed when dynamic to pass as an arg + enum DynType : uint8_t { STATIC = 0, DYNAMIC = 1 }; + SizeInput(DynType dt, int64_t v) : dyn_type(dt), value(v) {} + DynType dyn_type; + int64_t value; +}; + +struct CacheKeyBuffer { + CacheKeyBuffer(const uint8_t* key, uint16_t len) : data(new uint8_t[len]) { + std::memcpy(data.get(), key, len); + } + const uint8_t* get() const { + return data.get(); + } + + private: + // NOLINTNEXTLINE(*c-array*) + std::unique_ptr data; +}; + +struct CacheKey { + // Key to find the next node in the shadow graph. We use C++ RTTI for the + // type of the node (ntype), then a key generated with a visitor pattern. + CacheKey(const std::type_index& ntype, const uint8_t* key, uint16_t len) + : node_type(ntype), key_size(len), key(key) {} + + bool operator<(const CacheKey& other) const { + if (node_type != other.node_type) { + return node_type < other.node_type; + } + if (key_size != other.key_size) { + return key_size < other.key_size; + } + return std::memcmp(key, other.key, key_size) < 0; + } + + bool operator==(const CacheKey& other) const { + return node_type == other.node_type && key_size == other.key_size && + std::memcmp(key, other.key, key_size) == 0; + } + + size_t hash() const { + // don't bother hashing the key data, common case 1 cache entry per node + return std::hash()(node_type) ^ key_size; + } + + std::type_index node_type; + uint16_t key_size; + const uint8_t* key; +}; + +struct NodeCall { + NodeCall(uint32_t id_, std::shared_ptr node_) + : id(id_), node(std::move(node_)) {} + + void mark_output(int input_nr, int output_idx) { + graph_output.emplace_back(input_nr, output_idx); + } + + uint32_t id; + std::shared_ptr node; + std::vector> tensor_pre_hooks; + std::vector> cpp_tensor_pre_hooks; + std::vector pre_hooks; + std::vector post_hooks; + std::vector post_acc_grad_hooks; + std::vector> graph_output; + bool needed = true; +}; + +struct NodeCalls : public std::unordered_map { + NodeCall& lookup(const std::shared_ptr& function) { + auto it = find(function.get()); + if (it == end()) { + it = emplace(function.get(), NodeCall(_next_id++, function)).first; + nodes.emplace_back(function.get()); + } + return it->second; + } + + const NodeCall& lookup(uint32_t id) const { + TORCH_INTERNAL_ASSERT(id < nodes.size()); + auto it = find(nodes[id]); + TORCH_INTERNAL_ASSERT(it != end()); + return it->second; + } + + void clear() { + _next_id = 0; + std::unordered_map::clear(); + nodes.clear(); + } + + private: + uint32_t _next_id = 0; + std::vector nodes; +}; + +struct TensorArg { + // Represents a de-duplicated tensor that will be passed into the graph + TensorArg(uint32_t i = 0) : id(i) {} + uint32_t index() const { + TORCH_INTERNAL_ASSERT(defined()); + return id - 1; + } + bool defined() const { + return id != 0; + } + uint32_t id; + at::Tensor proxy_tensor; +}; + +struct TensorArgs { + // Manages a collection of TensorArgs and mappings from Tensors/SavedVariables + // to them. This also allows us to unpack SavedVariable exactly once and + // store the unpacked Tensor. + TensorArgs(const std::optional& active_node_call_idx) + : active_node_call_idx(active_node_call_idx) {} + + TensorArg& lookup(const at::Tensor& tensor, bool create = false) { + if (!tensor.defined()) { + return _undefined; + } + auto impl = tensor.unsafeGetTensorImpl(); + auto it = _args.find(impl); + if (it == _args.end()) { + TORCH_INTERNAL_ASSERT(create && inputs.size() == _next_id - 1); + it = _args.emplace(impl, TensorArg(_next_id++)).first; + inputs.emplace_back(tensor); + if (active_node_call_idx.has_value()) { + input_origins.emplace_back(active_node_call_idx.value()); + } + } + return it->second; + } + + TensorArg& lookup(const SavedVariable& sv) { + if (auto it = _saved_variables.find(&sv); it != _saved_variables.end()) { + // unpacked before graph + return *it->second; + } + // unpacked in graph + auto it2 = _saved_variables_proxies.find(&sv); + TORCH_INTERNAL_ASSERT(it2 != _saved_variables_proxies.end()); + return *it2->second; + } + + TensorArg& add(const at::Tensor& tensor) { + return lookup(tensor, true); + } + + TensorArg& add(const SavedVariable& sv, const std::shared_ptr& node) { + // no unpack hooks in this codepath + at::Tensor tensor = sv.unpack(node); + TensorArg& arg = add(tensor); + _saved_variables.emplace(&sv, &arg); + return arg; + } + + // the concrete tensors that will get passed into the graph as inputs + std::vector inputs; + // NodeCall id of each input, only when verbose logging is enabled + std::vector input_origins; + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional& active_node_call_idx; + std::unordered_map _args; + // Every TensorArg from this is actually owned by _args (or _undefined) and + // that's why we have an un-owned pointer here. + std::unordered_map _saved_variables; + std::unordered_map _saved_variables_proxies; + TensorArg _undefined; + uint32_t _next_id = 1; // id=0 used by _undefined +}; + +struct LiftedIValueArg { + LiftedIValueArg() = delete; + LiftedIValueArg(const at::IValue* ptr) + : actual_ptr(ptr), proxy(at::IValue::uninitialized()) {} + + const at::IValue* actual_ptr; // lifetime handled by autograd node + at::IValue proxy; +}; + +struct LiftedIValueArgs { + LiftedIValueArgs(const std::optional& active_node_call_idx) + : active_node_call_idx(active_node_call_idx) {} + + at::IValue& next_proxy(const at::IValue* actual_ptr) { + TORCH_INTERNAL_ASSERT(next < args.size()); + auto& iv_arg = args.at(next++); + TORCH_INTERNAL_ASSERT(iv_arg.actual_ptr == actual_ptr); + return iv_arg.proxy; + } + + void add(const at::IValue* iv) { + args.emplace_back(iv); + if (active_node_call_idx.has_value()) { + args_origins.emplace_back(active_node_call_idx.value()); + } + } + + std::vector args; + size_t next = 0; + // NodeCall id of each arg, only when verbose logging is enabled + std::vector args_origins; + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional& active_node_call_idx; +}; + +struct AutogradCompilerCall { + AutogradCompilerCall(SizeInput::DynType default_dyn_type) + : active_node_call_idx(std::nullopt), + tensor_args(active_node_call_idx), + lifted_ivalue_args(active_node_call_idx), + default_dyn_type(default_dyn_type) {} + void add_size_input(const c10::SymInt& s) { + all_size_inputs.emplace_back( + default_dyn_type, s.guard_int(__FILE__, __LINE__)); + if (active_node_call_idx.has_value()) { + size_input_origins.emplace_back(active_node_call_idx.value()); + } + } + + size_t emplace_hook(c10::SafePyObject&& fn) { + hooks.emplace_back(std::move(fn)); + return hooks.size() - 1; + } + + size_t emplace_cpp_tensor_pre_hook( + std::function&& fn) { + cpp_tensor_pre_hooks.emplace_back(std::move(fn)); + return cpp_tensor_pre_hooks.size() - 1; + } + + size_t emplace_packed_input(c10::SafePyObject&& input) { + packed_inputs.emplace_back(std::move(input)); + return packed_inputs.size() - 1; + } + + void set_active_node_call_idx(size_t node_call_idx) { + active_node_call_idx = node_call_idx; + } + + std::optional active_node_call_idx; + TensorArgs tensor_args; + std::vector all_size_inputs; + LiftedIValueArgs lifted_ivalue_args; + std::vector dyn_size_inputs; + std::vector hooks; + std::vector> + cpp_tensor_pre_hooks; + std::vector packed_inputs; + NodeCalls node_calls; + SizeInput::DynType default_dyn_type; + // NodeCall id of each size, only when verbose logging is enabled + std::vector size_input_origins; + std::unordered_map> + sv_to_hooks; + // pynode -> backward and backward state idx + std::unordered_map>> + pynode_objs; +}; + +class CompiledNodeArgs { + // CompiledNodeArgs builds a representation of the constant values found + // across all the nodes in the compiled graph, via 'collect' overloads. The + // collected constants are specialized on by concatenation into a cache key. + // Tensor, symint arguments (which are lifted to become graph inputs rather + // than specialized on) are forwarded to the compiler and not included in the + // key. + public: + void collect(const TensorArg& t) { + collect_size(t.id); + if (t.defined()) { + const at::Tensor& tensor = _compiler.tensor_args.inputs[t.index()]; + // including these in the cache key means dynamo-level tensor guards can + // be skipped + collect(tensor.device()); + collect(tensor.dtype()); + collect(tensor.requires_grad()); + } + } + + void collect(const at::Tensor& t) { + collect(_compiler.tensor_args.add(t)); + } + void collect(const SavedVariable& sv, bool is_output) { + if (auto hook_data = sv.retrieve_unpack_hook_data(); + hook_data.has_value()) { + // hooks, unpack in graph + auto& [hook, packed_input] = hook_data.value(); + size_t hook_id = _compiler.emplace_hook(std::move(hook)); + // rely on dynamo to dedup packed tensors from unpacked tensors + size_t input_id = _compiler.emplace_packed_input(std::move(packed_input)); + _compiler.sv_to_hooks.emplace(&sv, std::make_pair(hook_id, input_id)); + } else { + // no hooks, unpack now + collect( + _compiler.tensor_args.add(sv, is_output ? _node_call.node : nullptr)); + } + } + void collect(const c10::SymInt& t) { + _compiler.add_size_input(t); + } + void collect(const std::vector& t, bool is_output) { + collect_size(t.size()); + for (const SavedVariable& i : t) { + collect(i, is_output); + } + } + template + void collect(const std::vector& t) { + collect_size(t.size()); + for (const T& i : t) { + collect(i); + } + } + void collect(const c10::ArrayRef& t, bool is_output) { + collect_size(t.size()); + for (const SavedVariable& i : t) { + collect(i, is_output); + } + } + template + void collect(const c10::ArrayRef& t) { + collect_size(t.size()); + for (const T& i : t) { + collect(i); + } + } + template + void collect(const c10::OptionalArray& t) { + collect(t.list); + } + template + void collect(const std::optional& t) { + if (cond(t.has_value())) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + collect(*t); + } + } + template + void collect(const std::pair& t) { + collect(t.first); + collect(t.second); + } + template + void collect(const ska::flat_hash_map& m) { + collect_size(m.size()); + + std::vector keys; + keys.reserve(m.size()); + std::transform( + m.begin(), m.end(), std::back_inserter(keys), [](const auto& entry) { + return entry.first; + }); + std::sort(keys.begin(), keys.end()); + for (const auto& k : keys) { + collect(k); + collect(m.at(k)); + } + } + void collect(const at::IValue& iv, bool nested = false) { + // used by AutogradContext::saved_data from CppNode + if (iv.isList()) { + c10::List list = iv.toList(); + collect_size(list.size()); + for (auto&& value : list) { + collect(value, true); + } + } else if (iv.isGenericDict()) { + c10::Dict ordered_dict = iv.toGenericDict(); + collect_size(ordered_dict.size()); + // NOLINTNEXTLINE(modernize-loop-convert) + for (auto it = ordered_dict.begin(); it != ordered_dict.end(); it++) { + collect(it->key()); + collect(it->value(), true); + } + } else if (iv.isTensor()) { + collect(iv.toTensor()); + } else if ( + !nested && + (iv.isInt() || iv.isSymInt() || iv.isDouble() || iv.isSymFloat())) { + // can't lift ivalues nested in collections + _compiler.lifted_ivalue_args.add(&iv); + } else { + try { + collect(static_cast(at::IValue::hash(iv))); + } catch (const std::runtime_error& e) { + std::string msg = + "Compiled autograd can not trace unhashable IValues, error: " + + std::string(e.what()); + TORCH_CHECK_NOT_IMPLEMENTED(false, msg); + } + } + } + void collect(const c10::Scalar& t) { + auto type = t.type(); + specialize_on_bytes(type); + if (type == c10::ScalarType::Double) { + collect(t.toDouble()); + } else if (type == c10::ScalarType::Long) { + collect(t.toLong()); + } else if (type == c10::ScalarType::Bool) { + collect(t.toBool()); + } else if (type == c10::ScalarType::ComplexDouble) { + auto c = t.toComplexDouble(); + collect(c.real()); + collect(c.imag()); + } else { + TORCH_INTERNAL_ASSERT(false); + } + } + void collect(const c10::TensorOptions& t) { + collect(t.device()); + collect(t.dtype()); + collect(t.layout()); + collect(t.requires_grad()); + collect(t.pinned_memory()); + collect(t.memory_format_opt()); + } + void collect(const at::TensorGeometry& t) { + collect(t.sym_sizes()); + collect(t.sym_strides()); + collect(t.sym_storage_offset()); + } + void collect(const torch::autograd::TypeAndSize& t) { + collect(t.sym_sizes); + collect(t.options); + } + void collect(const c10::Device& t) { + collect(t.type()); + collect(t.index()); + } + void collect(const std::string& t) { + collect_size(t.size()); + for (char c : t) { + collect(c); + } + } + void collect(const caffe2::TypeMeta& t) { + specialize_on_bytes(t.id()); + } + void collect(const std::shared_ptr& t) { + // Note: this is only capturing the ID of the node not everything + // contained inside it. This is used for tracking connections between + // nodes and the actual details of the node itself must be handled by + // a separate call to `node->compiled_args()`. + if (cond((bool)t)) { + collect(_compiler.node_calls.lookup(t)); + } + } + void collect(const NodeCall& t) { + collect_size(t.id); + collect(t.graph_output); + collect_hooks_from(t.node.get()); + } + void collect(const Edge& t) { + if (cond(t.is_valid())) { + collect_size(_compiler.node_calls.lookup(t.function).id); + collect_size(t.input_nr); + collect(t.function->input_metadata(t.input_nr)); // for validate_outputs + } + } + void collect(const InputMetadata& t) { + TORCH_CHECK_NOT_IMPLEMENTED( + !t.is_nested_tensor(), "NestedTensor support not implemented. "); + collect(t.options()); + collect(t.is_tensor_subclass()); + collect(t.shape_as_dim_vector()); + } + void collect(const VariableInfo& t) { + collect(t.layout); + collect(t.device); + collect(t.scalar_type); + collect(t.size); + collect(t.requires_grad); + collect(t.is_empty); + } + bool cond(bool cond) { + collect(cond); + return cond; + } + +#define COLLECT_AS_BYTES(T) \ + void collect(T t) { \ + specialize_on_bytes(t); \ + } + COLLECT_AS_BYTES(c10::ScalarType) + COLLECT_AS_BYTES(c10::DeviceType) + COLLECT_AS_BYTES(c10::Layout) + COLLECT_AS_BYTES(c10::MemoryFormat) + COLLECT_AS_BYTES(int8_t) + COLLECT_AS_BYTES(int16_t) + COLLECT_AS_BYTES(int32_t) + COLLECT_AS_BYTES(int64_t) + COLLECT_AS_BYTES(uint8_t) + COLLECT_AS_BYTES(uint16_t) + COLLECT_AS_BYTES(uint32_t) + COLLECT_AS_BYTES(uint64_t) + COLLECT_AS_BYTES(bool) + COLLECT_AS_BYTES(float) + COLLECT_AS_BYTES(double) +#undef COLLECT_AS_BYTES + + void collect_hooks_from(Node* fn) { + for (auto& i : fn->tensor_pre_hooks()) { + i->compiled_args(*this); + } + for (auto& [_, i] : fn->retains_grad_hooks()) { + i->compiled_args(*this); + } + for (auto& i : fn->pre_hooks()) { + i->compiled_args(*this); + } + for (auto& i : fn->post_hooks()) { + i->compiled_args(*this); + } + collect_size(_node_call.tensor_pre_hooks.size()); + collect_size(_node_call.pre_hooks.size()); + collect_size(_node_call.post_hooks.size()); + for (const auto& h : _node_call.tensor_pre_hooks) { + collect_size(static_cast(h.second)); + } + } + + CacheKey key() const { + Node* node = _node_call.node.get(); + return CacheKey( + typeid(*node), _specialization_key, _specialization_key_size); + } + + void collect_pynode_objs( + const Node* pynode, + c10::SafePyObject&& bwd, + std::optional&& bwd_state) { + size_t bwd_idx = _compiler.emplace_hook(std::move(bwd)); + std::optional bwd_state_idx; + if (auto state = std::move(bwd_state); state.has_value()) { + bwd_state_idx = _compiler.emplace_hook(std::move(state.value())); + } + _compiler.pynode_objs.emplace( + pynode, std::make_pair(bwd_idx, bwd_state_idx)); + } + + void add_tensor_pre_hook(c10::SafePyObject&& obj, int index) { + auto fn_id = _compiler.emplace_hook(std::move(obj)); + collect_size(fn_id); + _node_call.tensor_pre_hooks.emplace_back(fn_id, index); + } + + void add_cpp_single_tensor_pre_hook( + const std::function& hook, + size_t idx) { + auto wrapper = [hook](const at::TensorBase& grad) { + // handle when hook returns nothing + auto out = hook(grad); + if (!out.defined()) { + return grad; + } + return out; + }; + + auto hook_id = _compiler.emplace_cpp_tensor_pre_hook(std::move(wrapper)); + collect_size(hook_id); + _node_call.cpp_tensor_pre_hooks.emplace_back(hook_id, idx); + } + + void add_pre_hook(c10::SafePyObject&& obj) { + auto fn_id = _compiler.emplace_hook(std::move(obj)); + collect_size(fn_id); + _node_call.pre_hooks.emplace_back(fn_id); + } + + void add_post_hook(c10::SafePyObject&& obj) { + auto fn_id = _compiler.emplace_hook(std::move(obj)); + collect_size(fn_id); + _node_call.post_hooks.emplace_back(fn_id); + } + + void add_post_acc_grad_hook(c10::SafePyObject&& obj) { + auto fn_id = _compiler.emplace_hook(std::move(obj)); + collect_size(fn_id); + _node_call.post_acc_grad_hooks.emplace_back(fn_id); + } + + // Need to template the size_t to silence internal 32-bit build errors due to + // a mix of -Werror, -Wtautological-type-limit-compare and + // -Wunknown-pragmas + template + std::enable_if_t, void> collect_size(T s) { + // we expect sizes to be small, so try to cram them into a single byte + constexpr uint8_t encode_as_u64 = std::numeric_limits::max(); + constexpr uint8_t encode_as_u32 = encode_as_u64 - 1; + constexpr uint8_t encode_as_u16 = encode_as_u64 - 2; + if (C10_UNLIKELY(s >= encode_as_u16)) { + // first write a byte indicating the path we followed, then the data + if (s <= std::numeric_limits::max()) { + // 3 bytes + specialize_on_bytes(encode_as_u16); + specialize_on_bytes(static_cast(s)); + } else if (s <= std::numeric_limits::max()) { + // 5 bytes + specialize_on_bytes(encode_as_u32); + specialize_on_bytes(static_cast(s)); + } else { + // 9 bytes + specialize_on_bytes(encode_as_u64); + specialize_on_bytes(s); + } + } else { + // happy case, 1 byte + specialize_on_bytes(static_cast(s)); + } + } + + SizeInput::DynType set_default_dyn_type(SizeInput::DynType default_dyn_type) { + return std::exchange(_compiler.default_dyn_type, default_dyn_type); + } + + CompiledNodeArgs(AutogradCompilerCall& compiler, NodeCall& node_call) + : _compiler(compiler), + _node_call(node_call), + _specialization_key( + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + (uint8_t*)std::malloc(_specialization_key_storage)) {} + CompiledNodeArgs(const CompiledNodeArgs&) = delete; + CompiledNodeArgs(CompiledNodeArgs&&) = delete; + CompiledNodeArgs& operator=(const CompiledNodeArgs&) = delete; + CompiledNodeArgs& operator=(CompiledNodeArgs&&) = delete; + ~CompiledNodeArgs() { + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + std::free(_specialization_key); + } + + private: + template + void specialize_on_bytes(const T& t) { + while (C10_UNLIKELY( + _specialization_key_size + sizeof(T) > _specialization_key_storage)) { + _specialization_key_storage *= 2; + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + _specialization_key = (uint8_t*)std::realloc( + _specialization_key, _specialization_key_storage); + } + std::memcpy(_specialization_key + _specialization_key_size, &t, sizeof(T)); + _specialization_key_size += sizeof(T); + } + + AutogradCompilerCall& _compiler; + NodeCall& _node_call; + size_t _specialization_key_size{0}; + size_t _specialization_key_storage{1024}; + uint8_t* _specialization_key; +}; + +struct TraceState { + TraceState(std::vector>&& ss, size_t num_outputs) + : sym_sizes(std::move(ss)), outputs(num_outputs) {} + + void debug_asserts() { + TORCH_INTERNAL_ASSERT(sym_sizes_index == sym_sizes.size()); + } + std::optional next_sym_size() { + TORCH_INTERNAL_ASSERT(sym_sizes_index < sym_sizes.size()); + return sym_sizes[sym_sizes_index++]; + } + + size_t sym_sizes_index{0}; + std::vector> sym_sizes; + variable_list outputs; +}; + +class SwapSavedVariables { + // SwapSavedVariables is used during the tracing/compilation phase after a + // cache-miss. It swaps any 'lifted' inputs (tensors, symints) to proxy nodes, + // allows tracing to happen, then swaps them back afterwards. + public: + std::pair> retrieve_pynode_objs( + Node* pynode) const { + auto it = compiler.pynode_objs.find(pynode); + TORCH_INTERNAL_ASSERT(it != compiler.pynode_objs.end()); + return it->second; + } + + void before(at::Tensor& t) { + TensorArg& arg = compiler.tensor_args.lookup(t); + stashed_tensors.save(&t, std::move(t)); + if (arg.defined()) { + TORCH_INTERNAL_ASSERT(arg.proxy_tensor.defined()); + t = arg.proxy_tensor; + } + } + void after(at::Tensor& t) { + stashed_tensors.restore(&t); + } + + void before(SavedVariable& t) { + if (auto it = compiler.sv_to_hooks.find(&t); + it != compiler.sv_to_hooks.end()) { + const auto& pyinterface = + torch::dynamo::autograd::getPyCompilerInterface(); + auto proxy_tensor = pyinterface->call_unpack( + get_py_compiler(), it->second.first, it->second.second); + stashed_variables.save(&t, std::move(t)); + bool prior = at::SavedTensorDefaultHooks::set_tracing(true); + t = SavedVariable(proxy_tensor, false); + at::SavedTensorDefaultHooks::set_tracing(prior); + } else { + // no hooks, was already unpacked + TensorArg& arg = compiler.tensor_args.lookup(t); + stashed_variables.save(&t, std::move(t)); + if (arg.defined()) { + bool prior = at::SavedTensorDefaultHooks::set_tracing(true); + TORCH_INTERNAL_ASSERT(arg.proxy_tensor.defined()); + t = SavedVariable(arg.proxy_tensor, false); + at::SavedTensorDefaultHooks::set_tracing(prior); + } + } + } + void after(SavedVariable& t) { + stashed_variables.restore(&t); + } + + void before(c10::SymInt& t) { + stashed_symints.save(&t, c10::SymInt(t)); + auto opt_value = state.next_sym_size(); + if (opt_value.has_value()) { + t = *opt_value; // dynamic shape + } + } + void after(c10::SymInt& t) { + stashed_symints.restore(&t); + } + + void before(at::IValue& iv) { + if (iv.isTensor()) { + before(iv.toTensor()); + } else { + stashed_ivalues.save(&iv, at::IValue(iv)); + if (iv.isInt() || iv.isSymInt() || iv.isDouble() || iv.isSymFloat()) { + iv = compiler.lifted_ivalue_args.next_proxy(&iv); + } + } + } + + void after(at::IValue& t) { + if (t.isTensor()) { + after(t.toTensor()); + } else { + stashed_ivalues.restore(&t); + } + } + + void before(Edge& t) { + if (t.is_valid()) { + // need for symints used by validate_outputs + before(t.function->mutable_input_metadata(t.input_nr)); + } + } + void after(Edge& t) { + if (t.is_valid()) { + after(t.function->mutable_input_metadata(t.input_nr)); + } + } + void before(InputMetadata& t) { + before(t.mutable_shape_as_dim_vector()); + } + void after(InputMetadata& t) { + after(t.mutable_shape_as_dim_vector()); + } + void before(at::TensorGeometry& t) { + before(t.mutable_sizes()); + before(t.mutable_strides()); + before(t.mutable_storage_offset()); + t.recompute(); + } + void after(at::TensorGeometry& t) { + after(t.mutable_sizes()); + after(t.mutable_strides()); + after(t.mutable_storage_offset()); + t.recompute(); + } + void before(torch::autograd::TypeAndSize& t) { + before(t.sym_sizes); + before(t.options); + } + void after(torch::autograd::TypeAndSize& t) { + after(t.sym_sizes); + after(t.options); + } + void before(VariableInfo& t) { + before(t.size); + } + void after(VariableInfo& t) { + after(t.size); + } + + template + void before(std::vector& t) { + for (T& i : t) { + before(i); + } + } + template + void after(std::vector& t) { + for (T& i : t) { + after(i); + } + } + template + void before(c10::SmallVector& t) { + for (T& i : t) { + before(i); + } + } + template + void after(c10::SmallVector& t) { + for (T& i : t) { + after(i); + } + } + + template + void before(c10::OptionalArray& t) { + before(t.list); + } + template + void after(c10::OptionalArray& t) { + after(t.list); + } + + template + void before(std::optional& t) { + if (t.has_value()) { + before(*t); + } + } + template + void after(std::optional& t) { + if (t.has_value()) { + after(*t); + } + } + + template + void before(ska::flat_hash_map& m) { + std::vector keys; + keys.reserve(m.size()); + std::transform( + m.begin(), m.end(), std::back_inserter(keys), [](const auto& entry) { + return entry.first; + }); + std::sort(keys.begin(), keys.end()); + for (auto& k : keys) { + before(m.at(k)); + } + } + + template + void after(ska::flat_hash_map& m) { + for (auto& [_, v] : m) { + after(v); + } + } + +#define NO_OP_VISIT(T) \ + void before(const T&) {} \ + void after(const T&) {} + NO_OP_VISIT(caffe2::TypeMeta) + NO_OP_VISIT(c10::Device) + NO_OP_VISIT(c10::DeviceType) + NO_OP_VISIT(c10::Layout) + NO_OP_VISIT(c10::MemoryFormat) + NO_OP_VISIT(c10::ScalarType) + NO_OP_VISIT(c10::Scalar) + NO_OP_VISIT(c10::TensorOptions) + NO_OP_VISIT(std::string) + NO_OP_VISIT(int64_t) + NO_OP_VISIT(bool) + NO_OP_VISIT(double) +#undef NO_OP_VISIT + + SwapSavedVariables( + AutogradCompilerCall& c, + TraceState& s, + PyObject* p, + const NodeCall& n) + : compiler(c), state(s), py_compiler(p), curr_node_call(n) {} + + PyObject* get_py_compiler() const { + return py_compiler; + } + + const NodeCall& get_curr_node_call() { + return curr_node_call; + } + + void debug_asserts() { + stashed_variables.debug_assert(); + stashed_tensors.debug_assert(); + stashed_symints.debug_assert(); + } + + private: + template + struct Stashed { + Stashed(T&& v) : prior_value(std::move(v)) {} + T prior_value; + // Note: we need count here to support duplicate calls to before() + // which happen when we have multiple autograd::Edge objects pointing + // to the same autograd::Node + int count = 1; + }; + + template + struct StashedVars : public std::unordered_map> { + void save(const T* key, T&& value) { + auto [it, inserted] = this->try_emplace(key, std::move(value)); + if (!inserted) { + // keep the value from the prior save() + it->second.count++; + } + } + void restore(T* var) { + auto it = this->find(var); + TORCH_INTERNAL_ASSERT(it != this->end(), "missing before())"); + if (--it->second.count == 0) { + // restore the value on the last restore() + *var = std::move(it->second.prior_value); + this->erase(it); + } + } + void debug_assert() { + TORCH_INTERNAL_ASSERT(this->empty(), "missing call to after()"); + } + }; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + AutogradCompilerCall& compiler; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + TraceState& state; + // This is a borrowed reference, we do not increment ownership, or lower it, + // it's lifecycle is entirely longer than this objects. + PyObject* py_compiler; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const NodeCall& curr_node_call; + + // These mappings are used to save the prior values when we overwrite things + // in before(). In after(), we use these to cleanup after ourselves. + StashedVars stashed_variables; + StashedVars stashed_tensors; + StashedVars stashed_symints; + StashedVars stashed_ivalues; +}; + +// NOTE: [Compiled Autograd and backward functions] +// Built-in autograd nodes have functional apply variants +// (e.g. MulBackward0_apply_functional). Compiled Autograd's initial graph +// capture wants to take a variant of this function and proxy it into the graph. +// Every autograd node defines an apply_with_saved function, that when invoked, +// proxies a call to a function into the Compiled Autograd graph. +// +// Some requirements that we have are: +// - The proxy'ed function must have inputs that are FX-graphable types. +// - Windows has a DLL symbol limit of 65536. +// - Node::apply_with_saved is in libtorch_cpu which does not have direct access +// to Python +// +// There were multiple ways to skin the cat, but what we end up doing is: +// - for e.g. MulBackward0_apply_functional, we create a new C++ function +// MulBackward0_apply_functional_ivalue that accepts vector. +// - We define how to pack and unpack arbitrary C++ types into IValues. +// - apply_with_saved passes MulBackward0_apply_functional_ivalue and +// the IValue arguments to Python via an indirection. +// In Python, these get proxy'ed into a graph. + +// Helper struct for packing/unpacking an arbitrary C++ type into a single +// IValue. There are various full and partial specializations for IValuePacker +// to handle packing specific types (like TensorOptions) into an IValue. +template +struct IValuePacker { + // Defines how to pack T into an IValue. + static at::IValue pack(const T& t) { + return t; + } + // Defines how to unpack an IValue into T. + static T unpack(const at::IValue& t) { + return t.to(); + } + // Returns the TypePtr for the IValue (this is like the "type" of the IValue). + // We use this when passing the packed IValue from Python to C++. + // In Python, the IValue is just a PyObject* with the native type. + // For example, it may be a Python int, a Python List[int], etc. + // When passing this PyObject* into C++, we need to know how to parse it + // into a C++ type that then gets put into an IValue. + // That's what the TypePtr is for: it contains the information to do the + // parsing. See torch::jit::toIValue for more information. + static at::TypePtr packed_type() { + // On windows CPU is support compiled autograd. +#if defined(_WIN32) && (defined(USE_CUDA) || defined(USE_ROCM)) + // NB: the if-constexpr usage triggers compilation errors on Windows + // with certain compiler settings + // (see https://github.com/pytorch/pytorch/pull/144707 for examples). + // It's not clear what the problem is, so we're going to ignore it for now. + TORCH_CHECK_NOT_IMPLEMENTED( + false, "torch.compile not supported on Windows"); +#else + if constexpr (::std::is_same_v) { + return at::TensorType::get(); + } else if constexpr (::std::is_same_v) { + return at::IntType::get(); + } else if constexpr (::std::is_same_v) { + return at::SymIntType::get(); + } else if constexpr (::std::is_same_v) { + return at::BoolType::get(); + } else if constexpr (::std::is_same_v) { + return at::FloatType::get(); + } else if constexpr (::std::is_same_v) { + return at::SymFloatType::get(); + } else if constexpr (::std::is_same_v) { + return at::SymBoolType::get(); + } else if constexpr (::std::is_same_v) { + return at::LayoutType::get(); + } else if constexpr (::std::is_same_v) { + return at::StringType::get(); + } else if constexpr (::std::is_same_v) { + return at::DeviceObjType::get(); + } else if constexpr (::std::is_same_v) { + return at::NumberType::get(); + } else if constexpr (::std::is_same_v) { + return at::MemoryFormatType::get(); + } else if constexpr (::std::is_same_v) { + return at::ScalarTypeType::get(); + } else { + // If you got here, you have probably added a member of a new type + // to a built-in C++ autograd node. + // Unfortunately, we don't know how to handle this type yet. + // To get this new type to work with Compiled Autograd, please + // either change it to be an IValue-constructible type, or + // define how to pack and unpack an object of this time into an IValue + // by creating a specialization of IValuePacker for this type. + // See NOTE: [Compiled Autograd and backward functions] for context. + TORCH_CHECK_NOT_IMPLEMENTED( + false, "IValuePacker not implemented for type"); + return at::NoneType::get(); + } +#endif + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const size_t& t) { + // We generally use size_t as the size of a list of Tensors or number of + // dimensions. The number of dimensions generally do not exceed 64 + // (TensorIterator has that limitation), and lists of Tensors generally do + // not exceed the int64_t max (you'd probably run out of RAM or run into + // significant Tensor overhead). If you run into this limitation the fix is + // to figure out how to pack size_t into int64_t. Note that size_t has some + // weird behavior on Mac OS. + uint64_t maximum_value = std::numeric_limits::max(); + TORCH_INTERNAL_ASSERT( + static_cast(t) <= maximum_value, + "size_t too large to pack into IValue"); + return static_cast(t); // pack as int64_t + } + static size_t unpack(const at::IValue& t) { + return static_cast(t.toInt()); + } + static at::TypePtr packed_type() { + return IValuePacker::packed_type(); + } +}; + +template <> +struct IValuePacker> { + static at::IValue pack(const std::vector& t) { + return t; + } + static std::vector unpack(const at::IValue& t) { + // We need this because there's no t.to>() override? + return t.toSymIntVector(); + } + static at::TypePtr packed_type() { + return at::ListType::create(at::SymIntType::get()); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const VariableInfo& t) { + auto tuple = std::make_tuple( + t.layout, t.device, t.scalar_type, t.size, t.requires_grad, t.is_empty); + return tuple; + } + static VariableInfo unpack(const at::IValue& t) { + auto tuple = t.toTuple(); + const auto& tuple_elements = tuple->elements(); + const auto elements = tuple_elements.asArrayRef(); + TORCH_INTERNAL_ASSERT(elements.size() == 6); + VariableInfo v; + v.layout = elements[0].toLayout(); + v.device = elements[1].toDevice(); + v.scalar_type = elements[2].toScalarType(); + v.size = elements[3].toSymIntVector(); + v.requires_grad = elements[4].toBool(); + v.is_empty = elements[5].toBool(); + return v; + } + static at::TypePtr packed_type() { + return at::TupleType::create({ + at::LayoutType::get(), + at::DeviceObjType::get(), + at::ScalarTypeType::get(), + at::ListType::create(at::SymIntType::get()), + at::BoolType::get(), + at::BoolType::get(), + }); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const caffe2::TypeMeta& t) { + return at::typeMetaToScalarType(t); // pack as at::ScalarType + } + static caffe2::TypeMeta unpack(const at::IValue& t) { + return caffe2::TypeMeta::fromScalarType(t.to()); + } + static at::TypePtr packed_type() { + return IValuePacker::packed_type(); + } +}; + +inline std::optional optTypeMetaToScalarType( + const std::optional& t) { + if (t.has_value()) { + return at::typeMetaToScalarType(t.value()); + } else { + return std::nullopt; + } +} + +using packed_tensoroptions_t = std::tuple< + std::optional, + std::optional, + std::optional, + std::optional, + std::optional, + std::optional>; + +inline packed_tensoroptions_t pack_TensorOptions(const at::TensorOptions& t) { + auto tuple = std::make_tuple( + t.requires_grad_opt(), + t.memory_format_opt(), + t.device_opt(), + optTypeMetaToScalarType(t.dtype_opt()), + t.layout_opt(), + t.pinned_memory_opt()); + return tuple; +} +inline at::TensorOptions unpack_TensorOptions( + const packed_tensoroptions_t& tuple) { + at::TensorOptions result; + auto maybe_requires_grad = std::get<0>(tuple); + if (maybe_requires_grad.has_value()) { + result = result.requires_grad(maybe_requires_grad); + } + auto maybe_memory_format = std::get<1>(tuple); + if (maybe_memory_format.has_value()) { + result = result.memory_format(maybe_memory_format); + } + auto maybe_device = std::get<2>(tuple); + if (maybe_device.has_value()) { + result = result.device(maybe_device.value()); + } + auto maybe_dtype = std::get<3>(tuple); + if (maybe_dtype.has_value()) { + result = + result.dtype(caffe2::TypeMeta::fromScalarType(maybe_dtype.value())); + } + auto maybe_layout = std::get<4>(tuple); + if (maybe_layout.has_value()) { + result = result.layout(maybe_layout); + } + auto maybe_pinned_memory = std::get<5>(tuple); + if (maybe_pinned_memory.has_value()) { + result = result.pinned_memory(maybe_pinned_memory); + } + return result; +} + +template <> +struct IValuePacker { + static at::IValue pack(const at::TensorOptions& t) { + return pack_TensorOptions(t); + } + static at::TensorOptions unpack(const at::IValue& t) { + auto tuple = t.to(); + return unpack_TensorOptions(tuple); + } + static at::TypePtr packed_type() { + return at::TupleType::create( + {at::OptionalType::create(at::BoolType::get()), + at::OptionalType::create(at::MemoryFormatType::get()), + at::OptionalType::create(at::DeviceObjType::get()), + at::OptionalType::create(at::ScalarTypeType::get()), + at::OptionalType::create(at::LayoutType::get()), + at::OptionalType::create(at::BoolType::get())}); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const TypeAndSize& t) { + auto tuple = std::make_tuple(t.sym_sizes, pack_TensorOptions(t.options)); + return tuple; + } + static TypeAndSize unpack(const at::IValue& t) { + auto tuple = + t.to, packed_tensoroptions_t>>(); + TypeAndSize result; + result.sym_sizes = std::get<0>(tuple); + result.options = unpack_TensorOptions(std::get<1>(tuple)); + return result; + } + static at::TypePtr packed_type() { + return at::TupleType::create( + {IValuePacker>::packed_type(), + IValuePacker::packed_type()}); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const std::optional& t) { + if (t.has_value()) { + return IValuePacker::pack(t.value()); + } else { + return std::nullopt; + } + } + static std::optional unpack(const at::IValue& t) { + if (t.isNone()) { + return std::nullopt; + } else { + return IValuePacker::unpack(t); + } + } + static at::TypePtr packed_type() { + return at::OptionalType::create(IValuePacker::packed_type()); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const std::vector& t) { + if constexpr (::std::is_constructible_v) { + return t; + } + if (t.empty()) { + auto lst = c10::impl::GenericList(at::AnyType::get()); + return lst; + } + auto type_ptr = IValuePacker::pack(t[0]).type(); + auto lst = c10::impl::GenericList(type_ptr); + for (const auto& elt : t) { + lst.emplace_back(IValuePacker::pack(elt)); + } + return lst; + } + static std::vector unpack(const at::IValue& t) { + if constexpr (::std::is_constructible_v) { + return t.to<::std::vector>(); + } + std::vector result; + auto lst = t.toList(); + for (size_t i = 0; i < lst.size(); ++i) { + const at::IValue& elt = lst.get(i); + result.emplace_back(IValuePacker::unpack(elt)); + } + return result; + } + static at::TypePtr packed_type() { + return at::ListType::create(IValuePacker::packed_type()); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const c10::List& t) { + return IValuePacker>::pack(t.vec()); + } + static c10::List unpack(const at::IValue& t) { + return c10::List(IValuePacker>::unpack(t)); + } + static at::TypePtr packed_type() { + return IValuePacker>::packed_type(); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const std::array& t) { + std::vector result(t.begin(), t.end()); + return IValuePacker>::pack(result); + } + static std::array unpack(const at::IValue& t) { + std::array result; + auto packed = IValuePacker>::unpack(t); + for (size_t i = 0; i < packed.size(); i++) { + result[i] = packed[i]; + } + return result; + } + static at::TypePtr packed_type() { + return IValuePacker>::packed_type(); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const at::TensorGeometry& t) { + auto tuple = std::make_tuple( + t.sym_sizes().vec(), t.sym_strides().vec(), t.sym_storage_offset()); + return tuple; + } + static at::TensorGeometry unpack(const at::IValue& t) { + auto tuple = t.to, + std::vector, + at::SymInt>>(); + return at::TensorGeometry( + std::get<0>(tuple), std::get<1>(tuple), std::get<2>(tuple)); + } + static at::TypePtr packed_type() { + return at::TupleType::create( + {IValuePacker>::packed_type(), + IValuePacker>::packed_type(), + at::SymIntType::get()}); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const InputMetadata& t) { + TORCH_INTERNAL_ASSERT(!t.is_nested_tensor()); + auto tuple = std::make_tuple( + pack_TensorOptions(t.options()), + t.shape_as_dim_vector().vec(), + t.is_tensor_subclass(), + t.grad_dtype()); + return tuple; + } + static InputMetadata unpack(const at::IValue& t) { + auto tuple = t.to, + bool, + std::optional>>(); + + return InputMetadata( + unpack_TensorOptions(std::get<0>(tuple)), + SymIntSmallVec(std::get<1>(tuple)), + std::get<2>(tuple), + false, + std::get<3>(tuple)); + } + static at::TypePtr packed_type() { + return at::TupleType::create( + {IValuePacker::packed_type(), + IValuePacker>::packed_type(), + at::BoolType::get(), + IValuePacker>::packed_type()}); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const at::OptionalArray& t) { + return IValuePacker>>::pack(t.list); + } + static at::OptionalArray unpack(const at::IValue& t) { + auto result = IValuePacker>>::unpack(t); + if (result.has_value()) { + return {result.value()}; + } else { + return {}; + } + } + static at::TypePtr packed_type() { + return IValuePacker>>::packed_type(); + } +}; + +// This is a helper struct for packing and unpacking multiple arguments into +// an ivalue_list. It leverages IValuePacker. +struct PackedArgs { + PackedArgs() = default; + + explicit PackedArgs(std::vector stack_) + : stack(std::move(stack_)) {} + + const std::vector& vec() const { + return stack; + } + + template + void pack(const T& t) { + stack.emplace_back(IValuePacker::pack(t)); + } + template + T unpack() { + return IValuePacker::unpack(std::move(stack[idx++])); + } + + void pack_saved_data(const ska::flat_hash_map& dct) { + std::vector keys; + std::vector values; + for (const auto& [key, value] : dct) { + keys.emplace_back(key); + values.emplace_back(value); + } + pack(keys); + for (const auto& value : values) { + pack(value); + } + } + + ska::flat_hash_map unpack_saved_data() { + ska::flat_hash_map dct; + auto keys = unpack>(); + for (const auto& key : keys) { + dct.insert({key, std::move(stack[idx++])}); + } + return dct; + } + + private: + std::vector stack; + int64_t idx = 0; +}; + +} // namespace torch::dynamo::autograd + +template <> +struct std::hash { + size_t operator()(const torch::dynamo::autograd::CacheKey& k) const { + return k.hash(); + } +}; + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpp_shim.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpp_shim.h new file mode 100644 index 0000000000000000000000000000000000000000..d764297efb4acb23aaadfea5a2658f8b5a3512f1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpp_shim.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct _PytorchRecordFunctionState; +typedef struct _PytorchRecordFunctionState _PytorchRecordFunctionState; + +_PytorchRecordFunctionState* _pytorch_record_function_enter(const char* name); +void _pytorch_record_function_exit(_PytorchRecordFunctionState* state); + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_defs.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_defs.h new file mode 100644 index 0000000000000000000000000000000000000000..d2d361c2b8ec4fd4b6331738ee01f9bc3d54356a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_defs.h @@ -0,0 +1,45 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// Functions that need to be copied from the CPython source +// should go in cpython_defs.c. Copying is required when, e.g., +// we need to call internal CPython functions that are not exposed. + +#if IS_PYTHON_3_11_PLUS + +typedef struct _PyInterpreterFrame _PyInterpreterFrame; + +PyFunctionObject* _PyFunction_CopyWithNewCode( + PyFunctionObject* o, + PyCodeObject* code); + +void THP_PyFrame_Clear(_PyInterpreterFrame* frame); + +_PyInterpreterFrame* THP_PyThreadState_BumpFramePointerSlow( + PyThreadState* tstate, + size_t size); + +void THP_PyThreadState_PopFrame( + PyThreadState* tstate, + _PyInterpreterFrame* frame); + +#endif + +// pointers to _PyOpcode_Caches for C++ +#ifdef __cplusplus +extern "C" { +#endif + +extern const uint8_t* THP_PyOpcode_Caches; +extern int THP_PyOpcode_Caches_size; +void init_THPCaches(); + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_includes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_includes.h new file mode 100644 index 0000000000000000000000000000000000000000..ea994e6fce119bcb14ed14239d80fe4faa4de1b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_includes.h @@ -0,0 +1,76 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// Problem in CPython includes when mixing core and non-core build +// The fix was not backported to 3.12 so this is needed here +// https://github.com/python/cpython/issues/105268 +#if IS_PYTHON_3_12_PLUS +#undef _PyGC_FINALIZED +#endif + +// see https://bugs.python.org/issue35886 +#define Py_BUILD_CORE + +#ifndef __cplusplus +// C-only headers +#include + +#endif // __cplusplus + +#if IS_PYTHON_3_11_PLUS +#include + +#include +#if IS_PYTHON_3_14_PLUS && !defined(_WIN32) +#include +#include +#include +#include +#elif IS_PYTHON_3_14_PLUS && defined(_WIN32) +#include // _PyInterpreterFrame +#endif + +#endif + +#undef Py_BUILD_CORE + +#ifdef __cplusplus +extern "C" { +#endif + +#if IS_PYTHON_3_14_PLUS + +#define F_CODE(x) \ + ((PyCodeObject*)THP_PyStackRef_AsPyObjectBorrow(&(x)->f_executable)) +#define PREV_INSTR(x) (x)->instr_ptr + +#else + +#if IS_PYTHON_3_13_PLUS +#define F_CODE(x) ((PyCodeObject*)(x)->f_executable) +#define PREV_INSTR(x) (x)->instr_ptr +#else +#define F_CODE(x) ((PyCodeObject*)(x)->f_code) +#define PREV_INSTR(x) (x)->prev_instr +#endif // IS_PYTHON_3_13_PLUS + +#endif // IS_PYTHON_3_14_PLUS + +#if IS_PYTHON_3_14_PLUS +#define FUNC(x) \ + ((PyFunctionObject*)THP_PyStackRef_AsPyObjectBorrow(&(x)->f_funcobj)) +#elif IS_PYTHON_3_12_PLUS +#define FUNC(x) ((PyFunctionObject*)(x)->f_funcobj) +#else +#define FUNC(x) ((PyFunctionObject*)(x)->f_func) +#endif + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/debug_macros.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/debug_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..49ef7b69fe4ab8a5a6948644c98008c11518489d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/debug_macros.h @@ -0,0 +1,107 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#ifdef __cplusplus +#include +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _WIN32 +#define unlikely(x) (x) +#else +#define unlikely(x) __builtin_expect((x), 0) +#endif + +#define NULL_CHECK(val) \ + if (unlikely((val) == NULL)) { \ + fprintf(stderr, "NULL ERROR: %s:%d\n", __FILE__, __LINE__); \ + PyErr_Print(); \ + abort(); \ + } else { \ + } + +// CHECK might be previously declared +#undef CHECK +#define CHECK(cond) \ + if (unlikely(!(cond))) { \ + fprintf(stderr, "DEBUG CHECK FAILED: %s:%d\n", __FILE__, __LINE__); \ + abort(); \ + } else { \ + } + +// Uncomment next line to print debug message +// #define TORCHDYNAMO_DEBUG 1 +#ifdef TORCHDYNAMO_DEBUG + +#define DEBUG_CHECK(cond) CHECK(cond) +#define DEBUG_NULL_CHECK(val) NULL_CHECK(val) +#define DEBUG_TRACE(msg, ...) \ + fprintf(stderr, "TRACE[%s:%d] " msg "\n", __func__, __LINE__, __VA_ARGS__) +#define DEBUG_TRACE0(msg) \ + fprintf(stderr, "TRACE[%s:%d] " msg "\n", __func__, __LINE__) + +#else + +#define DEBUG_CHECK(cond) +#define DEBUG_NULL_CHECK(val) +#define DEBUG_TRACE(msg, ...) +#define DEBUG_TRACE0(msg) + +#endif + +inline _PyFrameEvalFunction _debug_set_eval_frame( + PyThreadState* tstate, + _PyFrameEvalFunction eval_frame) { + _PyFrameEvalFunction prev = + _PyInterpreterState_GetEvalFrameFunc(tstate->interp); + _PyInterpreterState_SetEvalFrameFunc(tstate->interp, eval_frame); + return prev; +} + +// Inspect PyObject*'s from C/C++ at the Python level, in pdb. +// e.g. +// +// PyObject* obj1 = PyList_New(...); +// PyObject* obj2 = PyObject_CallFunction(...); +// INSPECT(obj1, obj2); +// (pdb) p args[0] +// # list +// (pdb) p args[1] +// # some object +// (pdb) p args[1].some_attr +// # etc. +// +// Implementation: set eval frame callback to default, call +// torch._dynamo.utils._breakpoint_for_c_dynamo, reset eval frame callback. +#define INSPECT(...) \ + { \ + PyThreadState* cur_tstate = PyThreadState_Get(); \ + _PyFrameEvalFunction prev_eval_frame = \ + _debug_set_eval_frame(cur_tstate, &_PyEval_EvalFrameDefault); \ + PyObject* torch__dynamo_utils_module = \ + PyImport_ImportModule("torch._dynamo.utils"); \ + NULL_CHECK(torch__dynamo_utils_module); \ + PyObject* breakpoint_for_c_dynamo_fn = PyObject_GetAttrString( \ + torch__dynamo_utils_module, "_breakpoint_for_c_dynamo"); \ + NULL_CHECK(breakpoint_for_c_dynamo_fn); \ + PyObject_CallFunctionObjArgs( \ + breakpoint_for_c_dynamo_fn, __VA_ARGS__, NULL); \ + _debug_set_eval_frame(cur_tstate, prev_eval_frame); \ + Py_DECREF(breakpoint_for_c_dynamo_fn); \ + Py_DECREF(torch__dynamo_utils_module); \ + } + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame.h new file mode 100644 index 0000000000000000000000000000000000000000..8bac42f0fc1fa59aa2b5cf8d9cd4c556cbd53553 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame.h @@ -0,0 +1,65 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include +#ifdef __cplusplus + +extern "C" { + +PyObject* torch_c_dynamo_eval_frame_init(void); + +#endif + +// All the eval APIs change in 3.11 so we need to decide which one to use on the +// fly https://docs.python.org/3/c-api/init.html#c._PyFrameEvalFunction +#if IS_PYTHON_3_11_PLUS +#define THP_EVAL_API_FRAME_OBJECT _PyInterpreterFrame +#else +#define THP_EVAL_API_FRAME_OBJECT PyFrameObject +#endif // IS_PYTHON_3_11_PLUS + +// We need to be able to return the _PyInterpreterFrame to python so create +// a python binding for it + +typedef struct THPPyInterpreterFrame { + PyObject_HEAD + THP_EVAL_API_FRAME_OBJECT* frame; // Borrowed reference + PyObject* locals; +} THPPyInterpreterFrame; + +THPPyInterpreterFrame* THPPyInterpreterFrame_New( + THP_EVAL_API_FRAME_OBJECT* frame); + +extern bool is_skip_guard_eval_unsafe; + +void clear_old_frame_if_python_312_plus( + PyThreadState* tstate, + THP_EVAL_API_FRAME_OBJECT* frame); + +void eval_frame_callback_set(PyObject* obj); + +const char* get_frame_name(THP_EVAL_API_FRAME_OBJECT* frame); + +PyObject* dynamo_eval_frame_default( + PyThreadState* tstate, + THP_EVAL_API_FRAME_OBJECT* frame, + int throw_flag); + +PyObject* dynamo_eval_custom_code( + PyThreadState* tstate, + THP_EVAL_API_FRAME_OBJECT* frame, + PyCodeObject* code, + const char* trace_annotation, + int throw_flag); + +#ifdef __cplusplus + +} // extern "C" + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame_cpp.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame_cpp.h new file mode 100644 index 0000000000000000000000000000000000000000..1a817972d2ffc8d092773a1a5b6cf880b1f6c389 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame_cpp.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include +#include +#ifdef __cplusplus + +extern "C" { + +#endif + +PyObject* dynamo__custom_eval_frame( + PyThreadState* tstate, + THP_EVAL_API_FRAME_OBJECT* frame, + int throw_flag, + PyObject* callback); + +PyObject* dynamo_set_code_exec_strategy(PyObject* dummy, PyObject* obj); +void dynamo_skip_code_recursive(PyCodeObject* code); + +void dynamo_set_c_recursion_limit(int32_t limit); +int32_t dynamo_get_c_recursion_limit(); + +#ifdef __cplusplus + +} // extern "C" + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/extra_state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/extra_state.h new file mode 100644 index 0000000000000000000000000000000000000000..04d8789fd3aaba74bda9291f7042b75152c89e2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/extra_state.h @@ -0,0 +1,213 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +#ifdef __cplusplus + +#include +#include +#include + +namespace py = pybind11; + +extern "C" { + +#else + +#include + +#endif + +enum FrameAction { + DEFAULT, // look through the cache, compile if not found + SKIP, // eager + RUN_ONLY, // look through the cache, run eager if not found +}; + +typedef struct FrameExecStrategy { + enum FrameAction cur_action; // action to take for current frame + enum FrameAction recursive_action; // action to take for recursive frames +} FrameExecStrategy; + +// Points to the extra scratch space on the code object +extern Py_ssize_t extra_index; + +// function to call when cache lookup errors +extern PyObject* guard_error_hook; + +typedef PyObject FrameState; +typedef struct CacheEntry CacheEntry; + +// ExtraState encasulates CacheEntry and FrameState. ExtraState is the highest +// level of abstraction of what is stored on the extra code object. Previously, +// we saved different parts on different extra indexes. We prefer this way +// because of cleaner abstraction and faster SetExtra access. + +#ifdef __cplusplus + +typedef struct VISIBILITY_HIDDEN PrecompileEntry { + py::object guard_manager; + py::object code; + void* root_mgr; + + PrecompileEntry(py::object gm, py::object c); +} PrecompileEntry; + +typedef struct VISIBILITY_HIDDEN ExtraState { + // A pointer to the orig_code object to prevent race conditions in invalidate + // function. + PyCodeObject* orig_code; + std::list precompile_entries; + // List of cache entries for compiled code objects + std::list cache_entry_list; + // Frame state to detect dynamic shape dims + py::dict frame_state; + // Actions to apply to all frames with this code object + FrameExecStrategy strategy{DEFAULT, DEFAULT}; + + ExtraState(PyCodeObject* orig_code_arg); + CacheEntry* get_first_entry(); + void move_to_front(CacheEntry* cache_entry); + void move_to_back(CacheEntry* cache_entry); + void invalidate(CacheEntry* cache_entry, py::object deleted_guard_manager); +} ExtraState; + +#else + +typedef struct ExtraState ExtraState; +typedef struct PrecompileEntry PrecompileEntry; + +#endif + +// Helper to extra the cache_entry from the extra state. +// Ownership contract +// args +// - extra_state: Borrowed +// return +// - CacheEntry: Borrowed. +CacheEntry* extract_cache_entry(ExtraState* extra_state); + +// Returns either the previously stored frame state or an empty dict. +// Ownership contract +// args +// - extra_state: Borrowed +// return +// - extra_state->frame_state: Borrowed. +FrameState* extract_frame_state(ExtraState* extra_state); + +// Returns the FrameExecStrategy stored in extra_state. +// Ownership contract +// args +// - extra_state: Borrowed +FrameExecStrategy extra_state_get_exec_strategy(ExtraState* extra_state); + +// Set the FrameExecStrategy to be done to all frames with code object +// corresponding to this extra_state. Ownership contract +// - extra_state: Borrowed +void extra_state_set_exec_strategy( + ExtraState* extra_state, + FrameExecStrategy strategy); + +// Ownership contract +// args +// - code: Borrowed +// return +// - extra_state: Borrowed. +ExtraState* get_extra_state(PyCodeObject* code); + +// This is passed as freefunc to _PyEval_RequestCodeExtraIndex. This acts as a +// deleter for the object on extra scratch space. This function is called +// internally in _PyCode_SetExtra and also during the code deallocation. + +// Destroys the extra state by deleting cache_entry, frame state and finally +// freeing the constructed extra state. + +// Developer note - You should not call this function directly. This is called +// directly inside set_extra_state. If you are in a situation trying to call +// this function, consider if set_extra_state should be called. +void destroy_extra_state(void* obj); + +// Clears the existing object sitting on the extra scratch spance and sets it +// up with the new state. Note that _PyCode_SetExtra calls the +// destroy_extra_state deleter internally, and therefore we don't call it +// explicitly here. + +// Ownership contract +// args +// - extra_state: Stolen +// return +// - there is no return, but the extra_state is stolen, so it becomes +// set_extra_state responsibility to clean it up. It will be deleted during +// the reset_code, when the set_extra_state is called with NULL. + +// Invariant - Dont set the extra state for the extra state that is already on +// the code object. Otherwise, we will first free up the old extra state +// (which is also the new extra state) and write something invalid on the +// scratch space. +void set_extra_state(PyCodeObject* code, ExtraState* extra_state); + +// Creates a new extra state and put it on the extra scratch space of the code +// object. + +// Ownership contract +// args +// - code: Borrowed +// return: +// - extra_state: New reference. +// These references are then further passed to set_extra_state which becomes +// the final owner of these references. +ExtraState* init_and_set_extra_state(PyCodeObject* code); + +// Lookup the cache held by extra_state. +// Ownership contract +// args +// - extra_state: Borrowed +// return: +// - Py_None or PyCodeObject: Borrowed reference. +// - Py_None or PyObject: Trace id of the compiled code. +void lookup( + ExtraState* extra_state, + FrameLocalsMapping* f_locals, + PyObject* backend, + PyObject** maybe_cached_code, + const char** trace_annotation, + bool is_skip_guard_eval_unsafe); + +// Create a new cache entry at extra_state holding on to guarded_code. +// Ownership contract +// args +// - extra_state: Borrowed +// - guarded_code: Borrowed +// return: +// - cache_entry: Borrowed reference +CacheEntry* create_cache_entry( + ExtraState* extra_state, + PyObject* guraded_code, + PyObject* callback); + +// Extracts the backend fn from the callback. +PyObject* get_backend(PyObject* callback); + +#ifdef __cplusplus + +} // extern "C" + +// Returns the list of CacheEntry corresponding to code_obj. +// Warning: returns references whose lifetimes are controlled by C++ +py::list _debug_get_cache_entry_list(const py::handle& code_obj); +void _reset_precompile_entries(const py::handle& code_obj); +void _load_precompile_entry( + const py::handle& code_obj, + py::object guard_manager, + py::object dynamo_code); +py::list _debug_get_precompile_entries(const py::handle& code_obj); +void _set_lru_cache(py::object boolean); + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/framelocals_mapping.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/framelocals_mapping.h new file mode 100644 index 0000000000000000000000000000000000000000..a604a35ff5a988ddfd6fc65c61b6200ee1d1814f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/framelocals_mapping.h @@ -0,0 +1,97 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#ifdef __cplusplus + +#include +#include + +#include +#include + +extern "C" { + +#if IS_PYTHON_3_11_PLUS +using FrameLocalsFrameType = _PyInterpreterFrame; +#else +using FrameLocalsFrameType = PyFrameObject; +#endif // IS_PYTHON_3_11_PLUS + +/** + * Utility to view a frame's localsplus (locals + cells + freevars) + * in C/C++ and Python, without changing the state of the frame. + * + * Notes on usage: + * - C/C++ can directly read the frame's localsplus using an index. + * - Cell/free variables are unboxed. + * - Can be converted into a dict for use in Python. + * The dict is constructed once per FrameLocalsMapping, lazily. + * - Lifetime should not exceed the lifetime of the frame + * + * How do guards use FrameLocalsMapping? + * - When a guard accesses a frame's localsplus, we find the index of the + * variable name in the frame's code object and create a + * FrameLocalsGuardAccessor. + * - We create a FrameLocalsMapping for the frame that we pass on to guard eval. + * - LeafGuards/GuardManagers/GuardAccessors now need to define how they + * handle FrameLocalsMapping. By default, the FrameLocalsMapping is converted + * to a Python dict and the guard check is performed on the resulting dict. + * - Some guard checks don't actually depend on the input arguments, e.g. they + * only check global state. In this case, no dict conversion of + * FrameLocalsMapping is done. + * - FrameLocalsGuardAccessor is like DictGetItemGuardAccessor, except it knows + * how to handle FrameLocalsMapping - by using the framelocals variable name + * index that it was given when it was built. + */ +typedef struct VISIBILITY_HIDDEN FrameLocalsMapping { + private: + py::object _code_obj; + // can't use localsplus directly due to closure variables: + // - in 3.11+, the closure vars in the frame's closure object and + // the corresponding localsplus entry is nullptr + // - regardless of Python version, we need to unbox the cell variable + std::vector _framelocals; + + py::object _dict{py::none()}; + + void _realize_dict(); + + public: + explicit FrameLocalsMapping(FrameLocalsFrameType* frame); + + PyObject* get(int idx); + + bool dict_realized() const { + return _dict.is_none(); + } + + // Borrowed reference + PyDictObject* to_dict() { + if (this->dict_realized()) { + _realize_dict(); + } + return (PyDictObject*)_dict.ptr(); + } +} FrameLocalsMapping; + +#else + +// opaque type for C +typedef struct FrameLocalsMapping FrameLocalsMapping; + +#endif + +// Borrowed reference +PyDictObject* framelocals_mapping_to_dict(FrameLocalsMapping* map); + +#ifdef __cplusplus +} // extern "C" + +py::tuple code_framelocals_names(py::handle code); +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/guards.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/guards.h new file mode 100644 index 0000000000000000000000000000000000000000..1541a95dccfbf2e4a39427e7721a1d5ecc259d29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/guards.h @@ -0,0 +1,119 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::dynamo { + +PyObject* torch_c_dynamo_guards_init(); + +// interfaces for extra_state and eval_frame.c because RootGuardManager class is +// not visible there. +void* convert_to_root_guard_manager(py::object root); +bool run_root_guard_manager(void* root, FrameLocalsMapping* f_locals); + +extern thread_local bool tls_is_in_mode_without_ignore_compile_internals; + +void set_is_in_mode_without_ignore_compile_internals(bool value); + +// If we're in a mode with ignore_compile_internals=False, we WON'T mask +// Python keys from guard checking (they should be visible, so eager fallback is +// possible). Otherwise (invisible mode or no mode), we WILL mask Python keys to +// avoid guard failures on the dispatch keyset at runtime. +bool get_is_in_mode_without_ignore_compile_internals(); + +struct LocalState { + // TLS state that changes operators + c10::impl::LocalDispatchKeySet dispatch_modifier; + c10::DispatchKeySet override_dispatch_key_set; + bool grad_mode_enabled; + bool should_mask_python_keys; + + at::DispatchKeySet apply(at::DispatchKeySet ks) const { + if (override_dispatch_key_set.empty()) { + auto result = + (ks | dispatch_modifier.included_) - dispatch_modifier.excluded_; + + if (should_mask_python_keys) { + result = result - + c10::DispatchKeySet( + {c10::DispatchKey::Python, + c10::DispatchKey::PythonTLSSnapshot}); + } + + return result; + } else { + return override_dispatch_key_set; + } + } + + LocalState() + : dispatch_modifier(c10::impl::tls_local_dispatch_key_set()), + override_dispatch_key_set(c10::BackendComponent::InvalidBit), + grad_mode_enabled(at::GradMode::is_enabled()), + should_mask_python_keys( + !get_is_in_mode_without_ignore_compile_internals()) {} + + void overrideDispatchKeySet(c10::DispatchKeySet ks) { + override_dispatch_key_set = ks; + } +}; + +class TensorCheck { + public: + TensorCheck( + const LocalState& state, + PyTypeObject* pt, + const at::Tensor& v, + c10::DispatchKeySet dispatch_key_set, + std::vector> dynamic_dims_sizes, + std::vector> dynamic_dims_strides); + + TensorCheck( + const LocalState& state, + PyTypeObject* pt, + c10::DispatchKeySet dispatch_key_set, + at::ScalarType dtype, + at::DeviceIndex device_index, + bool requires_grad, + std::vector> dynamic_dims_sizes, + std::vector> dynamic_dims_strides); + + bool check(const LocalState& state, const at::Tensor& v); + bool check( + const LocalState& state, + const c10::DispatchKeySet& dispatch_key_set, + const at::ScalarType& dtype, + const c10::Device& device, + const c10::SymIntArrayRef& dynamic_dims_sizes, + const c10::SymIntArrayRef& dynamic_dims_strides, + const bool& requires_grad); + std::string check_verbose( + const LocalState& state, + const at::Tensor& v, + const std::string& tensor_name); + + PyTypeObject* pytype; + + private: + uint64_t dispatch_key_; // DispatchKeySet includes device/layout + at::ScalarType dtype_; + // Note(voz): While dispatch_key_ is sufficiently representative of a device + // In that keys are more granular AND device specific - they do not + // necessarily capture device indices correctly. + at::DeviceIndex device_index_; + bool requires_grad_; + // NB: These are unset if dynamic shapes is enabled. + std::vector> sizes_; + std::vector> strides_; + // Not strictly required for dense tensors, but nested tensors need it. + int64_t dim_; +}; + +} // namespace torch::dynamo + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/init.h new file mode 100644 index 0000000000000000000000000000000000000000..74f5673ff3a012da01afa6b8386db56c48c9516a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/init.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// C2039 MSVC +#include +#include + +#include + +namespace torch::dynamo { +void initDynamoBindings(PyObject* torch); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/python_compiled_autograd.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/python_compiled_autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..dd48feff5884dacc2b37cb32264a6579f81f8daf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/python_compiled_autograd.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +// see [Note: Compiled Autograd] +namespace torch::dynamo::autograd { +PyObject* torch_c_dynamo_compiled_autograd_init(); +} // namespace torch::dynamo::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/stackref_bridge.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/stackref_bridge.h new file mode 100644 index 0000000000000000000000000000000000000000..6ad3a6390e68e35fdbbce7ce71b86169113094da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/stackref_bridge.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#if IS_PYTHON_3_14_PLUS + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +// Use a void* to avoid exposing the internal _PyStackRef union on this +// translation unit +PyObject* THP_PyStackRef_AsPyObjectBorrow(void* stackref); + +#ifdef __cplusplus +} +#endif // __cplusplus +#endif // IS_PYTHON_3_14_PLUS + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..3a6063bf47bf724386c321c87fe1baad658fada4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/utils.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +// C2039 MSVC +#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::dynamo { +PyObject* torch_c_dynamo_utils_init(); +} // namespace torch::dynamo + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/example_upgraders.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/example_upgraders.h new file mode 100644 index 0000000000000000000000000000000000000000..1fb15f1f81f0c047e26443519d168d853dea5751 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/example_upgraders.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::_export { + +/// Register example upgraders for the upgrader system for testing. +/// This function demonstrates common upgrade patterns and is primarily +/// used for testing and demonstration purposes. +void registerExampleUpgraders(); + +/// Deregister example upgraders for the upgrader system for testing. +/// This function cleans up the example upgraders that were registered +/// by registerExampleUpgraders(). +void deregisterExampleUpgraders(); + +} // namespace torch::_export + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/pt2_archive_constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/pt2_archive_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..1bcca4aabc64c5a27500098ca89090e0f1e3a857 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/pt2_archive_constants.h @@ -0,0 +1,76 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::_export::archive_spec { + +#define FORALL_CONSTANTS(DO) \ + DO(ARCHIVE_ROOT_NAME, "package") \ + /* Archive format */ \ + DO(ARCHIVE_FORMAT_PATH, "archive_format") \ + DO(ARCHIVE_FORMAT_VALUE, "pt2") \ + /* Archive version */ \ + DO(ARCHIVE_VERSION_PATH, "archive_version") \ + DO(ARCHIVE_VERSION_VALUE, "0") /* Sep.4.2024: This is the initial version of \ + the PT2 Archive Spec */ \ + /* \ + * ######## Note on updating ARCHIVE_VERSION_VALUE ######## \ + * When there is a BC breaking change to the PT2 Archive Spec, \ + * e.g. deleting a folder, or changing the naming convention of the \ + * following fields it would require bumping the ARCHIVE_VERSION_VALUE \ + * Archive reader would need corresponding changes to support loading both \ + * the current and older versions of the PT2 Archive. \ + */ \ + /* Model definitions */ \ + DO(MODELS_DIR, "models/") \ + DO(MODELS_FILENAME_FORMAT, "models/{}.json") /* {model_name} */ \ + /* AOTInductor artifacts */ \ + DO(AOTINDUCTOR_DIR, "data/aotinductor/") \ + /* MTIA artifacts */ \ + DO(MTIA_DIR, "data/mtia") \ + /* weights, including parameters and buffers */ \ + DO(WEIGHTS_DIR, "data/weights/") \ + DO(WEIGHT_FILENAME_PREFIX, "weight_") \ + DO(WEIGHTS_PARAM_CONFIG_FORMAT, "data/weights/{}_model_param_config.json") \ + DO(WEIGHTS_CONFIG_FILENAME_FORMAT, "data/weights/{}_weights_config.json") \ + /* constants, including tensor_constants, non-persistent buffers and script \ + * objects */ \ + DO(CONSTANTS_DIR, "data/constants/") \ + DO(CONSTANTS_PARAM_CONFIG_FORMAT, \ + "data/constants/{}_model_constants_config.json") \ + DO(CONSTANTS_CONFIG_FILENAME_FORMAT, \ + "data/constants/{}_constants_config.json") \ + DO(TENSOR_CONSTANT_FILENAME_PREFIX, "tensor_") \ + DO(CUSTOM_OBJ_FILENAME_PREFIX, "custom_obj_") \ + /* example inputs */ \ + DO(SAMPLE_INPUTS_DIR, "data/sample_inputs/") \ + DO(SAMPLE_INPUTS_FILENAME_FORMAT, \ + "data/sample_inputs/{}.pt") /* {model_name} */ \ + /* ExecuTorch artifacts, including PTE files */ \ + DO(EXECUTORCH_DIR, "data/executorch/") \ + /* extra folder */ \ + DO(EXTRA_DIR, "extra/") \ + DO(MODULE_INFO_PATH, "extra/module_info.json") \ + /* xl_model_weights, this folder is used for storing per-feature-weights for \ + * remote net data in this folder is consume by Predictor, and is not \ + * intended to be used by Sigmoid */ \ + DO(XL_MODEL_WEIGHTS_DIR, "xl_model_weights/") \ + DO(XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH, "xl_model_weights/model_param_config") + +#define DEFINE_GLOBAL(NAME, VALUE) \ + inline constexpr std::string_view NAME = VALUE; +FORALL_CONSTANTS(DEFINE_GLOBAL) +#undef DEFINE_GLOBAL + +#define DEFINE_ENTRY(NAME, VALUE) std::pair(#NAME, VALUE), +inline constexpr std::array kAllConstants{FORALL_CONSTANTS(DEFINE_ENTRY)}; +#undef DEFINE_ENTRY + +#undef FORALL_CONSTANTS +} // namespace torch::_export::archive_spec + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/pybind.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..a621d3cc80658866a78f6f44a0aecef59c6dabf2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/pybind.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::_export { + +void initExportBindings(PyObject* module); + +} // namespace torch::_export + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/upgrader.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/upgrader.h new file mode 100644 index 0000000000000000000000000000000000000000..d0c9d1f72fdb1c2a56014351d011f60fe6af2cec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/export/upgrader.h @@ -0,0 +1,124 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::_export { + +/// Function type for upgrading JSON fields during schema version migration. +/// Takes a JSON field and returns the upgraded version of that field. +using UpgraderFunction = std::function; + +/// Structure containing upgrader information for a specific keypath. +/// The version is stored as the map key in the registry, so it's not +/// duplicated here. +struct Upgrader { + /// Path to the field that should be upgraded (e.g., {"graph_module", "graph", + /// "nodes"}) Assuming top-level is a JSON object that represents + /// ExportedProgram + std::vector keypath; + + /// Function that performs the actual upgrade transformation + UpgraderFunction upgrade_func; + + /// Constructor for creating an upgrader with keypath and function + Upgrader(std::vector kp, UpgraderFunction func); + + /// Comparator for maintaining bottom-up ordering in the registry. + /// Deeper keypaths are processed first to ensure safe upgrade application + /// without conflicts between parent and child field modifications. + bool operator<(const Upgrader& other) const; +}; + +/// Register an upgrader function for a specific schema version and keypath. +/// +/// This function allows registration of custom upgrade logic that will be +/// applied when upgrading artifacts from the specified version. Upgraders +/// are applied in bottom-up order (deeper keypaths first) to prevent +/// conflicts between parent and child field modifications. +/// +/// @param version The schema version this upgrader applies to +/// @param keypath The key path to the field that should be upgraded +/// @param upgrade_func Function that performs the upgrade transformation +void registerUpgrader( + int version, + const std::vector& keypath, + const UpgraderFunction& upgrade_func); + +/// Register an upgrader function using dot-separated keypath notation. +/// +/// Convenience overload that accepts dot-separated keypath strings for +/// simpler syntax. For example: "graph_module.graph.nodes" instead of +/// {"graph_module", "graph", "nodes"}. +/// +/// @param version The schema version this upgrader applies to +/// @param dot_keypath Dot-separated keypath string (e.g., "graph.nodes") +/// @param upgrade_func Function that performs the upgrade transformation +void registerUpgrader( + int version, + const std::string& dot_keypath, + const UpgraderFunction& upgrade_func); + +/// Deregister an upgrader function for a specific schema version and keypath. +/// +/// This function allows removal of previously registered upgrade logic for +/// the specified version and keypath. This is useful for testing scenarios +/// where you need to clean up registered upgraders or modify upgrader +/// behavior dynamically. +/// +/// @param version The schema version to deregister the upgrader from +/// @param keypath The key path to the field that should be deregistered +/// @return true if an upgrader was found and removed, false otherwise +bool deregisterUpgrader(int version, const std::vector& keypath); + +/// Deregister an upgrader function using dot-separated keypath notation. +/// +/// Convenience overload that accepts dot-separated keypath strings for +/// simpler syntax. For example: "graph_module.graph.nodes" instead of +/// {"graph_module", "graph", "nodes"}. +/// +/// @param version The schema version to deregister the upgrader from +/// @param dot_keypath Dot-separated keypath string (e.g., "graph.nodes") +/// @return true if an upgrader was found and removed, false otherwise +bool deregisterUpgrader(int version, const std::string& dot_keypath); + +/// Utility function for throwing consistent upgrader errors. +/// +/// This function formats error messages in a standardized way for upgrader +/// failures, including version information and optional problematic object +/// details for debugging. +/// +/// @param upgrader_name Name of the upgrader that failed +/// @param from_version Source schema version being upgraded from +/// @param error_message Descriptive error message +/// @param problematic_object Optional JSON object that caused the error +/// @throws std::runtime_error Always throws with formatted error message +void throwUpgraderError( + const std::string& upgrader_name, + int from_version, + const std::string& error_message, + const nlohmann::json& problematic_object = nlohmann::json::object()); + +/// Upgrade a JSON artifact to a specific target version with available +/// upgraders until a target version is reached. +/// +/// This handles major version upgrade only. For minor version upgrade, +/// e.g. adding a new field with default value, it's automatically handled by +/// the default constructor in generated_serialization_types.h. +/// +/// @param artifact The JSON artifact to upgrade(passed by value: function +/// operates on a local copy, original remains unmodified) +/// @param target_version The target schema version to upgrade to +/// @return The upgraded JSON artifact with updated schema version +/// @throws std::runtime_error if artifact is missing schema_version field +/// @throws std::runtime_error if final version doesn't match target version +nlohmann::json upgrade(nlohmann::json artifact, int target_version); + +} // namespace torch::_export + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/functionalization/Module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/functionalization/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..8d9ef7eee21ea132de0b5ce75a25345bdfc2539f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/functionalization/Module.h @@ -0,0 +1,41 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +namespace torch::functionalization { + +// Creates the default bindings for `ViewMeta` specializations. +// +// Defines a constructor using the types in `SerializableTuple`, as well +// as pickle methods. +template +void create_binding_with_pickle(py::module m) { + py::class_, at::functionalization::ViewMeta>( + m, T::name()) + .def(py::init()) + .def( + "as_tuple", + [](const std::shared_ptr& meta) { + return meta->to_serializable_tuple(); + }) + .def(py::pickle( + [](const std::shared_ptr& meta) { + return meta->to_serializable_tuple(); + }, + [](const typename T::SerializableTuple& tpl) { + return std::make_shared(tpl); + })); +} + +void initModule(PyObject* module); +void initGenerated(PyObject* module); + +} // namespace torch::functionalization + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/functorch/init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/functorch/init.h new file mode 100644 index 0000000000000000000000000000000000000000..e92e68fc321237beb24195636ff4f689105e5733 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/functorch/init.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::functorch::impl { + +void initFuncTorchBindings(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/fx/node.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/fx/node.h new file mode 100644 index 0000000000000000000000000000000000000000..a4d3f2d4fdcb780ca683a63b5a384c1f6aafc93c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/fx/node.h @@ -0,0 +1,11 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +bool NodeBase_init(PyObject* module); +bool NodeIter_init(PyObject* module); + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h new file mode 100644 index 0000000000000000000000000000000000000000..b742973eeee6e6d1a9264fdc9d428cf2650c7c0a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h @@ -0,0 +1,117 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace torch::inductor { + +// Represent AOTI kernel. It contains all the parameter metadata of the kernel +// and the AOTI model runner. +struct AOTIKernelMetadata { + // Represent all the parameters of AOTI kernel + std::vector parameter_metadata_list_; + // AOTI model runner to run the AOTI kernel + std::shared_ptr kernel_runner_; + AOTIKernelMetadata() : kernel_runner_(nullptr) {} + + // Check whether the given parameter metadata list is the same as the + // parameter metadata list of the AOTI kernel. + bool check( + const std::vector& parameter_metadata_list) const { + if (parameter_metadata_list_.size() != parameter_metadata_list.size()) { + return false; + } + + for (size_t i = 0; i < parameter_metadata_list_.size(); ++i) { + if (parameter_metadata_list_[i] == parameter_metadata_list[i]) { + continue; + } else { + return false; + } + } + + return true; + } +}; + +// The AOTIPythonKernelHolder class uses the AOT Inductor to generate a kernel +// for a specified operation. To speed up this process, the generated kernel +// library is cached on disk. Detailed information from the input tensors is +// used as the key for caching the kernel library. On subsequent runs, these +// input tensors are used to search the cache. If a cache hit occurs, the cached +// kernel library is loaded and executed. If a cache miss occurs, the AOT +// Inductor is called again to generate the kernel library. +class AOTIPythonKernelHolder : public c10::OperatorKernel { + // A DispatchKey object that represents the dispatch key for the kernel. + c10::DispatchKey dispatch_key_; + // Namespace of the kernel. + std::string ns_; + // Name of the operation the kernel performs. + std::string op_name_with_overload_; + // The device on which the kernel is to be executed. + c10::Device device_; + // The Python interpreter to get OpOverload object with the given op_name and + // op_overload_name. + c10::impl::PyInterpreter* pyinterpreter_; + // Cache the produced kernels by AOTI and its metadata + std::vector aoti_kernel_cache_; + + public: + AOTIPythonKernelHolder( + c10::DispatchKey dispatch_key, + std::string_view ns, + std::string_view op_name_with_overload); + + void operator()( + const c10::OperatorHandle& op, + c10::DispatchKeySet keyset, + torch::jit::Stack* stack); + + private: + bool cache_lookup( + const c10::OperatorHandle& op, + const c10::DispatchKeySet& keyset, + const torch::jit::Stack* stack, + AOTIKernelMetadata& aoti_kernel_metadata); + void cache_miss( + const c10::OperatorHandle& op, + const c10::DispatchKeySet& keyset, + torch::jit::Stack* stack); + void cache_hit( + const AOTIKernelMetadata& aoti_kernel_metadata, + const c10::OperatorHandle& op, + const c10::DispatchKeySet& keyset, + torch::jit::Stack* stack); + // Invoke python utility function on the Inductor side to produce AOTI kernel + // for the given operation. + // Inductor utility function - + // torch._inductor.utils.aoti_compile_with_persistent_cache + std::string produce_aoti_kernel_lib( + const c10::OperatorHandle& op, + const c10::DispatchKeySet& keyset, + const torch::jit::Stack* stack); + // Invoke python utility function on the Inductor side to load AOTI kernel for + // the given operation. + // Inductor utility function - torch._inductor.utils.load_aoti_eager_cache + void init_aoti_kernel_cache(); + // Load the AOTIModelContainerRunner object from the given file path. + std::shared_ptr load_aoti_model_runner( + const std::string& /*so_path*/); +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h new file mode 100644 index 0000000000000000000000000000000000000000..c2f7db1289d19a202cc30661f94edd2a47387ff3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h @@ -0,0 +1,147 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include +#include + +#include + +namespace torch::inductor { + +// Regarding a aten operation implemented by AOTI, the metadata of the input +// tensors will be cached on the disk to accelerate next run. TensorMetada +// structure is to represent the metadata of each input tensor. It includes +// whether the tensor is symbolic, the dtype, the device, the sizes and the +// strides of the tensor. When the metadata of the input tensors is the same as +// the cached metadata, the cached kernel library will be loaded and executed. +// Otherwise, the AOT Inductor will be called again to generate the kernel +// library. +// Beyond the TensorMetadata, we build guard/TensorCheck for each input tensor +// as well to support symbolic shape. We intend to utilize TensorCheck to find +// out the proper kernel rather than TensorMetada comparison. Suppose an +// operation with a single input tensor and two kernels: +// kernel1: TensorMetadata(is_symbolic=false, dtype=Float, device=CPU, +// sizes=[s0, s1, s2], strides=[s1 * s2, s2, 1]) kernel2: +// TensorMetadata(is_symbolic=false, dtype=Float, device=CPU, sizes=[3, s1, +// s2], strides=[s1 * s2, s2, 1]) +// If a tensor with sizes=[3, 4, 5] is passed to the operation, both kernel1 and +// kernel2 support the tensor shape. In this case, we need to use TensorCheck +// plus some heruistic rules to find out the proper kernel. +struct TensorMetadata { + // Indicate whether the tensor is symbolic and it may be concluded by sizes_ + // and strides_ in the future. + bool is_symbolic_; + // Dtype of a tensor(For scalar, we will wrap it as a scalar tensor) + c10::ScalarType dtype_ = c10::ScalarType::Undefined; + // Device of a tensor. + c10::Device device_; + // Dispatch key set of a tensor + c10::DispatchKeySet dispatch_key_set_; + // Sizes of a tensor. Currently, we only support static shape and use int64_t + // to represent the sizes. In the future, we will create symbolic size and use + // SymInt to represent it to support symbolic shape. + std::vector sizes_; + // Strides of a tensor. For symbolic shape support, it is the same as sizes_ + std::vector strides_; + // requires grad + bool requires_grad_ = false; + // TensorCheck for the tensor + std::optional tensor_check_; + + TensorMetadata() + : is_symbolic_(false), + device_(c10::DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES), + sizes_({}), + strides_({}) {} + TensorMetadata(const at::Tensor& src_tensor); + TensorMetadata( + bool is_symbolic, + c10::ScalarType dtype, + c10::Device device, + c10::DispatchKeySet dispatch_key_set, + std::vector sizes, + std::vector strides, + bool requires_grad = false); + + // Build TensorCheck for the tensor by using the data fields in TensorMetadata + void build_guard(const dynamo::LocalState& local_state); + + // Compare two TensorMetadata objects + bool operator==(const TensorMetadata& other) const; +}; + +// ParameterTag is to represent the type of the input parameters of a aten +// operation. Currently, we support the following types: +// 1. TENSOR: a single tensor +// 2. TENSOR_OPTIONAL: a single optional tensor +// 3. TENSOR_LIST: a list of tensors +// 4. TENSOR_LIST_OPTIONAL: a list of optional tensors +// 5. SCALAR: a scalar value +// If we need to support more types in the future, we will add more types in the +// ParameterTag enum. For example, we will extend the enum to support string, +// Dimname and so on to support more types of input parameters of aten +// operations. +enum ParameterTag { + TENSOR, + TENSOR_OPTIONAL, + TENSOR_LIST, + TENSOR_LIST_OPTIONAL, + SCALAR, + STRING, + DEVICE, + INVALID, +}; + +// ParameterMetadataValue is to represent the value of the input parameters of a +// aten operation. +using ParameterMetadataValue = std::variant< + TensorMetadata, + std::vector, + c10::Scalar, + std::string, + c10::Device>; + +// ParameterMetadata is to represent the metadata of the input parameters of a +// aten operation. It includes the tag of the parameter, the value of the +// parameter and the order of the parameter. +struct ParameterMetadata { + // The tag of the parameter. It indicates the type of the parameter. + ParameterTag tag_; + // The value of the parameter. It can be a tensor, a list of tensors or a + // scalar. + ParameterMetadataValue value_; + // The order of the parameter is used to distinguish the parameters with the + // same tag. For example, an operation with two input tensors, the first + // tensor is a optional tensor and the second tensor is a tensor. The first + // tensor will have the order 0 and the second tensor will have the order 1. + uint64_t order_{}; + + ParameterMetadata() : tag_(INVALID) {} + ParameterMetadata(TensorMetadata tensor_metadata, uint64_t input_order); + ParameterMetadata(const at::Tensor& tensor, uint64_t input_order); + ParameterMetadata( + const std::vector& tensor_list, + uint64_t input_order); + ParameterMetadata( + const std::vector& tensor_metadata_list, + uint64_t input_order); + ParameterMetadata(const c10::Scalar& scalar, uint64_t input_order); + ParameterMetadata(const std::string& string_value, uint64_t input_order); + ParameterMetadata(const c10::Device& device, uint64_t input_order); + + bool operator==(const ParameterMetadata& other) const; + + private: + // Helper function to compare two ParameterMetadata objects with the same + // SCALAR tag. + bool equal_to(const c10::Scalar& scalar) const; +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/array_ref.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/array_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..27cd706592b540eab7f1dab3c76afec0d2789440 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/array_ref.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/common.h new file mode 100644 index 0000000000000000000000000000000000000000..a676e55c9d3b9844b801adbcba8ca3c7473fea95 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/common.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include + +#include +#include + +// Round up to the nearest multiple of 64 +[[maybe_unused]] inline int64_t align(int64_t nbytes) { + return (nbytes + 64 - 1) & -64; +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..08fe09380478cca15008bdbf611eb30606c4b908 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cpu.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..b7e910bf59b308eb889ea81c56a60dbbad8359e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cuda.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/mps.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/mps.h new file mode 100644 index 0000000000000000000000000000000000000000..6ed9ce406262d8402fe0ebbdb16822256051896e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/mps.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/xpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..59c681ea6a49947bb2b079d31a2669aec7b95ff6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/xpu.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..07ea91b062aac3878b110440f58cd343b0d75b7d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include +#include + +namespace torch::inductor { +class TORCH_API AOTIModelPackageLoader { + public: + AOTIModelPackageLoader( + const std::string& model_package_path, + const std::string& model_name = "model", + const bool run_single_threaded = false, + const size_t num_runners = 1, + const c10::DeviceIndex device_index = -1); + ~AOTIModelPackageLoader(); + + AOTIModelContainerRunner* get_runner(); + std::unordered_map get_metadata(); + + std::vector run( + const std::vector& inputs, + void* stream_handle = nullptr); + + // boxed_run will steal the ownership of the input tensors + std::vector boxed_run( + std::vector&& inputs, + void* stream_handle = nullptr); + + std::vector get_call_spec(); + void load_constants( + std::unordered_map& constants_map, + bool use_inactive, + bool check_full_update, + bool user_managed = false); + std::vector get_constant_fqns(); + + void update_constant_buffer( + std::unordered_map& tensor_map, + bool use_inactive, + bool validate_full_updates, + bool user_managed = false); + + // Static function to load metadata directly from a model package + static std::unordered_map load_metadata_from_package( + const std::string& model_package_path, + const std::string& model_name); + + private: + std::string temp_dir_; + std::unique_ptr runner_; + std::unordered_map metadata_; + + void load_metadata(const std::string& cpp_filename); +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/pybind.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..7c27556e79df2539098ffd878ea9a6aa44658fec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/pybind.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::inductor { + +void initAOTIPackageBindings(PyObject* module); + +} // namespace torch::inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..90048f79cec66edcf79dfa493e39dea131662f85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h @@ -0,0 +1,145 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include +#include + +// Forward declare DynamicLibrary +namespace at { +struct DynamicLibrary; +} + +namespace torch::inductor { +using TensorConstantMap = std::unordered_map; + +class TORCH_API AOTIModelContainerRunner { + public: + AOTIModelContainerRunner() = delete; + AOTIModelContainerRunner(const AOTIModelContainerRunner& other) = delete; + AOTIModelContainerRunner(AOTIModelContainerRunner&& other) = delete; + AOTIModelContainerRunner& operator=(const AOTIModelContainerRunner& other) = + delete; + AOTIModelContainerRunner& operator=(AOTIModelContainerRunner&& other) = + delete; + virtual ~AOTIModelContainerRunner(); + + std::vector run( + const std::vector& inputs, + void* stream_handle = nullptr); + + // boxed_run will steal the ownership of the input tensors + std::vector boxed_run( + std::vector&& inputs, + void* stream_handle = nullptr); + + std::unordered_map getConstantNamesToOriginalFQNs() + const; + std::unordered_map getConstantNamesToDtypes() const; + + const std::unordered_map extract_constants_map( + bool use_inactive) const; + void update_inactive_constant_buffer(const TensorConstantMap& const_map); + void update_constant_buffer( + std::unordered_map& tensor_map, + bool use_inactive, + bool validate_full_updates, + bool user_managed = false); + void update_constant_buffer( + const TensorConstantMap& const_map, + bool use_inactive, + bool validate_full_updates, + bool user_managed = false); + void run_const_fold( + bool use_inactive, + AOTInductorStreamHandle cuda_stream_handle = nullptr); + void swap_constant_buffer(); + void free_inactive_constant_buffer(); + void update_constant_buffer_from_blob(const std::string& weights_path); + + std::vector get_call_spec(); + + protected: + AOTIModelContainerRunner( + const std::string& model_so_path, + size_t num_models, + const std::string& device_str, + const std::string& cubin_dir, + const bool run_single_threaded); + + virtual std::vector run_impl( + std::vector& input_handles, + void* stream_handle); + + std::unique_ptr model_so_; + decltype(&AOTInductorModelContainerCreateWithDevice) create_func_{nullptr}; + decltype(&AOTInductorModelContainerDelete) delete_func_{nullptr}; + decltype(&AOTInductorModelContainerGetNumOutputs) get_num_outputs_func_{ + nullptr}; + decltype(&AOTInductorModelContainerRun) run_func_{nullptr}; + decltype(&AOTInductorModelContainerGetNumConstants) get_num_constants_func_{ + nullptr}; + decltype(&AOTInductorModelContainerGetConstantName) get_constant_name_func_{ + nullptr}; + decltype(&AOTInductorModelContainerGetConstantOriginalFQN) + get_constant_original_fqn_func_{nullptr}; + decltype(&AOTInductorModelContainerGetConstantDtype) get_constant_dtype_func_{ + nullptr}; + decltype(&AOTInductorModelContainerExtractConstantsMap) + extract_constants_map_func_{nullptr}; + decltype(&AOTInductorModelContainerUpdateUserManagedConstantBuffer) + update_user_managed_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerUpdateConstantBuffer) + update_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerUpdateInactiveConstantBuffer) + update_inactive_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerRunConstantFolding) run_const_fold_func_{ + nullptr}; + decltype(&AOTInductorModelContainerSwapConstantBuffer) + swap_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerFreeInactiveConstantBuffer) + free_inactive_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerGetCallSpec) get_call_spec_func_{nullptr}; + decltype(&AOTInductorModelContainerGetConstantsBlobSize) + get_constants_blob_size_func_{nullptr}; + decltype(&AOTInductorModelUpdateConstantsFromBlob) + update_constants_from_blob_func_{nullptr}; + + AOTInductorModelContainerHandle container_handle_ = nullptr; + + AOTIProxyExecutorHandle proxy_executor_handle_; + + private: + std::unique_ptr proxy_executor_; +}; + +using CreateAOTIModelRunnerFunc = std::unique_ptr (*)( + const std::string& model_so_path, + size_t num_models, + const std::string& device_str, + const std::string& bin_dir, + const bool run_single_threaded); + +// Return a global map "device name" -> "aoti model runner create function" for +// all registered in AOTI external backends +TORCH_API std::unordered_map& +getAOTIModelRunnerRegistry(); + +// To register a new external backend in AOTI one needs to create an instance of +// this struct. It is not thread-safe. Because it is expected to be called +// during the initialization of the program. +struct TORCH_API RegisterAOTIModelRunner{RegisterAOTIModelRunner( + const std::string& name, + CreateAOTIModelRunnerFunc create_aoti_model_runner_fn){ + getAOTIModelRunnerRegistry()[name] = create_aoti_model_runner_fn; +} // namespace torch::inductor +} +; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..83eecc1c684973fc4c30e5409ee9b4d48f61cf9a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include + +namespace torch::inductor { +class TORCH_API AOTIModelContainerRunnerCpu : public AOTIModelContainerRunner { + public: + AOTIModelContainerRunnerCpu( + const std::string& model_so_path, + size_t num_models = 1, + const bool run_single_threaded = false); + + ~AOTIModelContainerRunnerCpu() override; +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..dfdfdaf735409d2f5901b95b13678cd89ef4881c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h @@ -0,0 +1,40 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include + +namespace torch::inductor { + +// NOTICE: Following APIs are subject to change due to active development +// We provide NO BC guarantee for these APIs +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) +class TORCH_CUDA_CPP_API AOTIModelContainerRunnerCuda + : public AOTIModelContainerRunner { + public: + // @param device_str: cuda device string, e.g. "cuda", "cuda:0" + AOTIModelContainerRunnerCuda( + const std::string& model_so_path, + size_t num_models = 1, + const std::string& device_str = "cuda", + const std::string& cubin_dir = "", + const bool run_single_threaded = false); + + ~AOTIModelContainerRunnerCuda() override; + + std::vector run_impl( + std::vector& input_handles, + void* stream_handle) override; + + std::vector run_with_cuda_stream( + const std::vector& inputs, + const at::cuda::CUDAStream& cuda_stream); +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_mps.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_mps.h new file mode 100644 index 0000000000000000000000000000000000000000..2e36e600a6f575e2d8b05cbfdde89fd6837a87d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_mps.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if defined(__APPLE__) +#pragma once + +#include + +namespace torch::inductor { +class TORCH_API AOTIModelContainerRunnerMps : public AOTIModelContainerRunner { + public: + AOTIModelContainerRunnerMps( + const std::string& model_so_path, + size_t num_models = 1, + const bool run_single_threaded = false); + + ~AOTIModelContainerRunnerMps() override; +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_xpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..2a55999f70b8be633b9d90237b18ad8c6502b349 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_xpu.h @@ -0,0 +1,42 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include + +namespace torch::inductor { + +// NOTICE: Following APIs are subject to change due to active development +// We provide NO BC guarantee for these APIs + +// HERE we use C10_EXPORT because libtorch_python needs this Symbol be exported. +// And `TORCH_API and `TORCH_XPU_API`` do not export the symbol in Windows +// build. +class C10_EXPORT AOTIModelContainerRunnerXpu : public AOTIModelContainerRunner { + public: + // @param device_str: xpu device string, e.g. "xpu", "xpu:0" + AOTIModelContainerRunnerXpu( + const std::string& model_so_path, + size_t num_models = 1, + const std::string& device_str = "xpu", + const std::string& kernel_bin_dir = "", + const bool run_single_threaded = false); + + ~AOTIModelContainerRunnerXpu() override; + + std::vector run_impl( + std::vector& input_handles, + void* stream_handle) override; + + std::vector run_with_xpu_stream( + const std::vector& inputs, + const at::xpu::XPUStream& xpu_stream); +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..5a0eef2af2edaccf962ce0fc92de97761c2becf1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::inductor { + +void initAOTIRunnerBindings(PyObject* module); + +} // namespace torch::inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..eb556ed29b1d42777a6c38837ed62d80d908ce7c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h @@ -0,0 +1,247 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace torch::aot_inductor { + +using MiniIntArrayRef = MiniArrayRef; + +static_assert( + sizeof(MiniIntArrayRef) == sizeof(void*) + sizeof(size_t), + "changing the size of MiniArrayRef breaks ABI compatibility!"); + +inline bool is_contiguous_strides_for_shape( + int64_t ndim, + const int64_t* strides_ptr, + const int64_t* sizes_ptr) { + int64_t z = 1; + for (int64_t d = ndim - 1; d >= 0; d--) { + const auto& size_d = sizes_ptr[d]; + if (size_d != 1) { + if (strides_ptr[d] == z) { + z *= size_d; + } else { + return false; + } + } + } + return true; +} + +// Shim for AOTI generated code to pretend a raw array works like an +// AtenTensorHandle. +template +class ArrayRefTensor { + public: + ArrayRefTensor() = default; + + explicit ArrayRefTensor( + MiniArrayRef arr, + MiniArrayRef sizes, + MiniArrayRef strides, + int32_t device_type, + int32_t device_idx) + : arrayRef_(arr), + sizes_(sizes), + strides_(strides), + device_type_(device_type), + device_idx_(device_idx) { + assert(sizes.size() == strides.size()); + assert(is_contiguous_strides_for_shape( + sizes.size(), strides.data(), sizes.data())); + } + + AtenTensorHandle expensiveCopyToTensor() const { + AtenTensorHandle result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided( + sizes_.size(), + sizes_.data(), + strides_.data(), + aoti_torch_dtype>(), + device_type_, + device_idx_, + &result)); + void* dataPtr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(result, &dataPtr)); + std::memcpy(dataPtr, data(), numel() * sizeof(T)); + return result; + } + + // We need to look the same as RAIIAtenTensorHandle, which returns + // an owning AtenTensorHandle from release(). So, we allocate one! + AtenTensorHandle release() { + return expensiveCopyToTensor(); + } + + AtenTensorHandle borrowAsTensor() const { + AtenTensorHandle result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob_v2( + data(), + sizes_.size(), + sizes_.data(), + strides_.data(), + 0, + aoti_torch_dtype>(), + device_type_, + device_idx_, + &result, + aoti_torch_layout_strided(), + nullptr, + 0)); + return result; + } + + // We don't need to free any memory. + void reset() {} + + auto sizes() const { + return sizes_; + } + + auto strides() const { + return strides_; + } + + auto device_type() const { + return device_type_; + } + + auto device_idx() const { + return device_idx_; + } + + T* data() const { + return arrayRef_.data(); + } + + auto numel() const { + return arrayRef_.size(); + } + + void set_arrayref(MiniArrayRef new_arrayref) { + arrayRef_ = new_arrayref; + } + + private: + MiniArrayRef arrayRef_; + // We expect generated code to have statically available sizes & + // strides for us. + MiniArrayRef sizes_; + MiniArrayRef strides_; + int32_t device_type_ = 0; + int32_t device_idx_ = 0; + // We continue to zero-initialize this field in case we repurpose + // the space later; having predictable contents can only help. + int32_t unusedDoNotRemoveForABICompatibility_ = 0; +}; + +static_assert( + sizeof(ArrayRefTensor) == + 3 * sizeof(MiniIntArrayRef) + 3 * sizeof(int32_t) + + (alignof(ArrayRefTensor) > 4 ? sizeof(int32_t) : 0), + "changing the size of ArrayRefTensor breaks ABI compatibility!"); + +template +inline ArrayRefTensor reinterpret_tensor_wrapper( + const ArrayRefTensor& self, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset) { + // REVIEW: we should add a way to build the DSO in debug mode during + // tests so we can have checks like this! + assert(is_contiguous_strides_for_shape(ndim, strides_ptr, sizes_ptr)); + return ArrayRefTensor( + MiniArrayRef( + self.data() + storage_offset, self.numel() - storage_offset), + MiniArrayRef(sizes_ptr, ndim), + MiniArrayRef(strides_ptr, ndim), + self.device_type(), + self.device_idx()); +} + +template +inline T* get_data_ptr_wrapper(ArrayRefTensor& tensor) { + return tensor.data(); +} + +template +inline T* get_data_ptr_wrapper(const MiniArrayRef& arr) { + return arr.data(); +} + +template +inline const ArrayRefTensor& unwrap_raii_handle_if_needed( + const ArrayRefTensor& tensor) { + return tensor; +} + +template +inline ArrayRefTensor& unwrap_raii_handle_if_needed( + ArrayRefTensor& tensor) { + return tensor; +} + +template +inline const ArrayRefTensor& wrap_with_raii_handle_if_needed( + const ArrayRefTensor& tensor) { + return tensor; +} + +template +inline ArrayRefTensor& wrap_with_raii_handle_if_needed( + ArrayRefTensor& tensor) { + return tensor; +} + +template +inline ArrayRefTensor wrap_with_raii_handle_if_needed( + ArrayRefTensor&& tensor) { + return std::move(tensor); +} + +template +inline RAIIAtenTensorHandle expensive_copy_to_tensor_if_needed( + const ArrayRefTensor& tensor) { + return tensor.expensiveCopyToTensor(); +} + +inline AtenTensorHandle expensive_copy_to_tensor_if_needed( + AtenTensorHandle handle) { + return handle; +} + +template +const T& copy_arrayref_tensor_to_tensor(const T& t) { + return t; +} + +template +RAIIAtenTensorHandle copy_arrayref_tensor_to_tensor( + const ArrayRefTensor& art) { + return art.expensiveCopyToTensor(); +} + +template +const T& borrow_arrayref_tensor_as_tensor(const T& t) { + return t; +} + +template +RAIIAtenTensorHandle borrow_arrayref_tensor_as_tensor( + const ArrayRefTensor& art) { + return art.borrowAsTensor(); +} + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/constant_type.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/constant_type.h new file mode 100644 index 0000000000000000000000000000000000000000..8666e0556acbebc2e798e02d05b725be57a167ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/constant_type.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. + +namespace torch::aot_inductor { + +enum ConstantType : uint8_t { + Unknown = 0, + Parameter = 1, + Buffer = 2, + TensorConstant = 3, + FoldedConstant = 4, +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1c57f319b594df4f4ad0135aab86eff3424244a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h @@ -0,0 +1,72 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. + +#ifdef USE_CUDA + +// FIXME: Currently, CPU and CUDA backend are mutually exclusive. +// This is a temporary workaround. We need a better way to support +// multi devices. + +#include +#include + +#define AOTI_RUNTIME_CUDA_CHECK(EXPR) \ + do { \ + const cudaError_t code = EXPR; \ + const char* msg = cudaGetErrorString(code); \ + if (code != cudaSuccess) { \ + throw std::runtime_error( \ + std::string("CUDA error: ") + std::string(msg)); \ + } \ + } while (0) + +namespace torch::aot_inductor { + +using DeviceStreamType = cudaStream_t; + +} // namespace torch::aot_inductor + +#elif defined(USE_XPU) +#include +#include +#include +#define AOTI_RUNTIME_XPU_CHECK(EXPR) \ + do { \ + const ze_result_t status = EXPR; \ + if (status != ZE_RESULT_SUCCESS) { \ + std::stringstream ss; \ + ss << "L0 runtime error: " << std::hex << std::uppercase << status; \ + throw std::runtime_error(ss.str()); \ + } \ + } while (0) + +namespace torch::aot_inductor { + +using DeviceStreamType = sycl::queue*; + +} // namespace torch::aot_inductor + +#else + +#define AOTI_RUNTIME_CPU_CHECK(EXPR) \ + bool ok = EXPR; \ + if (!ok) { \ + throw std::runtime_error("CPU runtime error"); \ + } + +namespace torch::aot_inductor { + +using DeviceStreamType = void*; + +} // namespace torch::aot_inductor + +#endif // USE_CUDA + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..e452c68c0be1114b4ec23e05cb77da5a73deb938 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h @@ -0,0 +1,273 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include + +#ifdef _WIN32 +/* +On Windows, we need to explicit declaration for export APIs. And because the +package loader call these API via GetProcAddress(ldsym on Linux), we can ignore +the import case. +*/ +#define AOTI_API __declspec(dllexport) +#else +#define AOTI_API __attribute__((__visibility__("default"))) +#endif + +extern "C" { +struct AOTInductorModelOpaque; +using AOTInductorModelHandle = AOTInductorModelOpaque*; + +struct AOTInductorModelContainerOpaque; +using AOTInductorModelContainerHandle = AOTInductorModelContainerOpaque*; + +struct AOTInductorStreamOpaque; +using AOTInductorStreamHandle = AOTInductorStreamOpaque*; + +struct AOTInductorConstantMap; +using AOTInductorConstantMapHandle = AOTInductorConstantMap*; + +struct AOTInductorConstantMapEntry { + const char* name; + AtenTensorHandle handle; +}; + +// TODO: Deprecate this API. This was kept for BC compatibility. +// Please use AOTInductorModelContainerCreateWithDevice instead. +AOTI_API AOTIRuntimeError AOTInductorModelContainerCreate( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + bool is_cpu, + const char* cubin_dir); + +// Creates an AOTInductor model container. The parameter num_models +// specifies the number of model instances that may be run concurrently for +// the same input model. +// `device_str` MUST NOT be nullptr. It must be a valid device string, e.g. +// "cpu", "cuda", "cuda:0", etc. If the device index is not specified for CUDA +// device, runtime will use the device index returned by +// "cudaGetDevice(&device_idx)" +AOTI_API AOTIRuntimeError AOTInductorModelContainerCreateWithDevice( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + const char* device_str, + const char* cubin_dir); + +// Deletes the AOTInductor model container. +AOTI_API AOTIRuntimeError AOTInductorModelContainerDelete( + AOTInductorModelContainerHandle container_handle); + +// Runs the inference. +AOTI_API AOTIRuntimeError AOTInductorModelContainerRun( + AOTInductorModelContainerHandle container_handle, + AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + size_t num_inputs, + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + size_t num_outputs, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle); + +// Single-threaded variant of previous. +AOTI_API AOTIRuntimeError AOTInductorModelContainerRunSingleThreaded( + AOTInductorModelContainerHandle container_handle, + AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + size_t num_inputs, + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + size_t num_outputs, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle); + +// Retrieves the number of constants for the model. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetNumConstants( + AOTInductorModelContainerHandle container_handle, + size_t* num_constants); + +// Retrieves a constant's name. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantName( + AOTInductorModelContainerHandle container_handle, + size_t idx, + const char** name); + +// Retrieves a constant's original FQN. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantOriginalFQN( + AOTInductorModelContainerHandle container_handle, + size_t idx, + const char** original_fqn); + +// Retrieves whether a constant is from folded. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantFromFolded( + AOTInductorModelContainerHandle container_handle, + size_t idx, + bool* from_folded); + +// Retrieves the inductor constant type. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantType( + AOTInductorModelContainerHandle container_handle, + size_t idx, + int32_t* type); + +// Retrieves a constant's dtype. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantDtype( + AOTInductorModelContainerHandle container_handle, + size_t idx, + int32_t* dtype); + +// Retrieves a constant's data size. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantDataSize( + AOTInductorModelContainerHandle container_handle, + size_t idx, + size_t* data_size); + +// Extract the constants that is being used in the container. +AOTI_API AOTIRuntimeError AOTInductorModelContainerExtractConstantsMap( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive); + +// Setup the constant buffer in model container with provided ConstantMap. +// The ConstantMap is user managed, and the user would retain ownership. +AOTI_API AOTIRuntimeError +AOTInductorModelContainerUpdateUserManagedConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update); + +// Same as AOTInductorModelContainerUpdateUserManagedConstantBuffer, +// but no std::unordered_map crosses DLL boundaries for cross-compilation. +AOTI_API AOTIRuntimeError +AOTInductorModelContainerUpdateUserManagedConstantBufferPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs, + bool use_inactive, + bool validate_full_update); + +// Setup the constant buffer in model container with provided ConstantMap +// use_inactive should be set as true if the inactive buffer is to be updated. +// validate_full_update checks if all constants are included in the ConstantMap +AOTI_API AOTIRuntimeError AOTInductorModelContainerUpdateConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update); + +// Setup the inactive constant buffer in model container with provided +// ConstantMap +AOTI_API AOTIRuntimeError AOTInductorModelContainerUpdateInactiveConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle); + +// Free the inactive constant buffer in model container. +AOTI_API AOTIRuntimeError AOTInductorModelContainerFreeInactiveConstantBuffer( + AOTInductorModelContainerHandle container_handle); + +// Run constant folding on constant buffer. +AOTI_API AOTIRuntimeError AOTInductorModelContainerRunConstantFolding( + AOTInductorModelContainerHandle container_handle, + bool use_inactive, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle); + +// Swap the constant buffer being used to the inactive one. +AOTI_API AOTIRuntimeError AOTInductorModelContainerSwapConstantBuffer( + AOTInductorModelContainerHandle container_handle); + +// Retrieves the number of inputs for the model. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetNumInputs( + AOTInductorModelContainerHandle container_handle, + size_t* ret_num_inputs); + +// Retrieves the input name at the given index. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetInputName( + AOTInductorModelContainerHandle container_handle, + size_t input_idx, + const char** ret_input_names); + +// Retrieves the number of outputs for the model. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetNumOutputs( + AOTInductorModelContainerHandle container_handle, + size_t* ret_num_outputs); + +// Retrieves the output name at the given index. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetOutputName( + AOTInductorModelContainerHandle container_handle, + size_t output_idx, + const char** ret_output_names); + +// Creates an AOTInductorModel instance. This is a thin and light wrapper +// around the compiled model; it doesn't handle concurrency, queueing, device +// management, etc. Use this if bare-metal performance is needed and you are +// willing to handle other "management" aspects yourself. +// +// constant_map_handle is an opaque type to satisfy the C ABI. It should be a +// std::unordered_map*. +AOTI_API AOTIRuntimeError AOTInductorModelCreate( + AOTInductorModelHandle* model_handle, + AOTInductorConstantMapHandle constant_map_handle); + +// Run an AOTInductorModel (see AOTInductorModelCreate for when one should use +// this function versus AOTInductorModelContainerRun). +AOTI_API AOTIRuntimeError AOTInductorModelRun( + AOTInductorModelHandle model_handle, + AtenTensorHandle* input_handles, + AtenTensorHandle* output_handles); + +// Replace AOTInductorModel's constant map. Note it doesn't handle concurrency +// so be sure to handle ordering if AOTInductorModelRun is ran concurrently. +AOTI_API AOTIRuntimeError AOTInductorModelUpdateConstantsMap( + AOTInductorModelHandle model_handle, + AOTInductorConstantMapHandle constant_map_handle); + +// Get the size of the constant blob +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantsBlobSize( + AOTInductorModelContainerHandle container_handle, + uint64_t* ret_size); + +// Load weights from a single blob in weight_blob_ptr +AOTI_API AOTIRuntimeError AOTInductorModelUpdateConstantsFromBlob( + AOTInductorModelContainerHandle container_handle, + const uint8_t* weight_blob_ptr); + +// Delete an AOTInductorModel created by AOTInductorModelCreate. +AOTI_API AOTIRuntimeError +AOTInductorModelDelete(AOTInductorModelHandle model_handle); + +AOTI_API AOTIRuntimeError AOTInductorModelGetNumOutputs( + AOTInductorModelHandle model_handle, + size_t* ret_num_outputs); + +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetCallSpec( + AOTInductorModelContainerHandle container_handle, + const char** in_spec, + const char** out_spec); + +} // extern "C" + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/kernel_context_tls.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/kernel_context_tls.h new file mode 100644 index 0000000000000000000000000000000000000000..5aca1631d18490dc28b4ed631701d62968e7dfda --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/kernel_context_tls.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::aot_inductor { + +struct KernelContext { + std::string kernel_name; + std::string python_stack; + std::string compressed_python_stack; + + KernelContext(std::string name, std::string stack) + : kernel_name(std::move(name)), python_stack(std::move(stack)) { + compressed_python_stack = compress_python_stack(python_stack); + } + + KernelContext(const KernelContext&) = default; + KernelContext& operator=(const KernelContext&) = default; + KernelContext(KernelContext&&) = default; + KernelContext& operator=(KernelContext&&) = default; + + private: + static std::string compress_python_stack(const std::string& stack) { + namespace fs = std::filesystem; + char func[129]; + char path[1025]; + uint32_t line; + int ret; + std::string compressed_stack; + std::stringstream stream{stack}; + std::string str; + std::string fmt = "File \"%1024[^\"]\", line %u, in %128[^\n]\n"; + while (std::getline(stream, str)) { + ret = sscanf(str.c_str(), fmt.c_str(), path, &line, func); + if (ret == 3) { + compressed_stack += func; + compressed_stack += ' '; + compressed_stack += fs::path{path}.filename(); + compressed_stack += ':'; + compressed_stack += std::to_string(line); + compressed_stack += '\n'; + } + } + return compressed_stack; + } +}; + +// Thread-local pointer +extern thread_local KernelContext* tls_kernel_context; + +inline KernelContext* current_kernel_context() { + return tls_kernel_context; +} + +inline void set_kernel_context(KernelContext* ctx) { + tls_kernel_context = ctx; +} + +inline void clear_kernel_context() { + tls_kernel_context = nullptr; +} + +struct KernelContextGuard { + KernelContextGuard(const std::string& name, const std::string& stack) + : owned_context_(name, stack) { + set_kernel_context(&owned_context_); + } + ~KernelContextGuard() { + clear_kernel_context(); + } + + // Delete copy constructor and copy assignment operator + KernelContextGuard(const KernelContextGuard&) = delete; + KernelContextGuard& operator=(const KernelContextGuard&) = delete; + + KernelContextGuard(KernelContextGuard&&) = default; + KernelContextGuard& operator=(KernelContextGuard&&) = delete; + + private: + KernelContext owned_context_; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/mini_array_ref.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/mini_array_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..31cdf3063f928702619631d25997c1bd703e54db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/mini_array_ref.h @@ -0,0 +1,165 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::aot_inductor { + +// Can't use c10::ArrayRef because it's not truly header-only and +// pulls in other c10 headers. This is (sadly) copy-pasted and +// adapted. +template +class MiniArrayRef final { + public: + using iterator = T*; + using const_iterator = const T*; + using size_type = size_t; + using value_type = T; + + using reverse_iterator = std::reverse_iterator; + + private: + /// The start of the array, in an external buffer. + T* Data; + + /// The number of elements. + size_type Length; + + public: + /// @name Constructors + /// @{ + + /// Construct an empty MiniArrayRef. + /* implicit */ constexpr MiniArrayRef() : Data(nullptr), Length(0) {} + + /// Construct an MiniArrayRef from a single element. + // TODO Make this explicit + constexpr MiniArrayRef(const T& OneElt) : Data(&OneElt), Length(1) {} + + /// Construct an MiniArrayRef from a pointer and length. + constexpr MiniArrayRef(T* data, size_t length) : Data(data), Length(length) {} + + /// Construct an MiniArrayRef from a range. + constexpr MiniArrayRef(T* begin, T* end) : Data(begin), Length(end - begin) {} + + template < + typename Container, + typename = std::enable_if_t().data())>, + T*>>> + /* implicit */ MiniArrayRef(Container& container) + : Data(container.data()), Length(container.size()) {} + + /// Construct an MiniArrayRef from a std::vector. + // The enable_if stuff here makes sure that this isn't used for + // std::vector, because MiniArrayRef can't work on a std::vector + // bitfield. + template + /* implicit */ MiniArrayRef(const std::vector& Vec) + : Data(Vec.data()), Length(Vec.size()) { + static_assert( + !std::is_same_v, + "MiniArrayRef cannot be constructed from a std::vector bitfield."); + } + + /// Construct an MiniArrayRef from a std::array + template + /* implicit */ constexpr MiniArrayRef(std::array& Arr) + : Data(Arr.data()), Length(N) {} + + /// Construct an MiniArrayRef from a C array. + template + // NOLINTNEXTLINE(*c-array*) + /* implicit */ constexpr MiniArrayRef(T (&Arr)[N]) : Data(Arr), Length(N) {} + + // /// Construct an MiniArrayRef from an empty C array. + /* implicit */ constexpr MiniArrayRef(const volatile void* Arr) + : Data(nullptr), Length(0) {} + + /// Construct an MiniArrayRef from a std::initializer_list. + /* implicit */ constexpr MiniArrayRef(const std::initializer_list& Vec) + : Data( + std::begin(Vec) == std::end(Vec) ? static_cast(nullptr) + : std::begin(Vec)), + Length(Vec.size()) {} + + /// @} + /// @name Simple Operations + /// @{ + + constexpr iterator begin() const { + return Data; + } + constexpr iterator end() const { + return Data + Length; + } + + // These are actually the same as iterator, since MiniArrayRef only + // gives you const iterators. + constexpr const_iterator cbegin() const { + return Data; + } + constexpr const_iterator cend() const { + return Data + Length; + } + + constexpr reverse_iterator rbegin() const { + return reverse_iterator(end()); + } + constexpr reverse_iterator rend() const { + return reverse_iterator(begin()); + } + + /// empty - Check if the array is empty. + constexpr bool empty() const { + return Length == 0; + } + + constexpr T* data() const { + return Data; + } + + /// size - Get the array size. + constexpr size_t size() const { + return Length; + } + + /// equals - Check for element-wise equality. + constexpr bool equals(MiniArrayRef RHS) const { + return Length == RHS.Length && std::equal(begin(), end(), RHS.begin()); + } + + /// @} + /// @name Operator Overloads + /// @{ + constexpr const T& operator[](size_t Index) const { + return Data[Index]; + } + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t, MiniArrayRef>& operator=( + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + U&& Temporary) = delete; + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t, MiniArrayRef>& operator=( + std::initializer_list) = delete; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h new file mode 100644 index 0000000000000000000000000000000000000000..eca53e62494e348a7c5f75684f650b71c45caa7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h @@ -0,0 +1,67 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include + +namespace torch::aot_inductor { + +class AOTInductorModel : public AOTInductorModelBase { + public: + AOTInductorModel( + std::shared_ptr constants_map, + std::shared_ptr> constants_array, + const std::string& device_str, + std::optional cubin_dir); + + std::unordered_map const_run_impl( + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor, + bool initialization = false); + + void _const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor); + + void run_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor); + + template + Outputs run_impl_minimal_arrayref_interface( + const Inputs& inputs, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor); + + static std::unique_ptr Create( + std::shared_ptr constants_map, + std::shared_ptr> constants_array, + const std::string& device_str, + std::optional cubin_dir) { + return std::make_unique( + std::move(constants_map), + std::move(constants_array), + device_str, + std::move(cubin_dir)); + } + + private: + std::unique_ptr kernels_; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_base.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_base.h new file mode 100644 index 0000000000000000000000000000000000000000..86870dc944096a3752359c8b80f691af62a16eca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_base.h @@ -0,0 +1,1048 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#ifdef _WIN32 +#include +#include // std::function +#ifdef USE_MMAP_SELF +#include +#include +#include +#include + +#define PROT_READ 0x1 +#define PROT_WRITE 0x2 +#define PROT_EXEC 0x4 + +#define MAP_SHARED 0x01 +#define MAP_PRIVATE 0x02 +#define MAP_FAILED ((void*)-1) + +#define SEEK_SET 0 +#define SEEK_CUR 1 +#define SEEK_END 2 + +struct Dl_info { + char dli_fname[MAX_PATH]; /**< Filename of defining object */ + void* dli_fbase; /**< Load address of that object */ + const char* dli_sname; /**< Name of nearest lower symbol */ + void* dli_saddr; /**< Exact value of nearest symbol */ +}; +typedef struct Dl_info Dl_info; + +int dladdr(const void* addr, Dl_info* info) { + // only returns filename, FWIW. + CHAR tpath[MAX_PATH]; + MEMORY_BASIC_INFORMATION mbi; + char* path; + char* tmp; + size_t length; + int ret = 0; + + if (!info) + return 0; + + HMODULE hModule; + if (!GetModuleHandleExA( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCSTR)addr, + &hModule) || + hModule == NULL) + return 0; + + ret = GetModuleFileNameA(hModule, (LPSTR)&tpath, MAX_PATH); + if (!ret) + return 0; + + path = tpath; + + length = strlen(path); + if (length >= MAX_PATH) { + length = MAX_PATH - 1; + path[MAX_PATH - 1] = '\0'; + } + + tmp = path; + while (*tmp) { + if (*tmp == '\\') + *tmp = '/'; + tmp++; + } + + memcpy(info->dli_fname, path, length + 1); + info->dli_fbase = hModule; + info->dli_sname = NULL; + info->dli_saddr = NULL; + return 1; +} + +static DWORD get_creation_disposition(int flags) { + if (flags & O_CREAT) { + if (flags & O_EXCL) + return CREATE_NEW; + if (flags & O_TRUNC) + return CREATE_ALWAYS; + return OPEN_ALWAYS; + } + if (flags & O_TRUNC) + return TRUNCATE_EXISTING; + return OPEN_EXISTING; +} + +#define O_ACCMODE 03 +#define O_RDONLY 00 +#define O_WRONLY 01 +#define O_RDWR 02 + +static DWORD get_access_mode(int flags) { + switch (flags & O_ACCMODE) { + case O_RDONLY: + return GENERIC_READ; + case O_WRONLY: + return GENERIC_WRITE; + case O_RDWR: + return GENERIC_READ | GENERIC_WRITE; + default: + return GENERIC_READ; + } +} +#ifndef O_DSYNC +#define O_DSYNC 00010000 /* used to be O_SYNC, see below */ +#endif + +#ifndef O_SYNC +#define __O_SYNC 04000000 +#define O_SYNC (__O_SYNC | O_DSYNC) +#endif + +int open(char* pathname, int flags) { + DWORD dwDesiredAccess = get_access_mode(flags); + DWORD dwCreationDisposition = get_creation_disposition(flags); + DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; + DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; + + if (flags & O_SYNC) { + dwFlagsAndAttributes |= FILE_FLAG_WRITE_THROUGH; + } + + if (flags & O_SEQUENTIAL) { + dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN; + } + + if (flags & O_RANDOM) { + dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS; + } + + HANDLE hFile = CreateFileA( + pathname, + dwDesiredAccess, + dwShareMode, + NULL, + dwCreationDisposition, + dwFlagsAndAttributes, + NULL); + + if (hFile == INVALID_HANDLE_VALUE) { + switch (GetLastError()) { + case ERROR_FILE_NOT_FOUND: + errno = ENOENT; + break; + case ERROR_PATH_NOT_FOUND: + errno = ENOTDIR; + break; + case ERROR_ACCESS_DENIED: + errno = EACCES; + break; + case ERROR_FILE_EXISTS: + errno = EEXIST; + break; + case ERROR_TOO_MANY_OPEN_FILES: + errno = EMFILE; + break; + default: + errno = EIO; + } + return -1; + } + + int fd = _open_osfhandle((intptr_t)hFile, flags); + if (fd == -1) { + CloseHandle(hFile); + errno = EMFILE; + return -1; + } + + if (flags & O_APPEND) { + lseek(fd, 0, SEEK_END); + } + + return fd; +} + +int close(int fd) { + return _close(fd); +} + +void* mmap( + void* addr, + size_t length, + int prot, + int flags, + int fd, + off_t offset) { + HANDLE hFile = (HANDLE)_get_osfhandle(fd); + if (hFile == INVALID_HANDLE_VALUE) { + errno = EBADF; + return MAP_FAILED; + } + + DWORD flProtect; + if (prot & PROT_WRITE) { + flProtect = PAGE_READWRITE; + } else if (prot & PROT_READ) { + flProtect = PAGE_READONLY; + } else { + flProtect = PAGE_NOACCESS; + } + + flProtect = PAGE_READONLY; + + DWORD dwDesiredAccess = 0; + if (prot & PROT_READ) + dwDesiredAccess |= FILE_MAP_READ; + if (prot & PROT_WRITE) + dwDesiredAccess |= FILE_MAP_WRITE; + if (prot & PROT_EXEC) + dwDesiredAccess |= FILE_MAP_EXECUTE; + + dwDesiredAccess = FILE_MAP_READ; + + SYSTEM_INFO SysInfo; + GetSystemInfo(&SysInfo); + DWORD dwSysGran = SysInfo.dwAllocationGranularity; + + DWORD dwFileMapStart = (offset / dwSysGran) * dwSysGran; + DWORD dwMapViewSize = (offset % dwSysGran) + length; + DWORD dwFileMapSize = offset + length; + int iViewDelta = offset - dwFileMapStart; + + HANDLE hMapping = + CreateFileMapping(hFile, NULL, flProtect, 0, dwFileMapSize, NULL); + + if (!hMapping) { + DWORD dwErrCode = GetLastError(); + errno = EACCES; + return MAP_FAILED; + } + + void* lpMapAddress = MapViewOfFileEx( + hMapping, dwDesiredAccess, 0, dwFileMapStart, dwMapViewSize, addr); + if (!lpMapAddress) { + DWORD dwErrCode = GetLastError(); + errno = EINVAL; + } + + void* pData = (char*)lpMapAddress + iViewDelta; + + CloseHandle(hMapping); + + if (!lpMapAddress) { + return MAP_FAILED; + } + + return pData; +} + +int munmap(void* addr, size_t length) { + if (!UnmapViewOfFile(addr)) { + errno = EINVAL; + return -1; + } + return 0; +} +#endif // USE_MMAP_SELF +#else // !_WIN32 +#include +#include +#include +#endif // _WIN32 + +#include +#include +#include +#include +#include +#include + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include +#ifdef USE_MPS +#include +#endif // USE_MPS +#ifdef USE_XPU +#include +#else +#include +#endif // USE_XPU +#include + +#define AOTI_RUNTIME_CHECK(EXPR, MSG) \ + do { \ + bool ok = EXPR; \ + if (!ok) { \ + throw std::runtime_error(MSG); \ + } \ + } while (0) + +// At codegen time, we write out a binary file called constants.bin. +// We then turn the raw binary to an object file that exposes this +// symbol and link it into the final .so. +// For information on the binary format, see `man objcopy`, under +// the "binary-architecture" flag: +// https://man7.org/linux/man-pages/man1/objcopy.1.html +// todo: use #embed in C++ 23 once available +// The constants are NOT readonly because they may be mutated. +// NOLINTNEXTLINE(*array*) +extern uint8_t _binary_constants_bin_start[]; +// NOLINTNEXTLINE(*array*) +extern uint8_t _binary_constants_bin_end[]; + +#if defined(USE_CUDA) || defined(USE_XPU) +// Compute required blob size with 64-alignment if on GPU. +#define AOTI_CONST_ALIGNMENT 64 +#else +// Use 64-alignment (use something >=64)for better performance on CPU. +#define AOTI_CONST_ALIGNMENT 64 +#endif + +namespace { + +using RAIIDataPtr = std::unique_ptr>; + +#ifdef USE_CUDA + +// NOLINTNEXTLINE(clang-diagnostic-unneeded-internal-declaration) +RAIIDataPtr RAII_gpuMalloc(size_t num_bytes) { +#ifdef AOT_INDUCTOR_USE_CACHING_ALLOCATOR + // Use caching allocator for allocating GPU memory + void* data_ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_cuda_caching_allocator_raw_alloc(num_bytes, &data_ptr)); + auto deleter = [](void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_cuda_caching_allocator_raw_delete(ptr)); + }; + return RAIIDataPtr(data_ptr, deleter); +#else + // Use cudaMalloc directly for allocating GPU memory + void* data_ptr = nullptr; + AOTI_RUNTIME_CUDA_CHECK(cudaMalloc((void**)&data_ptr, num_bytes)); + auto deleter = [](void* ptr) { AOTI_RUNTIME_CUDA_CHECK(cudaFree(ptr)); }; + return RAIIDataPtr(data_ptr, deleter); +#endif +} + +#elif defined(USE_XPU) + +RAIIDataPtr RAII_gpuMalloc(size_t num_bytes) { + sycl::queue* queue_ptr = nullptr; + aoti_torch_get_current_sycl_queue((void**)&queue_ptr); + void* data_ptr = sycl::malloc_device(num_bytes, *queue_ptr); + auto deleter = [queue_ptr](void* ptr) { sycl::free(ptr, *queue_ptr); }; + return RAIIDataPtr(data_ptr, deleter); +} + +#elif defined(USE_MPS) + +RAIIDataPtr RAII_gpuMalloc(size_t num_bytes) { + void* data_ptr = nullptr; + aoti_torch_mps_malloc(&data_ptr, num_bytes); + auto deleter = [](void* ptr) { aoti_torch_mps_free(ptr); }; + return RAIIDataPtr(data_ptr, deleter); +} + +#else + +RAIIDataPtr RAII_cpuMalloc(size_t num_bytes) { + void* data_ptr = std::malloc(num_bytes); + if (!data_ptr) { + throw std::bad_alloc(); + } + auto deleter = [](void* ptr) { std::free(ptr); }; + return RAIIDataPtr(data_ptr, deleter); +} + +#endif // USE_CUDA + +} // anonymous namespace + +namespace torch::aot_inductor { + +using ConstantMap = + std::unordered_map; + +// valid device strs are: cpu, cuda, cuda:0, cuda:1, ... +// Update the list here if more devices are supported in the future +inline void parse_device_str( + const std::string& device_str, + int32_t& device_type, + int32_t& device_idx) { + std::regex re("(cpu|cuda|xpu|mps)(:([0-9]+))?"); + std::smatch sm; + bool matched = std::regex_match(device_str, sm, re); + AOTI_RUNTIME_CHECK(matched, "Invalid device: " + device_str); + + if (sm[1].str() == "cpu") { + device_type = aoti_torch_device_type_cpu(); + } else if (sm[1].str() == "cuda") { + device_type = aoti_torch_device_type_cuda(); +#ifdef USE_XPU + } else if (sm[1].str() == "xpu") { + device_type = aoti_torch_device_type_xpu(); +#endif +#ifdef USE_MPS + } else if (sm[1].str() == "mps") { + device_type = aoti_torch_device_type_mps(); +#endif + } else { + AOTI_RUNTIME_CHECK(false, "Invalid device: " + device_str); + } + + if (sm[3].matched) { + device_idx = stoi(sm[3].str()); + } else { + device_idx = -1; + } +} + +// Defines the base class for AOTInductorModel, which is generated by the +// AOTInductor cpp codegen. Since we do not need dynamic dispatch, we rely +// on curiously recurring template pattern (CRTP) to save some runtime +// v-table overhead. The generated AOTInductorModel is specialized with +// methods such as run_impl. +template +class AOTInductorModelBase { + public: + AOTInductorModelBase( + size_t num_inputs, + size_t num_outputs, + size_t num_constants, + const std::string& device_str, + std::optional cubin_dir, + bool include_weights = true) + : inputs_info_(num_inputs), + outputs_info_(num_outputs), + constants_info_(num_constants), + cubin_dir_(std::move(cubin_dir)), + include_weights(include_weights) { + parse_device_str(device_str, device_type_, device_idx_); + +#ifdef USE_CUDA + if (device_idx_ == -1) { + AOTI_RUNTIME_CUDA_CHECK(cudaGetDevice(&device_idx_)); + } else { + // If device_idx_ is passed in, we need to set the current device to it + AOTI_RUNTIME_CUDA_CHECK(cudaSetDevice(device_idx_)); + } +#endif // USE_CUDA +#ifdef USE_XPU + if (device_idx_ == -1) { + aoti_torch_get_current_xpu_device(&device_idx_); + } else { + aoti_torch_set_current_xpu_device(device_idx_); + } +#endif // USE_XPU +#ifdef USE_MPS + if (device_idx_ == -1) { + device_idx_ = 0; + } +#endif // USE_MPS + } + + // NOLINTNEXTLINE(modernize-use-equals-default) + ~AOTInductorModelBase() { +#ifdef USE_CUDA + if (run_finished_) { + auto code = cudaEventDestroy(*run_finished_); + if (code != cudaSuccess) { + std::cerr << "Failed to destroy CUDA event in AOTInductor model: " + << cudaGetErrorString(code) << '\n'; + } + } +#endif // USE_CUDA +#ifdef USE_XPU + if (run_finished_) { + (*run_finished_)->wait_and_throw(); + delete *run_finished_; + } +#endif // USE_XPU + } + + AOTInductorModelBase(AOTInductorModelBase&&) = delete; + AOTInductorModelBase& operator=(AOTInductorModelBase&&) = delete; + AOTInductorModelBase(const AOTInductorModelBase&) = delete; + AOTInductorModelBase& operator=(const AOTInductorModelBase&) = delete; + + void run( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { +#ifdef USE_CUDA + if (!run_finished_) { + cudaEvent_t run_finished = nullptr; + AOTI_RUNTIME_CUDA_CHECK(cudaEventCreate(&run_finished)); + run_finished_.emplace(run_finished); + } +#elif defined(USE_XPU) + if (run_finished_) { + (*run_finished_)->wait_and_throw(); + delete *run_finished_; + run_finished_.reset(); + } +#else // !USE_CUDA && !USE_XPU + run_finished_ = false; +#endif + + auto* model = static_cast(this); + model->run_impl(input_handles, output_handles, stream, proxy_executor); + +#ifdef USE_CUDA + AOTI_RUNTIME_CUDA_CHECK(cudaEventRecord(*run_finished_, stream)); +#elif defined(USE_XPU) + run_finished_ = std::make_optional(new sycl::event( + static_cast(stream)->ext_oneapi_submit_barrier())); +#else // !USE_CUDA && !USE_XPU + run_finished_ = true; +#endif // USE_CUDA + } + + // Non-thread-aware variant of run(). Obviously unsafe to use in a threaded + // environment :) + void run_single_threaded( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { + // don't bother with any of the run_finished stuff; this is unsafe to call + // in a threaded context + auto* model = static_cast(this); + model->run_impl(input_handles, output_handles, stream, proxy_executor); + } + + std::unordered_map run_const_fold( + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor, + bool initialization = false) { +#ifdef USE_CUDA + if (!run_finished_) { + cudaEvent_t run_finished = nullptr; + AOTI_RUNTIME_CUDA_CHECK(cudaEventCreate(&run_finished)); + run_finished_.emplace(run_finished); + } +#elif defined(USE_XPU) + if (run_finished_) { + (*run_finished_)->wait_and_throw(); + delete *run_finished_; + run_finished_.reset(); + } +#else // !USE_CUDA && !USE_XPU + run_finished_ = false; +#endif + + auto* model = static_cast(this); + auto folded_constants = + model->const_run_impl(stream, proxy_executor, initialization); + +#ifdef USE_CUDA + AOTI_RUNTIME_CUDA_CHECK(cudaEventRecord(*run_finished_, stream)); +#elif defined(USE_XPU) + // sycl::queue* queue_ptr = nullptr; + // aoti_torch_get_current_sycl_queue((void**)&queue_ptr); + run_finished_ = std::make_optional(new sycl::event( + static_cast(stream)->ext_oneapi_submit_barrier())); + +#else // !USE_CUDA && !USE_XPU + run_finished_ = true; +#endif // USE_CUDA + + return folded_constants; + } + + void update_constants_from_blob(const uint8_t* weight_blob_ptr) { +#if defined(USE_MMAP_EXTERNAL) + user_managed_mmap = const_cast(weight_blob_ptr); + load_constants(true); +#endif + } + + void load_constants(bool force = false) { + size_t num_constants = this->num_constants(); + size_t num_folded_constants = this->num_folded_constants(); + constants_map_->reserve(num_constants); + + std::vector constants_internal_offset( + num_constants - num_folded_constants); + size_t blob_size = 0; + compute_constant_blob(blob_size, constants_internal_offset); + if (!force && !include_weights) { + return; + } +#if defined(USE_CUDA) || defined(USE_XPU) || defined(USE_MPS) + constant_blob_ = RAII_gpuMalloc(blob_size); +#else + constant_blob_ = RAII_cpuMalloc(blob_size); +#endif + + size_t bytes_read = 0; + size_t non_folded_idx = 0; // Separate index for non-folded constants + for (size_t i = 0; i < num_constants; i++) { + bool from_folded = this->constant_from_folded(i); + if (from_folded) { + continue; + } + std::string name = this->constant_name(i); + size_t data_size = this->constant_data_size(i); + uint8_t* internal_ptr = (data_size != 0) + ? constant_ptr( + constants_internal_offset[non_folded_idx], + bytes_read, + data_size, + /* skip_copy = */ false) + : nullptr; + bytes_read += data_size; + non_folded_idx++; // Increment the non-folded index + + // Create at::Tensor from copied memory. + auto dtype = this->constant_dtype(i); + auto ndim = this->constant_ndim(i); + auto size = this->constant_shape(i); + auto stride = this->constant_stride(i); +#ifdef USE_MPS + auto offset = this->constant_offset(i) + + (constants_internal_offset[i] / aoti_torch_dtype_element_size(dtype)); +#else + auto offset = this->constant_offset(i); +#endif + auto layout = this->constant_layout(i); + auto opaque_metadata_ptr = this->opaque_metadata(i); + auto opaque_metadata_size = this->opaque_metadata_size(i); + + AtenTensorHandle tensor_handle = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob_v2( + internal_ptr, + ndim, + size, + stride, + offset, + dtype, + device_type_, + device_idx_, + &tensor_handle, + layout, + opaque_metadata_ptr, + opaque_metadata_size)); + constants_map_->emplace(std::move(name), tensor_handle); + } + if (constants_map_) { + this->update_constants_array_from_map(); + } + } + + RAIIDataPtr&& release_constant_blob() { + return std::move(constant_blob_); + } + + std::shared_ptr> get_constants_array() { + return constants_; + } + + int32_t get_device_type() const { + return device_type_; + } + + int32_t get_device_idx() const { + return device_idx_; + } + + uint8_t* constant_ptr( + size_t constant_offset, + size_t bytes_read, + size_t data_size, + bool skip_copy) { + auto* constants_ptr = static_cast(constant_blob_.get()); + uint8_t* internal_ptr = constants_ptr + constant_offset; + // TODO: Handle shared storage case. + if (!skip_copy) { +#ifdef USE_XPU + sycl::queue* queue_ptr = nullptr; + aoti_torch_get_current_sycl_queue((void**)&queue_ptr); + queue_ptr + ->memcpy(internal_ptr, _get_constants_start() + bytes_read, data_size) + .wait(); +#elif USE_CUDA + AOTI_RUNTIME_CUDA_CHECK(cudaMemcpy( + internal_ptr, + _get_constants_start() + bytes_read, + data_size, + cudaMemcpyHostToDevice)); +#elif USE_MPS + aoti_torch_mps_memcpy( + constants_ptr, + constant_offset, + bytes_read, + data_size, + _get_constants_start()); + return constants_ptr; +#else + memcpy(internal_ptr, _get_constants_start() + bytes_read, data_size); +#endif + } + return internal_ptr; + } + + void compute_constant_blob( + size_t& blob_size, + std::vector& constants_internal_offset) { + size_t num_constants = this->num_constants(); + blob_size = 0; + size_t curr_idx = 0; + for (size_t i = 0; i < num_constants; i++) { + if (this->constant_from_folded(i)) { + continue; + } + size_t data_size = this->constant_data_size(i); + if (data_size % AOTI_CONST_ALIGNMENT) { + data_size = AOTI_CONST_ALIGNMENT + + (data_size / AOTI_CONST_ALIGNMENT) * AOTI_CONST_ALIGNMENT; + } + constants_internal_offset[curr_idx++] = blob_size; + blob_size += data_size; + } + } + + size_t num_inputs() const { + return inputs_info_.size(); + } + + size_t num_outputs() const { + return outputs_info_.size(); + } + + size_t num_constants() const { + return constants_info_.size(); + } + + size_t num_folded_constants() const { + size_t total_consts = this->num_constants(); + size_t folded_consts = 0; + for (size_t i = 0; i < total_consts; i++) { + if (this->constant_from_folded(i)) { + folded_consts++; + } + } + return folded_consts; + } + + const char* input_name(int64_t idx) const { + return inputs_info_.at(idx).name; + } + + const char* output_name(int64_t idx) const { + return outputs_info_.at(idx).name; + } + + const char* constant_name(int64_t idx) const { + return constants_info_.at(idx).name; + } + + size_t constant_ndim(int64_t idx) { + return constants_info_.at(idx).shape.size(); + } + + const int64_t* constant_shape(int64_t idx) const { + return constants_info_.at(idx).shape.data(); + } + + const int64_t* constant_stride(int64_t idx) const { + return constants_info_.at(idx).stride.data(); + } + + int32_t constant_dtype(int64_t idx) const { + return constants_info_.at(idx).dtype; + } + + int32_t constant_layout(int64_t idx) const { + return constants_info_.at(idx).layout; + } + + size_t constant_offset(int64_t idx) const { + return constants_info_.at(idx).offset; + } + + size_t constant_data_size(int64_t idx) const { + return constants_info_.at(idx).data_size; + } + + const char* constant_original_fqn(int64_t idx) const { + return constants_info_.at(idx).original_fqn; + } + + const uint8_t* opaque_metadata(int64_t idx) const { + return constants_info_.at(idx).opaque_metadata.data(); + } + + size_t opaque_metadata_size(int64_t idx) { + return constants_info_.at(idx).opaque_metadata.size(); + } + + bool constant_from_folded(int64_t idx) const { + return constants_info_.at(idx).from_folded; + } + + int32_t constant_type(int64_t idx) const { + return constants_info_.at(idx).type; + } + + const char* get_in_spec() const { + return in_spec_.c_str(); + } + + const char* get_out_spec() const { + return out_spec_.c_str(); + } + + uint64_t constant_blob_size() const { +#if defined(USE_MMAP_SELF) || defined(USE_MMAP_EXTERNAL) + const uint64_t weights_size = + reinterpret_cast(_binary_constants_bin_start)[0]; + return weights_size; +#else + throw std::runtime_error{ + "constant blob size is only available for mmap'd weights"}; +#endif + } + + void update_constants_array_from_map() { + if (!constants_map_) { + throw std::runtime_error{ + "constants_map_ was not ready when constants_ is trying to be constructed from it!"}; + } + if (!constants_) { + constants_ = + std::make_shared>(constants_info_.size()); + } else { + constants_->resize(constants_info_.size()); + } + int idx = 0; + for (const auto& info : constants_info_) { + const auto it = constants_map_->find(info.name); + if (it != constants_map_->end()) { + constants_->at(idx) = ConstantHandle(it->second); + } + idx++; + } + } + + void update_constants_map( + std::shared_ptr constants_map, + bool remap_constants_array = true) { + constants_map_ = std::move(constants_map); + if (remap_constants_array) { + update_constants_array_from_map(); + } + } + + // This function allows us to update the constants_ that is used to look up + // the corresponding constant tensor during runtime. + void update_constants_array( + std::shared_ptr> constants_array) { + constants_ = std::move(constants_array); + } + + /// Returns true if the model is complete. + bool is_finished() { +#ifdef USE_CUDA + if (!run_finished_) { + throw std::runtime_error{"Model CUDA event was not initialized"}; + } + + auto event_status = cudaEventQuery(*run_finished_); + if (event_status == cudaSuccess) { + return true; + } else if (event_status == cudaErrorNotReady) { + return false; + } + + throw std::runtime_error( + std::string("The model did not finish successfully. Error: ") + + cudaGetErrorString(cudaGetLastError())); +#elif defined(USE_XPU) + if (!run_finished_) { + throw std::runtime_error{"Model XPU event was not initialized"}; + } + using namespace sycl::info; + return (*run_finished_)->get_info() == + event_command_status::complete; + +#else // !USE_CUDA && !USE_XPU + return run_finished_; +#endif // USE_CUDA + } + + /// Synchronizes completion event. + void wait_for_completion() { +#ifdef USE_CUDA + if (!run_finished_) { + throw std::runtime_error{"Model event was not initialized"}; + } + + AOTI_RUNTIME_CUDA_CHECK(cudaEventSynchronize(*run_finished_)); +#endif // USE_CUDA +#ifdef USE_XPU + if (!run_finished_) { + throw std::runtime_error{"Model event was not initialized"}; + } + (*run_finished_)->wait_and_throw(); +#endif + } + + protected: + uint8_t* _get_constants_start() { +#if defined(USE_MMAP_EXTERNAL) + if (!user_managed_mmap) { + throw std::runtime_error{ + "Constants are not mmap'd. Use AOTInductorModelUpdateConstantsBlob to initialize the constants first."}; + } + // Mapped memory for weights + return user_managed_mmap; +#endif + +#ifndef USE_MMAP_SELF + // NOLINTNEXTLINE(*const-cast*) + return const_cast(_binary_constants_bin_start); +#else + if (self_mmap) { + return self_mmap; + } + Dl_info dl_info; + // get pointer to constant which are appended to the binary + AOTI_RUNTIME_CHECK( + dladdr(__func__, &dl_info), "Can't find shared library name"); + int fd = open(dl_info.dli_fname, O_RDONLY); + AOTI_RUNTIME_CHECK(fd >= 0, "Shared library file cannot be opened"); + auto fsize = lseek(fd, 0, SEEK_END); + auto weights_size = + reinterpret_cast(_binary_constants_bin_start)[0]; + auto magic_number = + reinterpret_cast(_binary_constants_bin_start)[1]; + auto weights_offset = fsize - weights_size; + AOTI_RUNTIME_CHECK( + (weights_offset & 0x3fff) == 0, + "weights_offset must be aligned to 16K boundary"); + auto ptr = mmap( + NULL, + weights_size, + PROT_READ | PROT_WRITE, + MAP_PRIVATE, + fd, + weights_offset); + close(fd); + AOTI_RUNTIME_CHECK(ptr != MAP_FAILED, "mmap() failed"); + self_mmap = static_cast(ptr); + AOTI_RUNTIME_CHECK( + reinterpret_cast( + self_mmap + weights_size - sizeof(uint64_t))[0] == magic_number, + "Weights data seems corrupt"); + return self_mmap; +#endif + } + + struct ParamInfo { + const char* name = nullptr; + }; + + struct ConstInfo { + const char* name = nullptr; + std::vector shape; + std::vector stride; + int32_t dtype{}; + int64_t offset{}; + size_t data_size{}; + int32_t layout{}; + std::vector opaque_metadata; + int64_t opaque_metadata_size{}; + const char* original_fqn = nullptr; + bool from_folded{}; + int32_t type{}; + }; + + std::vector inputs_info_; + std::vector outputs_info_; + std::vector constants_info_; + std::string in_spec_; + std::string out_spec_; + + std::shared_ptr constants_map_; + std::shared_ptr> constants_; + + // Holds the blob storage for constants' at::Tensor. + RAIIDataPtr constant_blob_; + +#if defined(USE_MMAP_SELF) + // Mapped memory for weights + uint8_t* self_mmap = NULL; +#endif + +#if defined(USE_MMAP_EXTERNAL) + // Mapped memory for weights + uint8_t* user_managed_mmap = NULL; +#endif + + // A directory with CUDA binary files, e.g. compiled kernels, etc. + const std::optional cubin_dir_; + + // This is the flag that implies whether the weight is included in the model. + // If True, we would prepare the weight when loading the model, otherwise the + // model will be loaded without weights, and need to be provided by the user. + bool include_weights; + + // Record if the model finishes an inference run so that its owning + // AOTModelContainer can reuse this instance. +#ifdef USE_CUDA + std::optional run_finished_; +#elif defined(USE_XPU) + std::optional run_finished_; +#else // !USE_CUDA + bool run_finished_{}; +#endif + + // Generated model uses this device index to create CUDA guards. + int32_t device_type_{}; + int32_t device_idx_{}; +}; + +// Codegen-ed classes can derive from this to keep pointers to loaded kernels. +class AOTInductorModelKernelsBase { + public: + virtual ~AOTInductorModelKernelsBase() = default; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h new file mode 100644 index 0000000000000000000000000000000000000000..7eed530d84d1391f7d4e9f5b47304d15d7e0ed7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h @@ -0,0 +1,808 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include + +namespace torch::aot_inductor { +// The state transition is done by: +// (1) NONE state: The default state when created. This state should only exist +// when model_container is created and no constants are being loaded or updated. +// (2) INITIALIZED state: This state get set whenever we load the constants into +// the buffer. This could be done by load_constants or update_constants_buffer. +// (3) FOLDED state: This state should transition from INITIALIZED after +// const_fold is being invoked. +enum class ConstantState : uint8_t { NONE, INITIALIZED, FOLDED, UNKNOWN }; + +inline std::string toStringConstantState(ConstantState state) { + switch (state) { + case ConstantState::NONE: + return "ConstantState::NONE"; + case ConstantState::INITIALIZED: + return "ConstantState::INITIALIZED"; + case ConstantState::FOLDED: + return "ConstantState::FOLDED"; + case ConstantState::UNKNOWN: + return "ConstantState::UNKNOWN"; + default: + return "Unknown enum class state for ConstantState"; + } +} + +class AOTInductorModelContainer { + public: + AOTInductorModelContainer( + size_t num_models, + const std::string& device_str, + const std::optional& cubin_dir = std::nullopt) { + constants_map_ = std::make_shared(); + constants_array_ = std::make_shared>(); + + models_.reserve(num_models); + available_models_.reserve(num_models); + for (size_t i = 0; i < num_models; ++i) { + models_.push_back(AOTInductorModel::Create( + constants_map_, constants_array_, device_str, cubin_dir)); + available_models_.push_back(models_.back().get()); + } + + // Note that the all following fields (input_names_, output_names, + // etc) can be filled in by the AOT + // codegen. However, we choose to query such information from + // the owned AOTInductorModel for a couple of reasons: + // * simplify the codegen templates + // * reduce information fragmentation and duplication + // * the initialization process below is done only once when the container + // is constructed, so it would have little performance impact + auto* model = available_models_[0]; + size_t num_inputs = model->num_inputs(); + input_names_.reserve(num_inputs); + for (size_t i = 0; i < num_inputs; i++) { + input_names_.emplace_back(model->input_name(static_cast(i))); + } + + size_t num_outputs = model->num_outputs(); + output_names_.reserve(num_outputs); + for (size_t i = 0; i < num_outputs; i++) { + output_names_.emplace_back(model->output_name(static_cast(i))); + } + model->load_constants(); + constant_blob_ = model->release_constant_blob(); + constants_internal_offset_.resize( + model->num_constants() - model->num_folded_constants()); + model->compute_constant_blob(blob_size_, constants_internal_offset_); + constant_folded_ = ConstantState::INITIALIZED; + + for (auto& model : models_) { + model->update_constants_map(constants_map_); + } + + in_spec_ = model->get_in_spec(); + out_spec_ = model->get_out_spec(); + } + + void run( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { + std::shared_lock model_lk(model_exec_mutex_); + auto* model = get_available_model(); + + ConstantState& const_folded = + use_secondary_ ? constant_folded_secondary_ : constant_folded_; + if (const_folded == ConstantState::INITIALIZED) { + // At this point, constant is not ready yet. We need to call constant + // folding before we execute the model. We obtain a unique lock at this + // point to make sure constant is ready for all. + model_lk.unlock(); + std::unique_lock constants_folding_lk(model_exec_mutex_); + // Double locking to make sure constant folding is only ran once. + if (const_folded == ConstantState::INITIALIZED) { + auto folded_const_map = model->run_const_fold( + stream, proxy_executor, /* initialization = */ true); + update_constant_buffer( + std::move(folded_const_map), + /* use_inactive = */ false, + /* validate_full_update = */ false); + const_folded = ConstantState::FOLDED; + } + constants_folding_lk.unlock(); + model_lk.lock(); + } else if (const_folded != ConstantState::FOLDED) { + throw std::runtime_error( + "Unknown constant state: " + toStringConstantState(constant_folded_)); + } + + try { + model->run(input_handles, output_handles, stream, proxy_executor); + } catch (...) { + std::lock_guard lk(models_mutex_); + available_models_.push_back(model); + throw; + } + + { + std::lock_guard lk(models_mutex_); + pending_models_.push_back(model); + } + pending_models_available_.notify_one(); + } + + // Non-thread-aware variant of run(). Obviously unsafe to use in a threaded + // environment :) + void run_single_threaded( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { + auto* model = available_models_[0]; + + ConstantState& const_folded = + use_secondary_ ? constant_folded_secondary_ : constant_folded_; + if (const_folded == ConstantState::INITIALIZED) { + auto folded_const_map = model->run_const_fold( + stream, proxy_executor, /* initialization = */ true); + update_constant_buffer( + std::move(folded_const_map), + /* use_inactive = */ false, + /* validate_full_update = */ false); + const_folded = ConstantState::FOLDED; + } else if (constant_folded_ != ConstantState::FOLDED) { + throw std::runtime_error( + "Unknown constant state: " + toStringConstantState(constant_folded_)); + } + + model->run_single_threaded( + input_handles, output_handles, stream, proxy_executor); + } + + const std::unordered_map extract_constants_map( + bool use_inactive) const { + size_t n_consts = this->num_constants(); + std::unordered_map ret; + ret.reserve(n_consts); + + std::shared_ptr extract_map = constants_map_; + // Essentially a XOR + if (use_inactive != use_secondary_) { + extract_map = constants_map_secondary_; + } + for (size_t idx = 0; idx < n_consts; idx++) { + if (this->constant_from_folded(idx)) { + continue; + } + + auto it = extract_map->find(this->constant_name(idx)); + if (it != extract_map->end()) { + ret.emplace(this->constant_original_fqn(idx), it->second); + continue; + } + } + + return ret; + } + + size_t num_constants() const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->num_constants(); + } + + // retrieve the constant name of constants_info_[idx] + const char* constant_name(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_name(static_cast(idx)); + } + + // retrieve original FQN of constants_info_[idx] + const char* constant_original_fqn(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_original_fqn(static_cast(idx)); + } + + // retrieve whether constant is from folded of constants_info_[idx] + bool constant_from_folded(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_from_folded(static_cast(idx)); + } + + size_t constant_data_size(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_data_size(static_cast(idx)); + } + + // retrieve type of constants_info_[idx] + int32_t constant_type(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_type(static_cast(idx)); + } + + // retrieve dtype of constants_info_[idx] + int32_t constant_dtype(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_dtype(static_cast(idx)); + } + + uint64_t constant_blob_size() const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_blob_size(); + } + + void update_constants_from_blob(const uint8_t* weight_blob_ptr) { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->update_constants_from_blob(weight_blob_ptr); + } + + void run_const_fold( + bool inactive_buffer, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { + AOTInductorModel* model; + ConstantState& const_folded = inactive_buffer == use_secondary_ + ? constant_folded_ + : constant_folded_secondary_; + if (!inactive_buffer) { + // We would need to acquire a unique lock if we want to run constant + // folding on the active buffer. + std::unique_lock constants_folding_lk(model_exec_mutex_); + model = get_available_model(); + try { + auto folded_const_map = model->run_const_fold(stream, proxy_executor); + update_constant_buffer( + std::move(folded_const_map), + /* use_inactive = */ false, + /* validate_full_update = */ false); + const_folded = ConstantState::FOLDED; + } catch (...) { + std::lock_guard lk(models_mutex_); + available_models_.push_back(model); + throw; + } + } else { + std::shared_lock model_lk(model_exec_mutex_); + model = get_available_model(); + + // We swap the constant mapping to the inactive buffer in the model to run + // const run. + auto constants_map = get_constants_map(/* get_inactive= */ true); + auto constants_array = get_constants_array(/* get_inactive= */ true); + + try { + model->update_constants_map( + constants_map, /* remap_constants_array= */ false); + model->update_constants_array(constants_array); + + auto folded_const_map = model->run_const_fold(stream, proxy_executor); + update_constant_buffer( + std::move(folded_const_map), + /* use_inactive = */ true, + /* validate_full_update = */ false); + + // Swap back the model's constants mapping + constants_map = get_constants_map(/* get_inactive= */ false); + constants_array = get_constants_array(/* get_inactive= */ false); + model->update_constants_map( + constants_map, /* remap_constants_array= */ false); + model->update_constants_array(constants_array); + const_folded = ConstantState::FOLDED; + } catch (...) { + std::lock_guard lk(models_mutex_); + available_models_.push_back(model); + throw; + } + } + + { + std::lock_guard lk(models_mutex_); + pending_models_.push_back(model); + } + pending_models_available_.notify_one(); + } + + bool _is_tensor_constant_type(const size_t idx) const { + auto constant_type = models_[0]->constant_type(static_cast(idx)); + // We should skip constants + return constant_type == ConstantType::TensorConstant; + } + + bool _is_buffer_type(const size_t idx) const { + auto constant_type = models_[0]->constant_type(static_cast(idx)); + // Buffer can be optionally skipped, so if it not provided by upstream + // services, it is OK to relax the check. + return constant_type == ConstantType::Buffer; + } + + bool _is_empty_parameter_type(const size_t idx) const { + auto constant_type = models_[0]->constant_type(static_cast(idx)); + auto constant_data_size = + models_[0]->constant_data_size(static_cast(idx)); + // Empty parameters are skipped and not provided by the upstream services, + // it is OK to skip. + return constant_type == ConstantType::Parameter && constant_data_size == 0; + } + + bool _is_tensor_constant_or_buffer_type_or_empty_parameter( + const size_t idx) const { + return _is_tensor_constant_type(idx) || _is_buffer_type(idx) || + _is_empty_parameter_type(idx); + } + + void assert_all_constants( + const std::unordered_map& constants_map) { + auto num_constants = models_[0]->num_constants(); + for (size_t idx = 0; idx < num_constants; idx++) { + if (models_[0]->constant_from_folded(static_cast(idx))) { + continue; + } + + auto constant_name = + std::string(models_[0]->constant_name(static_cast(idx))); + auto it = constants_map.find(constant_name); + if (it == constants_map.end()) { + if (_is_tensor_constant_or_buffer_type_or_empty_parameter(idx)) { + // tracing sometimes creates tensors that are non-existent in + // original graph. We could skip those and do a direct copy. + std::cerr << "[WARNING] Found constant or module state buffer or " + << "empty module state parameter " << constant_name + << " in model, but not provided by user!\n"; + continue; + } + throw std::runtime_error( + std::string("Cannot find constants ") + constant_name + + std::string(" in constants_map!")); + } + } + } + + // We directly take ownership from AtenTensorHandle if constants are moved. + void update_constant_buffer( + std::unordered_map&& constants_map, + bool use_inactive, + bool validate_full_update) { + if (this->num_models() == 0) { + throw std::runtime_error("No model available in container!"); + } + if (validate_full_update) { + assert_all_constants(constants_map); + } + + ConstantState& const_folded = use_inactive == use_secondary_ + ? constant_folded_ + : constant_folded_secondary_; + const_folded = ConstantState::INITIALIZED; + + auto original_constants_map = get_constants_map(!use_inactive); + auto constants_map_to_update = get_constants_map(use_inactive); + + auto num_constants = models_[0]->num_constants(); + for (size_t idx = 0; idx < num_constants; idx++) { + auto constant_name = + std::string(models_[0]->constant_name(static_cast(idx))); + auto it = constants_map.find(constant_name); + if (it == constants_map.end() && + !(use_inactive && _is_tensor_constant_type(idx))) { + continue; + } + + AtenTensorHandle tensor; + if (it == constants_map.end()) { + aoti_torch_clone( + original_constants_map->find(constant_name)->second.get(), &tensor); + } else { + tensor = it->second; + } + + constants_map_to_update->insert_or_assign( + constant_name, RAIIAtenTensorHandle(tensor)); + } + // Update the inactive constant array. + update_array_from_map( + get_constants_array(use_inactive), constants_map_to_update); + } + + // This function updates the buffer for storing constants. + // It will update the buffer, the mapping and the array mapping. + void update_constant_buffer( + const std::unordered_map& constants_map, + bool use_inactive, + bool validate_full_update, + bool user_managed = false) { + if (this->num_models() == 0) { + throw std::runtime_error("No model available in container!"); + } + if (validate_full_update) { + assert_all_constants(constants_map); + } + + ConstantState& const_folded = use_inactive == use_secondary_ + ? constant_folded_ + : constant_folded_secondary_; + const_folded = ConstantState::INITIALIZED; + + auto original_constants_map = get_constants_map(!use_inactive); + auto constants_map_to_update = get_constants_map(use_inactive); + + auto num_constants = models_[0]->num_constants(); + for (size_t idx = 0; idx < num_constants; idx++) { + auto constant_name = + std::string(models_[0]->constant_name(static_cast(idx))); + auto it = constants_map.find(constant_name); + if (it == constants_map.end() && + !(use_inactive && + _is_tensor_constant_or_buffer_type_or_empty_parameter(idx))) { + continue; + } + + AtenTensorHandle tensor; + if (it == constants_map.end()) { + tensor = original_constants_map->find(constant_name)->second.get(); + } else { + tensor = it->second; + } + + if (user_managed) { + // If user managed, we pass in the pointer directly, and skip the + // copy. + constants_map_to_update->insert_or_assign( + constant_name, + MaybeOwningAtenTensorHandle(tensor, /* user_managed = */ true)); + continue; + } + + auto* constants_blob_ptr = + static_cast(get_constant_blob_ptr(use_inactive)); + + // Move the data to container handled blob. + uint8_t* internal_constants_ptr = + constants_blob_ptr + constants_internal_offset_[idx]; + void* user_constant_ptr; + int64_t constant_size; + int64_t* stride; + int64_t offset; + aoti_torch_get_data_ptr(tensor, &user_constant_ptr); + aoti_torch_get_storage_size(tensor, &constant_size); + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(tensor, &stride)); + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_storage_offset(tensor, &offset)); + auto dtype = models_[0]->constant_dtype(idx); + +#ifdef USE_XPU + sycl::queue* queue_ptr = nullptr; + aoti_torch_get_current_sycl_queue((void**)&queue_ptr); + queue_ptr + ->memcpy(internal_constants_ptr, user_constant_ptr, constant_size) + .wait(); +#elif USE_MPS + internal_constants_ptr = constants_blob_ptr; + aoti_torch_mps_copy_buffer( + user_constant_ptr, + constants_blob_ptr, + constant_size, + offset, + constants_internal_offset_[idx]); + // For mps tensors, all constants are stored in one buffer, with the + // offset being where the constant starts. So we want to change the + // constant tensor's offset to point to constants_internal_offset_[idx] + offset = constants_internal_offset_[idx] / + aoti_torch_dtype_element_size(dtype); +#elif USE_CUDA + AOTI_RUNTIME_CUDA_CHECK(cudaMemcpy( + internal_constants_ptr, + user_constant_ptr, + constant_size, + cudaMemcpyDefault)); +#else + memcpy(internal_constants_ptr, user_constant_ptr, constant_size); +#endif + // Generate Tensor from container handled blob. + // We extract stride and offset from provided Tensor since we do not + // guarantee that the tensor is contiguous. + AtenTensorHandle tensor_handle; + int device_type = models_[0]->get_device_type(); + int device_idx = models_[0]->get_device_idx(); + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob( + internal_constants_ptr, + models_[0]->constant_ndim(idx), + models_[0]->constant_shape(idx), + stride, + offset, + dtype, + device_type, + device_idx, + &tensor_handle)); + + // Now place the tensor to constants_map. Note at this point the + // ownership of the tensor_handle will be taken over. + constants_map_to_update->insert_or_assign( + constant_name, RAIIAtenTensorHandle(tensor_handle)); + } + // Update the inactive constant array. + update_array_from_map( + get_constants_array(use_inactive), constants_map_to_update); + } + + void update_array_from_map( + const std::shared_ptr>& constants_array, + const std::shared_ptr& constants_map) { + auto num_constants = models_[0]->num_constants(); + for (size_t idx = 0; idx < num_constants; idx++) { + if (constants_map->find(models_[0]->constant_name( + static_cast(idx))) != constants_map->end()) { + constants_array->at(idx) = ConstantHandle( + constants_map + ->find(models_[0]->constant_name(static_cast(idx))) + ->second); + } + } + } + + void swap_constant_buffer() { + std::lock_guard unique_lk(model_exec_mutex_); + + auto constants_map = get_constants_map(/* get_inactive= */ true); + auto constants_array = get_constants_array(/* get_inactive= */ true); + + for (auto& model : models_) { + model->update_constants_map( + constants_map, /* remap_constants_array = */ false); + model->update_constants_array(constants_array); + } + + use_secondary_ = !use_secondary_; + } + + void free_inactive_constant_buffer() { + if (use_secondary_) { + constant_folded_ = ConstantState::NONE; + constant_blob_.reset(); + } else { + constant_folded_secondary_ = ConstantState::NONE; + constant_blob_secondary_.reset(); + } + // Free the internally held constants + int num_constants = static_cast(models_[0]->num_constants()); + std::shared_ptr to_free_map = + use_secondary_ ? constants_map_ : constants_map_secondary_; + + for (int i = 0; i < num_constants; i++) { + if (models_[0]->constant_from_folded(i)) { + auto it = to_free_map->find(models_[0]->constant_name(i)); + if (it != to_free_map->end()) { + it->second.reset(); + } + } + } + } + + size_t num_inputs() const { + return input_names_.size(); + } + + size_t num_outputs() const { + return output_names_.size(); + } + + const char* input_name(size_t idx) const { + return input_names_.at(idx).c_str(); + } + + const char* output_name(size_t idx) const { + return output_names_.at(idx).c_str(); + } + + size_t num_models() const { + return models_.size(); + } + + const char* get_in_spec() const { + return in_spec_; + } + + const char* get_out_spec() const { + return out_spec_; + } + + private: + std::vector input_names_; + std::vector output_names_; + const char* in_spec_; + const char* out_spec_; + + // Holds the blob storage for constants' at::Tensor within the container. + // This blob of memory will be managed by the container. + RAIIDataPtr constant_blob_; + RAIIDataPtr constant_blob_secondary_; + + size_t blob_size_; + std::vector constants_internal_offset_; + + // Determine which constants is being used for the model. + // If true, + // constants_map_secondary/constant_blob_secondary/constants_array_secondary + // is being used. + bool use_secondary_{false}; + + // Determine whether we have ran constant folding + ConstantState constant_folded_{ConstantState::NONE}; + ConstantState constant_folded_secondary_{ConstantState::NONE}; + + // Holds the mapping of constants to at::Tensor. + // The underlying data of at::Tensor is in either constant_blob_ (for CUDA). + // or _binary_constants_bin_start (for CPU). + std::shared_ptr constants_map_; + std::shared_ptr constants_map_secondary_; + + // Holds the indexed array of constant for faster lookup during runtime. + std::shared_ptr> constants_array_; + std::shared_ptr> constants_array_secondary_; + + // Holds all the AOTInductorModel instances owned by this container. + std::vector> models_; + + // Holds the AOTInductorModel instances available for inference. + std::vector available_models_; + + // Holds the AOTInductorModel instances that have started running + // inference and can be placed onto available_models_ upon their + // completion. + std::deque pending_models_; + + // Protects available_models_ and pending_models_. + std::mutex models_mutex_; + + // Notified whenever a model is placed onto pending_models_. + std::condition_variable pending_models_available_; + + AOTInductorModel* get_available_model() { + std::unique_lock lk(models_mutex_); + if (available_models_.empty()) { + reclaim_finished_models(lk); + } + auto* result = available_models_.back(); + available_models_.pop_back(); + return result; + } + + // This mutex is used to protect execution of model. + // We acquire the mutex in shared mode if we allow concurrent execution. + // We acquire the mutex in unique mode when we want exclusive access of the + // model. One such case is when we want to do a weight swapping. We want to + // make sure no one is executing the model. + std::shared_mutex model_exec_mutex_; + + RAIIDataPtr allocate_constant_blob() { +#if defined(USE_CUDA) || defined(USE_XPU) || defined(USE_MPS) + return RAII_gpuMalloc(blob_size_); +#else + return RAII_cpuMalloc(blob_size_); +#endif // USE_CUDA + } + + void* get_constant_blob_ptr(bool get_inactive) { + if ((get_inactive && use_secondary_) || + (!get_inactive && !use_secondary_)) { + if (!constant_blob_) { + constant_blob_ = allocate_constant_blob(); + } + return constant_blob_.get(); + } else { + if (!constant_blob_secondary_) { + constant_blob_secondary_ = allocate_constant_blob(); + } + return constant_blob_secondary_.get(); + } + } + + std::shared_ptr get_constants_map(bool get_inactive) { + if ((get_inactive && use_secondary_) || + (!get_inactive && !use_secondary_)) { + return constants_map_; + } else { + if (!constants_map_secondary_) { + constants_map_secondary_ = std::make_shared(); + } + return constants_map_secondary_; + } + } + + std::shared_ptr> get_constants_array( + bool get_inactive) { + if ((get_inactive && use_secondary_) || + (!get_inactive && !use_secondary_)) { + return constants_array_; + } else { + if (!constants_array_secondary_) { + constants_array_secondary_ = + std::make_shared>( + models_[0]->num_constants()); + } + return constants_array_secondary_; + } + } + + void reclaim_finished_models(std::unique_lock& lk) { +#ifdef __aarch64__ + // push finished model instances to the end of pending_models_ + auto it = std::partition( + pending_models_.begin(), + pending_models_.end(), + [](AOTInductorModel* m) { return !m->is_finished(); }); +#else + // push finished model instances to the end of pending_models_ + auto it = std::stable_partition( + pending_models_.begin(), + pending_models_.end(), + [](AOTInductorModel* m) { return !m->is_finished(); }); +#endif + + if (it != pending_models_.end()) { + // We have finished model instances that can be pushed into + // available_models_ so that we don't have to be blocked on waiting + // the pending_models_available_ condition. + available_models_.insert( + available_models_.end(), it, pending_models_.end()); + pending_models_.erase(it, pending_models_.end()); + return; + } + + pending_models_available_.wait( + lk, [this]() { return !pending_models_.empty(); }); + // Let's make the schedule simple first. We always wait on the first + // pending_models_ to be complete. + auto* model = pending_models_.front(); + pending_models_.pop_front(); + lk.unlock(); + try { + model->wait_for_completion(); + } catch (...) { + lk.lock(); + available_models_.push_back(model); + throw; + } + lk.lock(); + available_models_.push_back(model); + } +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..3ba22f3a286f0cb7725f2d013ed0bc4c447a7ffb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::aot_inductor { + +template +inline RAIIAtenTensorHandle scalar_to_tensor_handle(T value) { + throw std::runtime_error("Unsupported scalar_to_tensor_handle"); +} + +// Specialize for supported C++ primitive types +#define AOTI_RUNTIME_SCALAR_TO_TENSOR(dtype, ctype) \ + template <> \ + inline RAIIAtenTensorHandle scalar_to_tensor_handle(ctype value) { \ + AtenTensorHandle tensor_handle; \ + AOTI_TORCH_ERROR_CODE_CHECK( \ + aoti_torch_scalar_to_tensor_##dtype(value, &tensor_handle)); \ + return RAIIAtenTensorHandle(tensor_handle); \ + } + +AOTI_RUNTIME_SCALAR_TO_TENSOR(float32, float) +AOTI_RUNTIME_SCALAR_TO_TENSOR(float64, double) +AOTI_RUNTIME_SCALAR_TO_TENSOR(uint8, uint8_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(uint16, uint16_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(uint32, uint32_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(uint64, uint64_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(int8, int8_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(int16, int16_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(int32, int32_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(int64, int64_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(bool, bool) +AOTI_RUNTIME_SCALAR_TO_TENSOR(complex64, c10::complex) +AOTI_RUNTIME_SCALAR_TO_TENSOR(complex128, c10::complex) +#undef AOTI_RUNTIME_SCALAR_TO_TENSOR + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h new file mode 100644 index 0000000000000000000000000000000000000000..5e013ef81634689ea01268d365e9c3b016568559 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h @@ -0,0 +1,172 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// NOLINT +#pragma once +#ifdef USE_XPU +#include +#include +#include +#include +#include +#include + +#define ZE_CHECK(status) \ + { \ + if (status != ZE_RESULT_SUCCESS) { \ + std::stringstream ss; \ + ss << "L0 runtime error: " << std::hex << std::uppercase << status; \ + throw std::runtime_error(ss.str()); \ + } \ + } + +static ze_module_handle_t _createModule( + const uint8_t* binaryPtr, + size_t binarySize) { + sycl::device& syclDevice = + c10::xpu::get_raw_device(c10::xpu::current_device()); + auto& syclContext = c10::xpu::get_device_context(); + auto device = + sycl::get_native(syclDevice); + auto context = + sycl::get_native(syclContext); + + const char* buildFlags = ""; + const ze_module_format_t format = ZE_MODULE_FORMAT_IL_SPIRV; + ze_module_desc_t moduleDescription = {}; + moduleDescription.stype = ZE_STRUCTURE_TYPE_MODULE_DESC; + moduleDescription.format = format; + moduleDescription.inputSize = binarySize; + moduleDescription.pInputModule = (uint8_t*)binaryPtr; + moduleDescription.pBuildFlags = buildFlags; + ze_module_build_log_handle_t buildLog = nullptr; + ze_module_handle_t module = nullptr; + auto error_no = ZE_RESULT_SUCCESS; + error_no = + zeModuleCreate(context, device, &moduleDescription, &module, &buildLog); + + if (error_no != ZE_RESULT_SUCCESS) { + size_t szLog = 0; + ZE_CHECK(zeModuleBuildLogGetString(buildLog, &szLog, nullptr)); + char* strLog = (char*)malloc(szLog); + ZE_CHECK(zeModuleBuildLogGetString(buildLog, &szLog, strLog)); + std::cerr << "L0 build module failed. Log: " << strLog << std::endl; + free(strLog); + } + if (buildLog) { + ZE_CHECK(zeModuleBuildLogDestroy(buildLog)); + } + ZE_CHECK(error_no); + return module; +} + +static std::unique_ptr _createKernel( + ze_module_handle_t module, + const char* kernelName) { + assert(module); + assert(kernelName); + ze_kernel_handle_t kernel = nullptr; + ze_kernel_desc_t kernelDescription = {}; + kernelDescription.stype = ZE_STRUCTURE_TYPE_KERNEL_DESC; + kernelDescription.pNext = nullptr; + kernelDescription.flags = ZE_KERNEL_FLAG_FORCE_RESIDENCY; + kernelDescription.pKernelName = kernelName; + ZE_CHECK(zeKernelCreate(module, &kernelDescription, &kernel)); + + auto& syclContext = c10::xpu::get_device_context(); + auto mod = sycl::make_kernel_bundle< + sycl::backend::ext_oneapi_level_zero, + sycl::bundle_state::executable>( + {module, sycl::ext::oneapi::level_zero::ownership::transfer}, + syclContext); + auto fun = sycl::make_kernel( + {mod, kernel, sycl::ext::oneapi::level_zero::ownership::transfer}, + syclContext); + return std::make_unique(fun); +} + +// GPU Cpp Wrapper API +[[maybe_unused]] static std::unique_ptr loadKernel( + std::string filePath, + const std::string& funcName, + uint32_t sharedMemBytes, + const std::optional& binDir = std::nullopt) { + if (binDir) { + std::filesystem::path p1{*binDir}; + std::filesystem::path p2{filePath}; + filePath = (p1 / p2.filename()).string(); + } + + std::ifstream IFS(filePath.c_str(), std::ios::binary); + std::ostringstream OSS; + OSS << IFS.rdbuf(); + std::string data(OSS.str()); + + auto mod = _createModule( + reinterpret_cast(data.c_str()), data.size()); + + return _createKernel(mod, funcName.c_str()); +} + +// GPU Cpp Wrapper API +[[maybe_unused]] static std::unique_ptr loadKernel( + const void* start, + const void* end, + const std::string& funcName, + uint32_t sharedMemBytes) { + size_t size = reinterpret_cast(end) - + reinterpret_cast(start); + + auto mod = _createModule(reinterpret_cast(start), size); + + return _createKernel(mod, funcName.c_str()); +} + +// GPU Cpp Wrapper API +[[maybe_unused]] static void launchKernel( + std::unique_ptr& kernelPtr, + uint32_t gridX, + uint32_t gridY, + uint32_t gridZ, + uint32_t numWarps, + uint32_t sharedMemory, + void** params, + sycl::queue* queuePtr, + uint32_t threadsPerWarp) { + std::string kernelName = + kernelPtr->get_info(); + uint32_t numParams = kernelPtr->get_info(); + size_t globalRangeX = gridX * threadsPerWarp * numWarps; + size_t globalRangeY = gridY; + size_t globalRangeZ = gridZ; + size_t localRangeX = numWarps * threadsPerWarp; + size_t localRangeY = 1; + size_t localRangeZ = 1; + sycl::range<3> globalRange(globalRangeZ, globalRangeY, globalRangeX); + sycl::range<3> localRange(localRangeZ, localRangeY, localRangeX); + sycl::nd_range<3> parallelWorkSize(globalRange, localRange); + if (sharedMemory) { + // numParams from sycl info = user provided args + sharedMemoryBuffer + numParams -= 1; + } + // Submit the imported kernel. + auto cgf = [&](sycl::handler& cgh) { + for (uint32_t i = 0; i < numParams; ++i) { + cgh.set_arg(i, *(static_cast(params[i]))); + } + + if (sharedMemory > 0) { + constexpr int dimensions = 1; + using share_mem_t = sycl::local_accessor; + share_mem_t localBuffer = share_mem_t(sharedMemory, cgh); + cgh.set_arg(numParams, localBuffer); + cgh.parallel_for(parallelWorkSize, *kernelPtr); + } else { + cgh.parallel_for(parallelWorkSize, *kernelPtr); + } + }; + auto event = queuePtr->submit(cgf); +} +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h new file mode 100644 index 0000000000000000000000000000000000000000..7aea78361dc5765eae78d748e3022cfbfa1ec63d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h @@ -0,0 +1,165 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::aot_inductor { + +template +struct ThreadLocalCachedOutputTensor; + +template <> +struct ThreadLocalCachedOutputTensor { + explicit ThreadLocalCachedOutputTensor(const RAIIAtenTensorHandle&) {} + void copy_data_from(const RAIIAtenTensorHandle& handle) { + throw std::runtime_error("can't happen"); + } + + AtenTensorHandle tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +template <> +struct ThreadLocalCachedOutputTensor { + explicit ThreadLocalCachedOutputTensor(const AtenTensorHandle&) {} + void copy_data_from(const AtenTensorHandle& handle) { + throw std::runtime_error("can't happen"); + } + + AtenTensorHandle tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +template <> +struct ThreadLocalCachedOutputTensor { + explicit ThreadLocalCachedOutputTensor(const ConstantHandle&) {} + void copy_data_from(const ConstantHandle& handle) { + throw std::runtime_error("can't happen"); + } + + AtenTensorHandle tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +template +struct ThreadLocalCachedOutputTensor> { + explicit ThreadLocalCachedOutputTensor(const ArrayRefTensor& t) { + realloc(t); + } + + void copy_data_from(const ArrayRefTensor& t) { + if (t.numel() > capacity_) { + realloc(t); + } + std::copy(t.data(), t.data() + t.numel(), storage_.get()); + } + + AtenTensorHandle tensor() const { + return tensor_.get(); + } + + private: + void realloc(const ArrayRefTensor& t) { + capacity_ = t.numel(); + // NOLINTNEXTLINE(*arrays*) + storage_ = std::make_unique(t.numel()); + AtenTensorHandle handle = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob( + storage_.get(), + t.sizes().size(), + t.sizes().data(), + t.strides().data(), + 0, + aoti_torch_dtype>(), + t.device_type(), + t.device_idx(), + &handle)); + tensor_ = handle; + } + + // NOLINTNEXTLINE(*arrays*) + std::unique_ptr storage_; + int64_t capacity_ = 0; + RAIIAtenTensorHandle tensor_; +}; + +template +struct ThreadLocalCachedOutputArray; + +// Just needs to compile, doesn't need to do anything. +template <> +struct ThreadLocalCachedOutputArray { + explicit ThreadLocalCachedOutputArray(const RAIIAtenTensorHandle&) { + throw std::runtime_error("can't happen"); + } + + // Not supported yet! We would need to put contiguous() or + // expect_contiguous() into the ABI. + void copy_data_from(const RAIIAtenTensorHandle&) { + throw std::runtime_error("can't happen"); + } + + template + ArrayRefTensor arrayref_tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +// Just needs to compile, doesn't need to do anything. +template <> +struct ThreadLocalCachedOutputArray { + explicit ThreadLocalCachedOutputArray(const ConstantHandle&) { + throw std::runtime_error("can't happen"); + } + + // Not supported yet! We would need to put contiguous() or + // expect_contiguous() into the ABI. + void copy_data_from(const ConstantHandle&) { + throw std::runtime_error("can't happen"); + } + + template + ArrayRefTensor arrayref_tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +template +struct ThreadLocalCachedOutputArray> { + explicit ThreadLocalCachedOutputArray(const ArrayRefTensor& t) {} + + template < + typename U, + std::enable_if_t< + std::is_same_v, std::remove_const_t>, + bool> = true> + ArrayRefTensor arrayref_tensor() const { + return tensor_; + } + + void copy_data_from(const ArrayRefTensor& t) { + if (t.numel() > capacity_) { + capacity_ = t.numel(); + // NOLINTNEXTLINE(*arrays*) + storage_ = std::make_unique(capacity_); + } + std::copy(t.data(), t.data() + t.numel(), storage_.get()); + tensor_ = t; + tensor_.set_arrayref(MiniArrayRef(storage_.get(), t.numel())); + } + + private: + // NOLINTNEXTLINE(*arrays*) + std::unique_ptr storage_; + uint32_t capacity_ = 0; + ArrayRefTensor tensor_; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1eb79da9f82d5bbb45f9e9452da1842cfacf7347 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h @@ -0,0 +1,484 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include +#include + +#if defined(__GNUC__) || defined(__clang__) +#define AOTI_NOINLINE __attribute__((noinline)) +#elif _MSC_VER +#define AOTI_NOINLINE __declspec(noinline) +#else +#define AOTI_NOINLINE +#endif + +#define AOTI_TORCH_ERROR_CODE_CHECK(call) \ + if ((call) != AOTI_TORCH_SUCCESS) { \ + torch::headeronly::detail::throw_exception(#call, __FILE__, __LINE__); \ + } + +using AOTIRuntimeError = int32_t; +#define AOTI_RUNTIME_SUCCESS 0 +#define AOTI_RUNTIME_FAILURE 1 + +#define AOTI_RUNTIME_ERROR_CODE_CHECK(call) \ + if ((call) != AOTI_RUNTIME_SUCCESS) { \ + torch::headeronly::detail::throw_exception(#call, __FILE__, __LINE__); \ + } + +namespace torch::aot_inductor { + +using DeleterFnPtr = void (*)(void*); + +inline void noop_deleter(void* /*unused*/) {} + +inline void delete_record_function_object(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_record_function_end( + reinterpret_cast(ptr))); +} + +inline void delete_tensor_object(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_delete_tensor_object(reinterpret_cast(ptr))); +} + +inline void delete_c10_value_object(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_c10_value_object( + reinterpret_cast(ptr))); +} + +class RAIIAtenRecordFunctionHandle { + public: + RAIIAtenRecordFunctionHandle() : handle_(nullptr, noop_deleter) {} + RAIIAtenRecordFunctionHandle(const RAIIAtenRecordFunctionHandle& other) = + delete; + RAIIAtenRecordFunctionHandle& operator=( + const RAIIAtenRecordFunctionHandle& other) = delete; + + // Initiate an RAII RecordFunction without Inputs + RAIIAtenRecordFunctionHandle(const char* name, IValueMapHandle kwargs) + : handle_(nullptr, delete_record_function_object) { + AtenRecordFunctionHandle tmp_handle = nullptr; + aoti_record_function_start(name, kwargs, nullptr, 0, &tmp_handle); + handle_.reset(tmp_handle); + } + + // Initiate an RAII RecordFunction with Inputs + RAIIAtenRecordFunctionHandle( + const char* name, + IValueMapHandle kwargs, + std::vector inputs) + : handle_(nullptr, delete_record_function_object) { + AtenRecordFunctionHandle tmp_handle = nullptr; + aoti_record_function_start( + name, kwargs, inputs.data(), inputs.size(), &tmp_handle); + handle_.reset(tmp_handle); + } + + // Steal the ownership from another RAIIAtenRecordFunctionHandle using + // std::move + RAIIAtenRecordFunctionHandle(RAIIAtenRecordFunctionHandle&& other) = default; + RAIIAtenRecordFunctionHandle& operator=( + RAIIAtenRecordFunctionHandle&& other) = default; + + // Steal the ownership from raw AtenRecordFunctionHandle + RAIIAtenRecordFunctionHandle(AtenRecordFunctionHandle handle) + : handle_(handle, delete_record_function_object) {} + + ~RAIIAtenRecordFunctionHandle() { + handle_.reset(); + } + + // Return a raw AtenRecordFunctionHandle to be used by aoti_torch functions + // Note: this function does NOT transfer the ownership of the handle + operator AtenRecordFunctionHandle() const { + return handle_.get(); + } + + AtenRecordFunctionHandle release() { + return handle_.release(); + } + + AtenRecordFunctionHandle get() const { + return handle_.get(); + } + + void reset() { + handle_.reset(); + } + + private: + std::unique_ptr handle_; +}; + +// RAIIAtenTensorHandle steals the tensor objects created by the libtorch C ABI +class RAIIAtenTensorHandle { + public: + RAIIAtenTensorHandle() : handle_(nullptr, noop_deleter) {} + RAIIAtenTensorHandle(const RAIIAtenTensorHandle& other) = delete; + RAIIAtenTensorHandle& operator=(const RAIIAtenTensorHandle& other) = delete; + + // Steal the ownership from another RAIIAtenTensorHandle using std::move + RAIIAtenTensorHandle(RAIIAtenTensorHandle&& other) = default; + RAIIAtenTensorHandle& operator=(RAIIAtenTensorHandle&& other) = default; + + // Steal the ownership from raw AtenTensorHandle + RAIIAtenTensorHandle(AtenTensorHandle handle) + : handle_(handle, delete_tensor_object) {} + + ~RAIIAtenTensorHandle() { + handle_.reset(); + } + + // Return a raw AtenTensorHandle to be used by aoti_torch functions + // Note: this function does NOT transfer the ownership of the handle + operator AtenTensorHandle() const { + return handle_.get(); + } + + AtenTensorHandle release() { + return handle_.release(); + } + + AtenTensorHandle get() const { + return handle_.get(); + } + + void reset() { + handle_.reset(); + } + + int64_t size(int64_t d) { + int64_t size = 0; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_size(handle_.get(), d, &size)); + return size; + } + + int64_t stride(int64_t d) { + int64_t stride = 0; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_stride(handle_.get(), d, &stride)); + return stride; + } + + int64_t storage_offset() { + int64_t storage_offset = 0; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_storage_offset(handle_.get(), &storage_offset)); + return storage_offset; + } + + void* data_ptr() const { + void* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_data_ptr(handle_.get(), &result)); + return result; + } + + int64_t* sizes() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(handle_.get(), &result)); + return result; + } + + int64_t* strides() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(handle_.get(), &result)); + return result; + } + + private: + std::unique_ptr handle_; +}; + +// RAIIC10IValueHandle steals the IValue objects created by the libtorch C ABI +class RAIIC10IValueHandle { + public: + RAIIC10IValueHandle() : handle_(nullptr, noop_deleter) {} + RAIIC10IValueHandle(const RAIIC10IValueHandle& other) = delete; + RAIIC10IValueHandle& operator=(const RAIIC10IValueHandle& other) = delete; + + // Steal the ownership from another RAIIC10IValueHandle using std::move + RAIIC10IValueHandle(RAIIC10IValueHandle&& other) = default; + RAIIC10IValueHandle& operator=(RAIIC10IValueHandle&& other) = default; + + // Steal the ownership from raw C10IValueHandle + RAIIC10IValueHandle(C10IValueHandle handle) + : handle_(handle, delete_c10_value_object) {} + + ~RAIIC10IValueHandle() { + handle_.reset(); + } + + // Return a raw C10IValueHandle to be used by aoti_torch functions + // Note: this function does NOT transfer the ownership of the handle + operator C10IValueHandle() const { + return handle_.get(); + } + + C10IValueHandle release() { + return handle_.release(); + } + + C10IValueHandle get() const { + return handle_.get(); + } + + void reset() { + handle_.reset(); + } + + private: + std::unique_ptr handle_; +}; + +class MaybeOwningAtenTensorHandle { + public: + MaybeOwningAtenTensorHandle() : handle_(nullptr) {} + // We skip copy constructor as MaybeOwningAtenTensorHandle might be RAII which + // makes it undefined. + MaybeOwningAtenTensorHandle(const MaybeOwningAtenTensorHandle& other) = + delete; + MaybeOwningAtenTensorHandle& operator=( + const MaybeOwningAtenTensorHandle& other) = delete; + + // Move constructor and move assignment operator + MaybeOwningAtenTensorHandle(MaybeOwningAtenTensorHandle&& other) = default; + MaybeOwningAtenTensorHandle& operator=(MaybeOwningAtenTensorHandle&& other) = + default; + + // Steal the ownership from another RAIIAtenTensorHandle using std::move + MaybeOwningAtenTensorHandle(RAIIAtenTensorHandle&& other) + : raii_handle_(std::move(other)) { + handle_ = raii_handle_.get(); + } + MaybeOwningAtenTensorHandle& operator=(RAIIAtenTensorHandle&& other) { + raii_handle_ = std::move(other); + handle_ = raii_handle_.get(); + return *this; + } + + // By default, steal the ownership from raw AtenTensorHandle + MaybeOwningAtenTensorHandle(AtenTensorHandle handle) : raii_handle_(handle) { + handle_ = raii_handle_.get(); + } + + // If user_managed is true, we do not steal the ownership. + MaybeOwningAtenTensorHandle(AtenTensorHandle handle, bool user_managed) { + if (user_managed) { + aoti_torch_new_tensor_handle(handle, &handle_); + } else { + raii_handle_ = RAIIAtenTensorHandle(handle); + handle_ = raii_handle_.get(); + } + } + + ~MaybeOwningAtenTensorHandle() { + // This is no-op if we don't hold raii_handle with the + // MaybeOwningAtenTensorHandle. + raii_handle_.reset(); + } + + // Return a raw AtenTensorHandle to be used by aoti_torch functions + // Note: this function does NOT transfer the ownership of the handle + operator AtenTensorHandle() const { + return handle_; + } + + AtenTensorHandle release() { + if (raii_handle_) { + return raii_handle_.release(); + } else { + AtenTensorHandle handle = handle_; + handle_ = nullptr; + return handle; + } + } + + AtenTensorHandle get() const { + return handle_; + } + + void reset() { + handle_ = nullptr; + raii_handle_.reset(); + } + + int64_t size(int64_t d) { + int64_t size = 0; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_size(handle_, d, &size)); + return size; + } + + int64_t stride(int64_t d) { + int64_t stride = 0; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_stride(handle_, d, &stride)); + return stride; + } + + int64_t storage_offset() { + int64_t storage_offset = 0; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_storage_offset(handle_, &storage_offset)); + return storage_offset; + } + + void* data_ptr() const { + void* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(handle_, &result)); + return result; + } + + int64_t* sizes() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(handle_, &result)); + return result; + } + + int64_t* strides() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(handle_, &result)); + return result; + } + + private: + // handle_ is the underlying AtenTensorHandle of raii_handle_ if raii_handle_ + // exists. Otherwise it would just be the AtenTensorHandle passed in by users. + AtenTensorHandle handle_; + RAIIAtenTensorHandle raii_handle_; +}; + +// Steal the ownership from raw AtenTensorHandle to RAIIAtenTensorHandle +inline std::vector steal_from_raw_handles_to_raii_handles( + AtenTensorHandle* handles, + size_t size) { + std::vector result; + result.reserve(size); + for (size_t i = 0; i < size; i++) { + result.emplace_back(handles[i]); + handles[i] = nullptr; + } + return result; +} + +inline AtenTensorHandle reinterpret_tensor_wrapper( + AtenTensorHandle self, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset) { + AtenTensorHandle result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch__reinterpret_tensor( + self, ndim, sizes_ptr, strides_ptr, storage_offset, &result)); + return result; +} + +inline void* get_data_ptr_wrapper(AtenTensorHandle tensor) { + void* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(tensor, &result)); + return result; +} + +inline AtenTensorHandle unwrap_raii_handle_if_needed( + const RAIIAtenTensorHandle& handle) { + return handle.get(); +} + +inline RAIIAtenTensorHandle wrap_with_raii_handle_if_needed( + AtenTensorHandle handle) { + return RAIIAtenTensorHandle(handle); +} + +class ConstantHandle { + public: + ConstantHandle() = default; + + explicit ConstantHandle(AtenTensorHandle handle) : handle_(handle) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(handle_, &data_)); + } + + operator AtenTensorHandle() const { + return handle_; + } + + AtenTensorHandle tensor() const { + return handle_; + } + + AtenTensorHandle get() const { + return handle_; + } + + void* data_ptr() const { + return data_; + } + + int64_t* sizes() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(handle_, &result)); + return result; + } + + int64_t* strides() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(handle_, &result)); + return result; + } + + private: + AtenTensorHandle handle_{}; + void* data_ = nullptr; +}; + +inline void* get_data_ptr_wrapper(const ConstantHandle& constant) { + return constant.data_ptr(); +} + +inline const ConstantHandle& unwrap_raii_handle_if_needed( + const ConstantHandle& handle) { + return handle; +} + +// Shouldn't be called. +inline AtenTensorHandle wrap_with_raii_handle_if_needed( + const ConstantHandle& handle) = delete; + +// DANGEROUS. Do not call unless you explicitly intend to get a reference to a +// temporary value, which will expire at the end of the current expression. +// This should only be called in cases where the C-shim API expects an optional +// input argument (passed by pointer), and a temporary needs to be passed to it. +template +T& temporary_reference(T&& t) { + return t; +} + +#define CACHE_TORCH_DTYPE(typename) \ + static auto cached_torch_dtype_##typename = aoti_torch_dtype_##typename() + +#define CACHE_TORCH_DEVICE(device) \ + static auto cached_torch_device_type_##device = \ + aoti_torch_device_type_##device() + +#define CACHE_TORCH_LAYOUT(layout) \ + static auto cached_torch_layout_##layout = aoti_torch_layout_##layout() + +#define CACHE_TORCH_MEMORY_FORMAT(format) \ + static auto cached_torch_memory_format_##format = \ + aoti_torch_memory_format_##format() + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..3dce90bd4059e185b68ead3729c2bb729cf7cbf7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h @@ -0,0 +1,68 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_CUDA +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include + +#include +#include +#ifndef USE_ROCM +#include +#include +#include +#endif + +namespace torch::aot_inductor { + +inline void delete_cuda_guard(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_delete_cuda_guard(reinterpret_cast(ptr))); +} + +inline void delete_cuda_stream_guard(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_cuda_stream_guard( + reinterpret_cast(ptr))); +} + +class AOTICudaGuard { + public: + AOTICudaGuard(int32_t device_index) : guard_(nullptr, delete_cuda_guard) { + CUDAGuardHandle ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_create_cuda_guard(device_index, &ptr)); + guard_.reset(ptr); + } + + void set_index(int32_t device_index) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_cuda_guard_set_index(guard_.get(), device_index)); + } + + private: + std::unique_ptr guard_; +}; + +class AOTICudaStreamGuard { + public: + AOTICudaStreamGuard(cudaStream_t stream, int32_t device_index) + : guard_(nullptr, delete_cuda_stream_guard) { + CUDAStreamGuardHandle ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_create_cuda_stream_guard(stream, device_index, &ptr)); + guard_.reset(ptr); + } + + private: + std::unique_ptr guard_; +}; + +} // namespace torch::aot_inductor +#endif // USE_CUDA + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_xpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..50149503b3117d912df41cabfe395af47bd7cbc5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_xpu.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_XPU +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include +#include + +namespace torch::aot_inductor { + +inline void delete_xpu_guard(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_delete_xpu_guard(reinterpret_cast(ptr))); +} + +inline void delete_xpu_stream_guard(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_xpu_stream_guard( + reinterpret_cast(ptr))); +} + +class AOTIXpuGuard { + public: + AOTIXpuGuard(int32_t device_index) : guard_(nullptr, delete_xpu_guard) { + XPUGuardHandle ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_create_xpu_guard(device_index, &ptr)); + guard_.reset(ptr); + } + + void set_index(int32_t device_index) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_xpu_guard_set_index(guard_.get(), device_index)); + } + + private: + std::unique_ptr guard_; +}; + +class AOTIXpuStreamGuard { + public: + AOTIXpuStreamGuard(void* stream, int32_t device_index) + : guard_(nullptr, delete_xpu_stream_guard) { + XPUStreamGuardHandle ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_create_xpu_stream_guard(stream, device_index, &ptr)); + guard_.reset(ptr); + } + + private: + std::unique_ptr guard_; +}; + +} // namespace torch::aot_inductor +#endif // USE_XPU + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/macros.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..e49cd39deac0c8f2f0a5939c1503f515abed0d04 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/macros.h @@ -0,0 +1,66 @@ +#ifndef AOTI_TORCH_MACRO_H +#define AOTI_TORCH_MACRO_H + +#include +#include +#ifdef __GNUC__ +#define AOTI_TORCH_EXPORT __attribute__((__visibility__("default"))) +#else // !__GNUC__ +#ifdef _WIN32 +// PyTorch2 doesn't currently work on Windows. Exporting these APIs can lead +// to symbol clashes at link time if libtorch is included in a DLL and binary +// that depends on the DLL. As a short term fix, we don't export the symbols. +// In the long term, this will need to be addressed when Windows is supported. +#ifdef OVRSOURCE +// Do not export AOTI on Windows for internal builds +#define AOTI_TORCH_EXPORT +#else /* OVRSOURCE */ +#ifdef EXPORT_AOTI_FUNCTIONS +#define AOTI_TORCH_EXPORT __declspec(dllexport) +#else +#define AOTI_TORCH_EXPORT __declspec(dllimport) +#endif +#endif /* OVRSOURCE */ +#else // !_WIN32 +#define AOTI_TORCH_EXPORT +#endif // _WIN32 +#endif // __GNUC__ + +#ifdef __cplusplus +extern "C" { +#endif +// AtenTensorHandle represents an abstract notion of Tensor that can be passed +// between model.so and libtorch.so. The contents of the structure itself +// are private; model.so is not allowed to access any fields directly, it must +// go through functions defined in this ABI. Under the hood, this is +// represented as at::Tensor*, but we reserve the right to change this (and in +// fact, we probably should change it to at::TensorImpl* at least). +// +// An AtenTensorHandle can be owning (please check the API reference for exact +// ownership/borrow semantics). If you have an owning AtenTensorHandle +// in model.so, you are obligated to aoti_torch_delete_tensor_object when you +// are done. You can use the helper C++ class RAIIAtenTensorHandle +// (see aot_runtime/model.h) to ensure the deallocator is called in RAII style +// (note that RAIIAtenTensorHandle is private to model.so, and never crosses +// the ABI boundary.) +struct AtenTensorOpaque; +using AtenTensorHandle = AtenTensorOpaque*; + +struct AtenGeneratorOpaque; +using AtenGeneratorHandle = AtenGeneratorOpaque*; + +struct AOTIProxyExecutorOpaque; +using AOTIProxyExecutorHandle = AOTIProxyExecutorOpaque*; + +struct C10IValueOpaque; +using C10IValueHandle = C10IValueOpaque*; + +using AOTITorchError = int32_t; +#define AOTI_TORCH_SUCCESS 0 +#define AOTI_TORCH_FAILURE 1 + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // AOTI_TORCH_MACRO_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h new file mode 100644 index 0000000000000000000000000000000000000000..2eda2b218e705e85c2566ef9dc26f0227ec18ce2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h @@ -0,0 +1,692 @@ +#ifndef AOTI_TORCH_SHIM +#define AOTI_TORCH_SHIM + +#include +#include + +// This header defines a stable C API for certain ATen functionality in +// libtorch. The AOTInductor compiled model.so will only refer to this header +// instead of other headers from aten/c10, which means it will NOT be able to +// directly use any data structures or call functions from libtorch. +// +// What problems are we trying to solve here? Direct use of aten/c10 APIs +// means use of C++ APIs on a library that doesn't have any ABI compatibility +// guarantees. However, we want model.so to remain usable across updates +// to the PyTorch C++ libraries, which requires a stable ABI. By introducing +// a C shim layer, we can minimize the surface that will cause breakage. The +// corresponding software stack can be illustrated as follows: +// +// |--------------------------------| +// | inference service code | +// |--------------------------------| +// | model.so | +// |--------------|-----------------| +// | | +// | libtorch.so | +// |--------------------------------| +// +// The general guidelines for the C API: +// +// - No exceptions, return an explicit error code to be checked at call site +// - Only pointers (AtenTensorHandle counts), integers and floats in headers +// +// If you want to make changes to this header, you MUST MAINTAIN ABI +// compatibility. Typically, this means you will have to add a _v2 version +// of a function that you, e.g., want to add a new function parameter to, and +// maintain the old and new versions of the APIs until all old model.so +// go out of use. + +// The following files are implemented in a header-only way and are guarded by +// test/cpp/aoti_abi_check +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Getter functions for retrieving various constants from the runtime, that +// can subsequently be passed to other aoti_* functions. By hiding these +// behind functions, the precise value of device/dtype is NOT part of the +// ABI contract. (In practice, aten/c10 is pretty good about not renumbering +// these, so we probably could later switch to having these in the ABI, if +// desired for perf reasons.) +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_cpu(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_cuda(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_meta(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_xpu(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_mps(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_privateuse1(); + +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e5m2(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e4m3fn(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e5m2fnuz(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e4m3fnuz(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_bfloat16(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float16(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float32(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float64(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint8(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint16(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint32(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint64(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int8(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int16(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int32(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int64(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_bool(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex32(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex64(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex128(); +AOTI_TORCH_EXPORT size_t aoti_torch_dtype_element_size(int32_t dtype); + +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_strided(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_coo(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_csr(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_csc(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_bsr(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_bsc(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout__mkldnn(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_jagged(); + +AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_contiguous_format(); +AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_channels_last(); +AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_channels_last_3d(); +AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_preserve_format(); + +// Get TORCH_ABI_VERSION of the built libtorch.so +AOTI_TORCH_EXPORT uint64_t aoti_torch_abi_version(); + +// Functions for converting a single-element tensor to a scalar value +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_float16(AtenTensorHandle tensor, c10::Half* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_float32(AtenTensorHandle tensor, float* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_float64(AtenTensorHandle tensor, double* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_uint8(AtenTensorHandle tensor, uint8_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_uint16(AtenTensorHandle tensor, uint16_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_uint32(AtenTensorHandle tensor, uint32_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_uint64(AtenTensorHandle tensor, uint64_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_int8(AtenTensorHandle tensor, int8_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_int16(AtenTensorHandle tensor, int16_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_int32(AtenTensorHandle tensor, int32_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_int64(AtenTensorHandle tensor, int64_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_bool(AtenTensorHandle tensor, bool* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_bfloat16(AtenTensorHandle tensor, c10::BFloat16* ret_value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_item_complex64( + AtenTensorHandle tensor, + c10::complex* ret_value); + +// Functions for wrapping a scalar value to a single-element tensor +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_float32( + float value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_float64( + double value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint8( + uint8_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint16( + uint16_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint32( + uint32_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint64( + uint64_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int8( + int8_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int16( + int16_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int32( + int32_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int64( + int64_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_scalar_to_tensor_bool(bool value, AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_complex64( + c10::complex value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_complex128( + c10::complex value, + AtenTensorHandle* ret_new_tensor); + +AOTI_TORCH_EXPORT bool aoti_torch_grad_mode_is_enabled(); +AOTI_TORCH_EXPORT void aoti_torch_grad_mode_set_enabled(bool enabled); + +// Free the tensor object +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_tensor_object(AtenTensorHandle tensor); + +// c10::IValue object conversion +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_int64_to_ivalue(int64_t val, C10IValueHandle* ivalue); + +// c10::IValue object conversions +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_strlist_to_ivalue( + const char** val, + int64_t len, + C10IValueHandle* ivalue); + +// c10::IValue object conversions +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_str_to_ivalue(const char* val, C10IValueHandle* ivalue); + +// c10::IValue object conversions +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_tensor_to_ivalue(AtenTensorHandle val, C10IValueHandle* ivalue); + +// Free the c10::IValue object +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_c10_value_object(C10IValueHandle handle); + +// Get a pointer to the underlying storage data +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_data_ptr( + AtenTensorHandle tensor, + void** ret_data_ptr // returns borrowed reference +); + +// Get the nbytes of the underlying storage +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_storage_size(AtenTensorHandle tensor, int64_t* ret_size); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_dim(AtenTensorHandle tensor, int64_t* ret_dim); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_numel(AtenTensorHandle tensor, int64_t* ret_numel); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_storage_numel(AtenTensorHandle tensor, int64_t* ret_numel); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_sizes( + AtenTensorHandle tensor, + int64_t** ret_sizes // returns borrowed reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_size(AtenTensorHandle tensor, int64_t d, int64_t* ret_size); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_strides( + AtenTensorHandle tensor, + int64_t** ret_strides // returns borrowed reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_stride(AtenTensorHandle tensor, int64_t d, int64_t* ret_stride); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_dtype(AtenTensorHandle tensor, int32_t* ret_dtype); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_device_type(AtenTensorHandle tensor, int32_t* ret_device_type); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_device_index(AtenTensorHandle tensor, int32_t* ret_device_index); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_layout(AtenTensorHandle tensor, int32_t* ret_layout); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_storage_offset( + AtenTensorHandle tensor, + int64_t* ret_storage_offset); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_is_contiguous(AtenTensorHandle tensor, bool* ret_is_contiguous); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_is_defined(AtenTensorHandle tensor, bool* ret_is_defined); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_new_tensor_handle( + AtenTensorHandle orig_handle, + AtenTensorHandle* new_handle); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__alloc_from_pool( + AtenTensorHandle self, + int64_t offset_bytes, + int32_t dtype, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + AtenTensorHandle* ret_new_tensor); + +// This function will create a new tensor object and its pointer is returned +// through *out. The caller is responsible for wrapping the tensor pointer +// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object +// when going out of scope. +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__reinterpret_tensor( + AtenTensorHandle self, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset, + AtenTensorHandle* ret_new_tensor // returns new reference +); + +// This function will create a new tensor object and its pointer is returned +// through *out. The caller is responsible for wrapping the tensor pointer +// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object +// when going out of scope. +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_empty_strided( + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int32_t dtype, + int32_t device_type, + int32_t device_index, + AtenTensorHandle* ret_new_tensor // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_empty_strided_pinned( + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int32_t dtype, + int32_t device_type, + int32_t device_index, + AtenTensorHandle* ret_new_tensor // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_as_strided( + AtenTensorHandle self, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + AtenTensorHandle* ret); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_tensor_from_blob( + void* data, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset, + int32_t dtype, + int32_t device_type, + int32_t device_index, + AtenTensorHandle* ret // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_tensor_from_blob_v2( + void* data, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset, + int32_t dtype, + int32_t device_type, + int32_t device_index, + AtenTensorHandle* ret, // returns new reference + int32_t layout, + const uint8_t* opaque_metadata, + int64_t opaque_metadata_size); + +// This function will create a new uninitialized tensor object +// and its pointer is returned through *ret. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_new_uninitialized_tensor(AtenTensorHandle* ret); + +// WARNING: This will be deprecated. Use aoti_torch_copy_ instead. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_tensor_copy_(AtenTensorHandle src, AtenTensorHandle dst); + +// Make the tensor referred to by dst an alias for the tensor referred +// to by src. The two tensors must still be deleted with +// aoti_torch_delete_tensor separately (or not) as before the call. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_assign_tensors(AtenTensorHandle src, AtenTensorHandle dst); + +// Make a shallow copy of the tensor referred to by src and assign +// it to the handle in the ret_dst. This is similar to the above +// aoti_torch_assign_tensors function, but creates and sets the +// ret_dst from within. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_assign_tensors_out(AtenTensorHandle src, AtenTensorHandle* ret_dst); + +// This function will create a new tensor object and its pointer is returned +// through *ret. The caller is responsible for wrapping the tensor pointer +// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object +// when going out of scope. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_clone(AtenTensorHandle self, AtenTensorHandle* ret); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_clone_preserve_strides(AtenTensorHandle self, AtenTensorHandle* ret); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_copy_( + AtenTensorHandle self, + AtenTensorHandle src, + int32_t non_blocking); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__mm_plus_mm_out( + AtenTensorHandle out, + AtenTensorHandle a, + AtenTensorHandle b, + AtenTensorHandle c, + AtenTensorHandle d); + +// This will soon be deprecated after ao_quantization is complete. +// Please refrain from using this or increasing callsites. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_wrapped_fbgemm_pack_gemm_matrix_fp16( + AtenTensorHandle weight, + AtenTensorHandle* out); + +// This will soon be deprecated after ao_quantization is complete. +// Please refrain from using this or increasing callsites. +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__wrapped_linear_prepack( + AtenTensorHandle weight, + AtenTensorHandle weight_scale, + AtenTensorHandle weight_zero_point, + AtenTensorHandle bias, + AtenTensorHandle* out); + +// This will soon be deprecated after ao_quantization is complete. +// Please refrain from using this or increasing callsites. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_wrapped_fbgemm_linear_fp16_weight( + AtenTensorHandle input, + AtenTensorHandle weight, + AtenTensorHandle bias, // optional argument + int64_t out_channel, + AtenTensorHandle* out); + +// This will soon be deprecated after ao_quantization is complete. +// Please refrain from using this or increasing callsites. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu__wrapped_quantized_linear_prepacked( + AtenTensorHandle input, + AtenTensorHandle input_scale, + AtenTensorHandle input_zero_point, + AtenTensorHandle weight, + AtenTensorHandle out_scale, + AtenTensorHandle out_zeropoint, + int64_t out_channel, + AtenTensorHandle* out); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_zero_(AtenTensorHandle self); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_check_inf_and_nan(const char* tensor_name, AtenTensorHandle tensor); + +struct AtenRecordFunctionOpaque; +using AtenRecordFunctionHandle = AtenRecordFunctionOpaque*; + +struct IValueMapOpaque; +using IValueMapHandle = IValueMapOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_record_function_start( + const char* name, + IValueMapHandle kwargs, + const C10IValueHandle* inputs, + const uint64_t n_inputs, + AtenRecordFunctionHandle* guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_record_function_end(AtenRecordFunctionHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scatter_out( + AtenTensorHandle out, + AtenTensorHandle self, + int64_t dim, + AtenTensorHandle index, + AtenTensorHandle src); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scatter_reduce_out( + AtenTensorHandle out, + AtenTensorHandle self, + int64_t dim, + AtenTensorHandle index, + AtenTensorHandle src, + const char* reduce, + int32_t include_self); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_index_put_out( + AtenTensorHandle out, + AtenTensorHandle self, + const AtenTensorHandle* indices, + const uint32_t num_indices, + const AtenTensorHandle values, + bool accumulate); + +AOTI_TORCH_EXPORT void aoti_torch_print_tensor_handle( + AtenTensorHandle self, + const char* msg); + +// When AOTI debug printer option is enabled, this function will be invoked to +// torch pickle save the intermediate tensor for debugging purpose. +AOTI_TORCH_EXPORT void aoti_torch_save_tensor_handle( + AtenTensorHandle self, + const char* tensor_name, + const char* launch_prefix, + const char* kernel_name); + +// helpers for converting between StableIValue and actual IValues +using StableIValue = uint64_t; + +class TorchLibraryOpaque; +using TorchLibraryHandle = TorchLibraryOpaque*; + +// stable corollary to torch::Library constructor with Kind::IMPL +// will create a new torch::Library object on the heap +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_impl( + const char* ns, + const char* k, + const char* file, + uint32_t line, + TorchLibraryHandle* ret_new_torch_lib); + +// stable corollary to torch::Library constructor with Kind::DEF +// will create a new torch::Library object on the heap +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_def( + const char* ns, + const char* file, + uint32_t line, + TorchLibraryHandle* ret_new_torch_lib); + +// stable corollary to torch::Library constructor with Kind::FRAGMENT +// will create a new torch::Library object on the heap +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_fragment( + const char* ns, + const char* file, + uint32_t line, + TorchLibraryHandle* ret_new_torch_lib); + +// stable corollary to torch::Library method m.impl(), should be +// called from StableLibrary +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_impl( + TorchLibraryHandle self, + const char* name, + void (*fn)(StableIValue*, uint64_t, uint64_t)); + +// stable corollary to torch::Library method m.def(), should be +// called from StableLibrary +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_library_def(TorchLibraryHandle self, const char* schema); + +// the above stable constructors for torch::Library add Library objects +// to the heap. if you are calling those functions directly, please use +// this function to free the Library's memory. The more user friendly +// alternative is to use StableLibrary, which will free its handle upon +// destruction +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_library_object(TorchLibraryHandle tlh); + +// calls the op overload defined by a given opName, overloadName, and a +// stack of StableIValues. This call will populate any return values of the +// op into the stack in their StableIValue form, with ret0 at index 0, ret1 +// at index 1, and so on. +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_call_dispatcher( + const char* opName, + const char* overloadName, + StableIValue* stack); + +// Device-generic guard for managing device context +struct DeviceGuardOpaque; +using DeviceGuardHandle = DeviceGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_device_guard( + int32_t device_index, + DeviceGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_device_guard(DeviceGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_device_guard_set_index( + DeviceGuardHandle guard, + int32_t device_index); + +// Device-generic stream for managing stream objects +struct StreamOpaque; +using StreamHandle = StreamOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_delete_stream(StreamHandle stream); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_stream_id(StreamHandle stream, int64_t* ret_stream_id); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_current_stream( + int32_t device_index, + StreamHandle* ret_stream // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_current_device_index(int32_t* ret_device_index); + +#ifdef USE_CUDA + +struct CUDAGuardOpaque; +using CUDAGuardHandle = CUDAGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_cuda_guard( + int32_t device_index, + CUDAGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_cuda_guard(CUDAGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cuda_guard_set_index(CUDAGuardHandle guard, int32_t device_index); + +struct CUDAStreamGuardOpaque; +using CUDAStreamGuardHandle = CUDAStreamGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_cuda_stream_guard( + void* stream, + int32_t device_index, + CUDAStreamGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_cuda_stream_guard(CUDAStreamGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_current_cuda_stream(int32_t device_index, void** ret_stream); + +// CUDA memory allocation using CUDACachingAllocator +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_caching_allocator_raw_alloc( + uint64_t nbytes, + void** ret_ptr // returns raw GPU memory pointer +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cuda_caching_allocator_raw_delete(void* ptr); + +#endif // USE_CUDA + +// See `ProxyExecutor Design Note` in ir.py for more details +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_proxy_executor_call_function( + AOTIProxyExecutorHandle proxy_executor, + int extern_node_index, + int num_ints, + int64_t* flatten_int_args, + int num_tensors, + AtenTensorHandle* flatten_tensor_args); + +AOTI_TORCH_EXPORT void aoti_torch_check( + bool cond, + const char* func, + const char* file, + uint32_t line, + const char* msg); + +#ifdef STRIP_ERROR_MESSAGES +#define AOTI_TORCH_CHECK(cond, ...) \ + if (!(cond)) { \ + aoti_torch_check( \ + false, \ + __func__, \ + __FILE__, \ + static_cast(__LINE__), \ + TORCH_CHECK_MSG(cond, "", __VA_ARGS__)); \ + } +#else +#define AOTI_TORCH_CHECK(cond, ...) \ + if (!(cond)) { \ + aoti_torch_check( \ + false, \ + __func__, \ + __FILE__, \ + static_cast(__LINE__), \ + TORCH_CHECK_MSG(cond, "", ##__VA_ARGS__)); \ + } +#endif + +AOTI_TORCH_EXPORT void aoti_torch_warn( + const char* func, + const char* file, + uint32_t line, + const char* msg); + +#ifdef DISABLE_WARN +#define AOTI_TORCH_WARN(...) ((void)0); +#else +#define AOTI_TORCH_WARN(...) \ + aoti_torch_warn( \ + __func__, __FILE__, static_cast(__LINE__), #__VA_ARGS__); +#endif + +#ifdef __cplusplus +} // extern "C" + +template +int32_t aoti_torch_dtype() = delete; + +#define DEFINE_DTYPE_SPECIALIZATION(ctype, typename) \ + template <> \ + inline int32_t aoti_torch_dtype() { \ + return aoti_torch_dtype_##typename(); \ + } + +DEFINE_DTYPE_SPECIALIZATION(c10::BFloat16, bfloat16) +DEFINE_DTYPE_SPECIALIZATION(c10::Half, float16) +DEFINE_DTYPE_SPECIALIZATION(c10::complex, complex64) +DEFINE_DTYPE_SPECIALIZATION(float, float32) +DEFINE_DTYPE_SPECIALIZATION(double, float64) +DEFINE_DTYPE_SPECIALIZATION(uint8_t, uint8) +DEFINE_DTYPE_SPECIALIZATION(int8_t, int8) +DEFINE_DTYPE_SPECIALIZATION(int16_t, int16) +DEFINE_DTYPE_SPECIALIZATION(int32_t, int32) +DEFINE_DTYPE_SPECIALIZATION(int64_t, int64) +DEFINE_DTYPE_SPECIALIZATION(bool, bool) + +#endif +#endif // AOTI_TORCH_SHIM diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_cpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..5a10290decd1db529a924a89596e17c8e6829dcc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_cpu.h @@ -0,0 +1,267 @@ +#ifndef AOTI_TORCH_SHIM_CPU +#define AOTI_TORCH_SHIM_CPU + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if AT_MKLDNN_ENABLED() + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_mkldnn__convolution_pointwise_binary( + AtenTensorHandle X, + AtenTensorHandle other, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_mkldnn__convolution_pointwise_binary_( + AtenTensorHandle other, + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mkldnn__convolution_pointwise( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* attr, + const double** scalars, + int64_t scalars_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_mkldnn__convolution_transpose_pointwise( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* output_padding, + int64_t output_padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* attr, + const double** scalars, + int64_t scalars_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mkldnn_rnn_layer( + AtenTensorHandle input, + AtenTensorHandle weight0, + AtenTensorHandle weight1, + AtenTensorHandle weight2, + AtenTensorHandle weight3, + AtenTensorHandle hx_, + AtenTensorHandle cx_, + int32_t reverse, + const int64_t* batch_sizes, + int64_t batch_sizes_len_, + int64_t mode, + int64_t hidden_size, + int64_t num_layers, + int32_t has_biases, + int32_t bidirectional, + int32_t batch_first, + int32_t train, + AtenTensorHandle* ret0, + AtenTensorHandle* ret1, + AtenTensorHandle* ret2, + AtenTensorHandle* ret3); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__linear_pointwise( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const char* attr, + const double** scalars, + int64_t scalars_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__linear_pointwise_binary( + AtenTensorHandle X, + AtenTensorHandle other, + AtenTensorHandle W, + AtenTensorHandle* B, + const char* attr, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__qlinear_pointwise_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* B, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + const char* post_op_name, + const double** post_op_args, + int64_t post_op_args_len_, + const char* post_op_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu__qlinear_pointwise_binary_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* other, + AtenTensorHandle* B, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + double other_scale, + int64_t other_zero_point, + const char* binary_post_op, + double binary_alpha, + const char* unary_post_op, + const double** unary_post_op_args, + int64_t unary_post_op_args_len_, + const char* unary_post_op_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__qconv_pointwise_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* B, + const int64_t* stride, + int64_t stride_len_, + const int64_t* padding, + int64_t padding_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + const char* attr, + const double** post_op_args, + int64_t post_op_args_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu__qconv2d_pointwise_binary_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle accum, + AtenTensorHandle* B, + const int64_t* stride_args, + int64_t stride_len_, + const int64_t* padding_args, + int64_t padding_len_, + const int64_t* dilation_args, + int64_t dilation_len_, + int64_t groups, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + double accum_scale, + int64_t accum_zero_point, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +#if AT_MKL_ENABLED() + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__mkl_linear( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle origin_W, + AtenTensorHandle* B, + int64_t prepack_batch_size, + AtenTensorHandle* ret0); + +#endif // AT_MKL_ENABLED + +#endif // AT_MKLDNN_ENABLED() + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__weight_int4pack_mm_cpu_tensor( + AtenTensorHandle X, + AtenTensorHandle w, + AtenTensorHandle qGroupSize, + AtenTensorHandle qScaleAndZeros, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__c10d_functional_all_reduce_( + AtenTensorHandle inp, + const char* reduce_op, + const char* group_name, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__c10d_functional_all_reduce( + AtenTensorHandle inp, + const char* reduce_op, + const char* group_name, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__c10d_functional_wait_tensor( + AtenTensorHandle inp, + AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif // AOTI_TORCH_SHIM_CPU diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_deprecated.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_deprecated.h new file mode 100644 index 0000000000000000000000000000000000000000..964db6b0076c97bcbaac3bf5a831b6b87cec54c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_deprecated.h @@ -0,0 +1,199 @@ +#ifndef AOTI_TORCH_SHIM_DEPRECATED +#define AOTI_TORCH_SHIM_DEPRECATED + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +[[deprecated( + "aoti_torch__embedding_bag is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__embedding_bag( + AtenTensorHandle weight, + AtenTensorHandle indices, + AtenTensorHandle offsets, + int32_t scale_grad_by_freq, + int32_t mode, + int32_t sparse, + AtenTensorHandle per_sample_weights, // optional argument + int32_t include_last_offset, + int32_t padding_idx, + AtenTensorHandle* ret0, // returns new reference + AtenTensorHandle* ret1, // returns new reference + AtenTensorHandle* ret2, // returns new reference + AtenTensorHandle* ret3 // returns new reference +); + +[[deprecated( + "aoti_torch__fft_c2c is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__fft_c2c( + AtenTensorHandle self, + const int64_t* dim_ptr, + int64_t dim_size, + int64_t normalization, + int32_t forward, + AtenTensorHandle* ret // returns new reference +); + +[[deprecated( + "aoti_torch__scaled_mm is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_mm( + AtenTensorHandle self, + AtenTensorHandle mat2, + AtenTensorHandle bias, + int32_t* out_dtype, + AtenTensorHandle scale_a, + AtenTensorHandle scale_b, + AtenTensorHandle scale_result, + int8_t use_fast_accum, + AtenTensorHandle* ret0, + AtenTensorHandle* ret1); + +[[deprecated( + "aoti_torch__scaled_mm_v2 is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_mm_v2( + AtenTensorHandle self, + AtenTensorHandle mat2, + AtenTensorHandle scale_a, + AtenTensorHandle scale_b, + AtenTensorHandle bias, + AtenTensorHandle scale_result, + int32_t* out_dtype, + int8_t use_fast_accum, + AtenTensorHandle* ret0); + +[[deprecated( + "aoti_torch_addmm_out is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_addmm_out( + AtenTensorHandle out, + AtenTensorHandle self, + AtenTensorHandle mat1, + AtenTensorHandle mat2, + float beta, + float alpha); + +[[deprecated( + "aoti_torch_bmm is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_bmm_out( + AtenTensorHandle out, + AtenTensorHandle self, + AtenTensorHandle mat2); + +[[deprecated( + "aoti_torch_convolution is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_convolution( + AtenTensorHandle input, + AtenTensorHandle weight, + AtenTensorHandle bias, // optional argument + const int64_t* stride_ptr, + int64_t stride_size, + const int64_t* padding_ptr, + int64_t padding_size, + const int64_t* dilation_ptr, + int64_t dilation_size, + int transposed, + const int64_t* output_padding_ptr, + int64_t output_padding_size, + int64_t groups, + AtenTensorHandle* ret // returns new reference +); + +[[deprecated( + "aoti_torch_mm_out is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mm_out( + AtenTensorHandle out, + AtenTensorHandle self, + AtenTensorHandle mat2); + +[[deprecated( + "aoti_torch_nonzero is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_nonzero(AtenTensorHandle self, AtenTensorHandle* out); + +[[deprecated( + "aoti_torch_repeat_interleave_Tensor is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_repeat_interleave_Tensor( + AtenTensorHandle repeats, + int64_t* output_size, + AtenTensorHandle* out); + +[[deprecated( + "aoti_torch_view_as_real is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_view_as_real( + AtenTensorHandle self, + AtenTensorHandle* ret // returns new reference +); + +[[deprecated( + "aoti_torch_view_dtype is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_view_dtype( + AtenTensorHandle self, + int32_t dtype, + AtenTensorHandle* ret // returns new reference +); + +[[deprecated( + "aoti_torch__scaled_dot_product_flash_attention is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_dot_product_flash_attention( + AtenTensorHandle query, + AtenTensorHandle key, + AtenTensorHandle value, + double dropout_p, + bool is_causal, + bool return_debug_mask, + double scale, + AtenTensorHandle* ret0, // returns new reference + AtenTensorHandle* ret1, // returns new reference + AtenTensorHandle* ret2, // returns new reference + AtenTensorHandle* ret3, // returns new reference + int64_t* ret4, + int64_t* ret5, + AtenTensorHandle* ret6, // returns new reference + AtenTensorHandle* ret7, // returns new reference + AtenTensorHandle* ret8 // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch__scaled_dot_product_flash_attention_v2( + AtenTensorHandle query, + AtenTensorHandle key, + AtenTensorHandle value, + double dropout_p, + int is_causal, + int return_debug_mask, + double* scale, // optional argument + AtenTensorHandle* ret0, // returns new reference + AtenTensorHandle* ret1, // returns new reference + AtenTensorHandle* ret2, // returns new reference + AtenTensorHandle* ret3, // returns new reference + int64_t* ret4, + int64_t* ret5, + AtenTensorHandle* ret6, // returns new reference + AtenTensorHandle* ret7, // returns new reference + AtenTensorHandle* ret8 // returns new reference +); + +[[deprecated( + "aoti_torch__scaled_dot_product_efficient_attention is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch__scaled_dot_product_efficient_attention( + AtenTensorHandle query, + AtenTensorHandle key, + AtenTensorHandle value, + AtenTensorHandle attn_bias, // optional argument + int compute_log_sumexp, + double dropout_p, + int is_causal, + double* scale, // optional argument + AtenTensorHandle* ret0, // returns new reference + AtenTensorHandle* ret1, // returns new reference + AtenTensorHandle* ret2, // returns new reference + AtenTensorHandle* ret3 // returns new reference +); + +#ifdef __cplusplus +} // extern "C" + +#endif +#endif // AOTI_TORCH_SHIM_DEPRECATED diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_mps.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_mps.h new file mode 100644 index 0000000000000000000000000000000000000000..2ab0057805121c902c23e18386cb6121073ebe92 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_mps.h @@ -0,0 +1,103 @@ +#ifndef AOTI_TORCH_SHIM_MPS +#define AOTI_TORCH_SHIM_MPS + +#include + +struct AOTIMetalKernelFunctionOpaque; +using AOTIMetalKernelFunctionHandle = AOTIMetalKernelFunctionOpaque*; + +struct AOTIMetalShaderLibraryOpaque; +using AOTIMetalShaderLibraryHandle = AOTIMetalShaderLibraryOpaque*; + +#ifdef __cplusplus +extern "C" { +#endif + +// MetalShaderLibrary functions +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_create_shader_library( + const char* metal_shader_source, + AOTIMetalShaderLibraryHandle* library_handle); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_delete_shader_library( + AOTIMetalShaderLibraryHandle library_handle); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_get_kernel_function( + AOTIMetalShaderLibraryHandle library_handle, + const char* kernel_name, + AOTIMetalKernelFunctionHandle* function_handle); + +// MetalKernelFunction functions +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_mps_start_encoding(AOTIMetalKernelFunctionHandle func); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_set_arg_tensor( + AOTIMetalKernelFunctionHandle func, + unsigned idx, + AtenTensorHandle tensor); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_set_arg_int( + AOTIMetalKernelFunctionHandle func, + unsigned idx, + int64_t val); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_dispatch_single( + AOTIMetalKernelFunctionHandle func, + uint64_t length); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_dispatch_single_with_group_size( + AOTIMetalKernelFunctionHandle func, + uint64_t length, + uint64_t group_size); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_dispatch_array( + AOTIMetalKernelFunctionHandle func, + const uint64_t* length, + size_t length_size); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_dispatch_array_with_group_size( + AOTIMetalKernelFunctionHandle func, + const uint64_t* length, + size_t length_size, + const uint64_t* group_size, + size_t group_size_size); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_mps_malloc(void** buffer, size_t num_bytes); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_free(void* ptr); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_memcpy( + void* buffer, + size_t constant_offset, + size_t bytes_read, + size_t data_size, + uint8_t* constants_start); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_copy_buffer( + void* src_buffer, + void* dst_buffer, + size_t data_size, + size_t src_offset, + size_t dst_offset); + +// C callback function type for command block execution +typedef void (*aoti_torch_mps_command_block_callback_t)( + AOTIMetalKernelFunctionHandle func, + void* user_data); + +// Shared callback function for std::function trampoline +AOTI_TORCH_EXPORT void aoti_torch_mps_shared_callback( + AOTIMetalKernelFunctionHandle func, + void* user_data); + +// Pure C version using function pointer and user data for trampoline pattern +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_run_command_block( + AOTIMetalKernelFunctionHandle func, + aoti_torch_mps_command_block_callback_t callback, + void* user_data); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // AOTI_TORCH_SHIM_MPS diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_xpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..c25fe6443c9485c1c4b82760b3ccd4012fa03802 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_xpu.h @@ -0,0 +1,210 @@ +#ifndef AOTI_TORCH_SHIM_XPU +#define AOTI_TORCH_SHIM_XPU + +#include +#include + +#ifdef USE_XPU +#ifdef __cplusplus +extern "C" { +#endif + +struct XPUGuardOpaque; +using XPUGuardHandle = XPUGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_xpu_guard( + int32_t device_index, + XPUGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_xpu_guard(XPUGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu_guard_set_index(XPUGuardHandle guard, int32_t device_index); + +struct XPUStreamGuardOpaque; +using XPUStreamGuardHandle = XPUStreamGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_xpu_stream_guard( + void* stream, + int32_t device_index, + XPUStreamGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_xpu_stream_guard(XPUStreamGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_current_xpu_stream(int32_t device_index, void** ret_stream); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_current_xpu_device(int32_t* device_index); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_set_current_xpu_device(const int32_t& device_index); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_current_sycl_queue(void** ret); + +#if AT_MKLDNN_ENABLED() + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu_mkldnn__convolution_pointwise_binary( + AtenTensorHandle X, + AtenTensorHandle other, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_mkldnn__convolution_pointwise( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* attr, + const double** scalars, + int64_t scalars_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu_mkldnn__convolution_pointwise_binary_( + AtenTensorHandle other, + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__qlinear_pointwise_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* B, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + const char* post_op_name, + const double** post_op_args, + int64_t post_op_args_len_, + const char* post_op_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu__qlinear_pointwise_binary_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* other, + AtenTensorHandle* B, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + double other_scale, + int64_t other_zero_point, + const char* binary_post_op, + double binary_alpha, + const char* unary_post_op, + const double** unary_post_op_args, + int64_t unary_post_op_args_len_, + const char* unary_post_op_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__qconv_pointwise_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* B, + const int64_t* stride, + int64_t stride_len_, + const int64_t* padding, + int64_t padding_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + const char* attr, + const double** post_op_args, + int64_t post_op_args_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu__qconv2d_pointwise_binary_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle accum, + AtenTensorHandle* B, + const int64_t* stride_args, + int64_t stride_len_, + const int64_t* padding_args, + int64_t padding_len_, + const int64_t* dilation_args, + int64_t dilation_len_, + int64_t groups, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + double accum_scale, + int64_t accum_zero_point, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +#endif // AT_MKLDNN_ENABLED() +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // USE_XPU +#endif // AOTI_TORCH_SHIM_XPU diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_aten.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_aten.h new file mode 100644 index 0000000000000000000000000000000000000000..96348d6a129be1c1be09b3e716edd6133315d840 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_aten.h @@ -0,0 +1,28 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +// This file corresponds to the aten_shimified_ops list in torchgen/aoti/fallback_ops.py + + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_amax(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int32_t keepdim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_fill__Scalar(AtenTensorHandle self, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_full(const int64_t* size, int64_t size_len_, double fill_value, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_new_empty(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_new_zeros(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_subtract_Tensor(AtenTensorHandle self, AtenTensorHandle other, double alpha, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..aced2b2f539de1559cc86d76b9706d02e70d1e70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h @@ -0,0 +1,160 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__addmm_activation(AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha, int32_t use_gelu, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__cdist_backward(AtenTensorHandle grad, AtenTensorHandle x1, AtenTensorHandle x2, double p, AtenTensorHandle cdist, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__cdist_forward(AtenTensorHandle x1, AtenTensorHandle x2, double p, int64_t* compute_mode, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__dyn_quant_matmul_4bit(AtenTensorHandle inp, AtenTensorHandle packed_weights, int64_t block_size, int64_t in_features, int64_t out_features, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__dyn_quant_pack_4bit_weight(AtenTensorHandle weights, AtenTensorHandle scales_zeros, AtenTensorHandle* bias, int64_t block_size, int64_t in_features, int64_t out_features, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__efficientzerotensor(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_dense_backward(AtenTensorHandle grad, AtenTensorHandle indices, AtenTensorHandle offset2bag, AtenTensorHandle bag_size, AtenTensorHandle maximum_indices, int64_t num_weights, int32_t scale_grad_by_freq, int64_t mode, AtenTensorHandle* per_sample_weights, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_forward_only(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_per_sample_weights_backward(AtenTensorHandle grad, AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, AtenTensorHandle offset2bag, int64_t mode, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fft_c2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t forward, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fft_r2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t onesided, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fused_moving_avg_obs_fq_helper(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fused_rms_norm(AtenTensorHandle input, const int64_t* normalized_shape, int64_t normalized_shape_len_, AtenTensorHandle* weight, double* eps, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__histogramdd_from_bin_cts(AtenTensorHandle self, const int64_t* bins, int64_t bins_len_, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__int_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__pdist_backward(AtenTensorHandle grad, AtenTensorHandle self, double p, AtenTensorHandle pdist, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__pdist_forward(AtenTensorHandle self, double p, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_flash_attention_for_cpu(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, double dropout_p, int32_t is_causal, AtenTensorHandle* attn_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_flash_attention_for_cpu_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, double dropout_p, int32_t is_causal, AtenTensorHandle* attn_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_fused_attention_overrideable(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_fused_attention_overrideable_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__segment_reduce_backward(AtenTensorHandle grad, AtenTensorHandle output, AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* offsets, int64_t axis, double* initial, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__weight_int8pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_abs(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_add_Scalar(AtenTensorHandle self, double other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_add_Tensor(AtenTensorHandle self, AtenTensorHandle other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_angle(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_baddbmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bernoulli__Tensor(AtenTensorHandle self, AtenTensorHandle p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bernoulli__float(AtenTensorHandle self, double p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bucketize_Tensor(AtenTensorHandle self, AtenTensorHandle boundaries, int32_t out_int32, int32_t right, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cat(const AtenTensorHandle* tensors, int64_t tensors_len_, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cholesky_inverse(AtenTensorHandle self, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cumprod(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cumsum(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fill__Scalar(AtenTensorHandle self, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_gcd(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_geqrf(AtenTensorHandle self, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_grid_sampler_2d_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle grid, int64_t interpolation_mode, int64_t padding_mode, int32_t align_corners, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_hann_window(int64_t window_length, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_histc(AtenTensorHandle self, int64_t bins, double min, double max, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_histogram_bin_ct(AtenTensorHandle self, int64_t bins, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_Tensor(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_reduce(AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle source, const char* reduce, int32_t include_self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_lu_unpack(AtenTensorHandle LU_data, AtenTensorHandle LU_pivots, int32_t unpack_data, int32_t unpack_pivots, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_masked_select(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool2d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool2d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool3d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool3d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_unpool2d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_unpool3d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_median(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mode(AtenTensorHandle self, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mul_Tensor(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_nanmedian(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_native_dropout(AtenTensorHandle input, double p, int32_t* train, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_nonzero(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_ormqr(AtenTensorHandle self, AtenTensorHandle input2, AtenTensorHandle input3, int32_t left, int32_t transpose, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_permute(AtenTensorHandle self, const int64_t* dims, int64_t dims_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Scalar(double self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Tensor_Scalar(AtenTensorHandle self, double exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Tensor_Tensor(AtenTensorHandle self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_repeat_interleave_Tensor(AtenTensorHandle repeats, int64_t* output_size, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_replication_pad1d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_replication_pad2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_resize_(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_src_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_value_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_reduce_two_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src, const char* reduce, int32_t include_self); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_searchsorted_Scalar(AtenTensorHandle sorted_sequence, double self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_searchsorted_Tensor(AtenTensorHandle sorted_sequence, AtenTensorHandle self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_segment_reduce(AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* indices, AtenTensorHandle* offsets, int64_t axis, int32_t unsafe, double* initial, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_set__source_Tensor(AtenTensorHandle self, AtenTensorHandle source); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_sort_stable(AtenTensorHandle self, int32_t* stable, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_squeeze_dim(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_topk(AtenTensorHandle self, int64_t k, int64_t dim, int32_t largest, int32_t sorted, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_triangular_solve(AtenTensorHandle self, AtenTensorHandle A, int32_t upper, int32_t transpose, int32_t unitriangular, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_bicubic2d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_linear1d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_trilinear3d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_d, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_as_complex(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_as_real(AtenTensorHandle self, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..c41487ae6dd8950ea240426196472c9a3a2c76f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h @@ -0,0 +1,168 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__addmm_activation(AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha, int32_t use_gelu, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cdist_backward(AtenTensorHandle grad, AtenTensorHandle x1, AtenTensorHandle x2, double p, AtenTensorHandle cdist, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cdist_forward(AtenTensorHandle x1, AtenTensorHandle x2, double p, int64_t* compute_mode, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cudnn_rnn(AtenTensorHandle input, const AtenTensorHandle* weight, int64_t weight_len_, int64_t weight_stride0, AtenTensorHandle* weight_buf, AtenTensorHandle hx, AtenTensorHandle* cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, int32_t batch_first, double dropout, int32_t train, int32_t bidirectional, const int64_t* batch_sizes, int64_t batch_sizes_len_, AtenTensorHandle* dropout_state, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficient_attention_backward(AtenTensorHandle grad_out_, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* bias, AtenTensorHandle out, AtenTensorHandle* cu_seqlens_q, AtenTensorHandle* cu_seqlens_k, int64_t max_seqlen_q, int64_t max_seqlen_k, AtenTensorHandle logsumexp, double dropout_p, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, int64_t custom_mask_type, int32_t bias_requires_grad, double* scale, int64_t* num_splits_key, int64_t* window_size, int32_t shared_storage_dqdkdv, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficient_attention_forward(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* bias, AtenTensorHandle* cu_seqlens_q, AtenTensorHandle* cu_seqlens_k, int64_t* max_seqlen_q, int64_t* max_seqlen_k, double dropout_p, int64_t custom_mask_type, int32_t compute_log_sumexp, double* scale, AtenTensorHandle* seqlen_k, int64_t* window_size, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficientzerotensor(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_dense_backward(AtenTensorHandle grad, AtenTensorHandle indices, AtenTensorHandle offset2bag, AtenTensorHandle bag_size, AtenTensorHandle maximum_indices, int64_t num_weights, int32_t scale_grad_by_freq, int64_t mode, AtenTensorHandle* per_sample_weights, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_forward_only(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_per_sample_weights_backward(AtenTensorHandle grad, AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, AtenTensorHandle offset2bag, int64_t mode, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fft_c2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t forward, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fft_r2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t onesided, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__flash_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle rng_state, AtenTensorHandle unused, double* scale, int64_t* window_size_left, int64_t* window_size_right, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__flash_attention_forward(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* cum_seq_q, AtenTensorHandle* cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, int64_t* window_size_left, int64_t* window_size_right, AtenTensorHandle* seqused_k, AtenTensorHandle* alibi_slopes, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fused_moving_avg_obs_fq_helper(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fused_rms_norm(AtenTensorHandle input, const int64_t* normalized_shape, int64_t normalized_shape_len_, AtenTensorHandle* weight, double* eps, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__int_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__pdist_backward(AtenTensorHandle grad, AtenTensorHandle self, double p, AtenTensorHandle pdist, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__pdist_forward(AtenTensorHandle self, double p, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_cudnn_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, int32_t compute_log_sumexp, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_cudnn_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, AtenTensorHandle attn_bias, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_efficient_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, int32_t compute_log_sumexp, double dropout_p, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_efficient_attention_backward(AtenTensorHandle grad_out_, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double dropout_p, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_flash_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_flash_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_fused_attention_overrideable(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_fused_attention_overrideable_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_grouped_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* offs, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__segment_reduce_backward(AtenTensorHandle grad, AtenTensorHandle output, AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* offsets, int64_t axis, double* initial, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__thnn_fused_lstm_cell(AtenTensorHandle input_gates, AtenTensorHandle hidden_gates, AtenTensorHandle cx, AtenTensorHandle* input_bias, AtenTensorHandle* hidden_bias, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__weight_int4pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, int64_t qGroupSize, AtenTensorHandle qScaleAndZeros, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__weight_int8pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_abs(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_add_Scalar(AtenTensorHandle self, double other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_add_Tensor(AtenTensorHandle self, AtenTensorHandle other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_angle(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_baddbmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bernoulli__Tensor(AtenTensorHandle self, AtenTensorHandle p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bernoulli__float(AtenTensorHandle self, double p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bucketize_Tensor(AtenTensorHandle self, AtenTensorHandle boundaries, int32_t out_int32, int32_t right, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cat(const AtenTensorHandle* tensors, int64_t tensors_len_, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cholesky_inverse(AtenTensorHandle self, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cumprod(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cumsum(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fill__Scalar(AtenTensorHandle self, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_gcd(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_geqrf(AtenTensorHandle self, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_grid_sampler_2d_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle grid, int64_t interpolation_mode, int64_t padding_mode, int32_t align_corners, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_hann_window(int64_t window_length, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_histc(AtenTensorHandle self, int64_t bins, double min, double max, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_Tensor(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_reduce(AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle source, const char* reduce, int32_t include_self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_lu_unpack(AtenTensorHandle LU_data, AtenTensorHandle LU_pivots, int32_t unpack_data, int32_t unpack_pivots, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_masked_select(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool2d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool2d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool3d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool3d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_unpool2d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_unpool3d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_median(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mode(AtenTensorHandle self, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mul_Tensor(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_nanmedian(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_native_dropout(AtenTensorHandle input, double p, int32_t* train, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_nonzero(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_ormqr(AtenTensorHandle self, AtenTensorHandle input2, AtenTensorHandle input3, int32_t left, int32_t transpose, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_permute(AtenTensorHandle self, const int64_t* dims, int64_t dims_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Scalar(double self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Tensor_Scalar(AtenTensorHandle self, double exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Tensor_Tensor(AtenTensorHandle self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_repeat_interleave_Tensor(AtenTensorHandle repeats, int64_t* output_size, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_replication_pad1d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_replication_pad2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_resize_(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_src_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_value_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_reduce_two_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src, const char* reduce, int32_t include_self); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_searchsorted_Scalar(AtenTensorHandle sorted_sequence, double self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_searchsorted_Tensor(AtenTensorHandle sorted_sequence, AtenTensorHandle self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_segment_reduce(AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* indices, AtenTensorHandle* offsets, int64_t axis, int32_t unsafe, double* initial, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_set__source_Tensor(AtenTensorHandle self, AtenTensorHandle source); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_sort_stable(AtenTensorHandle self, int32_t* stable, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_squeeze_dim(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_topk(AtenTensorHandle self, int64_t k, int64_t dim, int32_t largest, int32_t sorted, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_triangular_solve(AtenTensorHandle self, AtenTensorHandle A, int32_t upper, int32_t transpose, int32_t unitriangular, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_bicubic2d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_linear1d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_trilinear3d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_d, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_as_complex(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_as_real(AtenTensorHandle self, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_mps.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_mps.h new file mode 100644 index 0000000000000000000000000000000000000000..e075956e14d73112b4e1f46bdc1b769d94903693 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_mps.h @@ -0,0 +1,133 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__adaptive_avg_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__adaptive_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__cdist_forward(AtenTensorHandle x1, AtenTensorHandle x2, double p, int64_t* compute_mode, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__efficientzerotensor(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__embedding_bag(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__embedding_bag_dense_backward(AtenTensorHandle grad, AtenTensorHandle indices, AtenTensorHandle offset2bag, AtenTensorHandle bag_size, AtenTensorHandle maximum_indices, int64_t num_weights, int32_t scale_grad_by_freq, int64_t mode, AtenTensorHandle* per_sample_weights, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__embedding_bag_forward_only(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__embedding_bag_per_sample_weights_backward(AtenTensorHandle grad, AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, AtenTensorHandle offset2bag, int64_t mode, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__fft_c2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t forward, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__fft_r2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t onesided, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__fused_rms_norm(AtenTensorHandle input, const int64_t* normalized_shape, int64_t normalized_shape_len_, AtenTensorHandle* weight, double* eps, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__histogramdd_from_bin_cts(AtenTensorHandle self, const int64_t* bins, int64_t bins_len_, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__scaled_dot_product_attention_math_for_mps(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_mask, double dropout_p, int32_t is_causal, AtenTensorHandle* dropout_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__scaled_dot_product_fused_attention_overrideable(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__scaled_dot_product_fused_attention_overrideable_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__weight_int4pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, int64_t qGroupSize, AtenTensorHandle qScaleAndZeros, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__weight_int8pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_abs(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_adaptive_max_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_adaptive_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_add_Scalar(AtenTensorHandle self, double other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_add_Tensor(AtenTensorHandle self, AtenTensorHandle other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_angle(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_avg_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_avg_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_baddbmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_bernoulli__Tensor(AtenTensorHandle self, AtenTensorHandle p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_bernoulli__float(AtenTensorHandle self, double p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_bucketize_Tensor(AtenTensorHandle self, AtenTensorHandle boundaries, int32_t out_int32, int32_t right, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cat(const AtenTensorHandle* tensors, int64_t tensors_len_, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cumprod(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cumsum(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_fill__Scalar(AtenTensorHandle self, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_hann_window(int64_t window_length, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_histc(AtenTensorHandle self, int64_t bins, double min, double max, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_histogram_bin_ct(AtenTensorHandle self, int64_t bins, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_index_Tensor(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_lu_unpack(AtenTensorHandle LU_data, AtenTensorHandle LU_pivots, int32_t unpack_data, int32_t unpack_pivots, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_masked_select(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_pool2d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_pool2d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_pool3d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_pool3d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_unpool2d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_unpool3d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_median(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_mul_Tensor(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_nanmedian(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_native_dropout(AtenTensorHandle input, double p, int32_t* train, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_nonzero(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_permute(AtenTensorHandle self, const int64_t* dims, int64_t dims_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_pow_Scalar(double self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_pow_Tensor_Scalar(AtenTensorHandle self, double exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_pow_Tensor_Tensor(AtenTensorHandle self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_repeat_interleave_Tensor(AtenTensorHandle repeats, int64_t* output_size, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_replication_pad1d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_replication_pad2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_resize_(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_scatter_src_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_scatter_value_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_scatter_reduce_two_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src, const char* reduce, int32_t include_self); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_searchsorted_Scalar(AtenTensorHandle sorted_sequence, double self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_searchsorted_Tensor(AtenTensorHandle sorted_sequence, AtenTensorHandle self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_set__source_Tensor(AtenTensorHandle self, AtenTensorHandle source); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_sort_stable(AtenTensorHandle self, int32_t* stable, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_squeeze_dim(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_topk(AtenTensorHandle self, int64_t k, int64_t dim, int32_t largest, int32_t sorted, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_triangular_solve(AtenTensorHandle self, AtenTensorHandle A, int32_t upper, int32_t transpose, int32_t unitriangular, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_upsample_bicubic2d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_upsample_linear1d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_upsample_trilinear3d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_d, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_view_as_complex(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_view_as_real(AtenTensorHandle self, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_xpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..49adef8de403168dc8e2a3cf30380c3115527089 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_xpu.h @@ -0,0 +1,74 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__addmm_activation(AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha, int32_t use_gelu, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__fused_rms_norm(AtenTensorHandle input, const int64_t* normalized_shape, int64_t normalized_shape_len_, AtenTensorHandle* weight, double* eps, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__int_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_dot_product_flash_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_dot_product_flash_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_dot_product_fused_attention_overrideable(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_dot_product_fused_attention_overrideable_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__weight_int4pack_mm_with_scales_and_zeros(AtenTensorHandle self, AtenTensorHandle mat2, int64_t qGroupSize, AtenTensorHandle qScale, AtenTensorHandle qZeros, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__weight_int8pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_abs(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_add_Scalar(AtenTensorHandle self, double other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_baddbmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_hann_window(int64_t window_length, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_permute(AtenTensorHandle self, const int64_t* dims, int64_t dims_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_squeeze_dim(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..57aa0645fb79e83c94f30a120fc6898062e89bce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::aot_inductor { + +void* data_ptr_from_mkldnn(at::Tensor* mkldnn_tensor); + +at::Tensor mkldnn_tensor_from_data_ptr( + void* data_ptr, + at::IntArrayRef dims, + at::ScalarType dtype, + at::Device device, + const uint8_t* opaque_metadata, + int64_t opaque_metadata_size); + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..61428e2cef64ceb3c600d8a8dd03ac63e018c4b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h @@ -0,0 +1,158 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include // @manual +#include +#include + +namespace torch::aot_inductor { + +inline std::ostream& operator<<(std::ostream& os, DynamicArgType arg_type) { + os << static_cast(arg_type); + return os; +} + +struct OSSDynamicArg { + OSSDynamicArg( + int arg_index, + DynamicArgType arg_type, + int length, + std::optional> list_item_types = std::nullopt) + : arg_index(arg_index), + arg_type(arg_type), + length(length), + list_item_types(std::move(list_item_types)) {} + int arg_index; + DynamicArgType arg_type; + int length; + std::optional> + list_item_types; // only used for parsing list of optional tensors +}; + +struct OSSTorchBindArg { + OSSTorchBindArg(int arg_index, std::string arg_name) + : arg_index(arg_index), arg_name(std::move(arg_name)) {} + int arg_index; + // arg_name is used to find the corresponding IValue in customObjs_ + std::string arg_name; +}; + +struct OSSOpKernel { + explicit OSSOpKernel(std::string target) : target_(std::move(target)) {} + // Explicitly declare copy and move constructors + OSSOpKernel(const OSSOpKernel&) = default; + OSSOpKernel(OSSOpKernel&&) = default; + // Explicitly declare copy and move assignment operators + OSSOpKernel& operator=(const OSSOpKernel&) = default; + OSSOpKernel& operator=(OSSOpKernel&&) = default; + + std::string target_; + std::vector dynamic_args_; + std::vector torchbind_args_; + std::vector outputs_; + std::vector stack_; + + int num_output_tensors() const { + int num_output_tensors = 0; + for (const auto& output : outputs_) { + if (isTensorType(output.arg_type)) { + num_output_tensors += output.length; + } + } + return num_output_tensors; + } + + int num_output_ints() const { + int num_output_ints = 0; + for (const auto& output : outputs_) { + if (output.arg_type == DynamicArgType::IntType) { + num_output_ints += output.length; + } + } + return num_output_ints; + } + + virtual void run(std::vector& stack) = 0; + virtual c10::FunctionSchema schema() const = 0; + virtual ~OSSOpKernel() = default; +}; + +struct OSSOpKernelOperator : public OSSOpKernel { + OSSOpKernelOperator(std::string target, c10::OperatorHandle op_handle) + : OSSOpKernel(std::move(target)), op_handle_(std::move(op_handle)) {} + + c10::OperatorHandle op_handle_; + void run(std::vector& stack) override { + op_handle_.callBoxed(stack); + } + + c10::FunctionSchema schema() const override { + return op_handle_.schema(); + } +}; + +struct OSSCallTorchBindKernel : public OSSOpKernel { + OSSCallTorchBindKernel(std::string target, torch::jit::Function* method) + : OSSOpKernel(std::move(target)), method_(method) {} + torch::jit::Function* method_; + void run(std::vector& stack) override { + method_->run(stack); + } + + c10::FunctionSchema schema() const override { + return method_->getSchema(); + } +}; + +class OSSProxyExecutor : public ProxyExecutor { + public: + explicit OSSProxyExecutor( + const std::string& json_path, + bool is_cpu, + std::optional> custom_objs = + std::nullopt); + + void call_function( + int extern_node_index, + int num_ints, + int64_t* flatten_int_args, + int num_tensors, + AtenTensorHandle* flatten_tensor_args) override; + + private: + void prefill_stack_with_static_arguments( + size_t index, + const at::TypePtr& schema_arg_type, + const nlohmann::json& serialized_arg, + OSSOpKernel* op_kernel, + const std::string& torchbind_arg_name); + + void get_input_info_from_serialized( + const std::vector& schema_args, + const nlohmann::json& serialized_node, + OSSOpKernel& op_kernel); + + void get_output_info_from_serialized( + const std::vector& schema_returns, + const nlohmann::json& serialized_node, + OSSOpKernel& op_kernel); + + std::unique_ptr get_call_torch_bind_kernel( + const nlohmann::json& serialized_node); + + std::vector> op_kernels_; + std::unique_ptr device_; + std::unordered_map custom_objs_; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..b25a7e396c8c349810c56d59a20e800fa68d0882 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h @@ -0,0 +1,42 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::aot_inductor { + +enum class DynamicArgType : int { + TensorType = 0, + ListTensorType = 1, + ListOptionalTensorType = 2, + IntType = 3, + ListIntType = 4, + NoneType = 5, +}; + +inline bool isTensorType(DynamicArgType arg_type) { + return arg_type == DynamicArgType::TensorType || + arg_type == DynamicArgType::ListTensorType || + arg_type == DynamicArgType::ListOptionalTensorType; +} + +class ProxyExecutor { + public: + ProxyExecutor() = default; + virtual ~ProxyExecutor() = default; + + virtual void call_function( + int extern_node_index, + int num_ints, + int64_t* flatten_int_args, + int num_tensors, + AtenTensorHandle* flatten_tensor_args) = 0; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h new file mode 100644 index 0000000000000000000000000000000000000000..4461d682ad3a5f70ae83161c6590cab63bf6a675 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::aot_inductor { + +// Functions declared here are not meant to be called from the AOTInductor +// generated model.so + +// unsafe_alloc_new_handles_from_tensors is used for allocating new aten +// tensor objects and return them as a vector of AtenTensorHandle (raw +// pointers), and those pointers will be stolen by model.so. +TORCH_API std::vector unsafe_alloc_new_handles_from_tensors( + const std::vector& tensors); + +// alloc_tensors_by_stealing_from_handles is used for creating a vector of aten +// tensors by stealing from an array of handles. Only the handles are stolen, +// and the array itself is borrowed. +// +// WARNING: Can NOT be called in model.so +TORCH_API std::vector alloc_tensors_by_stealing_from_handles( + AtenTensorHandle* handles, + size_t length); + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0e71766b3f0a24a6129eac1e08fec84fefbbabbf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h @@ -0,0 +1,240 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define AOTI_TORCH_CONVERT_EXCEPTION_TO_ERROR_CODE(...) \ + try { \ + __VA_ARGS__ \ + } catch (const std::exception& e) { \ + LOG(ERROR) << "Exception in aoti_torch: " << e.what(); \ + return AOTI_TORCH_FAILURE; \ + } catch (...) { \ + LOG(ERROR) << "Exception in aoti_torch: UNKNOWN"; \ + return AOTI_TORCH_FAILURE; \ + } \ + return AOTI_TORCH_SUCCESS; + +namespace torch::aot_inductor { + +inline at::Tensor* tensor_handle_to_tensor_pointer(AtenTensorHandle handle) { + return reinterpret_cast(handle); +} + +inline AtenTensorHandle tensor_pointer_to_tensor_handle(at::Tensor* tensor) { + return reinterpret_cast(tensor); +} + +inline at::Tensor resolve_tensor_dispatch_flags(AtenTensorHandle handle) { + at::Tensor* tensor{tensor_handle_to_tensor_pointer(handle)}; + if (tensor->is_conj() || tensor->is_neg()) { + // If the conjugation or negation dispatch flags are set, runtime dispatch + // handles them by cloning the tensor before passing them to the native ATen + // function. Since the C-shim calls the native function directly, we have + // to handle the flags ourselves, or results will be silently incorrect. + return tensor->clone(); + } + return *tensor; +} + +inline std::optional resolve_tensor_dispatch_flags( + const AtenTensorHandle* handle) { + return handle ? std::make_optional(resolve_tensor_dispatch_flags(*handle)) + : std::nullopt; +} + +inline std::vector resolve_tensor_list_dispatch_flags( + const AtenTensorHandle* handle, + int64_t len) { + std::vector ret{}; + ret.reserve(len); + for (int64_t i{0}; i < len; ++i) { + ret.emplace_back(resolve_tensor_dispatch_flags(handle[i])); + } + return ret; +} + +inline std::vector> resolve_tensor_list_dispatch_flags( + const AtenTensorHandle** handle, + int64_t len) { + std::vector> ret{}; + ret.reserve(len); + for (int64_t i{0}; i < len; ++i) { + ret.emplace_back(resolve_tensor_dispatch_flags(handle[i])); + } + return ret; +} + +inline at::Generator* generator_handle_to_generator_pointer( + AtenGeneratorHandle handle) { + return reinterpret_cast(handle); +} + +inline AtenGeneratorHandle generator_pointer_to_generator_handle( + at::Generator* generator) { + return reinterpret_cast(generator); +} + +inline AtenTensorHandle new_tensor_handle(at::Tensor&& tensor) { + at::Tensor* new_tensor = new at::Tensor(std::move(tensor)); + return tensor_pointer_to_tensor_handle(new_tensor); +} + +inline void assert_inf_and_nan( + const std::string& tensor_name, + at::Tensor& check_tensor) { + auto isnan_tensor = check_tensor.isnan(); + if (isnan_tensor.any().item()) { + throw std::runtime_error("At least one NaN in " + tensor_name); + } + auto isinf_tensor = check_tensor.isinf(); + if (isinf_tensor.any().item()) { + throw std::runtime_error("At least one INF in " + tensor_name); + } +} + +// utility functions to convert a pointer to an optional value +template +inline std::optional pointer_to_optional(T* ptr) { + return ptr ? std::make_optional(*ptr) : std::nullopt; +} + +template >> +inline std::optional pointer_to_optional(U* ptr) { + return ptr ? std::make_optional(T(*ptr)) : std::nullopt; +} + +template <> +inline std::optional pointer_to_optional(AtenTensorHandle* ptr) { + return ptr ? std::make_optional(*tensor_handle_to_tensor_pointer(*ptr)) + : std::nullopt; +} + +template <> +inline std::optional pointer_to_optional( + const AtenTensorHandle* ptr) { + return ptr ? std::make_optional(*tensor_handle_to_tensor_pointer(*ptr)) + : std::nullopt; +} + +template <> +inline std::optional pointer_to_optional( + AtenGeneratorHandle* ptr) { + return ptr ? std::make_optional(*generator_handle_to_generator_pointer(*ptr)) + : std::nullopt; +} + +inline std::optional pointer_to_optional_device( + int32_t* device_type, + int32_t device_index) { + return device_type ? std::make_optional(c10::Device( + static_cast(*device_type), + static_cast(device_index))) + : std::nullopt; +} + +// utility functions to convert a pointer to a list +template +struct is_optional : std::false_type {}; +template +struct is_optional> : std::true_type {}; + +template +inline c10::ArrayRef pointer_to_list(T* ptr, int64_t len) { + return c10::ArrayRef(ptr, len); +} + +template < + class T, + class U, + typename = std::enable_if_t>, + typename = std::enable_if_t::value>> +inline std::vector pointer_to_list(U* ptr, int64_t len) { + // std::vector will be implicitly converted to c10::ArrayRef at the call + // site + std::vector result; + result.reserve(len); + for (int64_t i = 0; i < len; i++) { + result.emplace_back(T(ptr[i])); + } + return result; +} + +template ::value>> +inline std::vector pointer_to_list(U** ptr, int64_t len) { + // Here U** denotes a list of optional arguments + // std::vector will be implicitly converted to c10::ArrayRef at the call + // site + std::vector result; + result.reserve(len); + for (int64_t i = 0; i < len; i++) { + result.emplace_back(pointer_to_optional(ptr[i])); + } + return result; +} + +template <> +inline std::vector pointer_to_list( + const AtenTensorHandle* ptr, + int64_t len) { + std::vector result; + result.reserve(len); + for (int64_t i = 0; i < len; i++) { + result.emplace_back(*tensor_handle_to_tensor_pointer(ptr[i])); + } + return result; +} + +template <> +inline std::vector> pointer_to_list( + const AtenTensorHandle** ptr, + int64_t len) { + std::vector> result; + result.reserve(len); + for (int64_t i = 0; i < len; i++) { + result.emplace_back(pointer_to_optional(ptr[i])); + } + return result; +} + +template +inline std::array pointer_to_list(const int32_t* ptr) { + std::array result; + std::copy(ptr, ptr + N, result.begin()); + return result; +} + +// Utility function to convert a pointer to an optional list of values +template +inline std::optional> pointer_to_optional_list( + U** ptr, + int64_t len) { + return ptr + ? std::make_optional>(pointer_to_list(*ptr, len)) + : std::nullopt; +} + +template +static c10::List convert_to_c10_List(const T* scalars, const int64_t len) { + c10::List scalars_list; + scalars_list.reserve(len); + for (int64_t i = 0; i < len; i++) { + scalars_list.emplace_back(scalars[i]); + } + return scalars_list; +} + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/array_ref_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/array_ref_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..f61765114014dc45abc3a1d6002bd6c0fe182fc3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/array_ref_impl.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::aot_inductor { +template +void convert_output_to_handle( + const ArrayRefTensor& output, + AtenTensorHandle& handle) { + handle = output.expensiveCopyToTensor(); +} + +template +void convert_outputs_to_handles_helper( + const std::tuple...>& outputs, + AtenTensorHandle* output_handles, + std::index_sequence) { + (convert_output_to_handle(std::get(outputs), output_handles[Is]), ...); +} +template +void convert_outputs_to_handles( + const std::tuple...>& outputs, + AtenTensorHandle* output_handles) { + convert_outputs_to_handles_helper( + outputs, output_handles, std::make_index_sequence()); +} + +template +void convert_handle_to_arrayref_tensor( + AtenTensorHandle handle, + ArrayRefTensor& input) { + void* data_ptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(handle, &data_ptr)); + int64_t dim; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_dim(handle, &dim)); + int64_t numel; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_numel(handle, &numel)); + int64_t* sizes; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(handle, &sizes)); + int64_t* strides; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(handle, &strides)); + int32_t dtype; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype(handle, &dtype)); + int32_t device_type; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type(handle, &device_type)); + int32_t device_index; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_index(handle, &device_index)); + + input = ArrayRefTensor( + MiniArrayRef(reinterpret_cast(data_ptr), numel), + MiniArrayRef(sizes, dim), + MiniArrayRef(strides, dim), + device_type, + device_index); +} + +template +void convert_handles_to_inputs_helper( + AtenTensorHandle* input_handles, + std::tuple...>& inputs, + std::index_sequence) { + (convert_handle_to_arrayref_tensor(input_handles[Is], std::get(inputs)), + ...); +} + +template +void convert_handles_to_inputs( + AtenTensorHandle* input_handles, + std::tuple...>& inputs) { + convert_handles_to_inputs_helper( + input_handles, inputs, std::make_index_sequence()); +} + +template +void assert_numel(const ArrayRefTensor& tensor, uint64_t numel) { + TORCH_CHECK( + tensor.numel() == numel, + "incorrect numel for input tensor. expected ", + numel, + ", got ", + tensor.numel()); +} +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_prefix.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_prefix.h new file mode 100644 index 0000000000000000000000000000000000000000..5d867caf8b49364f006675c01cc03ee89c21a851 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_prefix.h @@ -0,0 +1,1328 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// WARNING: be extra careful when including more ATen/c10 header files here! +// Because AOTInductor generated code will copy-paste this cpp_prefix.h for +// the CPU backend, we have to make sure the used headers are implemented +// in a header-only way, i.e. all the function and class definitions are +// in .h files instead of .cpp files, to avoid ABI backward-compatibility +// breakage. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CPU_CAPABILITY_AVX512) || defined(CPU_CAPABILITY_AVX2) || \ + defined(CPU_CAPABILITY_ZVECTOR) || defined(CPU_CAPABILITY_NEON) || \ + defined(CPU_CAPABILITY_VSX) || defined(CPU_CAPABILITY_SVE256) +#define INDUCTOR_USE_VECTOR_TYPES() 1 +#else +#define INDUCTOR_USE_VECTOR_TYPES() 0 +#endif + +#if INDUCTOR_USE_VECTOR_TYPES() +#include +#include +#else +// For calc_erfinv +#include +#endif + +template +struct Welford { + T mean = T(0); + T m2 = T(0); + // Use weight for tail cases since the index of each element in the vec may be + // different. A single index can not express masked welford reduction. + T weight = T(0); + uint64_t index = 0; +}; + +template +struct IsVecType : std::false_type {}; + +template +struct IsVecMaskType : std::false_type {}; + +#if INDUCTOR_USE_VECTOR_TYPES() +template +struct IsVecType> : std::true_type {}; +template +struct IsVecType> : std::true_type {}; + +template +struct IsVecMaskType> : std::true_type {}; +#endif + +template +struct GetScalarType { + using type = T; +}; + +#if INDUCTOR_USE_VECTOR_TYPES() +template +struct GetScalarType> { + using type = T; +}; +template +struct GetScalarType> { + using type = T; +}; +#endif + +template +struct CascadeSumHelper { + // A data struct to help cascade summation: + std::vector sum_stk{}; + uint64_t depth{0}; // depth of sum_stk. + uint64_t num_chunks{0}; // number of chunks stored in sum_stk. + uint64_t index{0}; // index of the current data. + CascadeSumHelper() = default; + CascadeSumHelper(uint64_t N) { + uint64_t m = (N + kChunkSize - 1) / kChunkSize; // div up + depth = m > 0 + ? static_cast(ceil(log2(static_cast(m)))) + : 0; + if constexpr (IsVecType::value) { + sum_stk.assign( + std::max(depth, static_cast(1)), + T(typename T::value_type(0))); + } else { + sum_stk.assign(std::max(depth, static_cast(1)), T(0)); + } + } +}; + +template +inline T cascade_sum_combine(T& data, CascadeSumHelper* c) { + // Note: In order to be consistent with other reductions in inductor, + // the returned value may be wrong and cascade_sum_final must be executed to + // get the final correct result. Inductor uses the reduction suffix to ensure + // that cascade_sum_final is called in the end. + c->sum_stk[0] = c->sum_stk[0] + data; + // Use cascade summation to improve numerical stability. + // https://en.wikipedia.org/wiki/Pairwise_summation + if (c->depth > 0) { + c->index++; + if (c->index == kChunkSize) { + c->num_chunks += 1; + c->index = 0; + uint64_t mask = c->num_chunks; + uint64_t j = 1; + for (; j < c->depth && (mask & 1) == 0; ++j) { + c->sum_stk[j] = c->sum_stk[j] + c->sum_stk[j - 1]; + c->sum_stk[j - 1] = T(0); + mask >>= 1; + } + return c->sum_stk[j - 1]; + } + } + return c->sum_stk[0]; +} + +template +inline T cascade_sum_final(CascadeSumHelper* c) { + T result = c->sum_stk[0]; + for (const auto i : c10::irange(1, c->depth)) { + result = result + c->sum_stk[i]; + } + return result; +} + +template +struct WelfordHelper { + // A data struct to help welford reduction: + // 1. Save the reciprocal of weights to avoid redundant divisions. + // 2. Save the welford stack, which is used to combine welford reduction + // with cascade summation to improve numerical stability. + static std::vector::type> weight_recps; + std::vector> welford_stk{}; + uint64_t depth{0}; // depth of welford_stk. + uint64_t num_chunks{0}; // number of chunks stored in welford_stk. + WelfordHelper() = default; + WelfordHelper(uint64_t N) { + uint64_t m = (N + kChunkSize - 1) / kChunkSize; // div up + depth = m > 0 + ? static_cast(ceil(log2(static_cast(m)))) + : 0; + welford_stk.assign(depth, Welford()); + } +}; + +template +std::vector::type> + WelfordHelper::weight_recps = []() { + using scalar_t = typename GetScalarType::type; + std::vector temp(kChunkSize); + for (const auto i : c10::irange(kChunkSize)) { + temp[i] = scalar_t(static_cast(1) / static_cast(i + 1)); + } + return temp; + }(); + +template +Welford welford_combine( + const Welford& a, + const Welford& b, + bool use_index = false) { + if (a.index == 0) { + return b; + } + if (b.index == 0) { + return a; + } + auto delta = b.mean - a.mean; + auto a_weight = use_index ? T(a.index) : a.weight; + auto b_weight = use_index ? T(b.index) : b.weight; + auto new_weight = a_weight + b_weight; + auto new_index = a.index + b.index; + auto wb_over_w = b_weight / new_weight; + if constexpr (IsVecType::value) { + // Guard against division by zero + wb_over_w = T::blendv(wb_over_w, T(0), new_weight == T(0)); + } + auto result = Welford{ + a.mean + delta * wb_over_w, + a.m2 + b.m2 + delta * delta * a_weight * wb_over_w, + new_weight, + new_index}; + return result; +} + +template +Welford welford_combine( + Welford& acc, + T& data, + WelfordHelper* w = nullptr) { + // Combine welford reduction with cascade summation to improve numerical + // stability. + // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + // https://en.wikipedia.org/wiki/Pairwise_summation + if (w != nullptr && w->depth > 0 && acc.index == kChunkSize) { + w->welford_stk[0] = welford_combine(w->welford_stk[0], acc); + w->num_chunks += 1; + acc.mean = T(0); + acc.m2 = T(0); + acc.weight = T(0); + acc.index = 0; + uint64_t mask = w->num_chunks; + for (uint64_t j = 1; j < w->depth && (mask & 1) == 0; ++j) { + w->welford_stk[j] = + welford_combine(w->welford_stk[j], w->welford_stk[j - 1]); + w->welford_stk[j - 1] = Welford(); + mask >>= 1; + } + } + // Add a single data point + uint64_t new_index = acc.index + 1; + auto new_weight = acc.weight + T(1); + auto delta = data - acc.mean; + T new_mean; + // use new_index to fecth 1 / new_weight to avoid divisions + new_mean = acc.mean + + ((w == nullptr || acc.index >= w->weight_recps.size()) + ? delta / new_weight + : delta * T(w->weight_recps[acc.index])); + auto new_delta = data - new_mean; + auto result = + Welford{new_mean, acc.m2 + delta * new_delta, new_weight, new_index}; + return result; +} + +template +Welford welford_combine(Welford& acc, WelfordHelper* w) { + for (const auto i : c10::irange(w->depth)) { + acc = welford_combine(acc, w->welford_stk[i]); + } + return acc; +} + +template +struct IndexValue { + int64_t index{}; + T value; + IndexValue(int64_t idx, T val) : index(idx), value(val) {} + IndexValue() = default; +}; + +#if INDUCTOR_USE_VECTOR_TYPES() +template +Welford welford_combine( + Welford& acc, + T& data, + int64_t tail_size, + WelfordHelper* w = nullptr) { + auto out = welford_combine(acc, data, w); + return Welford{ + T::set(acc.mean, out.mean, tail_size), + T::set(acc.m2, out.m2, tail_size), + T::set(acc.weight, out.weight, tail_size), + out.index}; +} + +template +inline T cascade_sum_combine( + T& data, + int64_t tail_size, + CascadeSumHelper* c) { + auto out = c->sum_stk[0] + data; + c->sum_stk[0] = T::set(c->sum_stk[0], out, tail_size); + if (c->depth > 0) { + c->index++; + if (c->index == kChunkSize) { + c->num_chunks += 1; + c->index = 0; + uint64_t mask = c->num_chunks; + uint64_t j = 1; + for (; j < c->depth && (mask & 1) == 0; ++j) { + c->sum_stk[j] = c->sum_stk[j] + c->sum_stk[j - 1]; + c->sum_stk[j - 1] = T(0); + mask >>= 1; + } + return c->sum_stk[j - 1]; + } + } + return c->sum_stk[0]; +} + +template +inline T max_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = at::vec::maximum(a, b); + return T::set(a, out, tail_size); +} + +template <> +inline at::vec::VecMask max_masked_reduce( + const at::vec::VecMask& a, + const at::vec::VecMask& b, + const int64_t tail_size) { + auto out = a | b; + return at::vec::VecMask::set(a, out, tail_size); +} + +template +inline T min_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = at::vec::minimum(a, b); + return T::set(a, out, tail_size); +} + +template <> +inline at::vec::VecMask min_masked_reduce( + const at::vec::VecMask& a, + const at::vec::VecMask& b, + const int64_t tail_size) { + auto out = a & b; + return at::vec::VecMask::set(a, out, tail_size); +} + +template +inline T sum_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = a + b; + return T::set(a, out, tail_size); +} + +template <> +inline at::vec::VecMask sum_masked_reduce( + const at::vec::VecMask& a, + const at::vec::VecMask& b, + const int64_t tail_size) { + auto out = a | b; + return at::vec::VecMask::set(a, out, tail_size); +} + +template +T prod_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = a * b; + return T::set(a, out, tail_size); +} + +template +T xor_sum_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = a ^ b; + return T::set(a, out, tail_size); +} + +template +T any_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = a | b; + return T::set(a, out, tail_size); +} +#endif + +// Refer to +// https://github.com/pytorch/pytorch/blob/b5b36cf0c4e1958f1ff25120f5d4beeef3288187/ +// aten/src/ATen/native/SharedReduceOps.h#L419-L445 +template +inline bool greater_or_nan( + scalar_t a, + scalar_t b, + int64_t idx_a, + int64_t idx_b) { + // If (a == b), then choose the one with lower idx, else max(a, b) + if (at::_isnan(a)) { + if (at::_isnan(b)) { + return idx_a < idx_b; + } + return true; + } + return (a == b) ? idx_a < idx_b : (a > b); +} + +template +inline bool less_or_nan(scalar_t a, scalar_t b, int64_t idx_a, int64_t idx_b) { + // If (a == b), then choose the one with lower idx, else min(a, b) + if (at::_isnan(a)) { + if (at::_isnan(b)) { + return idx_a < idx_b; + } + return true; + } + return (a == b) ? idx_a < idx_b : (a < b); +} + +template +inline IndexValue& argmin_combine( + IndexValue& a, + T next_value, + int64_t next_index) { + if (!(less_or_nan(a.value, next_value, a.index, next_index))) { + a.value = next_value; + a.index = next_index; + } + return a; +} +template +inline IndexValue& argmax_combine( + IndexValue& a, + T next_value, + int64_t next_index) { + if (!(greater_or_nan(a.value, next_value, a.index, next_index))) { + a.value = next_value; + a.index = next_index; + } + return a; +} +template +inline IndexValue& argmin_combine( + IndexValue& a, + const IndexValue& next) { + return argmin_combine(a, next.value, next.index); +} +template +inline IndexValue& argmax_combine( + IndexValue& a, + const IndexValue& next) { + return argmax_combine(a, next.value, next.index); +} + +#if INDUCTOR_USE_VECTOR_TYPES() + +template +inline at::vec::Vectorized div_floor_floating_vec( + const at::vec::Vectorized& a, + const at::vec::Vectorized& b) { + using vec_t = at::vec::Vectorized; + const auto basic_div = a / b; + vec_t inf(std::numeric_limits::infinity()); + auto mod = a.fmod(b); + // Fixup for a case that isn't properly handled by Sleef_fmod + auto floor = + vec_t::blendv(a - mod, a, (basic_div.abs() == inf) & (a.abs() != inf)); + auto div = floor / b; + const auto zero = vec_t(0); + auto mask = (mod != zero) & ((b < zero) ^ (mod < zero)); + const auto one = vec_t(1); + div = vec_t::blendv(div, div - one, mask); + auto floordiv = div.floor(); + mask = (div - floordiv) > vec_t(0.5); + floordiv = vec_t::blendv(floordiv, floordiv + one, mask); + floordiv = vec_t::blendv(floordiv, zero.copysign(basic_div), div == zero); + floordiv = vec_t::blendv(floordiv, basic_div, b == zero); + return floordiv; +}; + +template +inline at::vec::VectorizedN div_floor_floating_vec( + const at::vec::VectorizedN& a, + const at::vec::VectorizedN& b) { + at::vec::VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result[i] = div_floor_floating_vec(a[i], b[i]); + } + return result; +} + +template +struct IndexValueVec { + at::vec::VectorizedN value; + at::vec::VectorizedN index; + + IndexValueVec(const T _value) { + value = at::vec::VectorizedN(_value); + index = at::vec::VectorizedN(0); + }; + + IndexValueVec() {}; +}; + +template < + typename T, + int NV, + int NI, + typename std::enable_if_t, int> = 0> +at::vec::VecMask inline get_mask_for_argmin_argmax( + const at::vec::VecMask& vmask, + const IndexValueVec& a, + const at::vec::VectorizedN& value, + const at::vec::VectorizedN& index) { + /* + vec impl for less_or_nan and greater_or_nan + example for argmin: + a.value = [NaN, NaN, 0, 2, 1, 0] + value = [NaN, 0, 0, 1, 2, NaN] + vmask = [false, false, false, false, true, false] + all_nan_or_equal = [true, false, true, false, false, false] + imask = [a.index[0] < index[0], ..., a.index[-1] < index[-1]] + iv_mask = blendv (vmask, imask, all_nan_or_equal) + [a.index[0] < index[0], false, a.index[2] < index[2], false, true, + false] a_nan_b_not: [false, false, false, false, false, true] mask = iv_mask | + a_nan_b_not [a.index[0] < index[0], false, a.index[2] < index[2], false, true, + true] + */ + using v_t = at::vec::VecMask; + using i_t = at::vec::VecMask; + i_t vmask_itype = vmask.template cast(); + // use itype here since there is vec impl for operator~ for itype + // while there may not vec impl for vtype + v_t isnan_a = a.value.isnan(); + i_t isnan_a_itype = isnan_a.template cast(); + v_t isnan_b = value.isnan(); + i_t isnan_b_type = isnan_b.template cast(); + i_t all_nan_mask = isnan_a_itype & isnan_b_type; + v_t equal_mask = (a.value == value); + i_t equal_mask_itype = equal_mask.template cast(); + i_t all_nan_or_equal = all_nan_mask | equal_mask_itype; + i_t imask(a.index < index); + i_t iv_mask = i_t::blendv(vmask_itype, imask, all_nan_or_equal); + i_t isnan_a_notnan_b = isnan_a_itype & (~isnan_b_type); + return iv_mask | isnan_a_notnan_b; +} + +template < + typename T, + int NV, + int NI, + typename std::enable_if_t, int> = 0> +at::vec::VecMask inline get_mask_for_argmin_argmax( + const at::vec::VecMask& vmask, + const IndexValueVec& a, + const at::vec::VectorizedN& value, + const at::vec::VectorizedN& index) { + using v_t = at::vec::VecMask; + using i_t = at::vec::VecMask; + i_t vmask_itype = vmask.template cast(); + v_t equal_mask = (a.value == value); + i_t equal_mask_itype = equal_mask.template cast(); + i_t imask(a.index < index); + return i_t::blendv(vmask_itype, imask, equal_mask_itype); +} + +template +inline IndexValueVec& argmin_vec_impl( + IndexValueVec& a, + at::vec::VectorizedN value, + at::vec::VectorizedN index, + std::optional tail_size) { + at::vec::VecMask vmask(a.value < value); + at::vec::VecMask final_mask = + get_mask_for_argmin_argmax(vmask, a, value, index); + if (tail_size.has_value()) { + a.value = at::vec::VectorizedN::set( + a.value, at::vec::minimum(a.value, value), tail_size.value()); + a.index = at::vec::VectorizedN::set( + a.index, + at::vec::VecMask::blendv(index, a.index, final_mask), + tail_size.value()); + } else { + a.value = at::vec::minimum(a.value, value); + a.index = at::vec::VecMask::blendv(index, a.index, final_mask); + } + return a; +} + +template +inline IndexValueVec& argmax_vec_impl( + IndexValueVec& a, + at::vec::VectorizedN value, + at::vec::VectorizedN index, + std::optional tail_size) { + at::vec::VecMask vmask(a.value > value); + at::vec::VecMask final_mask = + get_mask_for_argmin_argmax(vmask, a, value, index); + if (tail_size.has_value()) { + a.value = at::vec::VectorizedN::set( + a.value, at::vec::maximum(a.value, value), tail_size.value()); + a.index = at::vec::VectorizedN::set( + a.index, + at::vec::VecMask::blendv(index, a.index, final_mask), + tail_size.value()); + } else { + a.value = at::vec::maximum(a.value, value); + a.index = at::vec::VecMask::blendv(index, a.index, final_mask); + } + return a; +} + +template +inline at::vec::VectorizedN create_index(int64_t next_index) { + at::vec::VectorizedN next_idx; + if constexpr (horizontal) { + next_idx = at::vec::VectorizedN::arange(next_index, 1); + } else { + next_idx = at::vec::VectorizedN(next_index); + } + return next_idx; +} + +template +inline IndexValueVec& argmin_combine_vec( + IndexValueVec& a, + at::vec::VectorizedN next_value, + int64_t next_index, + std::optional tail_size = std::nullopt) { + auto next_idx = create_index(next_index); + return argmin_vec_impl(a, next_value, next_idx, tail_size); +} + +template +inline IndexValueVec& argmax_combine_vec( + IndexValueVec& a, + at::vec::VectorizedN next_value, + int64_t next_index, + std::optional tail_size = std::nullopt) { + auto next_idx = create_index(next_index); + return argmax_vec_impl(a, next_value, next_idx, tail_size); +} + +template +inline IndexValue argmin_vec_reduce_all( + const IndexValueVec& vec) { + constexpr int len = at::vec::VectorizedN::size(); + __at_align__ T tmpval[len]; + __at_align__ int64_t tmpidx[len]; + vec.value.store(tmpval); + vec.index.store(tmpidx); + IndexValue res = IndexValue(tmpidx[0], tmpval[0]); + for (int i = 1; i < len; i++) { + res = argmin_combine(res, tmpval[i], tmpidx[i]); + } + return res; +} + +template +inline IndexValue argmax_vec_reduce_all( + const IndexValueVec& vec) { + constexpr int len = at::vec::VectorizedN::size(); + __at_align__ T tmpval[len]; + __at_align__ int64_t tmpidx[len]; + vec.value.store(tmpval); + vec.index.store(tmpidx); + IndexValue res = IndexValue(tmpidx[0], tmpval[0]); + for (int i = 1; i < len; i++) { + res = argmax_combine(res, tmpval[i], tmpidx[i]); + } + return res; +} + +template +inline IndexValueVec& argmin_combine_vec( + IndexValueVec& vec_a, + const IndexValueVec& vec_b, + std::optional tail_size = std::nullopt) { + return argmin_vec_impl(vec_a, vec_b.value, vec_b.index, tail_size); +} + +template +inline IndexValueVec& argmax_combine_vec( + IndexValueVec& vec_a, + const IndexValueVec& vec_b, + std::optional tail_size = std::nullopt) { + return argmax_vec_impl(vec_a, vec_b.value, vec_b.index, tail_size); +} + +template +inline at::vec::Vectorized vec_shuffle_down( + at::vec::Vectorized x, + size_t n) { + using Vec = at::vec::Vectorized; + alignas(alignof(Vec)) scalar_t array[Vec::size()]; + x.store(array); + for (size_t i = 0; i + n < Vec::size(); i += 2 * n) { + array[i] = array[i + n]; + } + return Vec::loadu(array); +} + +#ifdef CPU_CAPABILITY_AVX2 +inline at::vec::Vectorized vec_shuffle_down( + at::vec::Vectorized x, + size_t n) { + using vec_t = at::vec::Vectorized; +#define SHUFFLE_MASK(z, y, x, w) ((z << 6) | (y << 4) | (x << 2) | w) + switch (n) { + case 1: + return vec_t(_mm256_permute_ps(x, SHUFFLE_MASK(1, 1, 3, 3))); + case 2: + return vec_t(_mm256_permute_ps(x, SHUFFLE_MASK(2, 2, 2, 2))); + case 4: + return vec_t(_mm256_permute2f128_ps(x, x, SHUFFLE_MASK(1, 1, 1, 1))); + } + + TORCH_CHECK(false, "Unhandled vec_shuffle_down value ", n); +} +#endif + +#ifdef CPU_CAPABILITY_AVX512 +inline at::vec::Vectorized vec_shuffle_down( + at::vec::Vectorized x, + size_t n) { + using vec_t = at::vec::Vectorized; +#define SHUFFLE_MASK(z, y, x, w) ((z << 6) | (y << 4) | (x << 2) | w) + switch (n) { + case 1: + return vec_t(_mm512_permute_ps(x, SHUFFLE_MASK(1, 1, 3, 3))); + case 2: + return vec_t(_mm512_permute_ps(x, SHUFFLE_MASK(2, 2, 2, 2))); + case 4: + return vec_t(_mm512_permutexvar_ps( + _mm512_set_epi32( + 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4), + x)); + case 8: + return vec_t(_mm512_permutexvar_ps( + _mm512_set_epi32(8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8), x)); + } + + TORCH_CHECK(false, "Unhandled vec_shuffle_down value ", n); +} +#endif + +template +Welford welford_vec_reduce_all( + Welford> acc) { + using Vec = at::vec::Vectorized; + Welford result; + if (acc.index == 0) { + return result; + } + // if all values of acc.weight are same as index, + // use index to reduce to save the overhead of vec_shuffle_down for acc.weight + bool use_index = (acc.weight - Vec(acc.index)).zero_mask() == + static_cast((1 << Vec::size()) - 1); + for (size_t n = 1; n < Vec::size(); n *= 2) { + auto shuffled = Welford{ + vec_shuffle_down(acc.mean, n), + vec_shuffle_down(acc.m2, n), + use_index ? Vec(0) : vec_shuffle_down(acc.weight, n), + acc.index}; + acc = welford_combine(acc, shuffled, use_index); + } + + alignas(alignof(Vec)) scalar_t array[Vec::size()]; + acc.mean.store(array); + result.mean = array[0]; + + acc.m2.store(array); + result.m2 = array[0]; + + acc.weight.store(array); + result.weight = array[0]; + result.index = result.weight; + + return result; +} + +template +Welford welford_vec_reduce_all( + Welford> acc) { + auto Welford0 = Welford>{ + acc.mean[0], acc.m2[0], acc.weight[0], acc.index}; + auto Welford1 = Welford>{ + acc.mean[1], acc.m2[1], acc.weight[1], acc.index}; + return welford_vec_reduce_all(welford_combine(Welford0, Welford1)); +} +#endif + +template +inline typename std::common_type_t mod(T a, U b) { + return a % b; +} +template <> +inline float mod(float a, float b) { + return std::fmod(a, b); +} +template <> +inline double mod(double a, double b) { + return std::fmod(a, b); +} + +template +inline scalar_t max_propagate_nan(scalar_t a, scalar_t b) { + if (at::_isnan(a)) { + return a; + } + return a > b ? a : b; +} + +template +inline scalar_t min_propagate_nan(scalar_t a, scalar_t b) { + if (at::_isnan(a)) { + return a; + } + return a < b ? a : b; +} + +constexpr float uint32_to_uniform_float(uint32_t value) { + // maximum value such that `MAX_INT * scale < 1.0` (with float rounding) + constexpr float scale = 4.6566127342e-10; + return static_cast(value & 0x7FFFFFFF) * scale; +} + +inline float normalized_rand_cpu(uint32_t seed, uint32_t offset) { + return uint32_to_uniform_float(at::Philox4_32(seed, 0, offset)()); +} + +inline float randn_cpu(uint32_t seed, uint32_t offset) { + at::Philox4_32 engine(seed, 0, offset); + return engine.randn(10); +} + +inline int64_t randint64_cpu( + uint32_t seed, + uint32_t offset, + int64_t low, + int64_t high) { + auto gen = at::Philox4_32(seed, 0, offset); + uint64_t r0 = gen(); + uint64_t r1 = gen(); + uint64_t result = r0 | (r1 << 32); + return static_cast(result % (high - low)) + low; +} + +template +struct AsIntegerType { + typedef T type; +}; +template <> +struct AsIntegerType { + typedef uint32_t type; +}; +template <> +struct AsIntegerType { + typedef uint64_t type; +}; +template <> +struct AsIntegerType { + typedef uint16_t type; +}; + +template +typename std::enable_if_t< + !c10::is_reduced_floating_point_v, + T> inline fetch_value(volatile T* addr) { + return *addr; +} + +template +typename std::enable_if_t< + c10::is_reduced_floating_point_v, + T> inline fetch_value(volatile T* addr) { + return T(addr->x, T::from_bits()); +} + +template +typename std::enable_if_t> atomic_add( + volatile T* addr, + T offset) { + typedef typename AsIntegerType::type alt_type; + + static_assert( + sizeof(std::atomic) == sizeof(T), "std::atomic issue"); + + alt_type expected; + + alt_type desired; + + std::atomic* atomic_addr = (std::atomic*)addr; + do { + T val = fetch_value(addr); + reinterpret_cast(&expected)[0] = val; + reinterpret_cast(&desired)[0] = val + offset; + } while (!atomic_addr->compare_exchange_weak( + expected, desired, std::memory_order_relaxed)); +} + +// Since C++20 float is supported by fetch_add, but the performance may not +// better than compare_exchange_weak, which can be checked by microbenchmark +// inductor_cpu_atomic.py +template +typename std::enable_if_t> atomic_add( + volatile T* addr, + T offset) { + static_assert(sizeof(std::atomic) == sizeof(T), "std::atomic issue"); + std::atomic* atomic_addr = (std::atomic*)addr; + atomic_addr->fetch_add(offset, std::memory_order_relaxed); +} + +#if INDUCTOR_USE_VECTOR_TYPES() +template +void atomic_add_vec( + T* addr, + at::vec::VectorizedN index, + at::vec::VectorizedN offset, + std::optional tail_size = std::nullopt) { + constexpr int len = at::vec::VectorizedN::size(); + static_assert(len <= at::vec::VectorizedN::size()); + __at_align__ std::array tmpbuf; + __at_align__ std::array tmpidx; + offset.store(tmpbuf.data(), len); + index.store(tmpidx.data(), len); + int size = tail_size.has_value() ? tail_size.value() : len; + for (int i = 0; i < size; i++) { + atomic_add(addr + tmpidx[i], tmpbuf[i]); + } +} + +template +struct transpose_mxn_helper; + +template +struct transpose_mxn_helper { + static void call( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst, + int M, + int N) { + for (int i = 0; i < M; i++) { + for (int j = 0; j < N; j++) { + atomic_add(&dst[j * ld_dst + i], src[i * ld_src + j]); + } + } + } +}; + +template +struct transpose_mxn_helper { + static void call( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst, + int M, + int N) { + at::vec::transpose_mxn(src, ld_src, dst, ld_dst, M, N); + } +}; + +template +inline void transpose_mxn( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst, + int M, + int N) { + transpose_mxn_helper::call(src, ld_src, dst, ld_dst, M, N); +} + +template +inline void transpose_mxn( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst) { + transpose_mxn(src, ld_src, dst, ld_dst, M, N); +} +#endif + +// NOLINTBEGIN(*-avoid-c-arrays) +inline std::tuple, int> _get_factors( + int64_t number) { + int count = 0; + for (auto i = static_cast(std::sqrt(number)); i > 0; --i) { + if (number % i == 0) { + count += 2; + } + } + auto factors = std::shared_ptr(new int64_t[count]); + int index = 0; + for (auto i = static_cast(std::sqrt(number)); i > 0; --i) { + if (number % i == 0) { + factors[index++] = number / i; + factors[index++] = i; + } + } + return std::make_tuple(factors, count); +} + +inline std::tuple, int> get_factors(int64_t number) { + thread_local std::map, int>> + cache; + auto it = cache.find(number); + if (it != cache.end()) { + return it->second; + } else { + auto factors = _get_factors(number); + cache[number] = factors; + return factors; + } +} +// NOLINTEND(*-avoid-c-arrays) + +inline void _mm_get_thread_blocking( + int num_threads, + int max_k_slices, + int64_t M, + int64_t N, + int64_t K, + int64_t Mr, + int64_t Nr, + int64_t Kr, + int64_t& Mt, + int64_t& Nt, + int64_t& Kt) { + // see NOTE [Thread blocking in Cpp GEMM] for heuristics + Mt = Nt = Kt = 0; + + auto get_blocking = [](int64_t m_factor, + int64_t n_factor, + int64_t k_factor, + int64_t m_blocks, + int64_t n_blocks, + int64_t k_blocks) { + int64_t thread_block_k = (k_blocks + k_factor - 1) / k_factor; + int64_t thread_block_n = (n_blocks + n_factor - 1) / n_factor; + int64_t thread_block_m = (m_blocks + m_factor - 1) / m_factor; + return std::make_tuple(thread_block_m, thread_block_n, thread_block_k); + }; + + auto is_better_blocking = [=](int64_t Mt_, + int64_t Nt_, + int64_t Kt_, + int64_t Mt, + int64_t Nt, + int64_t Kt) { + return Mt == 0 || Kt_ < Kt || Mt_ * Mr + Nt_ * Nr < Mt * Mr + Nt * Nr; + }; + + int64_t m_blocks = (M + Mr - 1) / Mr; + int64_t n_blocks = (N + Nr - 1) / Nr; + int64_t k_blocks = (K + Kr - 1) / Kr; + + auto [factors, count] = get_factors(num_threads); + assert(count > 0); + + for (int i = 0; i < count; ++i) { + int64_t n_factor = factors[i]; + int64_t m_factor = num_threads / n_factor; + if (n_blocks >= n_factor && m_blocks >= m_factor) { + auto [Mt_, Nt_, Kt_] = + get_blocking(m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks); + if (is_better_blocking(Mt_, Nt_, Kt_, Mt, Nt, Kt)) { + std::tie(Mt, Nt, Kt) = std::make_tuple(Mt_, Nt_, Kt_); + } + } + } + + if (Mt != 0) { + return; + } + + for (int i = 0; i < count; ++i) { + int64_t k_factor = factors[i]; + if (k_blocks >= k_factor && + (max_k_slices == 0 || k_factor <= max_k_slices)) { + auto [mxn_factors, mxn_count] = get_factors(num_threads / k_factor); + for (int j = 0; j < mxn_count; ++j) { + int64_t n_factor = mxn_factors[j]; + int64_t m_factor = num_threads / (k_factor * n_factor); + if (n_blocks >= n_factor && m_blocks >= m_factor) { + auto [Mt_, Nt_, Kt_] = get_blocking( + m_factor, n_factor, k_factor, m_blocks, n_blocks, k_blocks); + if (is_better_blocking(Mt_, Nt_, Kt_, Mt, Nt, Kt)) { + std::tie(Mt, Nt, Kt) = std::make_tuple(Mt_, Nt_, Kt_); + } + } + } + } + } + + if (Mt != 0) { + return; + } + + for (int i = 0; i < count; ++i) { + int64_t n_factor = factors[i]; + int64_t m_factor = num_threads / n_factor; + if (n_blocks >= n_factor || m_blocks >= m_factor) { + auto [Mt_, Nt_, Kt_] = + get_blocking(m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks); + if (is_better_blocking(Mt_, Nt_, Kt_, Mt, Nt, Kt)) { + std::tie(Mt, Nt, Kt) = std::make_tuple(Mt_, Nt_, Kt_); + } + } + } + + assert(Mt != 0); +} + +inline void mm_get_thread_blocking( + int num_threads, + int max_k_slices, + int64_t M, + int64_t N, + int64_t K, + int64_t Mr, + int64_t Nr, + int64_t Kr, + int64_t& Mt, + int64_t& Nt, + int64_t& Kt) { + thread_local std::map< + std:: + tuple, + std::tuple> + cache; + auto key = std::make_tuple(num_threads, max_k_slices, M, N, K, Mr, Nr, Kr); + auto it = cache.find(key); + if (it != cache.end()) { + std::tie(Mt, Nt, Kt) = it->second; + return; + } else { + _mm_get_thread_blocking( + num_threads, max_k_slices, M, N, K, Mr, Nr, Kr, Mt, Nt, Kt); + cache[key] = std::make_tuple(Mt, Nt, Kt); + } +} + +// NOLINTBEGIN(*-narrowing-conversions) +template +void _mm_get_cache_blocking( + int num_threads, + int64_t M, + int64_t N, + int64_t K, + int64_t Mr, + int64_t Nr, + int64_t Kr, + int64_t Mt_blocks, + int64_t Nt_blocks, + int64_t Kt_blocks, + int64_t& Mc_blocks, + int64_t& Nc_blocks, + int64_t& Kc_blocks, + uint32_t L1_cache_size, + uint32_t L2_cache_size) { + // See NOTE [CPP GEMM Cache Blocking Algorithm] for the cache blocking + // algorithm. + // TODO(jgong5): cache cache blocking results + // TODO: tune the factor here + float L1_limit_factor = 0.8; + float L2_limit_factor = 0.5; + + auto L1 = L1_cache_size * L1_limit_factor; + auto L2 = L2_cache_size * L2_limit_factor; + + constexpr size_t num_byte_A = sizeof(X_t); + constexpr size_t num_byte_B = sizeof(W_t); + + int64_t size_cache_B = Kr * Kt_blocks * Nr * num_byte_B; + Kc_blocks = Kt_blocks; + if (size_cache_B > L1) { + Kc_blocks = (int64_t)std::floor(L1 / (Kr * Nr * num_byte_B)); + } + + float min_Mc_ratio = 2; + int64_t min_Mc_blocks = std::ceil(min_Mc_ratio * Mr / Nr); + auto Kt_bytes = Kt_blocks * Kr * num_byte_A; + if (min_Mc_blocks * Mr * Kt_bytes < L2) { + Mc_blocks = std::min(Mt_blocks, (int64_t)std::floor(L2 / (Mr * Kt_bytes))); + Nc_blocks = 1; + } else { + Mc_blocks = Mt_blocks; + Nc_blocks = + std::min((int64_t)std::ceil((float)Mc_blocks * Mr / Nr), Nt_blocks); + auto Nc_bytes = Nc_blocks * Nr * 4; + auto Kc_bytes = Kc_blocks * Kr * num_byte_A; + if (Mc_blocks * Mr * (Kc_bytes + Nc_bytes) > L2) { + auto M_max = (std::sqrt(Kc_bytes * Kc_bytes + 16 * L2) - Kc_bytes) / 8; + if (M_max < Mc_blocks * Mr) { + Mc_blocks = (int64_t)std::floor(M_max / Mr); + Nc_blocks = + std::min((int64_t)std::ceil((float)Mc_blocks * Mr / Nr), Nt_blocks); + } + } + } +} +// NOLINTEND(*-narrowing-conversions) + +template +void mm_get_cache_blocking( + int num_threads, + int64_t M, + int64_t N, + int64_t K, + int64_t Mr, + int64_t Nr, + int64_t Kr, + int64_t Mt_blocks, + int64_t Nt_blocks, + int64_t Kt_blocks, + int64_t& Mc_blocks, + int64_t& Nc_blocks, + int64_t& Kc_blocks, + uint32_t L1_cache_size, + uint32_t L2_cache_size) { + thread_local std::map< + std::tuple< + int, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t>, + std::tuple> + cache; + auto key = std::make_tuple( + num_threads, + M, + N, + K, + Mr, + Nr, + Kr, + Mt_blocks, + Nt_blocks, + Kt_blocks, + L1_cache_size, + L2_cache_size); + auto it = cache.find(key); + if (it != cache.end()) { + std::tie(Mc_blocks, Nc_blocks, Kc_blocks) = it->second; + return; + } else { + _mm_get_cache_blocking( + num_threads, + M, + N, + K, + Mr, + Nr, + Kr, + Mt_blocks, + Nt_blocks, + Kt_blocks, + Mc_blocks, + Nc_blocks, + Kc_blocks, + L1_cache_size, + L2_cache_size); + cache[key] = std::make_tuple(Mc_blocks, Nc_blocks, Kc_blocks); + } +} + +struct amx_tilecfg { + uint8_t palette_id{0}; + uint8_t start_row{0}; + std::array reserved_0{}; + std::array colsb{}; + std::array rows{}; +}; + +class AMXState { + private: + amx_tilecfg tilecfg_{}; + uint8_t rows_{0}; + uint16_t colsb_{0}; + uint8_t num_tile_rows_{0}; + uint8_t num_tile_columns_{0}; + + public: + AMXState() = default; + + inline void configure( + uint8_t rows, + uint16_t colsb, + uint8_t num_tile_rows, + uint8_t num_tile_columns, + void (*loadconfig)(const amx_tilecfg&)) { + if (tilecfg_.palette_id == 1 && rows_ == rows && colsb_ == colsb && + num_tile_rows_ == num_tile_rows && + num_tile_columns_ == num_tile_columns) { + return; + } + tilecfg_.palette_id = 1; + rows_ = rows; + colsb_ = colsb; + num_tile_rows_ = num_tile_rows; + num_tile_columns_ = num_tile_columns; + const auto num_c_tiles = num_tile_rows * num_tile_columns; + // For C + for (int i = 0; i < num_c_tiles; i++) { + tilecfg_.rows[i] = rows; + tilecfg_.colsb[i] = 64; + } + // For A + for (int i = 0; i < num_tile_rows; i++) { + tilecfg_.rows[i + num_c_tiles] = rows; + tilecfg_.colsb[i + num_c_tiles] = colsb; + } + // For B + for (int i = 0; i < num_tile_columns; i++) { + tilecfg_.rows[i + num_c_tiles + num_tile_rows] = colsb / 4; + tilecfg_.colsb[i + num_c_tiles + num_tile_rows] = 64; + } + loadconfig(tilecfg_); + } + + inline void release(void (*tile_release)()) { + tilecfg_.palette_id = 0; + tile_release(); + } +}; + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/array_ref.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/array_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..3ff757120d49fa01155e8e20626bff05d9a0c9fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/array_ref.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/common.h new file mode 100644 index 0000000000000000000000000000000000000000..a335699653e1a4cce726683b08e0e7f8b3891f94 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/common.h @@ -0,0 +1,80 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +// Include some often-used cpp_wrapper headers, for precompiling. +#include +#include +#include +#include +#include +#include + +namespace py = pybind11; // NOLINT(misc-unused-alias-decls) + +class RAIIPyObject { + public: + RAIIPyObject() = default; + // steals a reference to a PyObject + RAIIPyObject(PyObject* obj) : obj_{obj} {} + RAIIPyObject(const RAIIPyObject& other) : obj_{other.obj_} { + Py_XINCREF(obj_); + } + RAIIPyObject(RAIIPyObject&& other) noexcept { + // refcount doesn't change, and obj_ is currently nullptr + std::swap(obj_, other.obj_); + } + ~RAIIPyObject() { + Py_XDECREF(obj_); + } + RAIIPyObject& operator=(const RAIIPyObject& other) { + if (this != &other) { + Py_XDECREF(obj_); + obj_ = other.obj_; + Py_XINCREF(obj_); + } + return *this; + } + RAIIPyObject& operator=(RAIIPyObject&& other) noexcept { + // refcount to the current object decreases, but refcount to other.obj_ is + // the same + Py_XDECREF(obj_); + obj_ = std::exchange(other.obj_, nullptr); + return *this; + } + operator bool() const noexcept { + return obj_; + } + operator PyObject*() { + return obj_; + } + PyObject* get() { + return obj_; + } + + private: + PyObject* obj_{nullptr}; +}; + +#include +#include +using namespace torch::aot_inductor; + +#include +#include + +// Round up to the nearest multiple of 64 +[[maybe_unused]] inline int64_t align(int64_t nbytes) { + return (nbytes + 64 - 1) & -64; +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..e98e987de358efd0ad1c810d837cae8205bbb33c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cpu.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..04e34e99ff997f6701ba699c3a50542274228429 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cuda.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..98fd14fb45fc6138446fcc80b9148b3471d4ebde --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h @@ -0,0 +1,8 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..2f9e7104c1b2a16f8d4a0dbd920e6a2816f059a2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cuda.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/mps.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/mps.h new file mode 100644 index 0000000000000000000000000000000000000000..7711a5e019966c970818c5e7082a5b99f22856e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/mps.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/xpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..eda98fd2052767ac360e31245fa94a9e350cbdaf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/xpu.h @@ -0,0 +1,10 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/mps.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/mps.h new file mode 100644 index 0000000000000000000000000000000000000000..00d4464071f64f8c46df042813e6bd56222a304e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/mps.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/xpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..787def8bd78bb93e2afc4dd16f025f90dec14ab7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/xpu.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/inductor_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/inductor_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..77eef6c69f5eb4725fcf08489bf57e27dd97ae30 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/inductor_ops.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::inductor { + +TORCH_API at::Tensor _mm_plus_mm_out( + at::Tensor& out, + const at::Tensor& a, + const at::Tensor& b, + const at::Tensor& c, + const at::Tensor& d); + +// After adding _mm_plus_mm_out, this should not be exposed and called by model +// code. Keeping it around for backward compatibility. Will be deprecated later. +TORCH_API at::Tensor _mm_plus_mm( + const at::Tensor& a, + const at::Tensor& b, + const at::Tensor& c, + const at::Tensor& d, + at::Tensor& out); + +TORCH_API at::Tensor _alloc_from_pool( + const at::Tensor& self, + int64_t offset_bytes, + at::ScalarType dtype, + at::IntArrayRef size, + at::IntArrayRef stride); + +// Similar to as_strided with the following differences +// - offset is added to the existing offset (rather than replacing it) +// - view tracking is disabled similar to unsafe_view +TORCH_API at::Tensor _reinterpret_tensor( + const at::Tensor& self, + at::IntArrayRef size, + at::IntArrayRef stride, + int64_t offset_increment = 0); + +} // namespace torch::inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/static_cuda_launcher.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/static_cuda_launcher.h new file mode 100644 index 0000000000000000000000000000000000000000..b28a38e70236d66e2ba2c927bf20e855c7612130 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/static_cuda_launcher.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#if defined(USE_CUDA) && !defined(USE_ROCM) +#include +#include + +bool StaticCudaLauncher_init(PyObject* module); +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/instruction_counter/Module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/instruction_counter/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..b7fbac85c979734a709aef89819ae609e54b6686 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/instruction_counter/Module.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::instruction_counter { + +void initModule(PyObject* module); + +} // namespace torch::instruction_counter + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/compilation_unit.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/compilation_unit.h new file mode 100644 index 0000000000000000000000000000000000000000..e6264f6f992a61123df6647a90176397261bc47f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/compilation_unit.h @@ -0,0 +1,356 @@ +#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 + +namespace torch::jit { + +struct Def; +struct Property; +struct ClassDef; +struct SugaredValue; +struct Resolver; + +using ResolverPtr = std::shared_ptr; +struct Self { + virtual ~Self() = default; + virtual std::shared_ptr makeSugared(Value* v) const = 0; + virtual ClassTypePtr getClassType() const = 0; +}; + +// A CompilationUnit is a list of named Functions +// with helper methods to iterate the list or invoke the function. +// Classes have a CompilationUnit holding the class methods, +// and Modules have a CompilationUnit holding the Functions that +// are used to implement their Methods + +struct TORCH_API CompilationUnit { + enum class FunctionType { Method, Hook, PreHook }; + // constructor that takes a set of functions to compile using the native + // resolver + explicit CompilationUnit(const std::string& source); + CompilationUnit() = default; + + CompilationUnit& operator=(CompilationUnit&&) = default; + CompilationUnit(CompilationUnit&&) = default; + CompilationUnit& operator=(const CompilationUnit&) = delete; + CompilationUnit(const CompilationUnit&) = delete; + + Function* find_function(const c10::QualifiedName& name) const { + auto it = dict_.find(name); + if (it == dict_.end()) { + return nullptr; + } + return functions_[it->second].get(); + } + + Function& get_function(const c10::QualifiedName& name) const { + if (auto r = find_function(name)) { + return *r; + } + TORCH_CHECK(false, "attempted to get undefined function ", name.name()); + } + + void set_optimized(bool o) { + TORCH_WARN( + "CompilationUnit::set_optimized() is deprecated and has no effect. " + "Please use setGraphExecutorOptimize()"); + } + + bool is_optimized() const { + TORCH_WARN( + "CompilationUnit::is_optimized() is deprecated and always returns true. " + "Please use getGraphExecutorOptimize()"); + return true; + } + + // for historic reasons, these are defined in ir_emitter.cpp + // Returns the list of Functions just defined. + std::vector define( + const std::optional& prefix, + const std::vector& properties, + const std::vector& propResolvers, + const std::vector& definitions, + const std::vector& + defResolvers, /* determines how we handle free + variables in each definition*/ + // if non-null, the first argument to each def, is bound to this value + const Self* self, + // see [name mangling] + bool shouldMangle = false, + std::optional operator_set_version = std::nullopt); + + void define_hooks( + const std::optional& prefix, + const std::vector& hookDefs, + const std::vector& hookResolvers, + const std::vector& preHookDefs, + const std::vector& preHookResolvers, + const Self* self, + bool shouldMangle = false); + + // same as above but parse the definitions from source + // Returns the list of Functions just defined. + std::vector define( + // prefix namespace to put all the defined functions into + const std::optional& prefix, + const std::string& source, + const ResolverPtr& resolver, + const Self* self); + + void define_interface( + const c10::QualifiedName& qualifiedName, + const ClassDef& classDef, + ResolverPtr rcb, + bool is_module = false); + + Function* create_function( + c10::QualifiedName name, + std::shared_ptr graph, + bool shouldMangle = false) { + if (shouldMangle) { + name = mangle(name); + } + auto fn = std::make_unique( + std::move(name), std::move(graph), nullptr); + auto ret = fn.get(); + register_function(std::move(fn)); + return ret; + } + + std::vector get_functions() const { + return fmap(functions_, [](const std::unique_ptr& fn) { + return fn.get(); + }); + } + + /// Run a method from this compilation. + /// + /// For example: + /// @code + /// IValue output = module->run("relu_script", a, b); + /// @endcode + /// + /// To get a compile a module from a source string, see torch::jit::compile + /// + /// @param method_name The name of the method to run + /// @param args Arguments to be passed to the method + /// @return An IValue containing the return value (or values if it is a tuple) + /// from the method + template + IValue run_method(const c10::QualifiedName& method_name, Types&&... args) { + return get_function(method_name)({IValue(std::forward(args))...}); + } + + void drop_all_functions() { + dict_.clear(); + functions_.clear(); + } + + /** + * Register a class as being owned by this compilation unit. + */ + void register_type(c10::NamedTypePtr namedType) { + // TODO: class types cannot be redefined because we have no way right now + // of invalidating their methods. NamedTuples are fine though, since they + // don't have methods. + TORCH_CHECK( + 0 == classDict_.count(*namedType->name()), + "class '", + namedType->name()->qualifiedName(), + "' already defined."); + classes_.push_back(std::move(namedType)); + classDict_[*classes_.back()->name()] = classes_.size() - 1; + } + + c10::ClassTypePtr get_class(const c10::QualifiedName& name) const { + auto type = get_type(name); + if (!type) { + return nullptr; + } + return type->cast(); + } + + c10::InterfaceTypePtr get_interface(const c10::QualifiedName& name) const { + auto type = get_type(name); + if (!type) { + return nullptr; + } + return type->cast(); + } + + c10::TupleTypePtr get_named_tuple(const c10::QualifiedName& name) const { + for (const auto& cls : classes_) { + if (cls->name()->qualifiedName() == name.qualifiedName()) { + return cls->expect(); + } + } + return nullptr; + } + + c10::NamedTypePtr get_type(const c10::QualifiedName& name) const { + auto it = classDict_.find(name); + if (it == classDict_.end()) { + return nullptr; + } + return classes_[it->second]; + } + + // For testing: clear all Python-defined classes to ensure that unit tests + // have isolation. + void _clear_python_cu() { + // Delete all the associated class methods + for (const auto& type : classes_) { + if (auto cls = type->cast()) { + for (auto method : cls->methods()) { + // Tombstone the method in the compilation unit. + // Don't erase because the dict_ + auto it = dict_.find(method->qualname()); + if (it != dict_.end()) { + functions_[it->second] = nullptr; + // Erase in our big lookup table + dict_.erase(it); + } + } + // Classes can have multiple pointers to the same hook, + // need to make sure to not delete it twice + std::unordered_set hooks_to_delete; + for (const auto& hook : cls->getForwardHooks()) { + hooks_to_delete.insert(hook); + } + for (const auto& pre_hook : cls->getForwardPreHooks()) { + hooks_to_delete.insert(pre_hook); + } + for (const auto& hook : hooks_to_delete) { + // Tombstone the hook in the compilation unit. + auto it = dict_.find(hook->qualname()); + if (it != dict_.end()) { + functions_[it->second] = nullptr; + // Erase in our big lookup table + dict_.erase(it); + } + } + } + } + classes_.clear(); + classDict_.clear(); + } + + // [Internal Only] Remove method. + // Note Used for freezing. + void unsafeRemoveMethod(const c10::QualifiedName& method_name) { + auto it = dict_.find(method_name); + TORCH_CHECK( + it != dict_.end(), + "method '", + method_name.qualifiedName(), + "' does not exist."); + functions_[it->second] = nullptr; + dict_.erase(it); + } + + // [name mangling] All code objects must have a unique qualified name in a + // CompilationUnit. In Python, sometimes functions won't have unique qualified + // name (for example, nested functions). So we mangle Python functions to + // ensure that they are uniquely named. + // + // We also use mangling to distinguish different Module instances. Since each + // Module is a singleton class instance, different instances of the same + // Python Module will have different types but the same qualified name. + c10::QualifiedName mangle(const c10::QualifiedName& name) const { + auto mangled = name; + while (get_type(mangled) || find_function(mangled)) { + mangled = mangler_.mangle(mangled); + } + return mangled; + } + + private: + std::unique_ptr define( + const std::optional& prefix, + const Def& def, + const ResolverPtr& resolver, + const Self* self, + const std::unordered_map& function_table, + bool shouldMangle = false, + FunctionType type = FunctionType::Method, + std::optional version = std::nullopt) const; + + // Define a property on \p self. + struct PropertyPair; + PropertyPair define_property( + const std::optional& prefix, + const Property& prop, + const ResolverPtr& resolver, + const Self* self, + const std::unordered_map& function_table, + bool shouldMangle = false) const; + + Function& register_function(std::unique_ptr fn) { + TORCH_CHECK( + 0 == dict_.count(fn->qualname().qualifiedName()), + "method '", + fn->qualname().qualifiedName(), + "' already defined."); + functions_.emplace_back(std::move(fn)); + dict_[functions_.back()->qualname()] = functions_.size() - 1; + return *functions_.back(); + } + std::vector> functions_; + // for fast lookup + std::unordered_map dict_; + std::unordered_map classDict_; + + // [class ownership] Right now there are two relationships between classes + // and compilation units: + // 1. Classes have compilation units internally that hold their methods. + // 2. On load, the TypePtrs of any imported classes are owned by the main + // module's compilation unit. + std::vector classes_; + + mutable NameMangler mangler_; +}; + +// An owning pointer to a Function. Just a pair of a raw Function ptr and it's +// owning CU. We need this because pybind requires a ref-counted way to refer to +// Functions. +struct StrongFunctionPtr { + StrongFunctionPtr(std::shared_ptr cu, Function* function) + : cu_(std::move(cu)), function_(function) { + TORCH_INTERNAL_ASSERT(cu_); + TORCH_INTERNAL_ASSERT(function_); + } + std::shared_ptr cu_; + Function* function_; +}; + +namespace script { +// We once had a `script::` namespace that was deleted. This is for backcompat +// of the public API; new code should not use this type alias. +using CompilationUnit = ::torch::jit::CompilationUnit; +} // namespace script +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/function_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/function_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..e311563890e13e39c5382b582953433131ab62cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/function_impl.h @@ -0,0 +1,185 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +struct TORCH_API GraphFunction : public Function { + GraphFunction( + c10::QualifiedName name, + std::shared_ptr graph, + std::function function_creator, + std::optional executor_execution_mode = + std::nullopt) + : name_(std::move(name)), + graph_(std::move(graph)), + executor_execution_mode_(executor_execution_mode), + function_creator_(std::move(function_creator)) {} + + bool isGraphFunction() const override { + return true; + } + + void run(Stack& stack) override; + + std::function function_creator() const { + return function_creator_; + } + + c10::intrusive_ptr runAsync( + Stack& stack, + TaskLauncher taskLauncher = at::launch) override; + + std::shared_ptr graph() const { + return graph_; + } + + std::shared_ptr optimized_graph() const; + + const c10::QualifiedName& qualname() const override { + return name_; + } + + // private/unstable api. sets the initial execution mode + // will not affect executor if there is an existing executor + // created for this function + void _set_initial_executor_execution_mode(ExecutorExecutionMode mode) { + executor_execution_mode_ = mode; + } + // private/unstable api. sets flag of whether or not to ignore amp. + // will not affect executor if there is an existing executor + // created for this function + void _set_ignore_amp(bool ignore_amp) { + force_no_amp_ = ignore_amp; + } + + // if this isn't yet defined, run its method_creator function + void ensure_defined() override; + + size_t num_inputs() const override { + return graph()->inputs().size(); + } + + Function& setSchema(FunctionSchema schema) override { + schema_ = std::make_unique(std::move(schema)); + return *this; + } + + const FunctionSchema& getSchema() const override; + + GraphExecutorState getDebugState() { + return get_executor().getDebugState(); + } + + bool is_optimized() const { + TORCH_WARN( + "GraphFunction::is_optimized() is deprecated and always returns true. " + "Please use getGraphExecutorOptimize()"); + return true; + } + + void check_single_output() { + TORCH_CHECK( + graph()->outputs().size() == 1, + "Method (but not graphs in general) require a single output. Use None/Tuple for 0 or 2+ outputs"); + } + + GraphExecutor& get_executor() { + ensure_defined(); + std::lock_guard lock(compile_mutex); + auto& executor = executors_[currentSpecialization()]; + if (executor) { + return *executor; + } + check_single_output(); + const std::string& name = name_.name(); + std::shared_ptr opt_graph = optimized_graph(); + if (!executor_execution_mode_) { + executor = GraphExecutor(opt_graph, name); + } else { + executor = GraphExecutor(opt_graph, name, *executor_execution_mode_); + } + return *executor; + } + + using Function::call; + bool call( + Stack& stack, + std::optional bailOut, + c10::function_ref f) override { + f(get_executor().getPlanFor(stack, bailOut).code); + return true; + } + + void clear_optimized_graphs() { + optimized_graphs_.fill(nullptr); + } + + private: + enum SpecializationKey { + AutocastOff, + CpuAutocastOn, + GpuAutocastOn, + CpuGpuAutocastOn, + + // This provides the number of specializations + // (Must be last entry) + TotalCount + }; + + SpecializationKey currentSpecialization() const; + + private: + c10::QualifiedName name_; + // The original, non-optimized graph + std::shared_ptr graph_; // for debugging and for inlining + + // allows users to specify Simple/Profiling Executor for function + // TODO: add more executors + mutable std::optional executor_execution_mode_; + + // if invoked on a graph that has already traced through amp + // don't invoke amp pass + mutable bool force_no_amp_ = false; + // Optimized graph, computed lazily. Used for inlining. + mutable std::array, SpecializationKey::TotalCount> + optimized_graphs_; + + // GraphFunctions are invocable from multiple threads, so this lock needs to + // be held when we're initializing graph executor for the first time or + // computing the optimized graph. We're using reentrant mutex so that we don't + // need to worry about causing a deadlock by calling one method from another + // (e.g. optimized_graph() from get_executor()). + mutable std::recursive_mutex compile_mutex; + + // executor_[0] - autocast off + // executor_[1] - autocast cpu on + // executor_[2] - autocast gpu on + // executor_[3] - autocast cpu & gpu on + std::array, SpecializationKey::TotalCount> + executors_; + + // an optional function that actually creates the method when + // ensure_defined() is called. This is used by the compiler so + // that it can construct methods out of order + std::function function_creator_; + + // if absent, then we generate a default schema based on the graph + // mutable because getSchema caches the default schema if one is requested + // before a call to setSchema + mutable std::unique_ptr schema_; +}; + +// Short hands for dynamic_cast. +TORCH_API GraphFunction* tryToGraphFunction(Function& /*function*/) noexcept; +TORCH_API GraphFunction& toGraphFunction(Function& /*function*/); +TORCH_API const GraphFunction& toGraphFunction(const Function& /*function*/); +} // namespace torch::jit +C10_DECLARE_bool(torch_jit_do_not_store_optimized_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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/method.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/method.h new file mode 100644 index 0000000000000000000000000000000000000000..d138f8f847d2d0074f0b1669022fa0f4b3e811f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/method.h @@ -0,0 +1,91 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +using ObjectPtr = c10::intrusive_ptr; + +// A method in a module, e.g. f in: +// +// class M(ScriptModule): +// @script_method +// def f(self, x): +// ... +// Note: because Method/Module are exposed to python these +// classes use python method naming conventions +struct TORCH_API Method : public torch::IMethod { + Method(ObjectPtr owner, Function* function); + + // the module that contains this method. + Module owner() const; + // the raw objectptr that owns this method, for when the method is owned by a + // torchbind object. + ObjectPtr raw_owner() const; + void run(Stack& stack); + void run(Stack&& stack) { + run(stack); + } + + c10::IValue operator()( + std::vector stack, + const Kwargs& kwargs = Kwargs()) const override; + + // Run method async. Invocation on this function would invokes a JIT + // interpreter that executes ops inline, one by one, on caller's thread. A + // model can utilize async op, i.e. `fork`, to launch an asynchronous task + // which will be launched on provided `taskLauncher`. + c10::intrusive_ptr run_async( + std::vector stack, + const Kwargs& kwargs = Kwargs(), + TaskLauncher taskLauncher = at::launch); + + std::shared_ptr graph() const { + return toGraphFunction(*function_).graph(); + } + + const std::string& name() const override { + return function_->name(); + } + + size_t num_inputs() const { + return function_->num_inputs(); + } + + GraphExecutor& get_executor() { + return toGraphFunction(*function_).get_executor(); + } + + Function& function() const { + return *function_; + } + + private: + void setArgumentNames( + std::vector& /*argumentNames*/ /*argumentNamesOut*/) + const override; + + // Methods are uniqued owned by a single module. This raw pointer allows + // looking up the module. + ObjectPtr owner_; + + // Underlying unbound function + Function* function_; +}; + +namespace script { +// We once had a `script::` namespace that was deleted. This is for backcompat +// of the public API; new code should not use this type alias. +using Method = ::torch::jit::Method; +} // namespace script + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/module.h new file mode 100644 index 0000000000000000000000000000000000000000..385c1ec489fc9d43caee073b604b4d5c777c286e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/module.h @@ -0,0 +1,690 @@ +#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 + +// This file contains classes which assist in desugaring Python style +// modules and their methods into flattened graphs which don't have any +// function calls. + +namespace torch::jit { + +using ::c10::Argument; +using ::c10::FunctionSchema; +using ::c10::QualifiedName; +// Map which stores filename to content. +using ExtraFilesMap = std::unordered_map; + +using ModulePtr = c10::intrusive_ptr; + +struct Module; + +template +struct slot_list_impl; + +template +struct Named { + std::string name; + T value; +}; + +using NameModule = Named; +using NameValue = Named; +using NameTensor = Named; + +namespace detail { +struct TORCH_API ModulePolicy; +struct TORCH_API ParameterPolicy; +struct TORCH_API AttributePolicy; +struct TORCH_API BufferPolicy; +template +struct NamedPolicy; +} // namespace detail + +using module_list = slot_list_impl; +using named_module_list = + slot_list_impl>; + +using parameter_list = slot_list_impl; +using named_parameter_list = + slot_list_impl>; + +using attribute_list = slot_list_impl; +using named_attribute_list = + slot_list_impl>; + +using buffer_list = slot_list_impl; +using named_buffer_list = + slot_list_impl>; + +using ModuleLookup = std::function&)>; + +struct TORCH_API Module : public Object { + explicit Module(c10::QualifiedName class_name); + Module(std::shared_ptr cu, const c10::ClassTypePtr& type); + Module() = default; + Module(const Module&) = default; + Module& operator=(const Module&) = default; + Module(Module&&) noexcept = default; + Module& operator=(Module&&) noexcept = default; + Module( + c10::QualifiedName /*class_name*/, + std::shared_ptr cu, + bool shouldMangle = false); + Module(ModulePtr module_value) : Object(std::move(module_value)) {} + ~Module() = default; + + void set_optimized(bool o) { + TORCH_WARN( + "Module::set_optimized() is deprecated and has no effect. " + "Please use setGraphExecutorOptimize()"); + } + + bool is_optimized() const { + TORCH_WARN( + "Module::is_optimized() is deprecated and always returns true. " + "Please use getGraphExecutorOptimize()"); + return true; + } + + IValue forward(std::vector inputs, const Kwargs& kwargs = Kwargs()) { + return get_method("forward")(std::move(inputs), kwargs); + } + + // In script modules, buffers are Tensors attribute that are _not_ registered + // as parameters. This is different than in nn.Module where there is a special + // register_buffer method. With this simplification, we only need to track + // whether a slot is a parameter to be able to classify it. + void register_buffer(const std::string& name, at::Tensor v) { + bool is_param = false; + bool is_buffer = true; + std::lock_guard lock(*register_mutex_); + type()->addOrCheckAttribute(name, TensorType::get(), is_param, is_buffer); + _ivalue()->setAttr(name, std::move(v)); + } + + void register_parameter( + const std::string& name, + at::Tensor v, + bool is_buffer) { + std::lock_guard lock(*register_mutex_); + type()->addOrCheckAttribute(name, TensorType::get(), !is_buffer, is_buffer); + _ivalue()->setAttr(name, std::move(v)); + } + + void register_attribute( + const std::string& name, + const TypePtr& t, + IValue v, + bool is_param = false, + bool is_buffer = false) { + type()->addOrCheckAttribute(name, t, is_param, is_buffer); + _ivalue()->setAttr(name, std::move(v)); + } + + void register_module(const std::string& name, const Module& module) { + type()->addOrCheckAttribute(name, module.type()); + _ivalue()->setAttr(name, module._ivalue()); + } + + void apply(const std::function& fn); + + buffer_list buffers(bool recurse = true) const; + named_buffer_list named_buffers(bool recurse = true) const; + + module_list children() const; // direct modules + named_module_list named_children() const; + module_list modules() const; // all modules, including this one, recursively + named_module_list named_modules() const; + + // all tensors involved in gradient optimization + parameter_list parameters(bool recurse = true) const; + named_parameter_list named_parameters(bool recurse = true) const; + + // all members of the object, similar to iterating over dir(obj) in python + attribute_list attributes(bool recurse = true) const; + named_attribute_list named_attributes(bool recurse = true) const; + + void dump( + bool print_method_bodies, + bool print_attr_values, + bool print_param_values) const; + + std::string dump_to_str( + bool print_method_bodies, + bool print_attr_values, + bool print_param_values) const; + + /// Enables "training" mode. + void train(bool on = true); + /// Calls train(false) to enable "eval" mode. + /// Do not override this method, override `train()` instead. + void eval() { + train(/*on=*/false); + } + /// True if the module is in training mode. + bool is_training() const { + return attr("training", true).toBool(); + } + + /// Recursively casts all parameters to the given `dtype` and `device`. + /// + /// If `non_blocking` is true and the source is in pinned memory and + /// destination is on the GPU or vice versa, the copy is performed + /// asynchronously with respect to the host. Otherwise, the argument has no + /// effect. + void to(at::Device device, at::ScalarType dtype, bool non_blocking = false); + + /// Recursively casts all parameters to the given dtype. + /// + /// If `non_blocking` is true and the source is in pinned memory and + /// destination is on the GPU or vice versa, the copy is performed + /// asynchronously with respect to the host. Otherwise, the argument has no + /// effect. + void to(at::ScalarType dtype, bool non_blocking = false); + + /// Recursively moves all parameters to the given device. + /// + /// If `non_blocking` is true and the source is in pinned memory and + /// destination is on the GPU or vice versa, the copy is performed + /// asynchronously with respect to the host. Otherwise, the argument has no + /// effect. + void to(at::Device device, bool non_blocking = false); + + void save( + std::ostream& out, + const ExtraFilesMap& extra_files = ExtraFilesMap()) const; + + void save( + const std::string& filename, + const ExtraFilesMap& extra_files = ExtraFilesMap()) const; + + void _save_for_mobile( + std::ostream& out, + const ExtraFilesMap& extra_files = ExtraFilesMap(), + bool save_mobile_debug_info = false, + bool use_flatbuffer = false) const; + + void _save_for_mobile( + const std::string& filename, + const ExtraFilesMap& extra_files = ExtraFilesMap(), + bool save_mobile_debug_info = false, + bool use_flatbuffer = false) const; + + Module copy() const; + + Module deepcopy(std::optional device = std::nullopt) const; + + // Clones both the underlying `ClassType` and the module instance(data), this + // function creates a new `ClassType` and returns a new instance that has the + // same data as the current instance but with the new type, shared ClassType + // will be preserved as well + Module clone(bool inplace = false) const; + + // Clones both the underlying `ClassType` and the module instance(data), this + // function creates a new `ClassType` and returns a new instance that has the + // same data as the current instance but with the new type, shared ClassType + // will be preserved as well. Also allows the caller to specify a set of + // method and attribute names to not clone. + Module clone( + bool inplace, + const std::unordered_set& ignored_method, + const std::unordered_set& ignored_attributes) const; + + void clone_method(const Module& orig, const std::string& name); + + IValue operator()(std::vector inputs); + + template + IValue create_class(const c10::QualifiedName& name, Types&&... args) const { + return create_class(name, {IValue(std::forward(args))...}); + } + + IValue create_class(const c10::QualifiedName& name, Stack stack) const; + + inline bool operator==(const Module& y) const noexcept { + return _ivalue() == y._ivalue(); + } + + void set_delete_memory(std::shared_ptr delete_mem) { + mem_to_delete_ = std::move(delete_mem); + } + + // A set of functions to maintain input shapes through torch.jit.save and + // torch.jit.load. It only works on tensors and lists/dicts of tensors + // because tracing is only supported by these types. + void store_traced_inputs( + const std::string& func_name, + std::vector inputs) { + if (inputs.empty()) { + return; + } + auto c10_inputs = c10::impl::GenericList(AnyType::get()); + for (IValue& value : inputs) { + // Not checking whether this is traceable type as that is already checked + // higher up in the stack and changing that would require a larger + // restructuring. + c10_inputs.emplace_back(std::move(value)); + } + traced_inputs_.insert_or_assign(func_name, c10_inputs); + } + + c10::Dict retrieve_traced_inputs() + const { + return traced_inputs_; + } + + private: + Module clone_impl( + std::unordered_map& type_remap, + bool inplace, + IValue::HashIdentityIValueMap memo, + const std::unordered_set& ignored_methods, + const std::unordered_set& ignored_attributes) const; + + void clone_method( + const Module& orig, + const Function& method, + const std::unordered_map& type_remap); + + c10::QualifiedName getNameForMethod(std::string basename) const { + return QualifiedName(*type()->name(), std::move(basename)); + } + + void to_impl( + const std::optional& device, + const std::optional& dtype, + bool non_blocking); + + // Extra handle for the module to delete when itself is deleted + std::shared_ptr mem_to_delete_; + + // Map of function names to the traced inputs that they have been traced with + c10::Dict traced_inputs_; + + // Mutex to keep registering buffer or parameter thread safe. + std::shared_ptr register_mutex_ = std::make_shared(); +}; + +// C++ equivalent api of `torch.jit.freeze`. See documentation there for +// details. +TORCH_API Module freeze( + const Module& module, + const std::optional>& preserved_attrs = + std::nullopt, + bool optimize_numerics = true); + +// C++ equivalent api of `torch.jit.optimize_for_inference`. See documentation +// there for details. +TORCH_API Module optimize_for_inference( + Module& module, + const std::vector& other_methods = {}); + +enum class FusionBehavior { STATIC, DYNAMIC }; + +using FusionStrategy = std::vector>; +// clang-format off +/* +Sets the type and number of specializations that can occur during fusion. + +Usage: provide a list of pairs (type, depth) where type is one of STATIC or DYNAMIC +and depth is an integer. + +Behavior - static vs dynamic: + In STATIC fusion, fused ops are compiled to have fixed input shapes. The shape is determined + based on some initial profiling runs. + In DYNAMIC fusion, fused ops are compiled to have variable input shapes, so that multiple + shapes are possible. + +In both cases, we also recompile on new striding behavior, device, or dtype. + +Behavior - fallback functions & depth: + When an input doesn't match the format required by the specialized compiled op, it will run + a fallback function. Fallback functions are recursively be compiled and specialized based + on the observed tensor shapes. Since compilation can be slow, the "depth" parameter is provided to + limit the number of specializations that can be compiled, before giving up on recompiling and + falling back to a completely un-fused, un-specialized implementation. + +The list of (type, depth) pairs controls the type of specializations and the number of +specializations. For example: [(STATIC, 2), (DYNAMIC, 2)] indicates that the first +two specializations will use static fusions, the following two specializations will use +dynamic fusion, and any inputs that satisfy none of the 4 options will run an +unfused implementation. + +NB: in the future, if more as more fusion backends are added there may be more granular +apis for specific fusers. +*/ +// clang-format on +TORCH_API FusionStrategy getFusionStrategy(); +// returns previous strategy +TORCH_API FusionStrategy setFusionStrategy(FusionStrategy& fusion_strategy); + +namespace detail { + +struct TORCH_API SlotCursor { + Module module_; + int64_t i_; // slot offset, -1 indicates the module itself +}; + +} // namespace detail + +// This iterator allows the (optionally recursive) enumeration of +// the members of a Module. It performs a depth-first pre-order +// traversal of the module. The Policy template parameter determines +// which slots of the object should be included. For instance, +// when iterating parameters, we return the parameter tensors, +// but skip modules, buffers, and other attributes. +// See ModulePolicy for comments about Policy object's API. +template +struct slot_iterator_impl { + using SlotCursor = detail::SlotCursor; + using value_type = typename Policy::value_type; + slot_iterator_impl( + Module root, + bool recurse, // if true, do a depth-first search, otherwise, just look at + // slots of root + bool return_module) // if true include root itself as the first thing + // visited (used in modules()) + : cursors_({SlotCursor{std::move(root), return_module ? -1 : 0}}), + recurse_(recurse) { + // advance iterator to first valid element (or the end, if empty) + while_not_valid_next(); + } + // empty cursors_, represents end of iteration + slot_iterator_impl() : recurse_(false) {} + value_type operator*() const { + return Policy::create(cursors_, cur()); + } + value_type operator->() const { + return **this; + } + slot_iterator_impl& operator++() { + next_valid(); + return *this; + } + slot_iterator_impl operator++(int) { + // this is really expensive, should we delete it so people don't use it + // instead of prefix? + slot_iterator_impl old = *this; + ++(*this); + return old; + } + + private: + // return_module() is a corner case where instead of returning a submodule + // of root, we are returning root itself, because we are iterating modules(), + // which contains the root module itself. + // It is represented with a single SlotCursor whose index is -1. + bool return_module() const { + return top().i_ == -1; + } + const SlotCursor& top() const { + return cursors_.back(); + } + SlotCursor& top() { + return cursors_.back(); + } + IValue cur() const { + return return_module() ? top().module_._ivalue() + : top().module_._ivalue()->getSlot(top().i_); + } + + // advance to the next slot in a depth first pre-order traversal of the + // modules slots. This function does not guarantee the next slot is a + // valid element of the iteration. That is done by valid(). + // invariant: !cursors_.empty() + void next() { + // we just returned the module itself, advance i_ to 0 so we are now + // at the first slot of the module. + if (return_module()) { + ++top().i_; + return; + } + // the last traversal action advanced beyond the number of slots in the + // module so continue the iteration in the parent. + if (top().i_ >= int64_t(top().module_._ivalue()->type()->numAttributes())) { + cursors_.pop_back(); + if (!cursors_.empty()) { + ++top().i_; + } + return; + } + // if the current thing is a module, we have to scan it for recursive + // traversals. We do this by adding a new SlotCursor to track the traversal. + if (recurse_ && + top().module_._ivalue()->type()->getAttribute(top().i_)->is_module()) { + cursors_.emplace_back(SlotCursor{cur().toModule(), 0}); + return; + } + // common case: advance to the next slot. + ++top().i_; + } + // is the current position of the iterator a valid one? + // otherwise, we have to continue advancing. + bool valid() const { + return top().i_ < + int64_t(top().module_._ivalue()->type()->numAttributes()) && + Policy::valid( + top().module_._ivalue()->type(), + top().i_, + top().module_._ivalue()->getSlot(top().i_)); + } + void while_not_valid_next() { + // advance iteration until we are either at the end (cursors_.empty()) + // or in a valid state. return_module() is a special case, + // and is always considered valid, regardless of Policy, because it is + // it is only true when we are iterating modules. + while (!cursors_.empty() && !return_module() && !valid()) { + next(); + } + } + void next_valid() { + // avoid crashing if this is empty + if (cursors_.empty()) { + return; + } + // advance to next element, which is maybe not valid + next(); + while_not_valid_next(); + } + + std::vector cursors_; + bool recurse_; + + friend inline bool operator!=( + const slot_iterator_impl& a, + const slot_iterator_impl& b) { + // we are finished iteration when we have no more iteration SlotCursors. + // end is always an empty iterator with no cursors. + return (a.cursors_.empty() != b.cursors_.empty()); + } +}; + +// This type represents lists of parameters, attributes, and +// submodules contained in the module. It is abstract because +// they are not stored directly in std::vectors but inside the +// module's IValue object itself. +template +struct slot_list_impl { + using iterator = slot_iterator_impl; + using const_iterator = slot_iterator_impl; + using value_type = typename iterator::value_type; + slot_iterator_impl begin() const { + return slot_iterator_impl(module_, recurse_, return_module_); + } + slot_iterator_impl end() const { + return slot_iterator_impl(); + } + size_t size() const { + if (!size_) { + size_ = size_t(0); + for ([[maybe_unused]] const value_type& _ : *(this)) { + ++*size_; + } + } + return *size_; + } + + slot_list_impl(Module module, bool recurse, bool return_module) + : module_(std::move(module)), + recurse_(recurse), + return_module_(return_module), + size_(std::nullopt) { + if (!recurse && !return_module && Policy::all_slots) { + size_ = module_.num_slots(); + } + } + + private: + Module module_; + bool recurse_; + bool return_module_; + // size of this list, cached on first request + // when we need to filter the slot list + mutable std::optional size_; + friend struct Module; +}; + +namespace detail { + +// slot_iterator_impl always iterate over all the slots in a module, +// the Policy template argument determines slots should be returned and their +// types +struct TORCH_API ModulePolicy { + // the type of the value being returned + using value_type = Module; + + // the logic for creating the type being returned, given the raw IValue + // of that object. + static value_type create( + const std::vector& cursors, + IValue v) { + return Module(std::move(v).toObject()); + } + // is slot i in typ something that this iterator should return, otherwise, + // we skip it. + static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) { + return typ->getAttribute(i)->is_module(); + } + // are we going to return everything? If so, we can optimize the calculate + // of the size of the list. + static constexpr bool all_slots = false; +}; + +struct TORCH_API ParameterPolicy { + using value_type = at::Tensor; + static value_type create( + const std::vector& cursors, + IValue v) { + return std::move(v).toTensor(); + } + static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) { + return typ->is_parameter(i) && v.isTensor(); + } + static constexpr bool all_slots = false; +}; + +struct TORCH_API BufferPolicy { + using value_type = at::Tensor; + static value_type create( + const std::vector& cursors, + IValue v) { + return std::move(v).toTensor(); + } + static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) { + return typ->getAttribute(i)->isSubtypeOf(*TensorType::get()) && + typ->is_buffer(i); + } + static constexpr bool all_slots = false; +}; + +struct TORCH_API AttributePolicy { + using value_type = IValue; + static value_type create( + const std::vector& cursors, + IValue v) { + return v; + } + static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) { + return true; + } + static constexpr bool all_slots = true; +}; + +// take a Policy object, and make a version of it that returns the slot. +// along with the fully qualified name of that slot. This is used for the named_ +// variants like named_parameters(). +template +struct NamedPolicy { + using value_type = Named; + static value_type create( + const std::vector& cursors, + IValue v) { + std::string name; + if (cursors.size() == 1) { + name = (cursors.back().i_ == -1) ? "" : nameFragment(cursors.back()); + } else { + std::ostringstream ss; + for (const auto i : c10::irange(cursors.size())) { + if (i > 0) { + ss << '.'; + } + ss << nameFragment(cursors[i]); + } + name = ss.str(); + } + return value_type{std::move(name), Policy::create(cursors, std::move(v))}; + } + static bool valid(const ClassTypePtr& t, size_t i, const IValue& v) { + return Policy::valid(t, i, v); + } + static constexpr bool all_slots = Policy::all_slots; + + private: + static std::string nameFragment(const detail::SlotCursor& f) { + return f.module_.type()->getAttributeName(f.i_); + } +}; + +} // namespace detail + +TORCH_API bool& getInlineEverythingMode(); + +namespace script { +// We once had a `script::` namespace that was deleted. This is for backcompat +// of the public API; new code should not use this type alias. +using Module = ::torch::jit::Module; +using ExtraFilesMap = ::torch::jit::ExtraFilesMap; +} // namespace script + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/object.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/object.h new file mode 100644 index 0000000000000000000000000000000000000000..f25e599974b138172c593fe2c3f9f9fac2e26397 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/object.h @@ -0,0 +1,205 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit { + +struct Resolver; +using ResolverPtr = std::shared_ptr; + +using ObjectPtr = c10::intrusive_ptr; + +// Throw this in C++ land if `attr` fails. This will be converted to a Python +// AttributeError by the Python binding code +class ObjectAttributeError : public std::runtime_error { + public: + ObjectAttributeError(const std::string& what) : std::runtime_error(what) {} +}; + +struct TORCH_API Object { + Object() = default; + Object(const Object&) = default; + Object& operator=(const Object&) = default; + Object(Object&&) noexcept = default; + Object& operator=(Object&&) noexcept = default; + Object(ObjectPtr _ivalue) : _ivalue_(std::move(_ivalue)) {} + Object(std::shared_ptr cu, const c10::ClassTypePtr& type); + Object( + c10::QualifiedName, + std::shared_ptr cu, + bool shouldMangle = false); + + ObjectPtr _ivalue() const { + TORCH_INTERNAL_ASSERT(_ivalue_); + return _ivalue_; + } + + c10::ClassTypePtr type() const { + return _ivalue()->type(); + } + + struct Property { + std::string name; + Method getter_func; + std::optional setter_func; + }; + + void setattr(const std::string& name, c10::IValue v) { + if (_ivalue()->type()->hasConstant(name)) { + TORCH_CHECK( + false, + "Can't set constant '", + name, + "' which has value:", + _ivalue()->type()->getConstant(name)); + } else if (auto slot = _ivalue()->type()->findAttributeSlot(name)) { + const c10::TypePtr& expected = _ivalue()->type()->getAttribute(*slot); + TORCH_CHECK( + v.type()->isSubtypeOf(*expected), + "Expected a value of type '", + expected->repr_str(), + "' for field '", + name, + "', but found '", + v.type()->repr_str(), + "'"); + _ivalue()->setSlot(*slot, std::move(v)); + } else { + TORCH_CHECK(false, "Module has no attribute '", name, "'"); + } + } + + c10::IValue attr(const std::string& name) const { + if (auto r = _ivalue()->type()->findAttributeSlot(name)) { + return _ivalue()->getSlot(*r); + } + if (auto r = _ivalue()->type()->findConstantSlot(name)) { + return _ivalue()->type()->getConstant(*r); + } + std::stringstream err; + err << _ivalue()->type()->repr_str() << " does not have a field with name '" + << name.c_str() << "'"; + throw ObjectAttributeError(err.str()); + } + + c10::IValue attr(const std::string& name, c10::IValue or_else) const { + if (auto r = _ivalue()->type()->findAttributeSlot(name)) { + return _ivalue()->getSlot(*r); + } + if (auto r = _ivalue()->type()->findConstantSlot(name)) { + return _ivalue()->type()->getConstant(*r); + } + return or_else; + } + + bool hasattr(const std::string& name) const { + return _ivalue()->type()->hasAttribute(name) || + _ivalue()->type()->hasConstant(name); + } + + // each object owns its methods. The reference returned here + // is guaranteed to stay valid until this module has been destroyed + Method get_method(const std::string& name) const { + if (auto method = find_method(name)) { + return *method; + } + TORCH_CHECK(false, "Method '", name, "' is not defined."); + } + + const std::vector get_methods() const { + return c10::fmap(type()->methods(), [&](Function* func) { + return Method(_ivalue(), func); + }); + } + + bool has_property(const std::string& name) const { + for (const auto& prop : type()->properties()) { + if (prop.name == name) { + return true; + } + } + return false; + } + + const Property get_property(const std::string& name) const { + for (const auto& prop : type()->properties()) { + if (prop.name == name) { + std::optional setter = std::nullopt; + if (prop.setter) { + setter = Method(_ivalue(), prop.setter); + } + return Property{ + prop.name, Method(_ivalue(), prop.getter), std::move(setter)}; + } + } + TORCH_CHECK(false, "Property '", name, "' is not defined."); + } + + const std::vector get_properties() const { + return c10::fmap(type()->properties(), [&](ClassType::Property prop) { + std::optional setter = std::nullopt; + if (prop.setter) { + setter = Method(_ivalue(), prop.setter); + } + return Property{ + std::move(prop.name), + Method(_ivalue(), prop.getter), + std::move(setter)}; + }); + } + + std::optional find_method(const std::string& basename) const; + + /// Run a method from this module. + /// + /// For example: + /// @code + /// IValue output = module->run("relu_script", a, b); + /// @endcode + /// + /// To get a compile a module from a source string, see torch::jit::compile + /// + /// @param method_name The name of the method to run + /// @param args Arguments to be passed to the method + /// @return An IValue containing the return value (or values if it is a tuple) + /// from the method + template + IValue run_method(const std::string& method_name, Types&&... args) { + return get_method(method_name)({IValue(std::forward(args))...}); + } + + // so that C++ users can easily add methods + void define(const std::string& src, const ResolverPtr& resolver = nullptr); + + size_t num_slots() const { + return _ivalue()->slots().size(); + } + + // shallow copy the object + Object copy() const; + + // Copies all the attributes of the object recursively without creating new + // `ClassType`, including deepcopy of Tensors + Object deepcopy() const; + + private: + // mutable be we lazily initialize in module_object. + mutable ObjectPtr _ivalue_; +}; + +namespace script { +// We once had a `script::` namespace that was deleted. This is for backcompat +// of the public API; new code should not use this type alias. +using Object = ::torch::jit::Object; +} // namespace script +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h new file mode 100644 index 0000000000000000000000000000000000000000..cea04920023b6876ac4c8123c4b887b88d457fbd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h @@ -0,0 +1,119 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit { +namespace { +inline c10::FunctionSchema getIsAvailableSchema() { + c10::Argument self("self", c10::AnyType::get()); + c10::Argument available("available", c10::BoolType::get()); + c10::FunctionSchema preprocessor_schema( + "is_available", + /*overload_name=*/"", + /*arguments=*/{self}, + /*returns=*/{available}); + return preprocessor_schema; +} + +constexpr static auto kBackendsNamespace = "__backends__"; + +inline c10::FunctionSchema getCompileSchema() { + c10::Argument self("self", c10::AnyType::get()); + c10::Argument mod("processed", c10::AnyType::get()); + auto any_dict_ty = + c10::DictType::create(c10::StringType::get(), c10::AnyType::get()); + c10::Argument method_compile_spec("method_compile_spec", any_dict_ty); + c10::Argument handles("handles", any_dict_ty); + + c10::FunctionSchema compile_schema( + "compile", + /*overload_name=*/"", + /*arguments=*/{self, mod, method_compile_spec}, + /*returns=*/{handles}); + return compile_schema; +} + +inline c10::FunctionSchema getExecuteSchema() { + auto any_list_ty = c10::ListType::create(c10::AnyType::get()); + c10::Argument self("self", c10::AnyType::get()); + c10::Argument handle("handle", c10::AnyType::get()); + c10::Argument input("input", any_list_ty); + c10::Argument output("output", any_list_ty); + return c10::FunctionSchema( + "execute", + /*overload_name=*/"", + /*arguments=*/{self, handle, input}, + /*returns=*/{output}); +} + +template +std::function getIsAvailableFunc() { + return [](Stack& stack) { + auto self = pop(stack).toCustomClass(); + auto ret = self->is_available(); + push(stack, ret); + }; +} + +template +std::function getCompileFunc() { + return [](Stack& stack) { + auto method_compile_spec = pop(stack).toGenericDict(); + auto processed = pop(stack); + auto self = pop(stack).toCustomClass(); + auto ret = self->compile(processed, method_compile_spec); + push(stack, ret); + }; +} + +template +std::function getExecuteFunc() { + return [](Stack& stack) { + auto args = pop(stack); + auto handle = pop(stack); + auto self = pop(stack); + auto backend = self.toCustomClass(); + auto res = backend->execute(handle, args.toList()); + push(stack, res); + }; +} +} // namespace + +// Static registration API for backends. +template +class backend { + static_assert( + std::is_base_of_v, + "torch::jit::backend requires T to inherit from PyTorchBackendInterface"); + std::string backend_name_; + + public: + // Registers a new backend with /p name, and the given /p preprocess + // function. + backend(const std::string& name) : backend_name_(name) { + static auto cls = torch::class_(kBackendsNamespace, name) + .def(torch::init<>()) + ._def_unboxed( + "is_available", + getIsAvailableFunc(), + getIsAvailableSchema()) + ._def_unboxed( + "compile", + getCompileFunc(), + getCompileSchema()) + ._def_unboxed( + "execute", + getExecuteFunc(), + getExecuteSchema()); + } +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_handler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..ec124d0cf8ae0cbee9a38a575c49c22e2712164d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_handler.h @@ -0,0 +1,143 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include +#include + +#include + +namespace torch::jit { + +/* + * BackendDebugHandleManager is responsible for issuing debug handles to + * backends. Debug handles are associated with nodes of a graph. + * BackendDebugHandleManager also maintains a map + * [debug-handle, DebugInfoTuple = {source range, inlined callstack ptr]} that + * will help generate a callstack for exception raised using debug handles. + * Effectively debug handles are something that is given to backend and later + * when an exception occurs in the backend, backend can tell, using debug + * handle, that an exception occurred here. Then the runtime can generate + * callstack corresponding to the exception. + * There are two parts to BackendDebugHandleManager: + * 1. static std::atomic debug_handle + * 2. Map of [debug-handle, DebugInfoTuple] + * + * About 1: + * Why do they have to be unique. The reason is that by ensuring + * uniqueness of debug handles, we remove the burden of another layer of + * mapping where we need to say this set of debug handles were generated for + * this lowered module or this bytecode function. This simplifies the API for + * serialization since debug handles can uniquely identify DebugInfoTuple. + * Thus simplifies the runtime API for throwing exception. Exception throwing + * only needs to know debug_handle and not which module or method threw it. + * There are 2 issues to keep in mind, though,for static std::atomic + * debug_handle: A. Performance implications of using atomic variable. However + * this is only used for compilation so we assume to absorb some of that + * penalty. Plus if there is no contention then we should have less to worry + * about. B. If repeated compilation is part of a long running process then we + * may overflow int64_t. We may detect and fail on this. For now this is not + * done. + * + * Now about 2: + * There are two usecases for [debug-handle, DebugInfoTuple] + * A. During bytecode generation the DebugInfoTuple corresponding to the nodes + * of the inlined graph being serialized, are stored in this object and a + * unique debug handle is returned. This unique debug handle is stored in + * mobile_debug info for pytorch lite models. It will be used for raising + * exceptions as well as profiling. B. During backend lowering, each backend's + * preprocess/compile method can compile method's graph and serialize those + * methods. Once the method is lowered to backend, graph is essentially lost. + * Without access to graph it is hard to generate model level debug info. Thus + * the debug handles provide a way to map nodes of the graph to the model level + * debug info. + * + * During byte-code model serialization, [debug-handle, DebugInfoTuple] is + * serialized. Now we know a. debug handles and b. how to map debug handles to + * model source code. Thus we can either do eager symbolication by converting + * debug handles to corresponding source code at runtime, or do lazy + * symbolicattion offline. + * + * Note that it is not necessary to serialize [debug-handle, DebugInfoTuple] + * corresponding to lowered backend if the lowering process, that is + * preprocess/compile, and execution happens in the same session, then eager + * symbolication can be employed. + * + * Now how does BackendDebugHandleManager capture all of the above? + * By providing two API. + * 1. getNextDebugHandle which given a Node* returns a unique debug handle, + * that will uniquely identify DebugInfoTuple. + * and + * 2. getCallStackPtrMap which returns the map + * [debug-handle, DebugInfoTuple] + * + * 1 provides debug handles to backends and 2 provides runtime a way to map + * debug handles to source level debug info. + * + * So why does debug handle map to DebugInfoTuple = {source range and inlined + * cs}? {debug_handle, source_range_tag, serialized_callstack} Take this + * example: class L(nn.Module): def __init__(self) -> None: + * ... + * def forward(self, x): + * return x * 5 + * class M(nn.Module): + * def __init__(self) -> None: + * ... + * def forward(self, x): + * return x - 2 + * class N(nn.Module): + * def __init__(self) -> None: + * self.m = M() + * def forward(self, x): + * return self.m(x) + 3 + * m = torch.jit.script(N()) + * Once you inline m's forward method, m.forward.graph will look something + * like this + * graph(%self...): + * %x = aten::mul(..) + * %x = aten::sub(x, ..) + * %y = aten::add(x, ..) + * .. + * Inlined callstack ptr for these two nodes will look like: + * aten::mul's inlined CS (callstack): [N.forward, source range] -> [M.forward, + * source range] aten::sub's inlined CS (callstack): [N.forward, source range] + * aten::add's inlined CS: null + * mul node's inlined CS contains only information about the callsites' source + * range The information about mul node's source range ('return x * 5') is not + * available in its inlined CS. It is rather part of node's source range + * instead of inlined CS. Thus to get full stack: [N.forward, source range] -> + * [M.forward, source range] -> [aten::mul's source range] We need to track + * mul's source range and inlined CS both. + */ + +using BackendDebugInfoMapType = + std::unordered_map; + +/* + * This class is used to generate debug info map. + * backend's preprocess will call generate_debug_handles (see + * backend_detail.cpp), which uses debug_handle_manager to generate debug + * handles. When lowering process finishes, calling stopRecording will + * return debug info map from debug_handle_manager + */ +class TORCH_API BackendDebugInfoRecorder { + public: + BackendDebugInfoRecorder() = default; + int64_t getNextDebugHandle(const Node* node); + // Reason this is not done as RAII is that work done in stopRecording + // can throw, and throwing with dtor will call terminate and thus voids any + // exception catching at a higher level. + BackendDebugInfoMapType stopRecording(); + NodeToDebugHandle generate_debug_handles(const std::shared_ptr& graph); + + private: + static std::atomic unique_debug_handle_; + BackendDebugInfoMapType handles_to_inlined_callstack_ptrs_; +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_info.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_info.h new file mode 100644 index 0000000000000000000000000000000000000000..b2ff9a3fe801206fba4bf40538e5770a3ae493e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_info.h @@ -0,0 +1,68 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifndef BUILD_LITE_INTERPRETER +#include +#endif +#include + +namespace torch::jit { + +constexpr static auto kBackendUtilsNamespace = "backendutils"; +constexpr static auto kBackendDebugInfoClass = "BackendDebugInfo"; + +#ifndef BUILD_LITE_INTERPRETER +/* + * Custom class for holding debug information in lowered modules, intended + * purely for keeping this information to be later serialized outside of the + * lowered module itself. + * Its usage pattern is: + * 1. LoweredModule declares an instance of this class in __backend_debug_info + * 2. During serialization, __backend_debug_info is used to obtain the debug + * information. + * 3. The contents of LoweredModule.__backend_debug_info are not serialized + * within the LoweredModule itself. + */ +class TORCH_API PyTorchBackendDebugInfo : public torch::CustomClassHolder { + public: + PyTorchBackendDebugInfo() = default; + + std::optional& getDebugInfoMap() { + return debug_info_map_; + } + + void setDebugInfoMap(BackendDebugInfoMapType&& debug_info_map) { + debug_info_map_ = std::move(debug_info_map); + } + + private: + std::optional debug_info_map_; +}; + +#else + +/* + * Dummy instance exists for the following reason: + * __backend_debug_info is of type BackendDebugInfo which is a torchbind' + * class backed by cpp class PyTorchBackendDebugInfo. + * PyTorchBackendDebugInfo, depends on ir.h., scope.h, source_range etc. + * We dont include this on lite interpreter side. Thus on lite interpreter side + * we cannot have valid definition of PyTorchBackendDebugInfo. However we do not + * need valid instance of __backend_debug_info in lite interpreter anyway as we + * dont serialize this info as part of LowerdModule as mentioned ealrier. + * However since LoweredModule has registered attribute of __backend_debug_info + * we still need to make sure that BackendDebugInfo is registered with + * TorchScript. However in this instance it does not have to be backed by + * PyTorchBackendDebugInfo, so we create a dummy PyTorchBackendDebugInfoDummy + * just for this purpose. + */ +class PyTorchBackendDebugInfoDummy : public torch::CustomClassHolder { + public: + PyTorchBackendDebugInfoDummy() = default; +}; +#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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_detail.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_detail.h new file mode 100644 index 0000000000000000000000000000000000000000..cca52f2866881927fa9db1b8f35cb20be87a5183 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_detail.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +#include + +namespace torch::jit { + +using DebugHandleType = int64_t; + +using NodeToDebugHandle = std::unordered_map; + +using BackendDebugHandleGenerator = + std::function&)>; + +namespace detail { + +using BackendPreprocessFunction = std::function&, + const BackendDebugHandleGenerator& generate_debug_handles)>; + +TORCH_API void registerBackendPreprocessFunction( + const std::string& name, + const BackendPreprocessFunction& preprocess); + +bool hasBackendPreprocessFunction(const std::string& name); + +BackendPreprocessFunction getBackendPreprocessFunction(const std::string& name); + +TORCH_API Module codegen_backend_module( + const std::string& backend_name, + const Module& orig_module, + const c10::Dict& method_compile_spec, + const c10::DictTypePtr& any_dict_ty); +} // 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_exception.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_exception.h new file mode 100644 index 0000000000000000000000000000000000000000..14a22a5704d99e3bdb2a347cecb906c7f8c681e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_exception.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include + +namespace c10 { +class TORCH_API BackendRuntimeException : public c10::Error { + public: + // Use debug_handle to throw exception + BackendRuntimeException( + SourceLocation loc, + std::string msg, + int64_t debug_handle) + : c10::Error(loc, std::move(msg)) { + debug_handles.push_back(debug_handle); + } + // If rethrowing, can push another debug_handle + // This is useful in couple of scenarios. + // 1. A submodule is lowered and lite interpreter has CallMethod + // to lowered module's method. In this case lowered module will throw with + // a handle, plus there will be another debug handle corresponding + // to the CallMethod node in lite interpreter. Both together give complete + // trace. This function allows lite interpreter to rethrow with debug + // handle it has for CallMethod. + // 2. Another scenarios is when lite interpreter can make function calls or + // the lowered backend also has function call ability. Thus we have + // multiple function frames. Now we need a stack of handles to symbolicate + // entire stack trace. + void pushDebugHandle(int64_t debug_handle) { + debug_handles.push_back(debug_handle); + } + const std::vector& getDebugHandles() { + return debug_handles; + } + + private: + // Stores stack of debug handles. + std::vector debug_handles; +}; + +} // namespace c10 +#define TORCH_DELEGATED_BACKEND_THROW(cond, msg, debug_handle) \ + if (C10_UNLIKELY_OR_CONST(!(cond))) { \ + throw ::c10::BackendRuntimeException( \ + {__func__, __FILE__, static_cast(__LINE__)}, \ + msg, \ + debug_handle); \ + } + +#define TORCH_DELEGATED_BACKEND_RETHROW(e, debug_handle) \ + do { \ + e.pushDebugHandle(debug_handle); \ + throw; \ + } while (false) + +#define DEBUG_HANDLE_UNKNOWN -1 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_init.h new file mode 100644 index 0000000000000000000000000000000000000000..bc490802ff882f7c10b304af7803b80d1c511b9e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_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 JIT to_ functions. +void initJitBackendBindings(PyObject* module); +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..5f7056a86d0628c1a861465c1cc30d46fc2d1db7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_interface.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Interface for a JIT backend. +class TORCH_API PyTorchBackendInterface : public torch::CustomClassHolder { + public: + PyTorchBackendInterface() noexcept; + ~PyTorchBackendInterface() override; + + // Returns true if the backend is available to process delegation calls. + virtual bool is_available() = 0; + + // Compile the module contained in \p processed using the details provided in + // \p method_compile_spec for each module method that should be compiled for + // the backend. \p method_compile_spec should be of type Dict. + // \returns a dictionary of type Dict that contains a backend + // handle each method that can run on the backend (i.e. each key in \p + // method_compile_spec). + virtual c10::impl::GenericDict compile( + c10::IValue processed, + c10::impl::GenericDict method_compile_spec) = 0; + + // Execute the method specified by \p handle using \p inputs. \returns the + // outputs as a tuple. + virtual c10::impl::GenericList execute( + c10::IValue handle, + c10::impl::GenericList inputs) = 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h new file mode 100644 index 0000000000000000000000000000000000000000..f0241ec96ef63b32e94b6116f8fcc31df5da9f51 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +namespace torch::jit { +class backend_preprocess_register { + std::string backend_name_; + + public: + backend_preprocess_register( + const std::string& name, + const detail::BackendPreprocessFunction& preprocess) + : backend_name_(name) { + detail::registerBackendPreprocessFunction(name, preprocess); + } +}; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_resolver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_resolver.h new file mode 100644 index 0000000000000000000000000000000000000000..aee7fac6ddfb3fe942a82ad33074e672a3422821 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_resolver.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { +// Create a Resolver for use in generating LoweredModules for specific backends. +TORCH_API std::shared_ptr loweredModuleResolver(); +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/cpp/context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/cpp/context.h new file mode 100644 index 0000000000000000000000000000000000000000..6ac2655639b3b0dc4a087056e90a7f75a593f226 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/cpp/context.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#ifndef PTM_COREML_Context_h +#define PTM_COREML_Context_h + +#include + +namespace torch::jit::mobile::coreml { + +struct ContextInterface { + virtual ~ContextInterface() = default; + virtual void setModelCacheDirectory(std::string path) = 0; +}; + +class BackendRegistrar { + public: + explicit BackendRegistrar(ContextInterface* ctx); +}; + +void setModelCacheDirectory(std::string path); + +} // namespace torch::jit::mobile::coreml + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLCompiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLCompiler.h new file mode 100644 index 0000000000000000000000000000000000000000..1b040c52c64f22364741a4c926686ec3579edd3b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLCompiler.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#import + +#include + +NS_ASSUME_NONNULL_BEGIN + +@interface PTMCoreMLCompiler : NSObject + ++ (void)setCacheDirectory:(const std::string&)dir; + ++ (NSString*)cacheDirectory; + ++ (BOOL)compileModel:(const std::string&)modelSpecs modelID:(const std::string&)modelID; + ++ (nullable MLModel*)loadModel:(const std::string)modelID + backend:(const std::string)backend + allowLowPrecision:(BOOL)allowLowPrecision + error:(NSError**)error; + +@end + +NS_ASSUME_NONNULL_END + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLExecutor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLExecutor.h new file mode 100644 index 0000000000000000000000000000000000000000..5a79337260dcc3099d395a1639f39420796ab6b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLExecutor.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#import + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface PTMCoreMLExecutor : NSObject + +@property(atomic, strong) MLModel* model; + +- (instancetype)initWithFeatureNames:(NSArray*)featureNames; + +- (void)setInputs:(c10::impl::GenericList)inputs; + +- (id)forward:(NSError**)error; + +@end + +NS_ASSUME_NONNULL_END + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLFeatureProvider.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLFeatureProvider.h new file mode 100644 index 0000000000000000000000000000000000000000..c0e536370b6ee5209dc88ae869539bad7a423260 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLFeatureProvider.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface PTMCoreMLFeatureProvider : NSObject + +- (instancetype)initWithFeatureNames:(NSSet*)featureNames; + +- (void)clearInputTensors; + +- (void)setInputTensor:(const at::Tensor&)tensor forFeatureName:(NSString*)name; + +@end + +NS_ASSUME_NONNULL_END + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLModelWrapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLModelWrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..5ee77404da4e52f35be363da00dbf4779b75af89 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLModelWrapper.h @@ -0,0 +1,46 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#include +#include + +namespace torch { +namespace jit { +namespace mobile { +namespace coreml { + +class MLModelWrapper : public CustomClassHolder { + public: + PTMCoreMLExecutor* executor; + std::vector outputs; + + MLModelWrapper() = delete; + + MLModelWrapper(PTMCoreMLExecutor* executor) : executor(executor) { + [executor retain]; + } + + MLModelWrapper(const MLModelWrapper& oldObject) { + executor = oldObject.executor; + outputs = oldObject.outputs; + [executor retain]; + } + + MLModelWrapper(MLModelWrapper&& oldObject) { + executor = oldObject.executor; + outputs = oldObject.outputs; + [executor retain]; + } + + ~MLModelWrapper() { + [executor release]; + } +}; + +} // namespace coreml +} // namespace mobile +} // namespace jit +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLTensorSpec.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLTensorSpec.h new file mode 100644 index 0000000000000000000000000000000000000000..7537f743d938199c4d13c8f8aca01c6e5b0c231b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLTensorSpec.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#import + +#include + +namespace torch::jit::mobile::coreml { + +struct TensorSpec { + std::string name; + c10::ScalarType dtype = c10::ScalarType::Float; +}; + +static inline c10::ScalarType scalar_type(const std::string& type_string) { + if (type_string == "0") { + return c10::ScalarType::Float; + } else if (type_string == "1") { + return c10::ScalarType::Double; + } else if (type_string == "2") { + return c10::ScalarType::Int; + } else if (type_string == "3") { + return c10::ScalarType::Long; + } + return c10::ScalarType::Undefined; +} + +} // namespace torch::jit::mobile::coreml + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/compiler/xnn_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/compiler/xnn_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..61bd88c05345fc626ef96149efa97d5235afa52b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/compiler/xnn_compiler.h @@ -0,0 +1,29 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include + +namespace torch::jit::xnnpack::delegate { + +class XNNCompiler { + public: + // Takes Flatbuffer Serialized XNNPack Model and rebuilds the xnn-subgraph + // returns an executor object that holds the xnn runtime object which we + // can then use to set inputs and run inference using the xnn graph. + static void compileModel( + const void* buffer_pointer, + size_t num_bytes, + XNNExecutor* executor); +}; + +} // namespace torch::jit::xnnpack::delegate + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/executor/xnn_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/executor/xnn_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..376de821a60acabd138d32b375e1c833bd077886 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/executor/xnn_executor.h @@ -0,0 +1,73 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// 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 + +namespace torch::jit::xnnpack::delegate { + +class XNNExecutor { + private: + std::unique_ptr runtime_{ + nullptr, + &xnn_delete_runtime}; + std::vector input_ids_; + std::vector output_ids_; + std::vector externals_; + + public: + XNNExecutor() = default; + + template + bool set_inputs(std::vector& inputs, std::vector& outputs) { + externals_.clear(); + + if (inputs.size() != input_ids_.size()) { + return false; + } + + for (int i = 0; i < inputs.size(); i++) { + externals_.emplace_back(xnn_external_value{input_ids_[i], inputs[i]}); + } + + if (outputs.size() != output_ids_.size()) { + return false; + } + + for (int i = 0; i < outputs.size(); i++) { + externals_.emplace_back(xnn_external_value{output_ids_[i], outputs[i]}); + } + + return true; + } + + bool forward() { + xnn_status status = + xnn_setup_runtime(runtime_.get(), externals_.size(), externals_.data()); + + if (status != xnn_status_success) { + return false; + } + + status = xnn_invoke_runtime(runtime_.get()); + + if (status != xnn_status_success) { + return false; + } + + return true; + } + + friend class XNNCompiler; +}; + +} // namespace torch::jit::xnnpack::delegate + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/serialization/serializer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/serialization/serializer.h new file mode 100644 index 0000000000000000000000000000000000000000..1ca44842bad03c04d60d83a20a67ae8f845a1213 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/serialization/serializer.h @@ -0,0 +1,94 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include +#include + +namespace torch { +namespace jit { +namespace xnnpack { +namespace delegate { + +using namespace fb_xnnpack; // Specified in the schema + +class XNNSerializer { + public: + // Constructors + // initial buffersize of 1024 which will grow + // automatically, constant buffer and buffer sizes initialized with dummy + // values as 0 index is reserved for non-constant tensors + XNNSerializer() : XNNSerializer(1024) {} + + explicit XNNSerializer(size_t bufferSize) + : _builder(bufferSize), + _nodes(), + _values(), + _constantBuffer({CreateBuffer( + _builder, + {})}), // index 0 is reserved for non-const data + _bufferSizes({0}) {} + + // Serializing Nodes + + // Serialize add node, we are serializing the argument needed to call + // xnn_define_add2. Serializing these values, and at run time we build + // the graph by re running xnn_define_add2 + void serializeAddNode( + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + + // Serializing Values + void serializeTensorValue( + uint32_t xnn_datatype, + size_t num_dims, + std::vector dims, + size_t buffer_data_idx, + uint32_t external_id, + uint32_t flags, + uint32_t id_out); + + // finish and serialize xnngraph returning serialized data + std::string finishAndSerialize( + std::vector input_ids, + std::vector output_ids, + size_t num_extern_ids); + + // decoupled data serialization with tensor values. This way constant tensor + // data can be referenced by multiple intermediate tensors. This call + // serializes the num_bytes of the data_ptr and returns the index it was + // placed in. + size_t serializeData(const uint8_t* data_ptr, size_t num_bytes); + + private: + // xnnpack version we are serializing + const char* _version_sha1 = "ae108ef49aa5623b896fc93d4298c49d1750d9ba"; + + // flatbuffer objects we will create and serialize together to create xnngraph + flatbuffers_fbsource::FlatBufferBuilder _builder; + + // Vector of the serialized xnnpack nodes + std::vector> _nodes; + + // Vector of the serialized xnnpack values + std::vector> _values; + + std::vector> _constantBuffer; + std::vector _bufferSizes; +}; + +} // namespace delegate +} // namespace xnnpack +} // namespace jit +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/xnnpack_graph_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/xnnpack_graph_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..369d56f8d9a33971d3047c5c499fe014a4dea7c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/xnnpack_graph_builder.h @@ -0,0 +1,102 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include +#include +#include + +#include + +namespace torch { +namespace jit { +namespace xnnpack { +namespace delegate { + +class XNNGraph { + private: + const float output_min = -std::numeric_limits::infinity(); + const float output_max = std::numeric_limits::infinity(); + + // serializer class + XNNSerializer _serializer; + // xnn subgraph + xnn_subgraph_t _subgraph_ptr; + // Set of all the tensor values throughout the jit graph + std::unordered_set _intermediate_tensors; + // Set of all the tensor values mapped to the xnnpack ids + std::unordered_map _val_to_ids; + // Vector containing the torch valued inputs/outputs, + // must be ordered to preserve the order of input/outputs + std::vector _inputs; + std::vector _outputs; + + // Graph passes for optimizing and tracing torchscript graph + // Essentially massaging the graph into a digestiable format for + // xnnpack graph lowering. + std::shared_ptr optimizeAndTraceGraph( + std::shared_ptr graph, + std::vector& example_inputs); + + // Gather all the intermediate tensor values within a graph. This + // skips through all prim constants. The purpose of this is for defining + // the tensor values beforehand for the xnnpack subgraph. + void gatherTensorValues(std::shared_ptr& graph); + + // Gathers the tensor values in a give node + void gatherNodeInputs(torch::jit::Node& node); + + // Helper function to determine if a jit value is a graph input + bool isGraphInput(torch::jit::Value* val); + + // Helper function to determine if a jit value is a graph output + bool isGraphOutput(torch::jit::Value* val); + + // Defines all xnnpack nodes for the nodes in the graph + void defineAllNodes(std::shared_ptr& graph); + + // Defines all xnn tensor values used throughout the graph + void defineAllTensorValues(); + + // Makes a pass through the graph and throws if any ops are unsupported + void checkOpsToDelegate(std::shared_ptr& graph); + + public: + XNNGraph() : _serializer(), _subgraph_ptr(nullptr) { + xnn_status status = xnn_initialize(/*allocator =*/nullptr); + TORCH_CHECK(xnn_status_success == status, "Failed to initialize xnnpack"); + } + + ~XNNGraph() { + xnn_deinitialize(); + if (_subgraph_ptr != nullptr) { + xnn_delete_subgraph(_subgraph_ptr); + } + } + + void buildXNNGraph( + std::shared_ptr& graph, + std::vector example_inputs); + + void runGraphOnInputs( + std::vector tensor_inputs, + std::vector tensor_outputs); + + std::string serializedXNNGraph(); + + std::vector> getGraphOutputShapes(); +}; + +} // namespace delegate +} // namespace xnnpack +} // namespace jit +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..211a2fe3a749f934e4c9347b46fb0c6eb111e7f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h @@ -0,0 +1,57 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +/* + * This file contains APIs for cuda fuser; + * + * We use an empty static struct to hold the function pointers, which are + * registered separately. This is to support cpu-only compilation. + * Registration is done in torch/csrc/jit/codegen/cuda/register_interface.cpp + */ + +namespace torch::jit::fuser::cuda { + +TORCH_API std::atomic& getCudaFusionGuardMode(); + +TORCH_API bool getSingletonFusion(); +TORCH_API bool setSingletonFusion(bool value); +TORCH_API bool getHorizontalFusion(); +TORCH_API bool setHorizontalFusion(bool value); + +// dummy struct to allow API registration +struct CudaFuserInterface { + void (*fn_compile_n)(Node*) = nullptr; + void (*fn_run_n_s)(const Node*, Stack&) = nullptr; + void (*fn_fuse_graph)(std::shared_ptr&) = nullptr; + bool (*fn_can_fuse_n)(const Node*) = nullptr; + void (*fn_insert_profile_inodes)(ProfilingRecord* pr) = nullptr; + bool (*fn_profile_n)(const Node*) = nullptr; + bool (*fn_skip_n)(const std::string&, bool flip) = nullptr; +}; + +// Get interface, this is used by registration and user facing API internally +TORCH_API CudaFuserInterface* getFuserInterface(); + +TORCH_API void compileFusionGroup(Node* fusion_node); +TORCH_API void runFusionGroup(const Node* fusion_node, Stack& stack); +TORCH_API void fuseGraph(std::shared_ptr& /*graph*/); +TORCH_API bool canFuseNode(const Node* node); +TORCH_API void InsertProfileNodesForCUDAFuser(ProfilingRecord* pr); +TORCH_API bool profileNode(const Node* node); + +TORCH_API bool skipNode(const std::string& symbol_str, bool flip = true); + +TORCH_API bool isEnabled(); +TORCH_API bool setEnabled(bool is_enabled); +TORCH_API bool canBeEnabled(); + +} // namespace torch::jit::fuser::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/arg_spec.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/arg_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..3621030aed0ee08ccf973d0d64ebe2592118a851 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/arg_spec.h @@ -0,0 +1,60 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include // fmap +#include +#include +#include + +#include +#include + +namespace torch::jit::fuser { + +// Describes the (runtime) arguments to a kernel. +// ArgSpecs are also used as keys to lookup instantiated kernels, so +// they are hashable. +// Note: the device to run on is included in the arg spec because kernels +// are compiled per-device. +struct TORCH_API ArgSpec { + ArgSpec(at::TensorList inputs, const int _device) + : descs_{c10::fmap(inputs)}, + hash_code_{c10::get_hash(_device, inputs.size(), descs_)}, + device_{_device} {} + + // (Common) hash function + static size_t hash(const ArgSpec& spec) { + return spec.hash_code_; + } + + // Comparators + bool operator==(const ArgSpec& other) const { + return (descs_ == other.descs_ && device_ == other.device_); + } + + bool operator!=(const ArgSpec& spec) const { + return !(*this == spec); + } + + // Getters + size_t hashCode() const { + return hash_code_; + } + const std::vector& descs() const { + return descs_; + } + int device() const { + return device_; + } + + private: + std::vector descs_; + size_t hash_code_; + int device_; +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/codegen.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..1cc359481bf7cb9eb5b1bf72b1f7043bf0612309 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/codegen.h @@ -0,0 +1,29 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::fuser { + +// Creates a CPU or CUDA kernel for the given graph. +// Returns the C++ or CUDA string implementing the kernel. +TORCH_API std::string generateKernel( + const std::string& name, + const Graph& graph, + const std::vector>>& + inputs, + const std::vector>& outputs, + const bool use_cuda); + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..e76959805a5cdee9d94582b09f76d3750e0ecdc4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/compiler.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::fuser { + +// Performs device-independent "upfront" compilation of the given fusion_group, +// if it has not been registered already. +// Returns a key that can be used to run the fusion later +TORCH_API int64_t registerFusion(const Node* fusion_group); + +// Performs device-specific "runtime" compilation of the given kernel +// with the runtime arguments specified in ArgSpec. +// Outputs are allocated using map_size on the specified device. +TORCH_API std::shared_ptr compileKernel( + const KernelSpec& spec, + const ArgSpec& arg_spec, + const std::vector& map_size, + const at::Device& device); + +TORCH_API size_t nCompiledKernels(); + +TORCH_API int debugFuser(); + +using FusedKernelConstructor = std::function( + int16_t device, + std::string name, + std::string code, + std::vector input_desc, + std::vector output_desc, + std::vector chunk_desc, + std::vector concat_desc, + bool has_random)>; + +TORCH_API void registerFusionBackend( + at::Device::Type backend_type, + FusedKernelConstructor ctor); +TORCH_API bool hasFusionBackend(at::Device::Type backend_type); +struct TORCH_API RegisterFusionBackend{RegisterFusionBackend( + at::Device::Type backend_type, + FusedKernelConstructor ctor){ + registerFusionBackend(backend_type, std::move(ctor)); +} // namespace torch::jit::fuser +} +; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/fused_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/fused_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..13e37fe47a442853f902b18967222dfd930cec2c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/fused_kernel.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser::cpu { + +// Represents a compiled CPU kernel and the metadata necessary to run it +struct TORCH_API FusedKernelCPU : public FusedKernel { + FusedKernelCPU( + std::string name, + std::string code, + std::vector input_desc, + std::vector output_desc, + std::vector chunk_desc, + std::vector concat_desc, + bool has_random); + + at::Backend backend() const override { + return at::Backend::CPU; + } + + void launch_raw(const uint32_t numel, std::vector& arguments) + const override { + kernel(numel, arguments.data()); + } + + private: + std::unique_ptr so_lib; + void (*kernel)(uint32_t, void**) = nullptr; +}; + +} // namespace torch::jit::fuser::cpu + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/resource_strings.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/resource_strings.h new file mode 100644 index 0000000000000000000000000000000000000000..62c3008b31ff5ecacfca5541068ced287dcb84cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/resource_strings.h @@ -0,0 +1,106 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::cpu { + +/*with type_as not checking type of its input, a fusion group can have non-fp32 +tensor as input. Correct code for this case is generated, however, nvrtc does +not know how to handle int*_t integer types, so typedefs help it handle those +cases*/ + +static auto type_declarations_template = at::jit::CodeTemplate(R"( + +#define POS_INFINITY INFINITY +#define NEG_INFINITY -INFINITY + +typedef ${IndexType} IndexType; +template +struct TensorInfo { + T* data; + IndexType sizes[N]; + IndexType strides[N]; +}; +template +struct TensorInfo { + T * data; +}; +)"); + +static auto cpu_compilation_unit_template = at::jit::CodeTemplate(R"( +#include +#include +#include + +double rsqrt(double x) { + return 1.0/sqrt(x); +} + +float rsqrtf(float x) { + return 1.0f/sqrtf(x); +} + +double frac(double x) { + return x - trunc(x); +} + +float fracf(float x) { + return x - truncf(x); +} + +${type_declarations} + +#ifdef _MSC_VER +template struct int_of_size; + +#define DEFINE_INT_OF_SIZE(int_t) \ +template<> struct int_of_size { using type = int_t; } + +DEFINE_INT_OF_SIZE(int64_t); +DEFINE_INT_OF_SIZE(int32_t); +DEFINE_INT_OF_SIZE(int16_t); +DEFINE_INT_OF_SIZE(int8_t); + +#undef DEFINE_INT_OF_SIZE + +template +using int_same_size_t = typename int_of_size::type; + +#define IndexTypeLoop int_same_size_t +#define ToIndexTypeLoop(x) static_cast(x) +#else +#define IndexTypeLoop IndexType +#define ToIndexTypeLoop(x) x +#endif + +#define OMP_THRESHOLD 100000 +static void ${kernelName}_kernel(IndexType totalElements, ${formals}) { + #pragma omp parallel for if(totalElements > OMP_THRESHOLD) + for (IndexTypeLoop linearIndex = 0; + linearIndex < ToIndexTypeLoop(totalElements); + linearIndex += 1) { + // Convert `linearIndex` into an offset of tensor: + ${tensorOffsets} + // calculate the results + ${kernelBody} + } +} + +#ifdef _WIN32 +#define JIT_API __declspec(dllexport) +#else +#define JIT_API +#endif + +extern "C" +JIT_API void ${kernelName}(IndexType totalElements, void ** args) { + ${kernelName}_kernel(totalElements ${,argument_loads}); +} +)"); + +} // namespace torch::jit::fuser::cpu + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/temp_file.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/temp_file.h new file mode 100644 index 0000000000000000000000000000000000000000..726ca1e7cc63e1fa32a04b9ca9995aad365ff778 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/temp_file.h @@ -0,0 +1,140 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#else +#include +#endif + +#include +#include + +namespace torch::jit::fuser::cpu { + +#ifdef _MSC_VER +inline int wmkstemps(wchar_t* tmpl, int suffix_len) { + int len; + wchar_t* name; + int fd = -1; + int save_errno = errno; + + len = wcslen(tmpl); + if (len < 6 + suffix_len || + wcsncmp(&tmpl[len - 6 - suffix_len], L"XXXXXX", 6)) { + return -1; + } + + name = &tmpl[len - 6 - suffix_len]; + + std::random_device rd; + do { + for (unsigned i = 0; i < 6; ++i) { + name[i] = "abcdefghijklmnopqrstuvwxyz0123456789"[rd() % 36]; + } + + fd = _wopen(tmpl, _O_RDWR | _O_CREAT | _O_EXCL, _S_IWRITE | _S_IREAD); + } while (errno == EEXIST); + + if (fd >= 0) { + errno = save_errno; + return fd; + } else { + return -1; + } +} +#endif + +struct TempFile { + AT_DISALLOW_COPY_AND_ASSIGN(TempFile); + + TempFile(const std::string& t, int suffix) { +#ifdef _MSC_VER + auto wt = c10::u8u16(t); + std::vector tt(wt.c_str(), wt.c_str() + wt.size() + 1); + int fd = wmkstemps(tt.data(), suffix); + AT_ASSERT(fd != -1); + file_ = _wfdopen(fd, L"r+"); + auto wname = std::wstring(tt.begin(), tt.end() - 1); + name_ = c10::u16u8(wname); +#else + // mkstemps edits its first argument in places + // so we make a copy of the string here, including null terminator + std::vector tt(t.c_str(), t.c_str() + t.size() + 1); + int fd = mkstemps(tt.data(), suffix); + AT_ASSERT(fd != -1); + file_ = fdopen(fd, "r+"); + // - 1 because tt.size() includes the null terminator, + // but std::string does not expect one + name_ = std::string(tt.begin(), tt.end() - 1); +#endif + } + + const std::string& name() const { + return name_; + } + + void sync() { + fflush(file_); + } + + void write(const std::string& str) { + size_t result = fwrite(str.c_str(), 1, str.size(), file_); + AT_ASSERT(str.size() == result); + } + +#ifdef _MSC_VER + void close() { + if (file_ != nullptr) { + fclose(file_); + } + file_ = nullptr; + } +#endif + + FILE* file() { + return file_; + } + + ~TempFile() { +#ifdef _MSC_VER + if (file_ != nullptr) { + fclose(file_); + } + auto wname = c10::u8u16(name_); + if (!wname.empty() && _waccess(wname.c_str(), 0) != -1) { + _wunlink(wname.c_str()); + } +#else + if (file_ != nullptr) { + // unlink first to ensure another mkstemps doesn't + // race between close and unlink + unlink(name_.c_str()); + fclose(file_); + } +#endif + } + + private: + FILE* file_ = nullptr; + std::string name_; +}; + +} // namespace torch::jit::fuser::cpu + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/fused_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/fused_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..85c23b394ab73e4cce98eb632a4979059f2429d3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/fused_kernel.h @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser::cuda { + +// query codegen output arch and target +TORCH_CUDA_CU_API void codegenOutputQuery( + const cudaDeviceProp* const prop, + int& major, + int& minor, + bool& compile_to_sass); + +// A class holding metadata for an actual CUDA function. +// Note: CUDA functions are per device. +struct TORCH_CUDA_CU_API FusedKernelCUDA + : public ::torch::jit::fuser::FusedKernel { + FusedKernelCUDA( + at::DeviceIndex device, + std::string name, + std::string code, + std::vector input_desc, + std::vector output_desc, + std::vector chunk_desc, + std::vector concat_desc, + bool has_random); + + ~FusedKernelCUDA() override; + + void launch_raw(const uint32_t numel, std::vector& arguments) + const override; + + at::Backend backend() const override { + return at::Backend::CUDA; + } + + private: + static constexpr auto kBlockSize = 128; + + // Note: per device to store device properties and compute launch heuristics + // Acquiring these values at launch time would be too slow + at::DeviceIndex device_; + int maxBlocks_{}; + cudaDeviceProp* prop_{}; + std::vector ptx_; + CUmodule module_{}; + CUfunction function_{}; +}; + +} // namespace torch::jit::fuser::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/resource_strings.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/resource_strings.h new file mode 100644 index 0000000000000000000000000000000000000000..b495251ad391d9d9a86ab1c8867e84dfd1f07f07 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/resource_strings.h @@ -0,0 +1,417 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit::fuser::cuda { + +/*with type_as not checking type of its input, a fusion group can have non-fp32 +tensor as input. Correct code for this case is generated, however, nvrtc does +not know how to handle int*_t integer types, so typedefs help it handle those +cases*/ + +static constexpr auto bfloat16_type_string = "__nv_bfloat16"; + +#if defined(USE_ROCM) && ROCM_VERSION < 70000 +static auto type_declarations_template = at::jit::CodeTemplate(R"( +${HalfHeader} +${BFloat16Header} +${RandHeader} + +#define NAN __int_as_float(0x7fffffff) +#define POS_INFINITY __int_as_float(0x7f800000) +#define NEG_INFINITY __int_as_float(0xff800000) + +typedef ${IndexType} IndexType; +template +struct TensorInfo { + T* data; + IndexType sizes[N]; + IndexType strides[N]; +}; +template +struct TensorInfo { + T * data; +}; +)"); +#else +static auto type_declarations_template = at::jit::CodeTemplate(R"( +typedef unsigned char uint8_t; +typedef signed char int8_t; +typedef short int int16_t; +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +${HalfHeader} +${BFloat16Header} +${RandHeader} + +#define NAN __int_as_float(0x7fffffff) +#define POS_INFINITY __int_as_float(0x7f800000) +#define NEG_INFINITY __int_as_float(0xff800000) + +typedef ${IndexType} IndexType; +template +struct TensorInfo { + T* data; + IndexType sizes[N]; + IndexType strides[N]; +}; +template +struct TensorInfo { + T * data; +}; +)"); +#endif + +// We rewrite the code for philox RNG from curand as nvrtc couldn't resolve the +// curand header correctly. +constexpr auto rand_support_literal = 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 uniform(unsigned int x) { + return x * M_RAN_INVM32; + } +)"; + +constexpr auto rand_param = + ",unsigned long long seed, unsigned long long offset"; + +constexpr auto rand_init = R"( + int idx = blockIdx.x*blockDim.x + threadIdx.x; + Philox rnd(seed, idx, offset); +)"; + +static auto cuda_compilation_unit_template = at::jit::CodeTemplate(R"( +${type_declarations} + +extern "C" __global__ +void ${kernelName}(IndexType totalElements, ${formals} ${RandParam}) { + ${RandInit} + // check whether do vectorized load/store and allocate buffer + bool flag_vec4 = true; + ${tensorChecks} + if (flag_vec4) { + for (IndexType linearIndex = 4 * (blockIdx.x * blockDim.x + threadIdx.x); + linearIndex < totalElements; + linearIndex += 4 * gridDim.x * blockDim.x) { + // Convert `linearIndex` into an offset of tensor as it is: + ${tensorOffsets} + // load 4 at a time + ${kernelLoad} + #pragma unroll 4 + for (int i=0; i<4; i++) { + // calculate the results + ${kernelBody_vec4} + } + // store 4 at a time + ${kernelStore} + } + } else { + for (IndexType linearIndex = blockIdx.x * blockDim.x + threadIdx.x; + linearIndex < totalElements; + linearIndex += gridDim.x * blockDim.x) { + // Convert `linearIndex` into an offset of tensor: + ${tensorOffsets} + // calculate the results + ${kernelBody} + } + } +} +)"); + +// This snippet enables half support in the jit. Following the pattern for +// reductions, fp16 input data is immediately upconverted to float +// with __half2float(). All mathematical operations are done on float +// values, and if needed the intermediate float representation is +// converted to half with __float2half() when writing to a half tensor. +#if defined(USE_ROCM) +constexpr auto half_support_literal = + R"( +typedef __half half; +)"; +#else +constexpr auto half_support_literal = + R"( +#define __HALF_TO_US(var) *(reinterpret_cast(&(var))) +#define __HALF_TO_CUS(var) *(reinterpret_cast(&(var))) +#if defined(__cplusplus) + struct __align__(2) __half { + __host__ __device__ __half() { } + + protected: + unsigned short __x; + }; + + /* All intrinsic functions are only available to nvcc compilers */ + #if defined(__CUDACC__) + /* Definitions of intrinsics */ + __device__ __half __float2half(const float f) { + __half val; + asm("{ cvt.rn.f16.f32 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "f"(f)); + return val; + } + + __device__ float __half2float(const __half h) { + float val; + asm("{ cvt.f32.f16 %0, %1;}\n" : "=f"(val) : "h"(__HALF_TO_CUS(h))); + return val; + } +)" + // MSVC's preprocessor (but not the standard compiler) has a bug + // where it incorrectly tokenizes raw string literals, ending when it sees a + // " this causes the #endif in this string literal to be treated as a + // preprocessor token which, in turn, cause sccache on windows CI to fail. + // See https://godbolt.org/z/eVTIJq as an example. + // This workaround uses string-pasting to separate the " and the #endif into + // different strings + R"( + #endif /* defined(__CUDACC__) */ +#endif /* defined(__cplusplus) */ +#undef __HALF_TO_US +#undef __HALF_TO_CUS + +typedef __half half; +)"; +#endif + +#if defined(USE_ROCM) + +#if ROCM_VERSION >= 70000 +#define BF16_UINT32_DEF "typedef unsigned int uint32_t;\n" +#else +#define BF16_UINT32_DEF "" +#endif + +constexpr auto bfloat16_support_literal = + R"( +#ifndef __align__ +#define __align__(x) __attribute__((aligned(x))) +#endif +)" BF16_UINT32_DEF R"( +typedef struct __align__(2) { + unsigned short x; +} +__nv_bfloat16_raw; + +#if defined(__cplusplus) +struct __align__(2) __nv_bfloat16 { + __host__ __device__ __nv_bfloat16() {} + + __host__ __device__ __nv_bfloat16& operator=(const __nv_bfloat16_raw& hr) { + __x = hr.x; + return *this; + } + + unsigned short __x; +}; + +__device__ unsigned short __internal_float2bfloat16( + const float f, + unsigned int& sign, + unsigned int& remainder) { + unsigned int x; + + x = __float_as_uint(f); + + if ((x & 0x7fffffffU) > 0x7f800000U) { + sign = 0U; + remainder = 0U; + return static_cast(0x7fffU); + } + sign = x >> 31; + remainder = x << 16; + return static_cast(x >> 16); +} + +/* Definitions of intrinsics */ +__device__ __nv_bfloat16 __float2bfloat16(const float a) { + __nv_bfloat16 val; + __nv_bfloat16_raw r; + unsigned int sign; + unsigned int remainder; + r.x = __internal_float2bfloat16(a, sign, remainder); + if ((remainder > 0x80000000U) || + ((remainder == 0x80000000U) && ((r.x & 0x1U) != 0U))) { + r.x++; + } + val = r; + return val; +} + +__device__ float __bfloat162float(const __nv_bfloat16 a) { + union + { + uint32_t int32; + float fp32; + } u = {uint32_t(a.__x) << 16}; + return u.fp32; +} +#endif /* defined(__cplusplus) */ +)"; +#else +constexpr auto bfloat16_support_literal = + R"( +#define __BFLOAT16_TO_US(var) *(reinterpret_cast(&(var))) +#define __BFLOAT16_TO_CUS(var) \ + *(reinterpret_cast(&(var))) + +typedef struct __align__(2) { + unsigned short x; +} +__nv_bfloat16_raw; + +#if defined(__cplusplus) +struct __align__(2) __nv_bfloat16 { + __host__ __device__ __nv_bfloat16() {} + + __host__ __device__ __nv_bfloat16& operator=(const __nv_bfloat16_raw& hr) { + __x = hr.x; + return *this; + } + + protected: + unsigned short __x; +}; + +#if defined(__CUDACC__) +__device__ unsigned short __internal_float2bfloat16( + const float f, + unsigned int& sign, + unsigned int& remainder) { + unsigned int x; + + x = __float_as_uint(f); + + if ((x & 0x7fffffffU) > 0x7f800000U) { + sign = 0U; + remainder = 0U; + return static_cast(0x7fffU); + } + sign = x >> 31; + remainder = x << 16; + return static_cast(x >> 16); +} + +/* Definitions of intrinsics */ +__device__ __nv_bfloat16 __float2bfloat16(const float a) { + __nv_bfloat16 val; +#if __CUDA_ARCH__ >= 800 + asm("{ cvt.rn.bf16.f32 %0, %1;}\n" : "=h"(__BFLOAT16_TO_US(val)) : "f"(a)); +#else + __nv_bfloat16_raw r; + unsigned int sign; + unsigned int remainder; + r.x = __internal_float2bfloat16(a, sign, remainder); + if ((remainder > 0x80000000U) || + ((remainder == 0x80000000U) && ((r.x & 0x1U) != 0U))) { + r.x++; + } + val = r; +#endif + return val; +} + +__device__ float __bfloat162float(const __nv_bfloat16 a) { + float val; + asm("{ mov.b32 %0, {0,%1};}\n" : "=f"(val) : "h"(__BFLOAT16_TO_CUS(a))); + return val; +} +#endif /* defined(__CUDACC__) */ +#endif /* defined(__cplusplus) */ +#undef __BFLOAT16_TO_US +#undef __BFLOAT16_TO_CUS +)"; +#endif + +} // namespace torch::jit::fuser::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/executor.h new file mode 100644 index 0000000000000000000000000000000000000000..aa6c691a0b807558cb4f5ce030dd156afb128a18 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/executor.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit::fuser { + +// Runs the fusion associated with the key (see registerFusion() in interface.h) +// on the inputs taken from the given Stack. +TORCH_API bool runFusion( + const int64_t key, + Stack& stack, + std::string* code_out = nullptr); + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fallback.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fallback.h new file mode 100644 index 0000000000000000000000000000000000000000..393127a6e99dc29fa41aecbb36d7e437e3a5bd51 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fallback.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit::fuser { + +void runFallback(int64_t key, Stack& stack); + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fused_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fused_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ca2adedd7b196d1db9dddca4b3319c51e7060226 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fused_kernel.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser { + +struct FusedKernel { + AT_DISALLOW_COPY_AND_ASSIGN(FusedKernel); + + FusedKernel( + std::string name, + std::string code, + std::vector input_desc, + std::vector output_desc, + std::vector chunk_desc, + std::vector concat_desc, + bool has_random) + : name_(std::move(name)), + code_(std::move(code)), + input_desc_(std::move(input_desc)), + output_desc_(std::move(output_desc)), + chunk_desc_(std::move(chunk_desc)), + concat_desc_(std::move(concat_desc)), + has_random_(has_random) {} + + virtual ~FusedKernel() = default; + + // arguments is a list of pointers to the arguments for the compiled CUDA/CPU + // code. + // The format of arguments is suitable for directly passing to a call to + // cuLaunchKernel as the kernel arguments. + // Currently the first argument is a pointer to numel (for passing to + // CUDA code), and the remainder are pointers to the TensorInfo structs + // that compiled code uses to load Tensor data. + // launch_with_tensors handles packing at::Tensors into this arguments array. + // CPU code uses the same convention so that launch_with_tensors can be + // shared. + virtual void launch_raw(const uint32_t numel, std::vector& arguments) + const = 0; + virtual at::Backend backend() const = 0; + + // Getters + const std::string& name() const { + return name_; + } + const std::string& code() const { + return code_; + } + const std::vector& inputDesc() const { + return input_desc_; + } + const std::vector& outputDesc() const { + return output_desc_; + } + const std::vector& chunkDesc() const { + return chunk_desc_; + } + const std::vector& concatDesc() const { + return concat_desc_; + } + bool hasRandom() const { + return has_random_; + } + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::string name_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::string code_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector input_desc_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector output_desc_; + + // same size as input_desc, describes whether an + // input should be broken into subtensors (chunks) + // to be consumed by the fusion group + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector chunk_desc_; + + // same size as output_desc, describes whether + // an output is actually a concatenation of + // many subtensors that the fusion group produces + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector concat_desc_; + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const bool has_random_; +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..516e192a0fb38a1c4af1cd56a9bff94509335347 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/interface.h @@ -0,0 +1,59 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit { + +constexpr int kCPUDevice = -1; + +// Assigns a "key" to the given fusion_group that it can use to run its +// fusion later (via runFusion() below). +TORCH_API int64_t registerFusion(const Node* fusion_group); + +// Runs the fusion corresponding to the given key on the inputs +// found on the stack. Outputs are placed on the same stack. +// In some cases a fusion cannot be run and a fallback path where +// PyTorch's interpreter runs the graph instead is attempted. +TORCH_API void runFusion(const int64_t key, Stack& stack); + +// True if the respective devices can fuse, false otherwise +TORCH_API bool canFuseOnCPU(); +TORCH_API bool canFuseOnGPU(); + +// Sets whether fusion on the CPU is allowed (disabled by default due to +// flakiness) +TORCH_API void overrideCanFuseOnCPU(bool value); + +// Sets whether fusion on CPU must use LLVM Codegen and not SimplieIREval +TORCH_API void overrideMustUseLLVMOnCPU(bool value); + +// Sets whether fusion on the GPU is allowed (enabled by default) +TORCH_API void overrideCanFuseOnGPU(bool value); + +// Treats the given graph as a fusion group and launches it on the +// specified device with the given inputs. +// Returns the outputs. +TORCH_API std::vector debugLaunchGraph( + Graph& graph, + at::ArrayRef inputs); + +// Treats the given graph as a fusion group and returns the generated code. +TORCH_API std::string debugGetFusedKernelCode( + Graph& graph, + at::ArrayRef inputs); + +TORCH_API size_t nCompiledKernels(); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..d2446f6aa8af57c66c8eeef1c5198cf5199e966f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_cache.h @@ -0,0 +1,38 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser { + +// A thread-safe cache interface. + +// Normalizes the graph by canonicalizing and erasing shape information +TORCH_API std::shared_ptr normalizeGraphForCache( + const std::shared_ptr& graph); + +// Stores the given graph, returning the key used to access it +TORCH_API int64_t store(std::shared_ptr graph); + +// Given a graph, find a KernelSpec based on it +TORCH_API std::optional lookupGraph( + const std::shared_ptr& graph); + +// Returns the graph corresponding to the given key (if it exists) +TORCH_API std::optional retrieve(const int64_t key); + +// Returns the size of the fusion key -> KernelSpec cache. +// Only used for testing. +TORCH_API int64_t debugNumCachedKernelSpecs(); + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_spec.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..a84bcc7b3b7c18de8bda1dfc1905a44f77cead26 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_spec.h @@ -0,0 +1,149 @@ +#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::fuser { + +// Helper struct containing partition information: the number of tensors +// created and the dimension the partitioning is performed on. +// Note: created during upfront compilation, once the tensors are known +// at runtime the partition info is logically combined with the tensor +// descriptions to create PartitionDesc objects. +struct TORCH_API PartitionInfo { + PartitionInfo(const int64_t _nSubTensors, const int64_t _dim) + : nSubTensors_{_nSubTensors}, dim_{_dim} {} + + int64_t nSubTensors() const { + return nSubTensors_; + } + int64_t dim() const { + return dim_; + } + + private: + int64_t nSubTensors_; + int64_t dim_; +}; + +// "Kernel Specification." - Contains device-independent fusion information. +// Each kernel specification contains a map of instantiated generated functions +// that implement some or most of its functionality. Multiple generated +// functions are needed by each abstract specification because of different +// devices (cpu vs gpu, different gpus) and different inputs (int vs float, +// contiguous vs discontiguous). +// Note: uses a mutex to control access to its kernel store +// Note: unordered containers do not invalidate references/pointers on +// rehashing, which is critical for thread-safety. +// TODO: allow abstract kernels to use multiple generated kernels +// TODO: allow abstract kernels to reuse generated kernels from common pool +struct TORCH_API KernelSpec { + // Note: assumes the spec is a single block + // Note: This is the appropriate place to generalize if you want to add other + // passes to upfront compilation that walk the graph. + KernelSpec(const int64_t _key, const std::shared_ptr& _graph) + : key_{_key}, + graph_{_graph}, + code_{_graph, ""}, + nInputs_{_graph->inputs().size()} + + { + // No need to iterate over reference since n is pointer + for (const auto n : graph_->nodes()) { + static_assert(std::is_pointer_v, "n must be a pointer"); + if (n->kind() == aten::rand_like) { + has_random_ = true; + break; + } + } + nTensorInputs_ = std::count_if( + graph_->inputs().begin(), graph_->inputs().end(), [](const Value* v) { + return v->type()->isSubtypeOf(*TensorType::get()); + }); + } + + // Getters + int64_t key() const { + return key_; + } + std::shared_ptr graph() const { + return graph_; + } + const Code& code() const { + return code_; + } + int64_t nInputs() const { + return nInputs_; + } + int64_t nTensorInputs() const { + return nTensorInputs_; + } + + std::vector>& inputBroadcastGroups() { + return inputBroadcastGroups_; + } + const std::vector>& inputBroadcastGroups() const { + return inputBroadcastGroups_; + } + + std::vector& inputChunks() { + return inputChunks_; + } + const std::vector& inputChunks() const { + return inputChunks_; + } + + bool hasRandom() const { + return has_random_; + } + + // Cache functions + std::optional> findKernel( + const ArgSpec& arg_spec) const { + std::lock_guard guard{mutex_}; + const auto it = kernels_.find(arg_spec); + if (it == kernels_.end()) + return std::nullopt; + return it->second; + } + void cacheKernel( + const ArgSpec& arg_spec, + const std::shared_ptr& kernel) const { + std::lock_guard guard{mutex_}; + kernels_.emplace(arg_spec, kernel); + } + + private: + int64_t key_; + std::shared_ptr graph_; + Code code_; + uint64_t nInputs_; + uint64_t nTensorInputs_{}; + std::vector> inputBroadcastGroups_; + std::vector inputChunks_; + bool has_random_{false}; + mutable std::mutex mutex_; + mutable std:: + unordered_map, c10::hash> + kernels_; +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/partition_desc.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/partition_desc.h new file mode 100644 index 0000000000000000000000000000000000000000..6eee194e80d162044d5065be72d9e2797df3db2f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/partition_desc.h @@ -0,0 +1,63 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser { + +// Descriptor for chunk-ing an input tensor into subtensors +// OR concat-ing an output tensor from subtensors +// Note: default constructed used for tensors that do not participate in +// chunk or cat operations. +struct TORCH_API PartitionDesc { + PartitionDesc() : nSubTensors_{1}, dim_{0} {} + + PartitionDesc(const TensorDesc& _desc, size_t _nSubTensors, size_t _dim) + : nSubTensors_{_nSubTensors}, dim_{_dim} { + AT_ASSERT(nSubTensors_ > 1); + std::vector cont = _desc.contiguity; + if (dim_ > 0) { + // when we narrow the concatenated output/chunked input + // we make the size[dim] smaller while keeping the stride[dim] the same, + // meaning: stride[dim - 1] != stride[dim]*size[dim] + // so dim - 1 is no longer contiguous + cont[dim_ - 1] = false; + } + subTensorDesc_ = std::make_shared(_desc.scalar_type, cont); + } + + bool isNoop() const { + return (nSubTensors_ == 1); + } + size_t nSubTensors() const { + return nSubTensors_; + } + size_t dim() const { + return dim_; + } + std::shared_ptr subTensorDesc() { + return subTensorDesc_; + } + const std::shared_ptr subTensorDesc() const { + return subTensorDesc_; + } + + private: + size_t nSubTensors_; // == 1 for tensors that should not be operated on via + // chunk/cat + size_t dim_; // dimension along which the chunk/concat occurs + std::shared_ptr + subTensorDesc_; // descriptor for the subtensor, if it exists +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_desc.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_desc.h new file mode 100644 index 0000000000000000000000000000000000000000..0376875925a04b26615051b34d72ff4bf481898f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_desc.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser { + +// type information needed by the compiler for input/outputs +// contiguity[i] is true if the dim i is contiguous with dim i + 1. +// contiguity.back() == true means strides.back() == 1. +struct TORCH_API TensorDesc { + at::ScalarType scalar_type; + std::vector contiguity; + + TensorDesc(const at::ScalarType& type, const std::vector& contiguity) + : scalar_type{type}, contiguity{contiguity} { + if (contiguity.empty()) { + nDim_ = 0; + } else { + nDim_ = std::count(contiguity.begin(), contiguity.end(), false) + + (lastIsContiguous() ? 1 : 0); + } + } + + // Delegating constructors + TensorDesc( + const at::ScalarType& type, + const at::IntArrayRef& sizes, + const at::IntArrayRef& strides) + : TensorDesc(type, TensorDesc::findContiguous(sizes, strides)) {} + + TensorDesc(const at::Tensor& t) + : TensorDesc(t.scalar_type(), t.sizes(), t.strides()) {} + + TensorDesc(const c10::TensorTypePtr& type) + : TensorDesc( + type->scalarType().value(), + type->sizes().concrete_sizes().value(), + type->strides().concrete_sizes().value()) {} + + // number of dimensions after contiguity compression + size_t nDim() const { + return nDim_; + } + + // True iff innermost stride is 1 + bool lastIsContiguous() const { + return (contiguity.empty() || contiguity.back()); + } + + static std::vector findContiguous( + const at::IntArrayRef& sizes, + const at::IntArrayRef& strides) { + AT_ASSERT(sizes.size() == strides.size()); + std::vector cont(sizes.size()); + for (size_t i = 0; i < sizes.size(); ++i) { + const auto expected_stride = + (i + 1 < sizes.size()) ? sizes[i + 1] * strides[i + 1] : 1; + cont[i] = (strides[i] == expected_stride); + } + return cont; + } + + bool operator==(const TensorDesc& desc) const { + return scalar_type == desc.scalar_type && contiguity == desc.contiguity; + } + + bool operator!=(const TensorDesc& desc) const { + return !(*this == desc); + } + + static size_t hash(const TensorDesc& spec) { + return c10::get_hash( + spec.scalar_type, + spec.nDim_, + std::hash>{}(spec.contiguity)); + } + + private: + size_t nDim_; +}; + +inline std::ostream& operator<<(std::ostream& out, const TensorDesc& d) { + out << d.scalar_type << '['; + for (const auto b : d.contiguity) + out << b << ';'; + out << ']'; + return out; +} + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_info.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_info.h new file mode 100644 index 0000000000000000000000000000000000000000..df2c1e12963bdaa58b56e688a3d6b950ee4e2f2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_info.h @@ -0,0 +1,29 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include + +namespace torch::jit::fuser { + +// Host-side view of TensorInfo +// Note dims[0] - we need to dynamically allocate the dims. +struct TORCH_API TensorInfo { + uint32_t* sizes(size_t nDim) { + return &sizes_strides[0]; + } + uint32_t* strides(size_t nDim) { + return &sizes_strides[nDim]; + } + + void* data; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + uint32_t sizes_strides[0]; +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/LlgaTensorImpl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/LlgaTensorImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..72f267a4cffaffb73f8d10d2b1b129efe5cb159f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/LlgaTensorImpl.h @@ -0,0 +1,277 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser::onednn { + +// Engine represents a device and its context. From the device kind, the engine +// knows how to generate code for the target device and what kind of device +// object to be expected. The device id ensures that there is a unique engine +// being created for each device. The device handle passed from PyTorch allows +// oneDNN Graph implementation to work on the device specified by PyTorch, which +// is currently CPU, so we only have one engine. +// Ref: +// https://oneapi-spec.uxlfoundation.org/specifications/oneapi/latest/elements/onednn/source/graph/programming_model#engine +struct Engine { + // CPU engine singleton + static dnnl::engine& getEngine(); + Engine(const Engine&) = delete; + void operator=(const Engine&) = delete; +}; + +// Stream is the logical abstraction for execution units. It is created on top +// of oneDNN Graph engine. A compiled oneDNN Graph partition is submitted to a +// stream for execution. +struct Stream { + // CPU stream singleton + static dnnl::stream& getStream(); + Stream(const Stream&) = delete; + void operator=(const Stream&) = delete; +}; + +struct LlgaTensorDesc { + using desc = dnnl::graph::logical_tensor; + + LlgaTensorDesc( + size_t tid, + std::vector sizes, + std::vector strides, + desc::data_type dtype, + desc::property_type property_type) + : tid_(tid), + sizes_(std::move(sizes)), + strides_(std::move(strides)), + dtype_(dtype), + property_type_(property_type), + layout_type_(desc::layout_type::strided), + layout_id_(-1) {} + + LlgaTensorDesc(const desc& t) + : tid_(t.get_id()), + sizes_(t.get_dims()), + strides_({-1}), + dtype_(t.get_data_type()), + property_type_(t.get_property_type()), + layout_type_(t.get_layout_type()), + layout_id_(-1) { + if (is_opaque()) { + layout_id_ = t.get_layout_id(); + } + if (is_strided()) { + strides_ = t.get_strides(); + } + } + + LlgaTensorDesc(const torch::jit::Value* v) + : LlgaTensorDesc( + v->unique(), + {}, + {}, + desc::data_type::f32, + get_property_type(v)) { + if (v->type()->isSubtypeOf(TensorType::get())) { + auto tt = v->type()->cast(); + + if (tt->scalarType()) { + dtype_ = getLlgaDataType(tt->scalarType().value()); + } + + auto sizes = tt->sizes(); + if (sizes.sizes()) { + for (auto d : *sizes.sizes()) { + sizes_.push_back(d.value_or(DNNL_GRAPH_UNKNOWN_DIM)); + } + } + + auto strides = tt->strides(); + if (strides.sizes()) { + for (auto d : *strides.sizes()) { + strides_.push_back(d.value_or(DNNL_GRAPH_UNKNOWN_DIM)); + } + } + } + } + + LlgaTensorDesc supplementTensorInfo(const at::Tensor& t) const; + + desc::data_type getLlgaDataType(at::ScalarType dt) const; + + at::ScalarType aten_scalar_type() const; + + const std::vector& sizes() const { + return sizes_; + } + + const std::vector& strides() const { + TORCH_CHECK(!is_opaque(), "Cannot get strides on opaque layout"); + return strides_; + } + + size_t tid() const { + return tid_; + } + + LlgaTensorDesc tid(uint64_t new_id) const { + auto ret = *this; + ret.tid_ = new_id; + return ret; + } + + desc::data_type dtype() const { + return dtype_; + } + + LlgaTensorDesc dtype(desc::data_type new_dtype) const { + return LlgaTensorDesc(tid_, sizes_, strides_, new_dtype, property_type_); + } + + desc::layout_type layout_type() const { + return layout_type_; + } + + LlgaTensorDesc layout_type(desc::layout_type new_layout_type) { + auto ret = *this; + ret.layout_type_ = new_layout_type; + return ret; + } + + desc::property_type get_property_type(const torch::jit::Value* v) { + switch (v->node()->kind()) { + case prim::Constant: + return desc::property_type::constant; + default: + return desc::property_type::variable; + } + } + + LlgaTensorDesc any() { + return layout_type(desc::layout_type::any); + } + + size_t storage_size() const { + return logical_tensor().get_mem_size(); + } + + desc logical_tensor() const { + if (is_dimensionality_unknown()) { + return desc( + tid_, dtype_, DNNL_GRAPH_UNKNOWN_NDIMS, layout_type_, property_type_); + } else if (is_opaque()) { + return desc(tid_, dtype_, sizes_, layout_id_, property_type_); + } else if (is_any()) { + return desc(tid_, dtype_, sizes_, layout_type_, property_type_); + } else { + return desc(tid_, dtype_, sizes_, strides_, property_type_); + } + } + + bool is_strided() const { + return layout_type_ == desc::layout_type::strided; + } + + bool is_any() const { + return layout_type_ == desc::layout_type::any; + } + + bool is_opaque() const { + return layout_type_ == desc::layout_type::opaque; + } + + bool operator==(const LlgaTensorDesc& desc) const { + return tid_ == desc.tid_ && sizes_ == desc.sizes_ && + dtype_ == desc.dtype_ && layout_type_ == desc.layout_type_ && + ((is_opaque() && layout_id_ == desc.layout_id_) || + strides_ == desc.strides_); + } + + bool operator!=(const LlgaTensorDesc& desc) const { + return (tid_ != desc.tid_) || (sizes_ != desc.sizes_) || + (dtype_ != desc.dtype_) || (layout_type_ != desc.layout_type_) || + !((is_opaque() && (layout_id_ == desc.layout_id_)) || + (strides_ == desc.strides_)); + } + + static size_t hash(const LlgaTensorDesc& desc) { + return c10::get_hash( + desc.tid_, + desc.sizes_, + desc.dtype_, + desc.layout_type_, + desc.layout_id_); + } + + void set_compute_inplace() { + compute_inplace_ = true; + } + + void set_input_tensor_index(size_t index) { + input_tensor_index_ = index; + } + + bool reuses_input_tensor() { + return compute_inplace_; + } + + size_t get_input_tensor_index() { + return input_tensor_index_; + } + + private: + bool is_dimensionality_unknown() const { + return sizes_.empty(); + } + + size_t tid_; + std::vector sizes_; + std::vector strides_; + desc::data_type dtype_; + desc::property_type property_type_; + desc::layout_type layout_type_; + size_t layout_id_; + // If this is an output tensor, and querying the compiled partition would + // determine that this tensor would reuse its input tensor, then + // compute_inplace would be true, and input_tensor_index would be the index of + // the corresponding input tensor in inputSpecs_ of the LlgaKernel object. + bool compute_inplace_ = false; + size_t input_tensor_index_{}; +}; + +// Initially, oneDNN Graph also used to have blocked layout for tensors between +// partitions, and the LlgaTensorImpl wrapper helped us bypass guard checks. +// oneDNN Graph has switched over to using strided tensors between partitions, +// but this wrapper still helps us bypass guard checks because the strides of +// tensors between partitions would be different from the ones the guard is +// otherwise expecting. +struct TORCH_API LlgaTensorImpl : public c10::TensorImpl { + LlgaTensorImpl( + at::Storage&& storage, + const caffe2::TypeMeta& data_type, + const LlgaTensorDesc& desc); + + const LlgaTensorDesc& desc() const { + return desc_; + } + + static at::Tensor llga_to_aten_tensor(LlgaTensorImpl* llgaImpl); + + private: + LlgaTensorDesc desc_; +}; + +at::Tensor empty_llga( + const LlgaTensorDesc& desc, + const c10::TensorOptions& options); + +dnnl::graph::tensor llga_from_aten_tensor(const at::Tensor& tensor); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/decompose_silu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/decompose_silu.h new file mode 100644 index 0000000000000000000000000000000000000000..24d20864e42cd77fa0540f8eb6378962af11f52c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/decompose_silu.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +void DecomposeSiluForLLGA(std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/defer_size_check.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/defer_size_check.h new file mode 100644 index 0000000000000000000000000000000000000000..0bb55003e88bb6c9d7b484ed761540a12a48e99a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/defer_size_check.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +void DeferSizeCheck(std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_fuser.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_fuser.h new file mode 100644 index 0000000000000000000000000000000000000000..8f14c5e33a9b3ac58392caaddb6b620c3444fc33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_fuser.h @@ -0,0 +1,52 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit::fuser::onednn { + +struct WorkBlock : public std::pair { + using pair::pair; + + Node* begin() { + return this->first; + } + Node* end() { + return this->second; + } +}; + +class GraphRewriter { + public: + GraphRewriter(Block* block, std::shared_ptr graph, AliasDb& aliasDb) + : block_(block), + graph_(std::move(graph)), + aliasDb_(aliasDb), + llgaHelper_(graph_) {} + + void cleanupSubgraphs(); + void buildupSubgraphs(); + + private: + Block* block_; + std::shared_ptr graph_; + AliasDb& aliasDb_; + LlgaGraphHelper llgaHelper_; + std::vector buildWorkBlocks(); + std::pair scanNode( + Node* consumer, + graph_node_list::iterator workblock_begin); + std::optional tryMerge(Node* consumer, Node* producer); +}; + +// This pass creates the subgraphs for oneDNN Graph Fusion Nodes. +// Its code-structure has been vastly inspired from +// torch/csrc/jit/passes/create_autodiff_subgraphs.cpp +void CreateLlgaSubgraphs(std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_helper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..582db7e71cf4856f2710c8e5aefe19b4383f957f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_helper.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::fuser::onednn { + +#define STRIDED_LAYOUT 0 +#define OPAQUE_LAYOUT 1 + +struct OpPartitionMap { + void add(uint64_t opId, uint64_t partitionId) { + opmap_[opId] = partitionId; + } + void add(Node* n, uint64_t partitionId) { + add(Operator::getId(n), partitionId); + } + bool has(uint64_t opId) { + return opmap_.count(opId) > 0; + } + bool has(Node* n) { + return has(Operator::getId(n)); + } + uint64_t get(uint64_t opId) { + return opmap_[opId]; + } + uint64_t get(Node* n) { + auto opId = Operator::getId(n); + TORCH_CHECK( + has(opId), + "Node ", + n->kind().toQualString(), + " does not belong to any LLGA partition"); + return get(opId); + } + + private: + std::unordered_map opmap_; +}; + +class LlgaGraphHelper { + public: + LlgaGraphHelper( + const std::shared_ptr& graph, + dnnl::graph::partition::policy policy = + dnnl::graph::partition::policy::fusion); + + bool shouldMerge(Node* toMerge, Node* subgraph); + + bool shouldConsiderForMerge(Node* node); + + bool checkForSingleOpPartition(Node* node); + + Node* createSingletonSubgraph(Node* n, AliasDb& db); + + void mergeNodeIntoSubgraph(Node* toMerge, Node* subgraphNode, AliasDb& db); + + void unmergeIfAnyNodeIsMissing(Node* subgraphNode); + + static bool isLlgaSubgraph(const Node* node); + + Operator makeEltwiseOp(Node* node, dnnl::graph::op::kind kind); + + Operator makeBinaryOp(Node* node, dnnl::graph::op::kind kind); + + std::vector getPartitions() const; + + std::map getTensorIdToValue() const; + + Operator createOperator(Node* node); + + private: + size_t countSupportedOps(const std::shared_ptr& graph) const; + std::unique_ptr dnnl_graph_ = nullptr; + std::unique_ptr aliasDb_ = nullptr; + OpPartitionMap opToOwningPartition_; + std::vector partitions_; + std::map + tensorIdToValue_; // map from tensorId to torch::jit::Value +}; + +class LlgaNodeWrapper { + public: + LlgaNodeWrapper(const Node* node); + + void setOpaqueLayout(size_t offset); + + bool useOpaqueLayout(size_t offset) const; + + friend class LlgaGraphHelper; + + private: + Node* n; +}; + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/guard_shape.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/guard_shape.h new file mode 100644 index 0000000000000000000000000000000000000000..73ca360ff573d42805ce3d65f350d9f5f8c9433f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/guard_shape.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +void prepareFusionGroupAndGuardOutputs(Block* block); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..68cc22c7d582f3589ab429c621424d86d73ae30d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/interface.h @@ -0,0 +1,63 @@ +#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{false}; + +static std::atomic& getLlgaEnabled() { + return onednn_enabled; +} + +C10_EXPORT 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0ac5b00556d552b765a6cfa21c76cb4ef0f36525 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/kernel.h @@ -0,0 +1,94 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include + +namespace torch::jit::fuser::onednn { + +using ArgSpec = LlgaTensorDesc; +using ArgSpecs = std::vector; +using RunArg = dnnl::graph::tensor; +using RunArgs = std::vector; +using TensorArgs = std::vector; + +class LlgaKernel { + public: + explicit LlgaKernel(const Node* fusionNode); + + void run(Stack& stack); + + void initialize(const TensorArgs& inputs); + + const std::string& debugName() const { + return debugName_; + } + + private: + bool useOpaqueLayout(size_t offset) const; + + // PyTorch copy constants inside the subgraph instead of referencing them. + // Constants inputs to the partition are no longer in the graph->inputs(). + // Need use the tid retrieved from the partition to find the missing + // constant inputs. + void initializeConstantInputs(); + + ArgSpecs initializeInputSpecs(const TensorArgs& inputs); + + ArgSpecs initializeOutputSpecs() const; + + dnnl::graph::compiled_partition compile( + const dnnl::graph::partition& partition); + + std::map initializeTensorIdToOccurence() const; + + std::tuple prepareRunArgs( + const TensorArgs& inputs, + TensorArgs& outputs) const; + + static std::string genDebugName() { + static size_t debugId = 0; + return "LlgaPartition_" + std::to_string(debugId++); + } + + static dnnl::graph::logical_tensor toLogicalTensor(const ArgSpec& s) { + return s.logical_tensor(); + } + + at::Device device_ = at::kCPU; + const Node* fusionNode_; + std::shared_ptr graph_; + int64_t nGraphInputs_ = 0; // number of inputs to graph_ on the IR + int64_t nOutputs_ = 0; + std::map tensorIdToValue_; + std::vector runArgsIdx_; + dnnl::graph::partition partition_; + // nPartitionInputs_ is the actual number of inputs to partition_ of graph_ + // needed by the backend. + // nPartitionInputs_ = nGraphInputs_ + constantInputs_.size() since Constant + // inputs are copied to the inside of the subgraph + int64_t nPartitionInputs_; + dnnl::graph::compiled_partition compilation_; + std::set initializedInputIds_; + std::vector constantValues_; + TensorArgs constantInputs_; + ArgSpecs inputSpecs_; + ArgSpecs outputSpecs_; + std::vector constantLogicalTensors_; + std::string debugName_; + c10::once_flag initialized_flag; + bool is_initialized_ = false; +}; + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/layout_propagation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/layout_propagation.h new file mode 100644 index 0000000000000000000000000000000000000000..a654d8e7d15afb46e8c142d1f918ade6a1d20770 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/layout_propagation.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +void PropagateLayout(const std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/operator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/operator.h new file mode 100644 index 0000000000000000000000000000000000000000..ab289941e48a7087b30ae65efb9e1da3be51baab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/operator.h @@ -0,0 +1,151 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit::fuser::onednn { + +class Operator { + public: + Operator(const Node* node, dnnl::graph::op::kind kind) + : n(node), o(getId(node), kind, node->kind().toQualString()), k(kind) {} + + // Returns output index if the Value is a graph output. + // Otherwise returns -1 + int32_t graphOutputIdx(Value* v) { + int32_t i = 0; + for (const Value* output : v->owningGraph()->outputs()) { + if (v == output) { + return i; + } + i++; + } + return -1; + } + + Operator& setInputValue(Value* v) { + if (v->mustNotBeNone()) { + if (v->type()->kind() == c10::TensorType::Kind) { + o.add_input(createLogicalTensor(v)); + } + } + return *this; + } + + Operator& setInput(size_t offset) { + return setInputValue(n->input(offset)); + } + + template + Operator& setInput(size_t offset, Ts... other) { + setInput(offset); + return setInput(other...); + } + + Operator& setOutputValue(Value* v) { + if (v->mustNotBeNone()) { + o.add_output(createLogicalTensor(v)); + } + return *this; + } + + // setOutputValue & setOutput require a pointer to the LLGA graph, as output + // logical tensors that are graph outputs should be connected to an End LLGA + // op. A value of NULL can be provided for the graph pointer in order to + // maintain the legacy functionality of this function. + Operator& setOutputValue(Value* v, std::unique_ptr& g) { + if (v->mustNotBeNone()) { + auto output_tensor = createLogicalTensor(v); + o.add_output(output_tensor); + if (g) { + int32_t outputIndex = graphOutputIdx(v); + if (outputIndex != -1) { + dnnl::graph::op newEndNode( + LONG_MAX - outputIndex, + dnnl::graph::op::kind::End, + "EndNodeForGraphOutput"); + newEndNode.add_input(output_tensor); + g->add_op(newEndNode); + } + } + } + return *this; + } + + Operator& setOutput(std::unique_ptr& g, size_t offset) { + return setOutputValue(n->output(offset), g); + } + + Operator& setOutput(size_t offset) { + return setOutputValue(n->output(offset)); + } + + template + Operator& setOutput( + std::unique_ptr& g, + size_t offset, + Ts... other) { + setOutput(g, offset); + return setOutput(g, other...); + } + + template + Operator& setAttr(dnnl::graph::op::attr name, Attr&& attr) { + o.set_attr(name, std::forward(attr)); + return *this; + } + + template + Operator& setAttr(dnnl::graph::op::attr name, const F& fn, size_t offset) { + return setAttr(name, fn(n, offset)); + } + + static float ScalarToFloat(const Node* node, size_t offset) { + return toIValue(node->input(offset))->toScalar().to(); + } + + static std::vector Ints(const Node* node, size_t offset) { + return toIValue(node->input(offset))->toIntVector(); + } + + static int64_t Int(const Node* node, size_t offset) { + return toIValue(node->input(offset))->toInt(); + } + + static float Float(const Node* node, size_t offset) { + return static_cast(toIValue(node->input(offset))->toDouble()); + } + + static bool Bool(const Node* node, size_t offset) { + return toIValue(node->input(offset))->toBool(); + } + + static uint64_t getId(const Node* node) { + return reinterpret_cast(node); // cast node address as op id + } + + dnnl::graph::op::kind kind() const { + return k; + } + + dnnl::graph::op llgaOp() const { + return o; + } + + private: + dnnl::graph::logical_tensor createLogicalTensor(Value* value) const { + return LlgaTensorDesc(value).logical_tensor(); + } + + const Node* n; + dnnl::graph::op o; + dnnl::graph::op::kind k; +}; + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/prepare_binary.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/prepare_binary.h new file mode 100644 index 0000000000000000000000000000000000000000..7e46d4d447b4922e96b66dbbf32b8d011af7cbae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/prepare_binary.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +// Prepare binary ops for LLGA +// +// The pass does the following: +// +// - Convert scalar input of aten::add and aten::mul into Float tensor with +// dimension [1] +// +// - Decompose fused add into aten::mul + aten::add when alpha != 1.0 +// +// - Eliminate identity add/mul, i.e., tensor + 0, tensor * 1 +// +void PrepareBinaryForLLGA(const std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/cuda/cuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/cuda/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..ff30c27553f68809ee4008c5c94c87d80c139042 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/cuda/cuda.h @@ -0,0 +1,184 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#include +#include +#include + +namespace torch::jit { + +class CUDAEvent; +// This class is a wrapper around c10::cuda::CUDAStream. +// It is needed because TorchBind does not support all of the argument types +// for c10::cuda::CUDAStream. For more details, please refer to +// c10/cuda/CUDAStream.h. +class CUDAStream final : public CustomClassHolder { + public: + CUDAStream( + std::optional device = std::nullopt, + int64_t priority = 0) { + c10::DeviceIndex device_index = + device.has_value() ? device->index() : c10::cuda::current_device(); + stream_ = std::make_unique( + c10::cuda::getStreamFromPool(static_cast(priority), device_index)); + } + + CUDAStream(c10::cuda::CUDAStream s) { + stream_ = std::make_unique(s); + } + + bool query() { + return stream_->query(); + } + + c10::intrusive_ptr recordEvent( + c10::intrusive_ptr event); + + void synchronize() { + stream_->synchronize(); + } + + void waitEvent(const c10::intrusive_ptr& event); + + void waitStream(const c10::intrusive_ptr& stream); + + /// Get the CUDA device index that this stream is associated with. + int64_t device_index() const { + return stream_->device_index(); + } + + /// Get the full Device that this stream is associated with. The Device + /// is guaranteed to be a CUDA device. + c10::Device device() const { + return stream_->device(); + } + + /// Return the stream ID corresponding to this particular stream. + int64_t id() const { + return stream_->id(); + } + + private: + std::unique_ptr stream_; + friend class CUDAEvent; +}; + +// This class is a wrapper around at::cuda::CUDAStream. +// It is needed because TorchBind does not support all of the argument types +// for at::cuda::CUDAEvent. For more details, please refer to +// aten/src/ATen/cuda/CUDAEvent.h. +class CUDAEvent final : public CustomClassHolder { + public: + CUDAEvent( + bool enable_timing = false, + bool blocking = false, + bool interprocess = false) { + int flags = cudaEventDisableTiming; + if (enable_timing) { + flags = cudaEventDefault; + } + if (blocking) { + flags |= cudaEventBlockingSync; + } + if (interprocess) { + TORCH_CHECK(!enable_timing); + flags |= cudaEventInterprocess; + } + + event_ = std::make_unique(flags); + } + + double elapsedTime(const c10::intrusive_ptr& end) { + return event_->elapsed_time(*end->event_); + } + + std::string ipcHandle() { + cudaIpcEventHandle_t handle{}; + event_->ipc_handle(&handle); + std::string str_handle((const char*)&handle, sizeof(handle)); + return str_handle; + } + + bool query() { + return event_->query(); + } + + void record(const c10::intrusive_ptr& stream); + + void synchronize() { + event_->synchronize(); + } + void wait(const c10::intrusive_ptr& stream); + + private: + void recordInternal(CUDAStream* stream); + std::unique_ptr event_; + + friend class CUDAStream; +}; + +inline c10::intrusive_ptr CUDAStream::recordEvent( + c10::intrusive_ptr event) { + if (!event) { + event = c10::make_intrusive(); + } + + event->recordInternal(this); + return event; +} + +inline void CUDAStream::waitEvent(const c10::intrusive_ptr& event) { + event->event_->block(*stream_); +} + +inline void CUDAStream::waitStream( + const c10::intrusive_ptr& stream) { + auto ev = c10::make_intrusive(); + stream->recordEvent(ev); + waitEvent(ev); +} + +inline void CUDAEvent::record(const c10::intrusive_ptr& stream) { + event_->record(*stream->stream_); +} + +inline void CUDAEvent::recordInternal(CUDAStream* stream) { + event_->record(*stream->stream_); +} + +inline void CUDAEvent::wait(const c10::intrusive_ptr& stream) { + event_->block(*stream->stream_); +} + +TORCH_LIBRARY(cuda, m) { + auto stream_class = m.class_("Stream").def( + torch::init, int64_t>(), + "", + {torch::arg("device") = std::nullopt, torch::arg("priority") = 0}); + auto event_class = m.class_("Event").def( + torch::init(), + "", + {torch::arg("enable_timing") = false, + torch::arg("blocking") = false, + torch::arg("interprocess") = false}); + + stream_class.def("query", &CUDAStream::query) + .def("record_event", &CUDAStream::recordEvent) + .def("synchronize", &CUDAStream::synchronize) + .def("wait_event", &CUDAStream::waitEvent) + .def("wait_stream", &CUDAStream::waitStream) + .def("device_index", &CUDAStream::device_index) + .def_property("device", &CUDAStream::device) + .def("id", &CUDAStream::id); + + event_class.def("elapsed_time", &CUDAEvent::elapsedTime) + .def("query", &CUDAEvent::query) + .def("record", &CUDAEvent::record) + .def("synchronize", &CUDAEvent::synchronize) + .def("wait", &CUDAEvent::wait); +} + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/builtin_functions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/builtin_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..ed412b4acd8d06928e751733ec40f109863fb149 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/builtin_functions.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API const std::vector& getAllBuiltinFunctionsFor(Symbol 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h new file mode 100644 index 0000000000000000000000000000000000000000..3dc39e392a8954600332b8e79ddf0a0e6a7b6a2f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include + +namespace torch::jit { + +struct Graph; + +// Transforms loops so that they can be represented as python +// for or while loops +TORCH_API void CanonicalizeModifiedLoops(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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h new file mode 100644 index 0000000000000000000000000000000000000000..65e0aff09acc68c5c93d6078d9ccc58bef79ad00 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h @@ -0,0 +1,244 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +enum class IterableModuleKind { NONE, LIST, DICT, PARAMLIST, PARAMDICT }; +class ConcreteModuleType; + +// You can think of an nn.Module as a template that corresponds to a family of +// JIT types. The template "arguments" are things like the constant values. +// e.g. +// class M(nn.Module): +// __constants__ = ["const"] +// ... +// +// Is similar to writing the following in C++: +// +// template +// class M { +// ... +// } +// +// We need to consider each different member of the type family a different JIT +// type because, e.g. different constant values lead to different versions of +// the same method. +// +// ConcreteModuleType corresponds to a single member of the type family, with +// all template arguments fully specified. Two Modules that share a +// ConcreteModuleType can share a JIT type, and vice versa. +// +// Why not just use a JIT type to represent concrete types? Because constants, +// function attributes, etc. are currently not representable in the type system, +// so this acts a non-first-class way of tracking concrete types. +// +// ConcreteModuleType is also the source of truth for servicing all +// ModuleValue::attr calls. This is so we can guarantee that if two Module's +// share a JIT type (and thus a ConcreteModuleType), then they behave the same +// way when you access attributes on them. + +// ConcreteModuleType has two phases. +// 1. Creation: First we build it up, during the ScriptModule conversion +// process. This is represented by ConcreteModuleTypeBuilder. +// ...then the converter calls ConcreteModuleTypeBuilder::build(), producing +// a +// ConcreteModuleType ready for querying. +// 2. Querying: We use ConcreteModuleType as a source of truth for +// ModuleValue::attr calls during method compilation. + +// Represents a concrete type during in the process for construction. We use +// this to decide whether we can share types between modules. +class VISIBILITY_HIDDEN ConcreteModuleTypeBuilder { + public: + explicit ConcreteModuleTypeBuilder(py::object pyClass) { + TORCH_INTERNAL_ASSERT(pyClass); + pyClass_ = std::move(pyClass); + } + + void addConstant(std::string name, py::object value); + void addConstant(std::string name, IValue value); + void addAttribute( + std::string name, + const TypePtr& type, + bool isParameter, + bool isBuffer); + void addFunctionAttribute( + std::string name, + const TypePtr& type, + py::object pyFunction); + + void addModule(std::string name, std::shared_ptr meta); + + void addForwardHook(py::object hook); + void addForwardPreHook(py::object pre_hook); + + void addOverload( + std::string methodName, + std::vector overloadedMethodNames); + void addBuiltinFunction(std::string name, const std::string& symbol_name); + void addFailedAttribute(std::string name, std::string failureReason); + void addIgnoredAttribute(std::string name); + void setIterableModuleKind(IterableModuleKind kind); + + // If a ConcreteModuleType is poisoned, it will never compare equal to any + // other concrete type + void setPoisoned(); + + std::shared_ptr build() const { + return std::make_shared(*this); + } + + // This determines whether two modules can share a type. The container structs + // used by ConcreteModuleType have been defined such that operator== + // implements a meaningful comparison in that context. + bool equals(const ConcreteModuleTypeBuilder& other) const; + + struct FunctionAttribute { + FunctionTypePtr function_; + py::object pyFunction_; + + friend bool operator==( + const FunctionAttribute& lhs, + const FunctionAttribute& rhs) { + // Functions are not first class, so we can't do type comparison like a + // regular attribute. So we do a pointer equality check on the actual + // Python function object. + return lhs.pyFunction_.is(rhs.pyFunction_); + } + }; + + struct Attribute { + Attribute(TypePtr type, bool isParam, bool isBuffer) + : type_(std::move(type)), isParam_(isParam), isBuffer_(isBuffer) {} + + friend bool operator==(const Attribute& lhs, const Attribute& rhs) { + return *(lhs.type_) == *(rhs.type_) && lhs.isParam_ == rhs.isParam_; + } + TypePtr type_; + bool isParam_; + bool isBuffer_; + }; + + struct ModuleInfo { + ModuleInfo(std::string name, std::shared_ptr meta) + : name_(std::move(name)), meta_(std::move(meta)) {} + + friend bool operator==(const ModuleInfo& lhs, const ModuleInfo& rhs); + + std::string name_; + std::shared_ptr meta_; + }; + + private: + ConcreteModuleTypeBuilder() = default; + ClassTypePtr createTypeFromThis() const; + + // If true, this type will never compare equally to anything else. This is + // used if we want to ensure that this type is not shared (for example, if it + // came from a traced module) + bool isPoisoned_ = false; + + // The value of any constants defined by the module. + std::unordered_map constants_; + // The types of any attributes + OrderedDict attributes_; + // Overloads, in the same format as `__overloads__` in Python + std::unordered_map> overloads_; + // Any attributes we failed to convert to TorchScript, along with a hint as to + // why + std::unordered_map failedAttributes_; + // Any attributes that were marked as ignored. They cannot be used in + // TorchScript but can still be used in ignored function in Python. + std::unordered_set ignoredAttributes_; + // Any function attributes. These are special right now because functions are + // not first-class in the type system. + std::unordered_map functionAttributes_; + // Function attributes that are calls to builtin functions. These get + // de-sugared directly into the corresponding aten:: call. The map is + // attribute name -> aten symbol name + std::unordered_map builtinFunctions_; + // The concrete types of any submodules + std::vector modules_; + // Hooks to be called before/after forward when the module + // is called directly. Used to ensure modules have different types + // when they have different python hooks + // Actual hooks are added to ClassType directly during compilation + std::vector forwardHooks_; + std::vector forwardPreHooks_; + + // If something is a ModuleDict/ModuleList, it means: + // 1. The order of the submodules matters for comparing the type + // 2. The compiler is allowed to treat it like a dict/tuple + IterableModuleKind iterableModuleKind_ = IterableModuleKind::NONE; + + // The original `nn.Module` class that we derived this ScriptModule from. + py::object pyClass_; + + // NOTE: If you ever add any more state to this struct, you need to make sure + // operator== still makes sense! + friend ConcreteModuleType; +}; + +// Represents a finalized concrete type, used to service ModuleValue::attr calls +// during method compilation. +class VISIBILITY_HIDDEN ConcreteModuleType { + public: + explicit ConcreteModuleType(ConcreteModuleTypeBuilder data); + + static std::shared_ptr fromJitType(TypePtr type); + + TypePtr getJitType() const; + std::optional getPyClass() const; + IterableModuleKind getIterableModuleKind() const; + std::optional> findOverloads( + const std::string& name) const; + std::optional findFunctionAttribute(const std::string& name) const; + std::optional findBuiltinFunction(const std::string& name) const; + std::shared_ptr findSubmoduleConcreteType( + const std::string& name) const; + std::optional findFailedAttribute(const std::string& name) const; + bool isIgnoredAttribute(const std::string& name) const; + + // These getters are only here to return things as types that can be + // automatically converted by pybind. + std::unordered_map getConstantsPy() const; + std::unordered_map> getAttributesPy() + const; + std::vector>> + getModulesPy() const; + + bool equals(const ConcreteModuleType& other) const { + if (jitType_ == other.jitType_) { + // If the computed types are the same, these modules can (obviously) share + // a type. + return true; + } + + return data_.equals(other.data_); + } + bool equals(const ConcreteModuleTypeBuilder& other) const { + return data_.equals(other); + } + + void dump() const; + + private: + ConcreteModuleType() = default; + + // The JIT type derived from this ConcreteModuleType. + ConcreteModuleTypeBuilder data_; + TypePtr jitType_; +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/convert_to_ssa.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/convert_to_ssa.h new file mode 100644 index 0000000000000000000000000000000000000000..d9a3677aa2ef21c2e8a2ee0f35778832f9eb49e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/convert_to_ssa.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include + +namespace torch::jit { + +// Convert a graph with Loads & Stores into SSA form +TORCH_API void ConvertToSSA(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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h new file mode 100644 index 0000000000000000000000000000000000000000..711ddee3edd41e1c3e6c0ccccf5ab08c9bb8568b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API size_t ComputeEditDistance( + const char* word1, + const char* word2, + size_t maxEditDistance); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h new file mode 100644 index 0000000000000000000000000000000000000000..041831252736664f16f0547d34e27e2fa6175942 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +struct Call { + std::string fn_name; + SourceRange caller_range; +}; + +struct TORCH_API ErrorReport : public std::exception { + ErrorReport(const ErrorReport& e); + + explicit ErrorReport(const SourceRange& r); + explicit ErrorReport(const TreeRef& tree) : ErrorReport(tree->range()) {} + explicit ErrorReport(const Token& tok) : ErrorReport(tok.range) {} + + const char* what() const noexcept override; + + class TORCH_API Calls { + private: + std::vector calls_; + mutable std::mutex mutex_; + + public: + void push_back(Call call) { + std::lock_guard lock(mutex_); + calls_.push_back(std::move(call)); + } + + void pop_back() { + std::lock_guard lock(mutex_); + calls_.pop_back(); + } + + bool empty() const { + std::lock_guard lock(mutex_); + return calls_.empty(); + } + + void update_pending_range(const SourceRange& range) { + std::lock_guard lock(mutex_); + calls_.back().caller_range = range; + } + + std::vector get_stack() const { + std::lock_guard lock(mutex_); + return calls_; + } + }; + + struct TORCH_API CallStack { + // These functions are used to report why a function was being compiled + // (i.e. what was the call stack of user functions at compilation time that + // led to this error) + CallStack(const std::string& name, const SourceRange& range); + ~CallStack(); + + // Change the range that is relevant for the current function (i.e. after + // each successful expression compilation, change it to the next expression) + static void update_pending_range(const SourceRange& range); + + private: + std::shared_ptr source_callstack_; + }; + + static std::string current_call_stack(); + + private: + template + friend const ErrorReport& operator<<(const ErrorReport& e, const T& t); + + mutable std::stringstream ss; + OwnedSourceRange context; + mutable std::string the_message; + std::vector error_stack; +}; + +template +const ErrorReport& operator<<(const ErrorReport& e, const T& t) { + e.ss << t; + return e; +} + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h new file mode 100644 index 0000000000000000000000000000000000000000..c33e7cb04d7c6cbc3e330f61b6af9ee90b72d8b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API void TransformExits(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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..2626cfb7f96042a67194589f4f5a47a214bd2113 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit { + +// allow_typevars: If true, we assume that lowercase types that we don't +// understand are type variables. This is only needed for TorchScript (and not +// not needed for custom ops). +// If false, we disallow typevars, except in certain cases for BC reason (i.e. +// your op is in the aten or prim namespace). +TORCH_API std::variant parseSchemaOrName( + const std::string& schemaOrName, + bool allow_typevars = true); +TORCH_API c10::FunctionSchema parseSchema( + const std::string& schema, + bool allow_typevars = true); +TORCH_API c10::OperatorName parseName(const std::string& 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h new file mode 100644 index 0000000000000000000000000000000000000000..6dba54dc8a69cc489da51be53469538908f4b849 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include + +namespace torch::jit { + +TORCH_API void InlineLoopCondition(std::shared_ptr& graph); +TORCH_API void InlineBlockBeforeNode(Node* before_node, 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..4e723618bab2d7f129dcd3a40f11d00237f66d2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/ir_emitter.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +TORCH_API void runCleanupPasses(std::shared_ptr& to_clean); + +TORCH_API bool meaningfulName(const std::string& 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/lexer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/lexer.h new file mode 100644 index 0000000000000000000000000000000000000000..d99be3ca74a0c21f9b0b284c19f6a462b194c937 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/lexer.h @@ -0,0 +1,568 @@ +#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 { + +// single character tokens are just the character itself '+' +// multi-character tokens need an entry here +// if the third entry is not the empty string, it is used +// in the lexer to match this token. + +// These kinds are also used in Tree.h as the kind of the AST node. +// Some kinds TK_APPLY, TK_LIST are only used in the AST and are not seen in the +// lexer. + +#define TC_FORALL_TOKEN_KINDS(_) \ + _(TK_EOF, "eof", "") \ + _(TK_WHITESPACE, "whitespace", "") \ + _(TK_WHITESPACE_EOF, "whitespace_eof", "") \ + _(TK_NUMBER, "number", "") \ + _(TK_NEWLINE, "newline", "") \ + _(TK_INDENT, "indent", "") \ + _(TK_DEDENT, "dedent", "") \ + _(TK_DEF, "def", "def") \ + _(TK_EQUIVALENT, "equivalent", "<=>") \ + _(TK_IDENT, "ident", "") \ + _(TK_STRING, "string", "") \ + _(TK_STRINGLITERAL, "string_literal", "") \ + _(TK_CONST, "const", "") \ + _(TK_LIST, "list", "") \ + _(TK_DICT, "dict", "") \ + _(TK_OPTION, "option", "") \ + _(TK_APPLY, "apply", "") \ + _(TK_COMPREHENSION, "comprehension", "") \ + _(TK_RANGE_CONSTRAINT, "range_constraint", "") \ + _(TK_PARAM, "param", "") \ + _(TK_INFERRED, "inferred", "") \ + _(TK_ACCESS, "access", "") \ + _(TK_ASSIGN, "assign", "") \ + _(TK_AUG_ASSIGN, "aug_assign", "") \ + _(TK_ATTRIBUTE, "attribute", "") \ + _(TK_IF, "if", "if") \ + _(TK_ELSE, "else", "else") \ + _(TK_ELIF, "elif", "elif") \ + _(TK_WHILE, "while", "while") \ + _(TK_EXPR_STMT, "expression statement", "") \ + _(TK_RETURN, "return", "return") \ + _(TK_IS, "is", "is") \ + _(TK_ISNOT, "is not", "is not") \ + _(TK_NE, "ne", "!=") \ + _(TK_EQ, "eq", "==") \ + _(TK_LE, "le", "<=") \ + _(TK_GE, "ge", ">=") \ + _(TK_FLOOR_DIV, "floordiv", "//") \ + _(TK_IF_EXPR, "if", "") \ + _(TK_TRUE, "True", "True") \ + _(TK_FALSE, "False", "False") \ + _(TK_NONE, "None", "None") \ + _(TK_AND, "and", "and") \ + _(TK_OR, "or", "or") \ + _(TK_NOT, "not", "not") \ + _(TK_LSHIFT, "<<", "<<") \ + _(TK_RSHIFT, ">>", ">>") \ + _(TK_CAST, "cast", "") \ + _(TK_PLUS_EQ, "+=", "+=") \ + _(TK_MINUS_EQ, "-=", "-=") \ + _(TK_TIMES_EQ, "*=", "*=") \ + _(TK_DIV_EQ, "/=", "/=") \ + _(TK_MOD_EQ, "%=", "%=") \ + _(TK_BIT_OR_EQ, "|=", "|=") \ + _(TK_BIT_AND_EQ, "&=", "&=") \ + _(TK_BIT_XOR_EQ, "^=", "^=") \ + _(TK_LSHIFT_EQ, "<<=", "<<=") \ + _(TK_RSHIFT_EQ, ">>=", ">>=") \ + _(TK_POW_EQ, "**=", "**=") \ + _(TK_GLOBAL, "global", "global") \ + _(TK_BUILT_IN, "built-in", "") \ + _(TK_SUBSCRIPT, "subscript", "") \ + _(TK_VAR, "variable", "") \ + _(TK_NOTHING, "nothing", "") \ + _(TK_DICT_LITERAL, "dict-literal", "") \ + _(TK_LIST_LITERAL, "list-literal", "") \ + _(TK_TUPLE_LITERAL, "tuple-literal", "") \ + _(TK_FOR, "for", "for") \ + _(TK_IN, "in", "in") \ + _(TK_NOTIN, "not in", "not in") \ + _(TK_STARRED, "starred", "") \ + _(TK_UNARY_MINUS, "unary minus", "") \ + _(TK_POW, "pow operator", "**") \ + _(TK_ARROW, "arrow", "->") \ + _(TK_DECL, "decl", "") \ + _(TK_SLICE_EXPR, "slice expr", "") \ + _(TK_TYPE_COMMENT, "type comment", "# type:") \ + _(TK_RAISE, "raise", "raise") \ + _(TK_ASSERT, "assert", "assert") \ + _(TK_DOTS, "dots", "...") \ + _(TK_LIST_COMP, "list comprehension", "") \ + _(TK_DICT_COMP, "dict comprehension", "") \ + _(TK_BREAK, "break", "break") \ + _(TK_CONTINUE, "continue", "continue") \ + _(TK_DELETE, "del", "del") \ + _(TK_PASS, "pass", "pass") \ + _(TK_CLASS_DEF, "class", "class") \ + _(TK_IMPORT, "import", "import") \ + _(TK_WITH, "with", "with") \ + _(TK_WITH_ITEM, "withitem", "") \ + _(TK_AS, "as", "as") \ + _(TK_PROP, "property", "") \ + _(TK_ELLIPSIS, "Ellipsis", "Ellipsis") \ + _(TK_NONE_TYPE, "NoneType", "NoneType") + +enum TokenKind { + // we use characters to represent themselves so skip all valid characters + // before + // assigning enum values to multi-char tokens. + TK_DUMMY_START = 256, +#define DEFINE_TOKEN(tok, _, _2) tok, + TC_FORALL_TOKEN_KINDS(DEFINE_TOKEN) +#undef DEFINE_TOKEN +}; + +TORCH_API std::string kindToString(int kind); +TORCH_API int stringToKind(const std::string& str); + +// nested hash tables that indicate char-by-char what is a valid token. +struct TokenTrie; +using TokenTrieRef = std::unique_ptr; +struct TokenTrie { + TokenTrie() = default; + void insert(const char* str, int tok) { + if (*str == '\0') { + AT_ASSERT(kind == 0); + kind = tok; + return; + } + + for (size_t i = 0, e = child_chars.size(); i < e; ++i) { + if (child_chars[i] == *str) { + child_tries[i]->insert(str + 1, tok); + return; + } + } + + child_chars.emplace_back(*str); + child_tries.emplace_back(std::make_unique()); + child_tries.back()->insert(str + 1, tok); + } + int kind{0}; // 0 == invalid token + + std::vector child_chars; + std::vector child_tries; +}; + +// stuff that is shared against all TC lexers/parsers and is initialized only +// once. +struct TORCH_API SharedParserData { + SharedParserData() : head(new TokenTrie()) { + for (const char* c = valid_single_char_tokens; *c; c++) { + std::string str(1, *c); + head->insert(str.c_str(), *c); + } + +#define ADD_CASE(tok, _, tokstring) \ + if (*(tokstring) != '\0') { \ + head->insert((tokstring), (tok)); \ + } + TC_FORALL_TOKEN_KINDS(ADD_CASE) +#undef ADD_CASE + } + + bool match( + StringCordView::Iterator pos, + bool continuation, // are we inside a scope where newlines don't count + // (e.g. inside parens) + bool whitespace_token, // should we treat whitespace as a token + int* kind, + StringCordView::Iterator* start, + StringCordView::Iterator* end) { + *start = pos; + // skip whitespace + while (pos.has_next() && isblank(*pos)) { + ++pos; + } + + // special handling + if (pos.has_next()) { + if (*pos == '#' && !isTypeComment(pos)) { + // skip comments + while (pos.has_next() && *pos != '\n') + ++pos; + // tail call, handle whitespace and more comments + return match(pos, continuation, whitespace_token, kind, start, end); + } + if (*pos == '\\') { + auto newiter = pos; + ++newiter; + if (newiter.has_next() && *newiter == '\n' && !whitespace_token) { + ++newiter; + return match(newiter, continuation, false, kind, start, end); + } + } + if (*pos == '\n') { + return match(++pos, continuation, !continuation, kind, start, end); + } + } + // we handle white space before EOF because in the case we have something + // like the following where we need to generate the dedent token if foo: + // ... + // else: + // pass + if (whitespace_token) { + *kind = !pos.has_next() ? TK_WHITESPACE_EOF : TK_WHITESPACE; + *end = pos; + return true; + } + if (!pos.has_next()) { + *kind = TK_EOF; + *start = pos; + *end = *start; + return true; + } + // invariant: the next token is not whitespace or newline + *start = pos; + // check for a valid number + size_t len = 0; + if (isNumber(pos.rest_line(), 0, &len)) { + *end = *start; + *end += len; + *kind = TK_NUMBER; + return true; + } + // check for string + if (isString(pos.rest_line(), 0, &len)) { + *kind = TK_STRINGLITERAL; + *end = *start; + *end += len; + return true; + } + + // check for either an ident or a token + // ident tracks whether what we have scanned so far could be an identifier + // matched indicates if we have found any match. + bool matched = false; + bool ident = true; + TokenTrie* cur = head.get(); + // for (size_t i = 0; pos + i < str.size() && (ident || cur != nullptr); + // i++) + for (size_t i = 0; pos.has_next() && (ident || cur != nullptr); + ++pos, ++i) { + ident = ident && validIdent(i, *pos); + if (ident) { + matched = true; + *end = pos.next_iter(); + *kind = TK_IDENT; + } + // check for token second, so that e.g. 'max' matches the token TK_MAX + // rather the + // identifier 'max' + if (cur) { + const auto begin_it = cur->child_chars.begin(); + const auto end_it = cur->child_chars.end(); + const auto ch_it = std::find(begin_it, end_it, *pos); + + cur = (ch_it == end_it) ? nullptr + : cur->child_tries[ch_it - begin_it].get(); + + if (cur && cur->kind != 0) { + matched = true; + *end = pos.next_iter(); + *kind = cur->kind; + } + } + } + return matched; + } + + bool isUnary(int kind, int* prec); + bool isBinary(int kind, int* prec); + bool isRightAssociative(int kind) { + switch (kind) { + case '?': + case TK_POW: + case TK_IF: + return true; + default: + return false; + } + } + + private: + bool validIdent(size_t i, char n) { + return isalpha(n) || n == '_' || (i > 0 && isdigit(n)); + } + + // 1. skip whitespace + // 2. handle comment or newline + // + bool isNumber(std::string_view str, size_t start, size_t* len) { + char first = str[start]; + // strtod allows numbers to start with + or - or nan or inf + // http://en.cppreference.com/w/cpp/string/byte/strtof + // but we want only the number part, otherwise 1+3 will turn into two + // adjacent numbers in the lexer + if (first == '-' || first == '+' || isalpha(first)) + return false; + const char* startptr = str.data() + start; + char* endptr = nullptr; + torch::jit::strtod_c(startptr, &endptr); + *len = endptr - startptr; + // check if the number is complex valued + // access is safe because string is assumed to be null terminated + if (endptr != nullptr && *endptr == 'j') { + *len += 1; + } + return *len > 0; + } + + bool isCharCount(char c, std::string_view str, size_t start, int len) { + // count checks from [start, start + len) + return start + len <= str.size() && + std::count(str.begin() + start, str.begin() + start + len, c) == len; + } + + // python concatenates all adjacent strings "a" "b" == "ab" + // strings can be enclosed with 1 or 3 single or double quotes + // if enclosed with 3 quotes newlines are valid + // as elsewhere, backslash and new line should be ignored + bool isString(std::string_view str, size_t start, size_t* len) { + char quote = str[start]; + if (quote != '\"' && quote != '\'') + return false; + int quote_len = isCharCount(quote, str, start, 3) ? 3 : 1; + + // end is now set past the opening quotation marks + size_t end = start + quote_len; + while (end < str.size() && !isCharCount(quote, str, end, quote_len)) { + if (str[end] == '\n' && quote_len != 3) { + return false; + } + // handle escaped characters. advances past escaped quotation marks, + // escaped newlines and escaped backslashes + // multi-char escapes like \x1A are handled fine here because the + // remainder of the escape are valid string characters anyway + if (str[end] == '\\') { + end++; + } + end++; + } + // set length equal to the complete string including quotations + *len = end - start + quote_len; + // if end finished without going past the last character of the string than + // there is a match + return end < str.size(); + } + + bool isblank(int n) { + return isspace(n) && n != '\n'; + } + + bool isTypeComment(StringCordView::Iterator str_iter) { + std::string_view rest_line = str_iter.rest_line(); + const std::string type_string = "# type:"; + if (rest_line.size() < type_string.length()) { + return false; + } + auto match_string = rest_line.substr(0, type_string.size()); + return match_string == type_string; + } + + // Make an exception ignoring comments for type annotation comments + bool isTypeComment(const StringCordView& str, size_t pos) { + const std::string type_string = "# type:"; + if (str.size() < pos + type_string.length()) { + return false; + } + auto match_string = str.substr(pos, type_string.size()); + return match_string == type_string; + } + + TokenTrieRef head; +}; + +TORCH_API SharedParserData& sharedParserData(); + +struct Token { + int kind; + SourceRange range; + Token(int kind, SourceRange range) : kind(kind), range(std::move(range)) {} + std::string text() const { + return std::string(range.token_text()); + } + + std::string_view text_view() const { + return range.token_text(); + } + + std::string kindString() const { + return kindToString(kind); + } +}; + +struct Lexer { + explicit Lexer(std::shared_ptr source) + : source(std::move(source)), shared(sharedParserData()) { + auto first_indent = lexRaw(true); + indent_stack.push_back(first_indent.range.size()); + lex(); + } + // Return the current token, and then move to the next one + Token next() { + if (next_tokens.empty()) + reportError("Lexer invariant violated: empty token queue"); + Token r = std::move(next_tokens.front()); + next_tokens.erase(next_tokens.begin()); + if (next_tokens.empty()) { + lex(); + } + return r; + } + // Skip the current token if it matches the given kind + bool nextIf(int kind) { + if (cur().kind != kind) + return false; + next(); + return true; + } + + [[noreturn]] void reportError(const std::string& what) { + reportError(what, cur()); + } + [[noreturn]] void reportError(const std::string& what, const Token& t) { + std::stringstream ss; + ss << what << ":\n"; + t.range.highlight(ss); + throw std::runtime_error(ss.str()); + } + [[noreturn]] void expected(const std::string& what, const Token& t) { + std::stringstream ss; + ss << "expected " << what << " but found '" << t.kindString() + << "' here:\n"; + t.range.highlight(ss); + throw std::runtime_error(ss.str()); + } + [[noreturn]] void expected(const std::string& what) { + expected(what, cur()); + } + // Check that the current token has a given kind, return the current token, + // and advance to the next one. + Token expect(int kind) { + if (cur().kind != kind) { + expected(kindToString(kind)); + } + return next(); + } + Token& lookahead() { + if (next_tokens.size() < 2) { + lex(); + } + return next_tokens[1]; + } + Token& cur() { + return next_tokens.front(); + } + + private: + void lex() { + auto r = lexRaw(); + switch (r.kind) { + case '(': + case '[': + case '{': + nesting++; + break; + case ')': + case ']': + case '}': + nesting--; + break; + case TK_WHITESPACE: + case TK_WHITESPACE_EOF: { + const auto depth = + r.kind == TK_WHITESPACE_EOF ? indent_stack.front() : r.range.size(); + // note: TK_WHITESPACE_EOF is whitespace right before the EOF token + // just like we allow the code to be indented to a particular initial + // indent level, we allow the final indent to be anything and set + // it back to the initial indent level. This allows the code to be + // put into string literals inside code without worrying about final + // whitespace + if (depth > indent_stack.back()) { + indent_stack.push_back(depth); + r.kind = TK_INDENT; + } else if (depth == indent_stack.back()) { + r.kind = TK_NEWLINE; + } else { + next_tokens.emplace_back(TK_NEWLINE, r.range); + while (indent_stack.back() != depth) { + indent_stack.pop_back(); + next_tokens.emplace_back(TK_DEDENT, r.range); + if (indent_stack.empty()) { + reportError("invalid indent level " + std::to_string(depth), r); + } + } + return; // We've already queued the tokens + } + } break; + default: + break; + } + next_tokens.push_back(std::move(r)); + } + Token lexRaw(bool whitespace_token = false) { + AT_ASSERT(source); + if (current == nullptr) { + AT_ASSERT(pos == 0); + current = std::make_unique( + source->text_str().begin()); + } + + StringCordView::Iterator start_iter = *current; + StringCordView::Iterator end_iter = *current; + int kind = 0; + if (!shared.match( + *current, + nesting > 0, + whitespace_token, + &kind, + &start_iter, + &end_iter)) { + expected( + "a valid token", + Token( + **current, + SourceRange(source, start_iter, start_iter.pos() + 1))); + } + + auto t = Token(kind, SourceRange(source, start_iter, end_iter.pos())); + pos = end_iter.pos(); + *current = end_iter; + return t; + } + + std::shared_ptr source; + std::unique_ptr current; + size_t pos{0}; + size_t nesting{0}; // depth of ( [ { nesting... + std::vector indent_stack; // stack of indentation level of blocks + // Invariant: this should always contain at least a single element + std::vector next_tokens; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + SharedParserData& shared; +}; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/mini_environment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/mini_environment.h new file mode 100644 index 0000000000000000000000000000000000000000..dfb7e43fe4b371b620fe1c1fd99ae675e71936da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/mini_environment.h @@ -0,0 +1,60 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +// Simple data structure for containing a type T in nested control blocks +// Should only be used after initial compilation where type checking and +// loads and stores are emitted + +template +struct MiniEnvironment { + MiniEnvironment(Block* b, std::shared_ptr next = nullptr) + : next(std::move(next)) {} + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr> next; + + T findInThisFrame(const std::string& name) { + auto it = table.find(name); + if (it != table.end()) { + return it->second; + } + return nullptr; + } + + T findInAnyFrame(const std::string& name) { + for (auto runner = this; runner; runner = runner->next.get()) { + if (auto r = runner->findInThisFrame(name)) { + return r; + } + } + return nullptr; + } + + void setVar(const std::string& name, T value) { + table[name] = value; + } + + std::vector definedVariables() { + std::vector result; + result.reserve(table.size()); + for (auto& kv : table) { + result.push_back(kv.first); + } + std::sort(result.begin(), result.end()); + return result; + } + + private: + std::unordered_map 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h new file mode 100644 index 0000000000000000000000000000000000000000..2cede9aaaffb8a0fe6c376845796614b8c7cf408 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +/** + * class NameMangler + * + * Utility to mangle qualified names in order to make them unique. We use this + * in various places where we to de-duplicate qualified names. + */ +class TORCH_API NameMangler { + public: + // Given a qualified name, return a mangled version that is guaranteed to be + // unique with respect to previous/future calls of `mangled()` on this name + // mangler instance. + c10::QualifiedName mangle(const c10::QualifiedName& name); + + private: + size_t mangleIndex_ = 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parse_string_literal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parse_string_literal.h new file mode 100644 index 0000000000000000000000000000000000000000..16f32df8d9b12fb47d3f117019380aa3f4344b52 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parse_string_literal.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::jit { + +inline bool isCharCount(char c, const std::string& str, size_t start, int len) { + // count checks from [start, start + len) + return start + len <= str.size() && + std::count( + str.begin() + static_cast(start), + str.begin() + static_cast(start + len), + c) == len; +} + +inline std::optional parseOctal(const std::string& str, size_t pos) { + //\xxx where x are 0-7 + if (pos + 3 >= str.size()) + return std::nullopt; + size_t c = 0; + for (size_t i = 1, b = 64; i < 4; ++i, b /= 8) { + auto d = str[pos + i]; + if (d < '0' || d > '7') + return std::nullopt; + c += b * (d - '0'); + } + if (c >= 256) + return std::nullopt; + return c; +} + +inline std::string parseStringLiteral( + const SourceRange& range, + const std::string& str) { + size_t quote_len = isCharCount(str[0], str, 0, 3) ? 3 : 1; + auto ret_str = str.substr(quote_len, str.size() - quote_len * 2); + size_t pos = ret_str.find('\\'); + while (pos != std::string::npos) { + // invariant: pos has to escape a character because it is a valid string + char c = ret_str[pos + 1]; + size_t to_erase = 2; + switch (ret_str[pos + 1]) { + case '\\': + case '\'': + case '\"': + case '\n': + break; + case 'a': + c = '\a'; + break; + case 'b': + c = '\b'; + break; + case 'f': + c = '\f'; + break; + case 'n': + c = '\n'; + break; + case 'v': + c = '\v'; + break; + case 't': + c = '\t'; + break; + case 'x': + throw(ErrorReport(range) << "unsupported hex specifier"); + case 'u': + case 'U': + throw(ErrorReport(range) << "unsupported unicode specifier"); + default: + // octal value in format \nnn, n is [0-7] + if (auto v = parseOctal(ret_str, pos)) { + to_erase = 4; + c = *v; + } else { + throw(ErrorReport(range) << " ill formed octal specifier"); + } + } + ret_str.replace(pos, to_erase, /* num copies */ 1, c); + pos = ret_str.find('\\', pos + 1); + } + return ret_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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h new file mode 100644 index 0000000000000000000000000000000000000000..77653ee4c4ab4dc00da00851d41d59344768295b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h @@ -0,0 +1,36 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::jit { + +struct Decl; +struct ParserImpl; +struct Lexer; + +TORCH_API Decl mergeTypesFromTypeComment( + const Decl& decl, + const Decl& type_annotation_decl, + bool is_method); + +struct TORCH_API Parser { + explicit Parser(const std::shared_ptr& src); + TreeRef parseFunction(bool is_method); + TreeRef parseClass(); + Decl parseTypeComment(); + Expr parseExp(); + Lexer& lexer(); + ~Parser(); + + private: + std::unique_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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..b71bc27928ebf8667f1b6df5b9d4e4596aa70a23 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h @@ -0,0 +1,11 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::jit { +static constexpr const char* valid_single_char_tokens = + "+-*/%@()[]:,={}><.?!&^|~"; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h new file mode 100644 index 0000000000000000000000000000000000000000..6be0d3b08423d6260e015246e0a36cd521a0eeab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h @@ -0,0 +1,71 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +struct Resolver; +using ResolverPtr = std::shared_ptr; + +/** + * class Resolver + * + * Represents an "outer environment" in which we an look up names and return + * a corresponding SugaredValue. This is used during compilation to resolve + * references to names which are not defined internal to the graph. + * + * Example: PythonResolver looks at the enclosing Python scope for `name`. + * + * NOTE: When adding methods, keep this an abstract class (i.e. all new methods + * should be purely virtual). Resist the urge to provide a default + * implementation; you should explicitly think about how each resolver would + * handle the method. + */ +struct Resolver { + virtual ~Resolver() = default; + + // Resolve a given name to a SugaredValue. This takes the method `m` that the + // caller is currently constructing, since we may need to insert nodes into + // the graph to create a value. + virtual std::shared_ptr resolveValue( + const std::string& name, + GraphFunction& m, + const SourceRange& loc) { + return nullptr; + } + + // Resolve `name` to a TypePtr. + virtual TypePtr resolveType(const std::string& name, const SourceRange& loc) { + return nullptr; + } +}; + +// A resolver that only understands "torch.foo()" lookups. +struct NativeResolver : public Resolver { + std::shared_ptr resolveValue( + const std::string& name, + GraphFunction& m, + const SourceRange& loc) override { + if (name == "torch") { + return std::make_shared("aten"); + } + return nullptr; + } + + TypePtr resolveType(const std::string& name, const SourceRange& loc) + override { + return nullptr; + } +}; + +inline std::shared_ptr nativeResolver() { + return std::make_shared(); +} +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h new file mode 100644 index 0000000000000000000000000000000000000000..c84708353f64269d594eb45c5819c2e293bdfe3f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h @@ -0,0 +1,73 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include + +namespace torch::jit { + +// Try to match a list of inputs and keyword 'attributes' to this +// schema. Return the flat list of positional inputs to the call or +// `std::nullopt` on failure (`failure_messages` contains a good error +// report in this case) + +struct MatchedSchema { + std::vector inputs; + std::vector return_types; + c10::OptNameList return_field_names; + std::string schema_name; +}; + +TORCH_API bool isBlockListedSchema(const FunctionSchema& schema); + +TORCH_API MatchedSchema matchSchema( + const ::c10::FunctionSchema& schema, + const SourceRange& loc, + Graph& graph, + at::ArrayRef args, + at::ArrayRef kwargs, + const std::optional& self = std::nullopt); + +TORCH_API std::pair matchSchemas( + const std::vector& schemas, + const SourceRange& loc, + Graph& graph, + at::ArrayRef args, + at::ArrayRef kwargs, + const std::optional& self = std::nullopt, + bool render_errors = false); + +TORCH_API bool convertibleToList( + const TypePtr& type, + const TypePtr& list_type_); + +TORCH_API std::string getFullSchemaName(const ::c10::FunctionSchema& schema); + +TORCH_API Value* emitBuiltinCall( + const SourceRange& loc, + Graph& graph, + Symbol name, + at::ArrayRef args, + at::ArrayRef kwargs, + const std::optional& self = std::nullopt); + +TORCH_API std::optional findInputWithName( + const std::string& name, + at::ArrayRef kwargs, + bool is_aten = false); + +// applies implicit conversion from value trying to turn it into type +// concrete_type it succeeds if the return_value->isSubtypeOf(concrete_type) +TORCH_API Value* tryConvertToType( + const SourceRange& loc, + Graph& graph, + const TypePtr& concrete_type, + Value* value, + bool allow_conversions); +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..b031c47a4f17fcb47a0ec7c972c45b79edaa7273 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h @@ -0,0 +1,52 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +using TypePtr = c10::TypePtr; + +TORCH_API void registerOpaqueType(const std::string& type_name); +TORCH_API bool isRegisteredOpaqueType(const std::string& type_name); + +struct TORCH_API SchemaTypeParser { + TypePtr parseBaseType(); + std::optional parseAliasAnnotation(); + std::pair> parseType(); + std::tuple> + parseFakeAndRealType(); + std::optional parseTensorDType(const std::string& dtype); + TypePtr parseRefinedTensor(); + + SchemaTypeParser( + Lexer& L, + bool parse_complete_tensor_types, + bool allow_typevars) + : complete_tensor_types(parse_complete_tensor_types), + L(L), + allow_typevars_(allow_typevars) {} + + private: + std::optional tryToParseRequiresGrad(); + std::optional tryToParseDeviceType(); + void parseList( + int begin, + int sep, + int end, + c10::function_ref callback); + + bool complete_tensor_types; + Lexer& L; + size_t next_id = 0; + bool allow_typevars_; +}; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/script_type_parser.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/script_type_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..aa4105637e51d13b451484ebac382c6f6e32037c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/script_type_parser.h @@ -0,0 +1,58 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::jit { + +/** + * class ScriptTypeParser + * + * Parses expressions in our typed AST format (TreeView) into types and + * typenames. + */ +class TORCH_API ScriptTypeParser { + public: + explicit ScriptTypeParser() = default; + explicit ScriptTypeParser(ResolverPtr resolver) + : resolver_(std::move(resolver)) {} + + c10::TypePtr parseTypeFromExpr(const Expr& expr) const; + + std::optional> parseBroadcastList( + const Expr& expr) const; + + c10::TypePtr parseType(const std::string& str); + + FunctionSchema parseSchemaFromDef(const Def& def, bool skip_self); + + c10::IValue parseClassConstant(const Assign& assign); + + private: + c10::TypePtr parseTypeFromExprImpl(const Expr& expr) const; + + std::optional parseBaseTypeName(const Expr& expr) const; + at::TypePtr subscriptToType( + const std::string& typeName, + const Subscript& subscript) const; + std::vector evaluateDefaults( + const SourceRange& r, + const std::vector& default_types, + const std::vector& default_exprs); + std::vector parseArgsFromDecl(const Decl& decl, bool skip_self); + + std::vector parseReturnFromDecl(const Decl& decl); + + ResolverPtr resolver_ = nullptr; + + // Need to use `evaluateDefaults` in serialization + friend struct ConstantTableValue; + friend struct SourceImporterImpl; +}; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h new file mode 100644 index 0000000000000000000000000000000000000000..f58ab00fac5e62175b160977891f89e3f1d17351 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h @@ -0,0 +1,608 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +class SourceRangeUnpickler; +struct SourceRange; + +// A stringlike class backed by a vector of string_view +// the string represented are logically the concatenation of the string_views +// This has advantage of not needing continues memory. +struct TORCH_API StringCordView { + StringCordView(); + StringCordView(const StringCordView&) = default; + StringCordView(StringCordView&&) noexcept = default; + StringCordView( + std::vector inputs, + std::vector> ownerships); + + StringCordView& operator=(const StringCordView&) = default; + StringCordView& operator=(StringCordView&&) noexcept = default; + + size_t size() const { + return accumulated_sizes_.back(); + } + + size_t find(const std::string& tok, size_t start) const; + size_t find_regex(const std::string& tok, size_t start) const; + StringCordView substr(size_t start, size_t size) const; + + char at(size_t index) const { + return *iter_for_pos(index); + } + char operator[](size_t index) const { + return at(index); + } + + std::string str() const { + std::stringstream ss; + for (auto s : pieces_) { + ss << std::string(s); + } + return ss.str(); + } + + bool operator==(const std::string& rhs) const; + + bool operator==(const StringCordView& rhs) const; + + std::string_view piece(size_t index) const { + return pieces_[index]; + } + + // General-case iterator implementation. + struct IteratorImpl { + IteratorImpl( + const StringCordView* str, + size_t start_line, + size_t start_pos, + size_t size) + : line_(start_line), pos_(start_pos), str_(str), size_(size) {} + explicit IteratorImpl(const StringCordView* str) + : IteratorImpl(str, 0, 0, str->size()) {} + + IteratorImpl() : IteratorImpl(nullptr, 0, 0, 0) {} + + IteratorImpl(const IteratorImpl&) = default; + IteratorImpl(IteratorImpl&&) = default; + IteratorImpl& operator=(const IteratorImpl&) = default; + IteratorImpl& operator=(IteratorImpl&&) = default; + + IteratorImpl& operator++() { + if (size_ == 0) { + return *this; + } + if ((pos_ + 1) < str_->pieces_[line_].size()) { + pos_++; + } else { + line_++; + pos_ = 0; + } + return *this; + } + + IteratorImpl operator++(int) { + IteratorImpl prev(*this); + ++(*this); + return prev; + } + + IteratorImpl next_iter() const { + IteratorImpl next(*this); + ++next; + return next; + } + + IteratorImpl& operator+=(size_t num); + + IteratorImpl operator+(size_t num) const { + IteratorImpl it(*this); + it += num; + return it; + } + + bool operator==(const IteratorImpl& rhs) const { + if (!has_next() && !rhs.has_next()) { + return true; + } + return (str_ == rhs.str_) && (line_ == rhs.line_) && (pos_ == rhs.pos_); + } + + bool operator!=(const IteratorImpl& rhs) const { + return !((*this) == rhs); + } + bool has_next() const { + return size_ > 0 && (line_ < str_->pieces_.size()); + } + + char operator*() const { + TORCH_INTERNAL_ASSERT(line_ < str_->pieces_.size()); + TORCH_INTERNAL_ASSERT(pos_ < str_->pieces_[line_].size()); + return str_->pieces_[line_].at(pos_); + } + + // returns rest of the line of the current iterator + std::string_view rest_line() const { + if (line_ >= str_->pieces_.size()) { + return ""; + } + + std::string_view cur_line = str_->pieces_[line_]; + return cur_line.substr(pos_, std::string::npos); + } + + size_t pos() const { + if (size_ == 0) { + return 0; + } + return str_->accumulated_sizes_[line_] + pos_; + } + + private: + size_t line_; + size_t pos_; + const StringCordView* str_; + size_t size_; + friend struct StringCordView; + }; + + // Either an IteratorImpl, or a simple std::string_view::iterator + // (which is faster) if possible. + struct Iterator { + Iterator() = default; + + Iterator( + const StringCordView* str, + size_t start_line, + size_t start_pos, + size_t size) + : repr_( + str->pieces_.size() == 1 + ? repr_type(FastRepr( + start_line ? str->pieces_[0].end() + : str->pieces_[0].begin() + start_pos, + str)) + : repr_type(IteratorImpl(str, start_line, start_pos, size))) { + } + + Iterator(const StringCordView* str) : Iterator(str, 0, 0, str->size()) {} + + Iterator& operator++() { + if (auto* pit = std::get_if(&repr_)) { + ++(*pit); + } else { + ++fast_repr().it; + } + return *this; + } + + Iterator operator++(int) { + Iterator prev(*this); + ++(*this); + return prev; + } + + Iterator next_iter() const { + Iterator next(*this); + ++next; + return next; + } + + Iterator& operator+=(size_t num) { + if (auto* pit = std::get_if(&repr_)) { + *pit += num; + } else { + fast_repr().it += num; + } + return *this; + } + + Iterator operator+(size_t num) const { + Iterator it(*this); + it += num; + return it; + } + + bool operator==(const Iterator& rhs) const { + return repr_ == rhs.repr_; + } + + bool operator!=(const Iterator& rhs) const { + return repr_ != rhs.repr_; + } + + bool has_next() const { + if (const auto* pit = std::get_if(&repr_)) { + return pit->has_next(); + } else { + return fast_repr().it != fast_repr().str->pieces_[0].end(); + } + } + + char operator*() const { + if (const auto* pit = std::get_if(&repr_)) { + return **pit; + } else { + return *fast_repr().it; + } + } + + std::string_view rest_line() const { + if (const auto* pit = std::get_if(&repr_)) { + return pit->rest_line(); + } else { + // NOTE: std::string_view(it, end) ctor wasn't added until C++20. + const auto fast_repr_end = fast_repr().str->pieces_[0].end(); + if (fast_repr().it != fast_repr_end) { + return std::string_view( + &*fast_repr().it, fast_repr_end - fast_repr().it); + } + return std::string_view(); + } + } + + size_t pos() const { + if (const auto* pit = std::get_if(&repr_)) { + return pit->pos(); + } else { + return fast_repr().it - fast_repr().str->pieces_[0].begin(); + } + } + + private: + // When we have only one entry in pieces_ (importantly, such as + // when called from torch::Library::def during startup), we can + // skip extra complexity and just use string_view::iterator + // directly. + struct FastRepr { + std::string_view::iterator it; + const StringCordView* str; + + FastRepr() : str(nullptr) {} + + explicit FastRepr( + std::string_view::iterator it_, + const StringCordView* str_) + : it(it_), str(str_) {} + + bool operator==(const FastRepr& rhs) const { + return it == rhs.it && str == rhs.str; + } + + bool operator!=(const FastRepr& rhs) const { + return !operator==(rhs); + } + }; + using repr_type = std::variant; + repr_type repr_; + + FastRepr& fast_repr() { + // -Oz refuses to inline std::get. + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(std::holds_alternative(repr_)); + return *std::get_if(&repr_); + } + + const FastRepr& fast_repr() const { + // -Oz refuses to inline std::get. + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(std::holds_alternative(repr_)); + return *std::get_if(&repr_); + } + }; + + Iterator begin() const { + return Iterator(this, 0, 0, size()); + } + Iterator end() const { + return Iterator(this, pieces_.size(), 0, 0); + } + Iterator iter_for_pos(size_t pos) const; + + private: + IteratorImpl begin_impl() const { + return IteratorImpl(this, 0, 0, size()); + } + IteratorImpl end_impl() const { + return IteratorImpl(this, pieces_.size(), 0, 0); + } + IteratorImpl iter_impl_for_pos(size_t pos) const; + std::vector pieces_; + std::vector accumulated_sizes_; + std::vector> owned_strings_; +}; + +// Source represents a code segment. It keeps track of: +// - text_view : the view into text of the code segment +// - filename (optional) : if present, represents the name of the file from +// which the code segment originated. +// - starting_line_no : represents the line in the original file where the +// code segment started. +struct TORCH_API Source { + // Whether or not Source should copy the string passed in the constructor. + enum CopiesString { COPIES_STRING, DONT_COPY }; + + explicit Source( + std::string_view text_view, + std::optional filename = std::nullopt, + size_t starting_line_no = 0, + std::shared_ptr gen_ranges = nullptr, + CopiesString copies_str = COPIES_STRING) + : text_view_(create_text_view(copies_str, text_view)), + filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + calc_line_start_offsets(); + } + + explicit Source( + StringCordView str, + std::optional filename = std::nullopt, + size_t starting_line_no = 0, + std::shared_ptr gen_ranges = nullptr) + : text_view_(std::move(str)), + filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + calc_line_start_offsets(); + } + // Given a line number (within source_), return the byte offset of the + // beginning of that line. + size_t offset_for_line(size_t line) const { + return line_starting_offsets_.at(line); + } + + // Returns number of lines present. + size_t num_lines() const { + return line_starting_offsets_.size(); + } + + // Calculate the line (within the code segment) on which `offset` resides. + size_t lineno_for_offset(size_t offset) const { + auto iter = std::upper_bound( + line_starting_offsets_.begin(), line_starting_offsets_.end(), offset); + return iter - line_starting_offsets_.begin() - 1; + } + + // Calculate the line (within the original source file, if present) on which + // `lineno` resides. + size_t lineno_to_source_lineno(size_t lineno) const { + if (filename_) { + return lineno + starting_line_no_; + } else { + return lineno; + } + } + + StringCordView get_line(size_t lineno) const { + auto start = offset_for_line(lineno); + auto size = (lineno + 1) < num_lines() ? offset_for_line(lineno + 1) - start + : text_view_.size() - start; + return text_view_.substr(start, size); + } + + const StringCordView& text_str() const { + return text_view_; + } + + char char_at(size_t index) const { + return text_view_.at(index); + } + + size_t size() const { + return text_view_.size(); + } + + std::optional& filename() { + return filename_; + } + + size_t starting_line_no() const { + return starting_line_no_; + } + + std::optional findSourceRangeThatGenerated( + const SourceRange& range); + + ~Source() = default; + + private: + void calc_line_start_offsets() { + line_starting_offsets_.clear(); + line_starting_offsets_.push_back(0); + size_t pos = 0; + while ((pos = text_view_.find("\n", pos)) != std::string::npos) { + line_starting_offsets_.push_back(++pos); + } + } + + static StringCordView create_text_view( + CopiesString copies_str, + std::string_view text_view) { + if (copies_str == COPIES_STRING) { + auto allocated_str = + std::make_shared(text_view.data(), text_view.size()); + return StringCordView({*allocated_str}, {allocated_str}); + } else { + return StringCordView({text_view}, {}); + } + } + + StringCordView text_view_; + + std::optional filename_; + // If filename_ is not present, starting_line_no_ is don't care + size_t starting_line_no_; + // Starting offsets for lines into the source. e.g. line 0 starts at + // line_starting_offsets_[0], etc. + std::vector line_starting_offsets_; + + std::shared_ptr gen_ranges_; +}; + +// A SourceRange is a reference to subset of a Source, specified by `start` and +// `end` byte offsets into the source text. +struct TORCH_API SourceRange { + SourceRange(std::shared_ptr source_view, size_t start_, size_t end_) + : source_view_(std::move(source_view)), start_(start_), end_(end_) { + if (source_view_) { + start_iter_ = source_view_->text_str().iter_for_pos(start_); + } + } + + SourceRange() : source_view_(nullptr), start_(0), end_(0) {} + + SourceRange( + std::shared_ptr source_view_, + StringCordView::Iterator start_iter, + size_t end_) + : source_view_(std::move(source_view_)), + start_(start_iter.pos()), + end_(end_), + start_iter_(start_iter) {} + + const std::string_view token_text() const { + size_t size = end() - start(); + return start_iter_.rest_line().substr(0, size); + } + + const StringCordView text() const { + return source_view_->text_str().substr(start(), end() - start()); + } + size_t size() const { + return end() - start(); + } + static const size_t CONTEXT = 3; + void highlight(std::ostream& out) const; + + // Customizable version of 'highlight' method. + void print_with_context( + std::ostream& out, + size_t context, + bool highlight, + const std::string& funcname) const; + + const std::shared_ptr& source() const { + return source_view_; + } + size_t start() const { + return start_; + } + size_t end() const { + return end_; + } + std::string str() const { + std::stringstream ss; + highlight(ss); + return ss.str(); + } + + std::optional> file_line_col() const { + if (!source_view_ || !source()->filename()) { + return std::nullopt; + } + + auto lineno = source_view_->lineno_for_offset(start_); + auto col_offset = (int)start_ - (int)source_view_->offset_for_line(lineno); + // TODO: std::optional<>::value returns an rvalue ref so can't use it here?? + return std::make_tuple( + source_view_->filename().value_or(""), + source_view_->lineno_to_source_lineno(lineno), + (size_t)col_offset); + } + + bool operator==(const SourceRange& rhs) const { + return start() == rhs.start() && end() == rhs.end() && + source() == rhs.source(); + } + + bool operator!=(const SourceRange& rhs) const { + return !(*this == rhs); + } + + std::optional findSourceRangeThatGenerated() const { + if (!source_view_) { + return std::nullopt; + } + return source_view_->findSourceRangeThatGenerated(*this); + } + + protected: + std::shared_ptr source_view_; + + private: + size_t start_; + size_t end_; + StringCordView::Iterator start_iter_; +}; + +// OwnedSourceRange is just like a SourceRange except that it owns a `Source` +// instead of `Source`. Thus OwnedSourceRange owns a copy of source text. +struct OwnedSourceRange : public SourceRange { + explicit OwnedSourceRange(const SourceRange& source_range) + : SourceRange(source_range) { + const auto& source = source_range.source(); + if (source) { + source_view_ = std::make_shared( + source->text_str().str(), + source->filename(), + source->starting_line_no()); + } + } +}; + +struct TORCH_API SourceRangeHasher { + public: + size_t operator()(const torch::jit::SourceRange& key) const; +}; + +struct StackEntry { + std::string filename; + SourceRange range; +}; + +TORCH_API void format_stack_trace( + std::ostream& out, + const std::vector& entries); + +inline std::ostream& operator<<(std::ostream& out, const SourceRange& range) { + range.highlight(out); + return out; +} + +// A pair of (byte offset, SourceRange) describing a specific segment +// of the output stream +struct TaggedRange { + TaggedRange(size_t bytes, SourceRange range) + : bytes(bytes), range(std::move(range)) {} + size_t bytes; + SourceRange range; +}; +using SourceRangeRecords = std::vector; +using SourceRangeTagMap = + std::unordered_map; + +} // namespace torch::jit + +namespace std { +template <> +struct iterator_traits { + using value_type = char; + using difference_type = ptrdiff_t; + using pointer = char*; + using reference = char&; + using iterator_category = std::forward_iterator_tag; +}; +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..c786cc523c9aa42e6f15afd81290e1e6619d0074 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch::jit { + +/** + * SourceRef does two things: + * 1. Owns a Source object. + * 2. Serves as lookup key to the owned Source in associative containers, for + * runtime data aggregation. + * We don't want to use std::shared_ptr directly because we want to + * support heteogeneous lookup, and also shared_ptr is an implementation detail + * which should be encapsulated. + */ +class TORCH_API SourceRef : public CustomClassHolder { + public: + explicit SourceRef(std::shared_ptr source_view) + : source_view_(std::move(source_view)) {} + bool operator==(const SourceRef& other) const { + return source_view_ == other.source_view_; + } + bool operator<(const Source& other) const { + return source_view_.get() < &other; + } + friend bool operator<(const Source& other, const SourceRef& self) { + return &other < self.source_view_.get(); + } + bool operator<(const SourceRef& other) const { + return *this < *other.source_view_; + } + const Source* operator->() const { + return source_view_.get(); + } + + private: + std::shared_ptr source_view_; +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h new file mode 100644 index 0000000000000000000000000000000000000000..fefb4c36e6fd2682401ab299aa8a4fa9fcb6122b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +TORCH_API double strtod_c(const char* nptr, char** endptr); +TORCH_API float strtof_c(const char* nptr, char** endptr); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/sugared_value.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/sugared_value.h new file mode 100644 index 0000000000000000000000000000000000000000..24e3bcf8cb3130700b604ec8d4b7f31993215b74 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/sugared_value.h @@ -0,0 +1,880 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +using SugaredValuePtr = std::shared_ptr; + +// The AST can contain nodes like `self`, `self.b` or `python_fn` that +// are not first-class values in the graph representation, but instead +// will be desugared based on how they are used in the AST. + +// SugaredValue is used to temporarily represent these values in a way +// that separates their behavior from the AST -> IR converter itself. +// This allows us to keep dependencies on python minimal. + +struct TORCH_API SugaredValue + : public std::enable_shared_from_this { + // what is this node? for error reporting (e.g. Module, python function) + virtual std::string kind() const = 0; + + // what can we do with this thing? + // use it as a value e.g. `this + 4` + virtual Value* asValue(const SourceRange& loc, GraphFunction& m) { + throw(ErrorReport(loc) << kind() << " cannot be used as a value"); + } + + // select an attribute on it, e.g. `this.field` + virtual std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) { + throw(ErrorReport(loc) << "attribute lookup is not defined on " << kind()); + } + + virtual bool hasAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) { + throw(ErrorReport(loc) << "attribute lookup is not defined on " << kind()); + } + + // assign an attribute on it, e.g. `this.field = newValue` + virtual void setAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field, + Value* newValue) { + throw( + ErrorReport(loc) << "attribute assignment is not defined on " + << kind()); + } + + // use it as a vector of values, e.g. a tuple of values as return value from + // a method invocation + virtual std::vector> asTuple( + const SourceRange& loc, + GraphFunction& m, + const std::optional& size_hint = {}) { + throw(ErrorReport(loc) << kind() << " cannot be used as a tuple"); + } + + // TODO @wconstab refactor to use ModuleValue::asTuple instead of new API + virtual SugaredValuePtr asTupleValue( + const SourceRange& loc, + GraphFunction& m) { + throw(ErrorReport(loc) << kind() << " cannot be used as a tuplevalue"); + } + + virtual std::vector> asType( + const SourceRange& loc, + Method& m) { + throw(ErrorReport(loc) << kind() << " cannot be used as a type"); + } + + // call it like a function, e.g. `outputs = this(inputs)` + virtual std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + // note: names for args will be 'argument 0', 'argument 1', etc.. + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) { + // n_binders is always set to the number of variables an expression is + // syntactically bound to: + // a = foo() # 1 binder (note in this case the single binder might be a + // tuple) a, * b = foo() # 1 binder a, b = foo() # 2 binders foo() # 0 + // binders + // + // In subexpressions, like bar() in foo(bar()), n_binders is always set to + // 1. n_binders is used as a hint to subexpressions to determine how many + // values they should return when that number is ambiguous statically. In + // particular it is currently used to decide how many tensors a call to a + // python function will return. It is only a hint, functions do not have to + // check that n_binders match the number of things they are returning, the + // assignment logic will do that anyway. + + throw(ErrorReport(loc) << "cannot call a " << kind()); + } + + // This function is called when to convert a SugaredValue to its iterator. + // For example, when iterating through a Dict we iterate over its keys + virtual std::shared_ptr iter( + const SourceRange& loc, + GraphFunction& m) { + throw(ErrorReport(loc) << kind() << " cannot be used as an iterable"); + } + + // If we are iterating over a Sugared Value and it returns a value from this + // function, then we emit an unrolled loop over the variable. This allows us + // to support containers of Heterogeneous types, like Module Containers & + // Tuples + virtual std::optional staticLen() { + return std::nullopt; + } + + // When iterating over this SugaredValue, should we emit the for loop as an + // unrolled loop. + bool shouldEmitUnrolled() { + return staticLen() != std::nullopt; + } + + // return length of this thing, if not then it can't be iterated. + // If it does not have a statically-determinable length, then it cannot + // be iterated over with a modulelist. If it does it must return a constant + // Value * + virtual Value* len(const SourceRange& loc, GraphFunction& m) { + throw( + ErrorReport(loc) << "'" << kind() << "'" << " object is not iterable"); + } + + // expression for ith element for iterable value + virtual std::shared_ptr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) { + throw( + ErrorReport(loc) << "'" << kind() << "'" + << " object is not subscriptable"); + } + + virtual ~SugaredValue() = default; +}; + +// most things in the environment are just simple value types +// and not special python syntax sugar types +struct TORCH_API SimpleValue : public SugaredValue { + SimpleValue(Value* value) : value_(value) {} + std::string kind() const override { + std::stringstream ss; + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) + ss << "value of type '" << value_->type()->annotation_str() << "'"; + return ss.str(); + } + Value* asValue(const SourceRange& range, GraphFunction& m) override { + return value_; + } + 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; + + bool hasAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + void setAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field, + Value* newValue) override; + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + // note: names for args will be 'argument 0', 'argument 1', etc.. + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + std::shared_ptr iter(const SourceRange& loc, GraphFunction& m) + override; + + Value* getValue() const { + return value_; + } + + Value* len(const SourceRange& loc, GraphFunction& m) override; + SugaredValuePtr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) override; + + private: + Value* value_; +}; + +struct TORCH_API BuiltinFunction : public SugaredValue { + BuiltinFunction(Symbol symbol, std::optional self) + : symbol(symbol), self(std::move(self)) {} + + // The symbol of the function (e.g. `aten::relu`). + Symbol symbol; + + // if this is method, then this is the self argument. + std::optional self; + std::string kind() const override { + return "builtin"; + } + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + // try to create this builtin but if it doesn't exist or the self argument + // cannot possibly match, then return nullptr. Use in situations where it is + // not clear if it is a valid builtin + static std::shared_ptr tryCreate( + Symbol symbol, + std::optional self); +}; + +struct TORCH_API SugaredTupleValue : public SugaredValue { + explicit SugaredTupleValue(std::vector> tup) + : tup_(std::move(tup)) {} + + std::vector> asTuple( + const SourceRange& loc, + GraphFunction& m, + const std::optional& size_hint = {}) override { + return tup_; + } + + Value* asValue(const SourceRange& loc, GraphFunction& m) override { + std::vector vec; + vec.reserve(tup_.size()); + for (const auto& sv : tup_) { + vec.push_back(sv->asValue(loc, m)); + } + Graph& g = *m.graph(); + return g.insertNode(g.createTuple(vec))->output(); + } + + std::string kind() const override { + return "Tuple"; + } + + SugaredValuePtr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) override { + if (!(idx->type()->cast() && toIValue(idx))) { + throw( + ErrorReport(loc) + << "Expected integer literal for index but got a variable or non-integer. " + << "ModuleList/Sequential indexing is only supported with integer literals. " + << "For example, 'i = 4; self.layers[i](x)' will fail because i is not a literal. " + << "Enumeration is supported, e.g. 'for index, v in enumerate(self): out = v(inp)'"); + } + auto index = toIValue(idx)->toInt(); + int64_t adj_index = + (index < 0) ? index + static_cast(tup_.size()) : index; + if (!(adj_index >= 0 && adj_index < static_cast(tup_.size()))) { + throw( + ErrorReport(loc) << "Index " << index << " out of range of length " + << tup_.size()); + } + return tup_.at(adj_index); + } + + // This function is called when a SugaredValue is used to convert a + // SugaredValue to its iterator. For example, when iterating through a Dict we + // iterate over its keys + std::shared_ptr iter(const SourceRange& loc, GraphFunction& m) + override { + return shared_from_this(); + } + + // Because this is used to contain SugaredValues of Heterogeneous types, + // we define staticLen() so that when this is iterated over it is emitted + // as an unrolled loop. + std::optional staticLen() override { + return static_cast(tup_.size()); + } + + std::vector> tup_; +}; + +struct TORCH_API BuiltinModule : public SugaredValue { + BuiltinModule(std::string name, std::optional version = std::nullopt) + : name(std::move(name)), version(version) {} + + std::string kind() const override { + return "builtin module"; + } + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override { + if (field == "autograd") { + // When referring torch.autograd, it is also considered to be a + // BuiltinModule and we will dispatch to the aten operators for the + // methods under its module. + return std::make_shared("aten", version); + } + + auto sym = Symbol::fromQualString(name + "::" + field); + return std::make_shared(sym, std::nullopt); + } + + private: + std::string name; + // when we add operator versioning, emit this op as it existing at 'version' + // if not set, use the latest version + std::optional version; +}; + +// Represents a class, analogous to `int` or `dict`. Instances of classes, +// like `1` or `{"foo": 5}`, are represented as SimpleValues +struct TORCH_API ClassValue : public SugaredValue { + explicit ClassValue(ClassTypePtr type) : type_(std::move(type)) {} + + // Call the type's constructor, as in: + // n = Foo(constructor_arg) + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + std::string kind() const override { + return type_->str(); + } + + ClassTypePtr type_; +}; + +struct TORCH_API NamedTupleConstructor : public SugaredValue { + explicit NamedTupleConstructor(TupleTypePtr type) : type_(std::move(type)) {} + + 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 { + return type_->str(); + } + + TupleTypePtr type_; +}; + +struct FunctionValue : public SugaredValue { + FunctionValue(Function* callee) : callees_({callee}) {} + FunctionValue(const StrongFunctionPtr& p) + : callees_({p.function_}), cu_(p.cu_) {} + FunctionValue(const std::vector& callees) { + for (const StrongFunctionPtr& callee : callees) { + cu_ = cu_ ? cu_ : callee.cu_; + TORCH_INTERNAL_ASSERT(callee.cu_ == cu_); + callees_.push_back(callee.function_); + } + } + + std::string kind() const override { + return "function"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& f, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + std::vector schemas; + for (Function* callee : callees_) { + try { + callee->ensure_defined(); + } catch (const RecursiveMethodCallError&) { + throw( + ErrorReport(loc) + << " function '" << callee->name() << "' is called recursively. " + << "Recursive calls are not supported"); + } + schemas.push_back(&callee->getSchema()); + } + auto match = matchSchemas(schemas, loc, *f.graph(), args, kwargs); + Value* output = + f.graph()->insertFunctionCall(callees_[match.first], match.second); + output->node()->setSourceRange(loc); + return std::make_shared(output); + } + + const std::vector& callees() { + return callees_; + } + + private: + std::vector callees_; + // TODO holding this thing is creepy + std::shared_ptr cu_; +}; + +struct TORCH_API ClosureValue : public SugaredValue { + ClosureValue(Value* value) : value_(value) { + TORCH_INTERNAL_ASSERT(value_->node()->kind() == prim::Closure); + } + std::string kind() const override { + return "closure"; + } + Value* asValue(const SourceRange& range, GraphFunction& m) override { + return value_; + } + Value* value_; +}; + +// defines how a method obtained from a module/class/interface behaves in script +struct MethodValue : public SugaredValue { + MethodValue(Value* self, std::vector method_names) + : self_(self), method_names_(std::move(method_names)) {} + MethodValue(Value* self, std::string method_name) + : MethodValue(self, std::vector({std::move(method_name)})) {} + + std::string kind() const override { + return "method"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& f, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + std::vector argsWithSelf = {self_}; + argsWithSelf.insert(argsWithSelf.end(), args.begin(), args.end()); + std::vector schemas; + for (const std::string& method_name : method_names_) { + if (auto class_type = self_->type()->cast()) { + Function& method = class_type->getMethod(method_name); + try { + method.ensure_defined(); + } catch (const RecursiveMethodCallError&) { + throw( + ErrorReport(loc) + << " method '" << method.name() << "' is called recursively. " + << "Recursive calls are not supported"); + } + schemas.push_back(&method.getSchema()); + } else if (auto interface_type = self_->type()->cast()) { + schemas.push_back(interface_type->getMethod(method_name)); + } else { + TORCH_INTERNAL_ASSERT( + false, "method constructed that is not a class or interface"); + } + } + auto match = matchSchemas(schemas, loc, *f.graph(), argsWithSelf, kwargs); + Value* output = + f.graph()->insertMethodCall(method_names_[match.first], match.second); + output->node()->setSourceRange(loc); + return std::make_shared(output); + } + + private: + Value* self_; + std::vector method_names_; +}; + +struct TORCH_API PrintValue : public SugaredValue { + std::string kind() const override { + return "print"; + } + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; +}; + +// expressions like int(x) +// these are the same as call prim::Int or equivalent except it +// is a noop when the input is a subtype of 'type' +struct TORCH_API CastValue : public BuiltinFunction { + CastValue(TypePtr type, c10::Symbol method) + : BuiltinFunction(method, std::nullopt), type_(std::move(type)) {} + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + if (args.size() == 1 && kwargs.empty()) { + auto len_op = std::make_shared(aten::len, std::nullopt); + auto gt_op = std::make_shared(aten::gt, std::nullopt); + auto zero = m.graph()->insertConstant(0); + + auto v = args[0].value(*m.graph()); + if (v->type()->isSubtypeOf(*type_)) { + return std::make_shared(v); + } else if ( + *type_ == *BoolType::get() && + (v->type()->isSubtypeOf(*AnyListType::get()) || + v->type()->isSubtypeOf(*StringType::get()) || + v->type()->cast())) { + auto len = len_op->call(loc, m, {v}, {}, 1); + return gt_op->call(loc, m, {len->asValue(loc, m), zero}, {}, 1); + } + } + return BuiltinFunction::call(loc, m, args, kwargs, n_binders); + } + + private: + TypePtr type_; +}; + +struct TORCH_API TensorCastValue : public SugaredValue { + TensorCastValue(at::ScalarType type, NamedValue self) + : dtype_(type), self_(std::move(self)) {} + + std::string kind() const override { + return "Cast"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + TORCH_INTERNAL_ASSERT(args.empty() && kwargs.empty()); + Value* dtype_const = m.graph()->insertConstant(dtype_, loc); + std::vector kwargs_{ + self_, NamedValue(loc, "dtype", dtype_const)}; + Value* casted_val = m.graph()->insert( + /*opname=*/Symbol::fromQualString("aten::to"), + /*args=*/args, + /*kwargs=*/kwargs_, + /*range=*/loc); + return std::make_shared(casted_val); + } + + at::ScalarType dtype_; + NamedValue self_; +}; + +// builtins operators and functions that call a method if it exists +// on a class type, like 'len(x)' and 'x + y' +struct TORCH_API MagicMethod : public SugaredValue { + MagicMethod(std::string desugared_name, SugaredValuePtr base) + : base_value_(std::move(base)), + desugared_name_(std::move(desugared_name)) {} + + std::string kind() const override { + return desugared_name_; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + private: + SugaredValuePtr base_value_; + std::string desugared_name_; +}; + +// things that look like function applications, but +// perform non-standard evaluation are represented +// with SpecialFormValues, e.g. +// isinstance(x, int) +// fork(fn) +// annotate(int, 3) +// The implementation of each value is handled by a case inside emitApplyExpr +struct TORCH_API SpecialFormValue : public SugaredValue { + SpecialFormValue(Symbol form) : form_(form) {} + std::string kind() const override { + return form_.toUnqualString(); + } + Symbol form() const { + return form_; + } + static std::shared_ptr create(Symbol form) { + return std::make_shared(form); + } + + private: + Symbol form_; +}; + +struct TORCH_API LegacyTensorConstructor : public SpecialFormValue { + LegacyTensorConstructor(Symbol form, at::ScalarType dtype, at::Device device) + : SpecialFormValue(form), device_(device), dtype_(dtype) {} + + static std::shared_ptr create( + Symbol form, + at::ScalarType dtype, + at::Device device) { + return std::make_shared(form, dtype, device); + } + at::ScalarType dtype() const { + return dtype_; + } + + private: + at::Device device_; + at::ScalarType dtype_; +}; + +// matched against for special handling of range expressions +struct TORCH_API RangeValue : SugaredValue { + RangeValue( + const SourceRange& loc, + GraphFunction& m, + std::vector input, + std::optional static_len = std::nullopt); + + std::string kind() const override { + return "range"; + } + Value* len(const SourceRange& loc, GraphFunction& m) override; + SugaredValuePtr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) override; + std::shared_ptr iter(const SourceRange& loc, GraphFunction& m) + override; + + // When Range is instantiated via enumerate(iterable_with_static_len), + // then it takes the static length of the iterable + std::optional staticLen() override { + return static_len_; + } + + private: + Value* start_{}; + Value* end_{}; + Value* step_{}; + // a flag to determine if it's a simple range() call with only end_ from + // arguments If true, we will not insert length calculation and index + // derivation nodes to simplify the graph and enable more possible + // optimizations + bool has_only_end_{}; + std::optional static_len_; +}; + +// Specialized Tree structure to matched against for special handling +// of builtin functions iterables expressions like zip(), enumerate(), etc. +// zip and enumerate can be modeled as a tree of SimpleValue/RangeValue: +// zip(x, y) -> (x, y) with tuple assignment to each loop target +// enumerate(x) -> (range(0, math.inf, 1), x) +// So a complicated expression like zip(a, enumerate(b), range(0, 100)) will be: +// (a, (range(0, math.inf, 1), b), range(0, 100)) +// We use those base iterables to fill in the loop information like +// max_trip_count and set the value table for loop targets +// Iterables can contain lists of SugaredValues like ModuleLists. If it +// does, then we emit it unrolled and require that all values it contains +// have a statically-determinable length. +struct TORCH_API IterableTree : SugaredValue { + IterableTree() = default; + IterableTree( + const SourceRange& range, + GraphFunction& m, + at::ArrayRef children) { + for (const auto& child : children) { + addChild(range, m, child); + } + } + std::string kind() const override { + return "iterabletree"; + } + + std::shared_ptr iter(const SourceRange& loc, GraphFunction& m) + override { + return shared_from_this(); + } + + void addChild( + const SourceRange& range, + GraphFunction& m, + const SugaredValuePtr& iter_value); + + std::vector get_children() { + return children_; + } + + // If this iterable contains a ModuleList or Tuple, then it will have a + // static length, and we will emit it as an unrolled for loop. + std::optional staticLen() override { + return unroll_length_; + } + + // given a IterableTree node, get all the base iterables/leaves under the + // IterableTree node. This enables + // us to get all the basic SugaredValues that contains valid loop information + // with len() and getitem() + std::vector get_base_iterables(); + + Value* len(const SourceRange& loc, GraphFunction& m) override; + SugaredValuePtr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) override; + + private: + std::optional unroll_length_ = std::nullopt; + std::vector children_; +}; + +static inline std::vector toValues( + Graph& g, + at::ArrayRef nvs) { + return fmap(nvs, [&](const NamedValue& v) { return v.value(g); }); +} + +struct SimpleSelf : public Self { + explicit SimpleSelf(ClassTypePtr classType) + : Self(), classType_(std::move(classType)) {} + std::shared_ptr makeSugared(Value* v) const override { + v->setType(classType_); + return std::make_shared(v); + } + ClassTypePtr getClassType() const override { + return classType_; + } + + private: + ClassTypePtr classType_; +}; + +// This is not a SimpleValue so it can not pass through the code paths that +// expect a SimpleValue as a sugared value. +struct TORCH_API ExceptionMessageValue : public SugaredValue { + explicit ExceptionMessageValue( + Value* value, + Value* qualified_class_name = nullptr) + : value_(value), qualified_class_name_(qualified_class_name) {} + + std::string kind() const override { + return "exception message"; + } + + Value* getValue() { + return value_; + } + + // qualified python class name + Value* getQualifiedClassName() { + return qualified_class_name_; + } + + private: + Value* value_; + Value* qualified_class_name_; +}; + +struct TORCH_API ExceptionValue : public SugaredValue { + explicit ExceptionValue(std::string message) : message_(std::move(message)) {} + + std::string kind() const override { + return "exception"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef /*attributes*/, + size_t /*n_binders*/) override { + auto exception_message = insertConstant(*m.graph(), message_ + ": ", loc); + for (auto& input : args) { + auto input_str = input.value(*m.graph()); + if (!input_str->type()->isSubtypeOf(*StringType::get())) { + input_str = + emitBuiltinCall(loc, *m.graph(), aten::str, {input_str}, {}); + } + exception_message = emitBuiltinCall( + loc, *m.graph(), aten::add, {exception_message, input_str}, {}); + } + return std::make_shared(exception_message); + } + + std::string message_; +}; + +struct TORCH_API SugaredEnumClass : public SugaredValue { + explicit SugaredEnumClass(EnumTypePtr enum_type) + : enum_type_(std::move(enum_type)) {} + + std::string kind() const override { + return "EnumClass"; + } + + SugaredValuePtr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + SugaredValuePtr iter(const SourceRange& loc, GraphFunction& m) override; + + private: + EnumTypePtr enum_type_; +}; + +struct TORCH_API SliceValue : public SugaredValue { + explicit SliceValue(Value* start, Value* stop, Value* step) + : start_(start), stop_(stop), step_(step) {} + + std::string kind() const override { + return "Python slice value"; + } + + Value* start() { + return start_; + } + Value* stop() { + return stop_; + } + Value* step() { + return step_; + } + + private: + Value* start_; + Value* stop_; + Value* step_; +}; + +struct TORCH_API TorchCheckValue : public SugaredValue { + explicit TorchCheckValue() = default; + + std::string kind() const override { + return "torch._check sugared value"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..a3383b06b939c78f776d408f991fa573548e699b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h @@ -0,0 +1,418 @@ +#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 { +struct Node; +struct Value; +struct Graph; +struct Module; + +namespace tracer { + +using ::c10::ivalue::Shared; + +using ::c10::IValue; +using ::c10::ivalue::Future; + +using ::c10::ArrayRef; +using ::c10::TupleType; +using ::c10::TupleTypePtr; +using ::c10::ivalue::ConstantString; + +using torch::autograd::Variable; +using variable_list = std::vector; + +TORCH_API std::atomic& getTracerStateWarnMode(); + +struct TORCH_API TracingState + : public std::enable_shared_from_this { + TracingState(); + ~TracingState(); + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr graph; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool warn = getTracerStateWarnMode(); + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool strict = true; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool force_outplace = false; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::function lookup_var_name_fn = + [](const Variable& var) { return ""; }; + + void enterFrame() { + env_stack.emplace_back(); + } + + void leaveFrame() { + env_stack.pop_back(); + } + + void setValue(const IValue& v, Value* value); + void delValue(const IValue& var); + Value* getValue(const IValue& var); + Value* getOutput(const IValue& var, size_t i); + bool hasValue(const IValue& var) const; + + Node* createNode(c10::Symbol op_name, size_t num_outputs); + void insertNode(Node* node); + + private: + using WeakIValue = at::WeakIValue; + + struct WeakIValueHasher { + size_t operator()(const WeakIValue& t) const { + return t.hash(); + } + }; + + struct WeakIValueEq { + bool operator()(const WeakIValue& t1, const WeakIValue& t2) const { + return t1.isSameIdentity(t2); + } + }; + + using Frame = + std::unordered_map; + std::vector env_stack; +}; + +// This is meant to be used as a thread local place, where we can store extra +// info that gets lost when we call into ATen from Python bindings. One example +// for when this happens is when we get an IntArrayRef argument with e.g. sizes +// for view. When tracing, those might be tensors, which let us encode extra +// data dependencies, but once they get to the ATen call where we actually have +// the tracing logic, they get converted into a raw IntArrayRef, and we loose +// all information. To prevent this, we temporarily stash it in here. +struct ArgumentStash { + struct IntArrayRefTrace : std::vector { + IntArrayRefTrace(size_t size) : std::vector(size, nullptr) {} + }; + + static bool empty() { + return stash.intlists.empty(); + } + + TORCH_API static void stashIntArrayRefElem( + const std::string& arg_name, + size_t size, + size_t idx, + const Variable& var); + + static bool hasIntArrayRef(const std::string& arg_name) { + return stash.intlists.count(arg_name) > 0; + } + + static IntArrayRefTrace popIntArrayRef(const std::string& arg_name) { + auto info = std::move(stash.intlists.at(arg_name)); + stash.intlists.erase(arg_name); + return info; + } + + // Value stashing: Use these methods to stash arguments which correspond + // to regular Value*'s in the graph. i.e. they don't require special + // handling like in the case of IntArrayRefs + TORCH_API static void stashValue( + const std::string& arg_name, + size_t idx, + const Variable& var, + const c10::TypePtr& type = nullptr); + + static bool hasValue(const std::string& arg_name) { + return stash.values.count(arg_name) > 0; + } + + static Value* popValue(const std::string& arg_name) { + auto info = stash.values.at(arg_name); + stash.values.erase(arg_name); + return info; + } + + private: + static thread_local ArgumentStash stash; + std::unordered_map intlists; + std::unordered_map values; +}; + +// Retrieve or set the current tracing state. Returns a nullptr if tracing is +// disabled. +TORCH_API const std::shared_ptr& getTracingState(); +TORCH_API void setTracingState(std::shared_ptr state); + +inline bool isTracing() { + return static_cast(getTracingState()); +} + +using warn_fn_type = void (*)(const std::string& msg); +TORCH_API extern const char* WARN_PYTHON_DATAFLOW; +TORCH_API extern const char* WARN_CONSTRUCTOR; +TORCH_API extern const char* WARN_RESIZE; +TORCH_API extern const char* STRICT_TRACER_MSG; +TORCH_API void _do_warn(const char* _reason, const char* _kind); +inline void warn(const char* _reason, const char* _kind = nullptr) { + if (const auto& state = getTracingState()) { + if (!state->warn) + return; + _do_warn(_reason, _kind); + } +} +TORCH_API void setWarn(warn_fn_type fn); + +struct TORCH_API NoWarn { + NoWarn() : state(getTracingState()) { + if (state) { + prev = state->warn; + state->warn = false; + } + } + ~NoWarn() { + if (state) { + state->warn = prev; + } + } + std::shared_ptr state; + bool prev{false}; +}; + +struct WithNestedTracingFrame { + WithNestedTracingFrame() { + getTracingState()->enterFrame(); + } + + ~WithNestedTracingFrame() { + getTracingState()->leaveFrame(); + } +}; +TORCH_API void recordSourceLocation(Node* n); +TORCH_API void setRecordSourceLocation(void (*v)(Node*)); + +TORCH_API std::vector pythonCallstack(); +TORCH_API void setPythonCallstack(std::vector (*v)()); + +// Having finished adding a new 'node' to the graph IR 'setValueTrace' +// associates this node with an output variable, so that further operations +// involving this variable know which node in the IR to reference. +TORCH_API void setValueTrace(const IValue& v, Value* value); + +TORCH_API void delValueTrace(const IValue& var); + +TORCH_API std::function pauseTracing(); + +TORCH_API Value* getValueTrace(const IValue& var); + +TORCH_API std::pair, Stack> trace( + Stack inputs, + const std::function& traced_fn, + std::function var_name_lookup_fn, + bool strict = true, + bool force_outplace = false, + Module* self = nullptr, + const std::vector& argument_names = {}); + +TORCH_API void abandon(); + +// NB: those serve both as an intermediate steps in addInputs below, +// as well as the overloads that terminate template recursion +TORCH_API void addInputs(Node* n, const char* name, int64_t value); +TORCH_API void addInputs(Node* n, const char* name, const c10::SymInt& value); +TORCH_API void addInputs( + Node* n, + const char* name, + std::optional value); +TORCH_API void addInputs(Node* n, const char* name, bool value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, double value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, const at::Scalar& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, const at::Tensor& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, ArrayRef value); +TORCH_API void addInputs(Node* n, const char* name, c10::SymIntArrayRef value); +TORCH_API void addInputs( + Node* n, + const char* name, + std::optional value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const at::OptionalIntArrayRef& opt_value); +TORCH_API void addInputs( + Node* n, + const char* name, + const at::OptionalSymIntArrayRef& opt_value); +TORCH_API void addInputs( + Node* n, + const char* name, + ArrayRef value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::vector& value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + at::ITensorListRef value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + const List>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + ArrayRef> value, + const c10::ClassTypePtr& class_type); +TORCH_API void addInputs(Node* n, const char* name, ArrayRef value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::string_view value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, at::Device value); +TORCH_API void addInputs(Node* n, const char* name, c10::Stream stream); +TORCH_API void addInputs(Node* n, const char* name, at::Layout value); +TORCH_API void addInputs(Node* n, const char* name, at::ScalarType value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, at::MemoryFormat value); +TORCH_API void addInputs( + Node* n, + const char* name, + std::optional value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); + +inline void addInputs( + Node* n, + const char* name, + const std::vector& value) { + TORCH_CHECK(false, "Tracing a list of bool type is currently not supported!"); +} + +template +void addInputs(Node* n, const char* name, ArrayRef value) { + TORCH_CHECK( + false, "Tracing a list of arbitrary type is currently not supported!"); +} +template +void addInputs( + Node* n, + const char* name, + const std::unordered_map& value) { + TORCH_CHECK( + false, "Tracing a dict of arbitrary types is currently not supported!"); +} + +template +void addInputs(Node* n, const char* name, std::array value) { + throw std::runtime_error( + "Found an unsupported argument type in the JIT tracer. File a bug report."); +} + +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::intrusive_ptr& obj); + +TORCH_API void ensureUniqueIfOutOfPlaced( + const char* name, + const at::Tensor& tensor); +TORCH_API void ensureUniqueIfOutOfPlaced( + const char* name, + const std::optional& tensor); + +template < + typename T, + typename = std::enable_if_t< + (!std::is_convertible_v, at::TensorList> && + !std::is_convertible_v, c10::List> && + !std::is_convertible_v, at::Tensor> && + !std::is_convertible_v< + std::decay_t, + c10::intrusive_ptr>)>> +void addOutput(Node* node, T&& /*unused*/) { + TORCH_CHECK( + false, + "Found an unsupported argument type ", + c10::demangle_type(), + " in the JIT tracer. File a bug report."); +} +TORCH_API void addOutput(Node* node, const at::Tensor& tensor); +TORCH_API void setOutput(Value* value, const at::Tensor& output); +TORCH_API void addOutput(Node* node, const std::vector& list); +TORCH_API void addOutput(Node* node, const c10::List& list); +TORCH_API void addOutput( + Node* node, + const c10::intrusive_ptr& output); + +TORCH_API autograd::Variable getSizeOf( + const autograd::Variable& var, + int64_t dim); + +TORCH_API autograd::Variable getNumelOf(const autograd::Variable& var); + +} // 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree.h new file mode 100644 index 0000000000000000000000000000000000000000..99ae0ff06622e087a299ade7da2b39419aa840f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree.h @@ -0,0 +1,227 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace torch::jit { + +// Trees are used to represent all forms of TC IR, pre- and post-typechecking. +// Rather than have a full class hierarchy for all TC statements, trees are a +// slight variation of Lisp s-expressions. For instance, the expression a*b+1 +// is represented as: +// (+ (* (ident a) (ident b)) (const 1)) +// Atoms like 'a', 'b', and '1' are represented by subclasses of Tree which +// define stringValue(). Everything else is a Compound object, which has a +// 'kind' that is a token from lexer.h's TokenKind enum. Single-character +// operators like '+' are represented using the character itself (so, add.kind() +// would be '+'). Each Compound object also contains a list of subtrees and is +// associated with a SourceRange for error reporting. +// Memory management of trees is done using intrusive_ptr. + +struct Tree; +using TreeRef = c10::intrusive_ptr; +using TreeList = at::SmallVector; + +struct Tree : c10::intrusive_ptr_target { + Tree(int kind_) : kind_(kind_) {} + int kind() const { + return kind_; + } + virtual bool isAtom() const { + return true; + } + virtual const SourceRange& range() const { + TORCH_CHECK(false, "is an Atom"); + } + virtual const std::string& stringValue() const { + TORCH_CHECK(false, "stringValue can only be called on TK_STRING"); + } + virtual const TreeList& trees() const { + static const TreeList empty_trees = {}; + return empty_trees; + } + const TreeRef& tree(size_t i) const { + return trees().at(i); + } + virtual TreeRef map(const std::function& fn) { + (void)fn; + c10::raw::intrusive_ptr::incref(this); // we are creating a new pointer + // from a raw `this` pointer + // so we need to bump the refcount + // to account for this ownership + return TreeRef::reclaim(this); + } + template + void match(int k, Args&... args) const { + matchD(k, "unknown", 0, args...); + } + template + void matchD(int k, const char* filename, int lineno, Args&... args) const { + std::initializer_list vars = {args...}; + matchNumSubtreesD(k, filename, lineno, vars.size(), true); + size_t i = 0; + for (TreeRef* v : vars) { + *v = trees()[i++]; + } + } + void matchNumSubtrees(int k, size_t expected_subtrees) { + return matchNumSubtreesD(k, "unknown", 0, expected_subtrees, false); + } + void matchNumSubtreesD( + int k, + const char* filename, + int lineno, + size_t expected_subtrees, + bool allow_more) const { + TORCH_CHECK( + kind() == k, + filename, + ":", + lineno, + ": expecting kind '", + kindToString(k), + "' but found '", + kindToString(kind()), + "'\n"); + if (trees().size() < expected_subtrees || + (!allow_more && trees().size() != expected_subtrees)) { + std::stringstream ss; + ss << filename << ':' << lineno << ": expected at least " + << expected_subtrees << " subtrees, but found only " << trees().size() + << '\n'; + range().highlight(ss); + TORCH_CHECK(false, ss.str()); + } + } + ~Tree() override = default; + + private: + int kind_; +}; + +struct String : public Tree { + String(std::string value) : Tree(TK_STRING), value_(std::move(value)) {} + const std::string& stringValue() const override { + return value_; + } + template + static TreeRef create(Args&&... args) { + return c10::make_intrusive(std::forward(args)...); + } + + private: + std::string value_; +}; + +static SourceRange mergeRanges(SourceRange c, const TreeList& others) { + for (const auto& t : others) { + if (t->isAtom()) + continue; + size_t s = std::min(c.start(), t->range().start()); + size_t e = std::max(c.end(), t->range().end()); + c = SourceRange(c.source(), s, e); + } + return c; +} + +struct Compound : public Tree { + Compound(int kind, SourceRange range) + : Tree(kind), range_(std::move(range)) {} + Compound(int kind, const SourceRange& range_, TreeList&& trees_) + : Tree(kind), + range_(mergeRanges(range_, trees_)), + trees_(std::move(trees_)) {} + const TreeList& trees() const override { + return trees_; + } + static TreeRef create( + int kind, + const SourceRange& range_, + TreeList&& trees_) { + return c10::make_intrusive(kind, range_, std::move(trees_)); + } + bool isAtom() const override { + return false; + } + TreeRef map(const std::function& fn) override { + TreeList ret; + for (auto& t : trees()) { + ret.push_back(fn(t)); + } + return Compound::create(kind(), range(), std::move(ret)); + } + + const SourceRange& range() const override { + return range_; + } + + private: + SourceRange range_; + TreeList trees_; +}; + +// tree pretty printer +struct pretty_tree { + pretty_tree(const TreeRef& tree, size_t col = 40) : tree(tree), col(col) {} + const TreeRef& tree; + size_t col; + std::unordered_map flat_strings; + const std::string& get_flat(const TreeRef& t) { + auto it = flat_strings.find(t); + if (it != flat_strings.end()) + return it->second; + + std::stringstream out; + switch (t->kind()) { + case TK_STRING: + out << t->stringValue(); + break; + default: + out << '(' << kindToString(t->kind()); + for (const auto& e : t->trees()) { + out << ' ' << get_flat(e); + } + out << ')'; + break; + } + auto it_ = flat_strings.emplace(t, out.str()); + return it_.first->second; + } + void print(std::ostream& out, const TreeRef& t, int indent) { + const std::string& s = get_flat(t); + if (indent + s.size() < col || t->isAtom()) { + out << s; + return; + } + std::string k = kindToString(t->kind()); + out << '(' << k; + for (const auto& e : t->trees()) { + out << '\n' << std::string(indent + 2, ' '); + print(out, e, indent + 2); + } + out << ')'; + } +}; + +static inline std::ostream& operator<<(std::ostream& out, pretty_tree t_) { + t_.print(out, t_.tree, 0); + return out << '\n'; +} + +static inline std::ostream& operator<<(std::ostream& out, const TreeRef& t) { + return out << pretty_tree(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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree_views.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree_views.h new file mode 100644 index 0000000000000000000000000000000000000000..1dc386d938f69651b4f9dd3cf9d5a335531c63e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree_views.h @@ -0,0 +1,1285 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::jit { + +// clang-format off +// TreeView provides a statically-typed way to traverse the tree, which should +// be formed according to the grammar below. +// +// A few notes on types and their aliases: +// - List is really a Tree with kind TK_LIST and elements as subtrees +// - Maybe is really a Tree with kind TK_OPTION that has 0 or 1 subtree of type T +// - Builtin types are: Ident (TK_IDENT), String (TK_STRING) +// +// Param = Param(Maybe type, Ident name) TK_PARAM +// +// Decl = Decl(List params, Maybe return_type) TK_DECL +// Def = Def(Ident name, Decl decl, List body) TK_DEF +// ClassDef = ClassDef(Ident name, TK_CLASS_DEF +// Maybe superclass, +// List body) +// +// Stmt = If(Expr cond, List true_body, List false_body) TK_IF +// | For(List targets, List iters, List body) TK_FOR +// | While(Expr cond, List body) TK_WHILE +// | Global(List idents) TK_GLOBAL +// -- NB: the only type of Expr's allowed on lhs are Var +// Or a tuple containing Var with an optional terminating Starred +// | Assign(Expr lhs, Maybe rhs, Maybe type) TK_ASSIGN +// | AugAssign(Expr lhs, AugAssignKind aug_op, Expr rhs) TK_AUG_ASSIGN +// | Return(List values) TK_RETURN +// | ExprStmt(List expr) TK_EXPR_STMT +// | Raise(Expr expr) TK_RAISE +// | Def TK_DEF +// | With(List targets, List body) TK_WITH +// +// Expr = TernaryIf(Expr cond, Expr true_expr, Expr false_expr) TK_IF_EXPR +// | BinOp(Expr lhs, Expr rhs) +// | And TK_AND +// | Or TK_OR +// | Lt '<' +// | Gt '>' +// | Eq TK_EQ +// | Le TK_LE +// | Ge TK_GE +// | Ne TK_NE +// | Is TK_IS +// | IsNot TK_ISNOT +// | Add '+' +// | Sub '-' +// | Mul '*' +// | Div '/' +// | Mod '%' +// | MatMult '@' +// | Pow TK_POW +// | UnaryOp(Expr expr) +// | Not TK_NOT +// | USub '-' +// | Const(String value) TK_CONST +// -- NB: x.name(y) is desugared into name(x, y) +// | Apply(Ident name, List args, List kwargs) TK_APPLY +// | Select(Expr value, Ident selector) '.' +// | Subscript(Expr value, List subscript_exprs) TK_SUBSCRIPT +// | SliceExpr(Maybe start, Maybe end) TK_SLICE_EXPR +// | Var(Ident name) TK_VAR +// | ListLiteral(List inputs) TK_LIST_LITERAL +// | TupleLiteral(List inputs) TK_TUPLE_LITERAL +// | Starred(Expr expr) TK_STARRED +// | WithItem(Expr target, Maybe var) TK_WITH_ITEM +// -- NB: only allowed expressions are Const or List(Const) +// (List as a value, not type constructor) +// Attribute = Attribute(Ident name, Expr value) TK_ATTRIBUTE +// +// AugAssignKind = +// | Add() TK_PLUS_EQ +// | Sub() TK_MINUS_EQ +// | Mul() TK_TIMES_EQ +// | Div() TK_DIV_EQ +// | Mod() TK_MOD_EQ +// + +// Each subclass of TreeView should provide: +// 1. Constructor that takes a TreeRef, and checks that it's of the right type. +// 2. Accessors that get underlying information out of the object. If they +// return subtrees, they should wrap them in appropriate views too. +// 3. Static method 'create' that creates the underlying TreeRef object +// for every TreeRef kind that has a TreeView, the parser always uses +// (e.g.) Ident::create rather than Compound::Create, this means that +// changes to the structure of Ident are always made right here rather +// than both in the parser and in this code. +// XXX: these structs should have no fields to prevent slicing when passing by value +// clang-format on +struct TreeView { + explicit TreeView(TreeRef tree) : tree_(std::move(tree)) {} + TreeRef tree() const { + return tree_; + } + const SourceRange& range() const { + return tree_->range(); + } + operator TreeRef() const { + return tree_; + } + const TreeRef& get() const { + return tree_; + } + int kind() const { + return tree_->kind(); + } + void dump() const { + std::cout << tree_; + } + + protected: + const TreeRef& subtree(size_t i) const { + return tree_->trees().at(i); + } + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + TreeRef tree_; +}; + +template +struct ListIterator { + ListIterator(TreeList::const_iterator it) : it(it) {} + bool operator!=(const ListIterator& rhs) const { + return it != rhs.it; + } + bool operator==(const ListIterator& rhs) const { + return it == rhs.it; + } + T operator*() const { + return T(*it); + } + ListIterator& operator+=(std::ptrdiff_t n) { + it += n; + return *this; + } + ListIterator& operator++() { + ++it; + return *this; + } + ListIterator& operator--() { + --it; + return *this; + } + + private: + TreeList::const_iterator it; +}; + +template +struct List : public TreeView { + using iterator = ListIterator; + using const_iterator = ListIterator; + + List(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_LIST); + // Iterate over list to temporarily instantiate Ts that will check the type + for (const T& elem : *this) { + (void)elem; // silence unused warning + } + } + iterator begin() const { + return iterator(tree_->trees().begin()); + } + iterator end() const { + return iterator(tree_->trees().end()); + } + bool empty() const { + return tree_->trees().begin() == tree_->trees().end(); + } + T operator[](size_t i) const { + return T(subtree(i)); + } + TreeRef map(const std::function& fn) { + return tree_->map([&](TreeRef v) { return fn(T(v)); }); + } + static List create(const SourceRange& range, const std::vector& subtrees) { + TreeList type_erased_sub{subtrees.begin(), subtrees.end()}; + return List(Compound::create(TK_LIST, range, std::move(type_erased_sub))); + } + static List unsafeCreate(const SourceRange& range, TreeList&& subtrees) { + return List(Compound::create(TK_LIST, range, std::move(subtrees))); + } + size_t size() const { + return tree_->trees().size(); + } +}; + +template +struct Maybe : public TreeView { + explicit Maybe(const TreeRef& tree) : TreeView(tree) { + tree_->match(TK_OPTION); + if (tree_->trees().size() > 1) + throw(ErrorReport(tree) << "Maybe trees can have at most one subtree"); + } + /* implicit */ Maybe(const T& tree) : TreeView(tree) {} + bool present() const { + return tree_->trees().size() > 0; + } + T get() const { + return T(tree_->trees().at(0)); + } + TreeRef map(const std::function& fn) { + return tree_->map([&](TreeRef v) { return fn(T(v)); }); + } + static Maybe create(const SourceRange& range) { + return Maybe(Compound::create(TK_OPTION, range, {})); + } + static Maybe create(const SourceRange& range, const T& value) { + return Maybe(Compound::create(TK_OPTION, range, {value})); + } +}; + +struct Ident : public TreeView { + explicit Ident(const TreeRef& tree) : TreeView(tree) { + tree_->match(TK_IDENT); + } + const std::string& name() const { + return subtree(0)->stringValue(); + } + static Ident create(const SourceRange& range, std::string name) { + return Ident( + Compound::create(TK_IDENT, range, {String::create(std::move(name))})); + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// Base types (production LHS) +//////////////////////////////////////////////////////////////////////////////// + +struct Stmt : public TreeView { + explicit Stmt(const TreeRef& tree) : TreeView(tree) { + switch (tree->kind()) { + case TK_IF: + case TK_FOR: + case TK_WHILE: + case TK_GLOBAL: + case TK_ASSIGN: + case TK_AUG_ASSIGN: + case TK_RETURN: + case TK_EXPR_STMT: + case TK_RAISE: + case TK_ASSERT: + case TK_PASS: + case TK_BREAK: + case TK_DELETE: + case TK_CONTINUE: + case TK_DEF: + case TK_WITH: + return; + default: + throw( + ErrorReport(tree) + << kindToString(tree->kind()) << " is not a valid Stmt"); + } + } +}; + +struct Expr : public TreeView { + explicit Expr(const TreeRef& tree) : TreeView(tree) { + switch (tree->kind()) { + case TK_IF_EXPR: + case TK_AND: + case TK_OR: + case '<': + case '>': + case TK_IS: + case TK_ISNOT: + case TK_EQ: + case TK_LE: + case TK_GE: + case TK_NE: + case '+': + case '-': + case TK_UNARY_MINUS: + case '~': + case '*': + case TK_STARRED: + case '/': + case '%': + case TK_NOT: + case TK_CONST: + case TK_STRINGLITERAL: + case TK_TRUE: + case TK_FALSE: + case TK_NONE: + case TK_NONE_TYPE: + case TK_CAST: + case TK_APPLY: + case '.': + case TK_SUBSCRIPT: + case TK_SLICE_EXPR: + case TK_VAR: + case TK_LIST_LITERAL: + case TK_TUPLE_LITERAL: + case TK_DICT_LITERAL: + case '@': + case TK_POW: + case TK_LSHIFT: + case TK_RSHIFT: + case TK_FLOOR_DIV: + case '&': + case '^': + case '|': + case TK_LIST_COMP: + case TK_DICT_COMP: + case TK_DOTS: + case TK_IN: + case TK_WITH_ITEM: + return; + default: + throw( + ErrorReport(tree) + << kindToString(tree->kind()) << " is not a valid Expr"); + } + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// Helper nodes (mostly for function arguments) +//////////////////////////////////////////////////////////////////////////////// + +struct Attribute : public TreeView { + explicit Attribute(const TreeRef& tree) : TreeView(tree) { + tree_->match(TK_ATTRIBUTE); + } + Ident name() const { + return Ident(subtree(0)); + } + Expr value() const { + return Expr(subtree(1)); + } + static Attribute create( + const SourceRange& range, + const Ident& name, + const TreeRef& value) { + return Attribute(Compound::create(TK_ATTRIBUTE, range, {name, value})); + } +}; + +struct Param : public TreeView { + explicit Param(const TreeRef& tree) : TreeView(tree) { + tree_->match(TK_PARAM); + } + static Param create( + const SourceRange& range, + const Ident& ident, + const Maybe& type, + const Maybe& def, + bool kwarg_only) { + TreeRef kwarg_only_tree = + Compound::create(kwarg_only ? TK_TRUE : TK_FALSE, range, {}); + return Param(Compound::create( + TK_PARAM, range, {ident, type, def, std::move(kwarg_only_tree)})); + } + Ident ident() const { + return Ident(subtree(0)); + } + Maybe type() const { + return Maybe(subtree(1)); + } + Maybe defaultValue() const { + return Maybe(subtree(2)); + } + bool kwarg_only() const { + return TK_TRUE == subtree(3)->kind(); + } + Param withType(const Maybe& typ) const { + return Param::create(range(), ident(), typ, defaultValue(), kwarg_only()); + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// Top level definitions +//////////////////////////////////////////////////////////////////////////////// + +struct Decl : public TreeView { + explicit Decl(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_DECL); + } + List params() const { + return List(subtree(0)); + } + Maybe return_type() const { + return Maybe(subtree(1)); + } + static Decl create( + const SourceRange& range, + const List& params, + const Maybe& return_type) { + return Decl(Compound::create(TK_DECL, range, {params, return_type})); + } +}; + +struct Def : public TreeView { + explicit Def(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_DEF); + } + Def withName(std::string new_name) const { + auto new_ident = Ident::create(name().range(), std::move(new_name)); + return create(range(), new_ident, decl(), statements()); + } + Def withDecl(const Decl& decl) const { + return create(range(), name(), decl, statements()); + } + Ident name() const { + return Ident(subtree(0)); + } + Decl decl() const { + return Decl(subtree(1)); + } + List statements() const { + return List(subtree(2)); + } + static Def create( + const SourceRange& range, + const Ident& name, + const Decl& decl, + const List& stmts) { + return Def(Compound::create(TK_DEF, range, {name, decl, stmts})); + } +}; + +// Property represents a named attribute combined with a getter and setter +// method to access and mutate that attribute. +struct Property : public TreeView { + explicit Property(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_PROP); + } + Ident name() const { + return Ident(subtree(0)); + } + Def getter() const { + return Def(subtree(1)); + } + Maybe setter() const { + return Maybe(subtree(2)); + } + static Property create( + const SourceRange& range, + const Ident& name, + const Def& getter, + const Maybe& setter) { + return Property(Compound::create(TK_PROP, range, {name, getter, setter})); + } +}; + +struct Assign; + +struct ClassDef : public TreeView { + explicit ClassDef(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_CLASS_DEF); + } + explicit ClassDef(TreeRef&& tree) : TreeView(std::move(tree)) { + tree_->match(TK_CLASS_DEF); + } + ClassDef withName(std::string new_name) const { + auto new_ident = Ident::create(name().range(), std::move(new_name)); + return create(range(), new_ident, superclass(), body()); + } + Ident name() const { + return Ident(subtree(0)); + } + Maybe superclass() const { + return Maybe(subtree(1)); + } + List body() const { + return List(subtree(2)); + } + Maybe> properties() const { + return Maybe>(subtree(3)); + } + Maybe> assigns() const { + return Maybe>(subtree(4)); + } + static ClassDef create( + const SourceRange& range, + const Ident& name, + const Maybe& superclass, + const List& body) { + return ClassDef(Compound::create( + TK_CLASS_DEF, + range, + {name, + superclass, + body, + Maybe>::create(range), + Maybe>::create(range)})); + } + static ClassDef create( + const SourceRange& range, + const Ident& name, + const Maybe& superclass, + const List& body, + const List& properties, + const List& assigns); +}; + +TORCH_API std::vector getUnresolvedClassAttributes( + const ClassDef& def); + +//////////////////////////////////////////////////////////////////////////////// +// Statements +//////////////////////////////////////////////////////////////////////////////// + +struct If : public Stmt { + explicit If(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_IF); + } + Expr cond() const { + return Expr(subtree(0)); + } + List trueBranch() const { + return List(subtree(1)); + } + List falseBranch() const { + return List(subtree(2)); + } + If withNewBranches( + const List& true_branch, + const List& false_branch) const { + return create(range(), cond(), true_branch, false_branch); + } + static If create( + const SourceRange& range, + const Expr& cond, + const List& true_branch, + const List& false_branch) { + return If( + Compound::create(TK_IF, range, {cond, true_branch, false_branch})); + } +}; + +struct While : public Stmt { + explicit While(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_WHILE); + } + Expr cond() const { + return Expr(subtree(0)); + } + List body() const { + return List(subtree(1)); + } + static While create( + const SourceRange& range, + const Expr& cond, + const List& body) { + return While(Compound::create(TK_WHILE, range, {cond, body})); + } +}; + +struct For : public Stmt { + explicit For(const TreeRef& tree) : Stmt(tree) { + tree->match(TK_FOR); + } + List targets() const { + return List(subtree(0)); + } + List itrs() const { + return List(subtree(1)); + } + List body() const { + return List(subtree(2)); + } + static For create( + const SourceRange& range, + const List& targets, + const List& itrs, + const List& body) { + return For(Compound::create(TK_FOR, range, {targets, itrs, body})); + } +}; + +// TODO: supports only single comprehension for now +struct ListComp : public Expr { + explicit ListComp(const TreeRef& tree) : Expr(tree) { + tree->match(TK_LIST_COMP); + } + Expr elt() const { + return Expr(subtree(0)); + } + Expr target() const { + return Expr(subtree(1)); + } + Expr iter() const { + return Expr(subtree(2)); + } + // TODO: no ifs for now + static ListComp create( + const SourceRange& range, + const Expr& elt, + const Expr& target, + const Expr& iter) { + return ListComp(Compound::create(TK_LIST_COMP, range, {elt, target, iter})); + } +}; + +// TODO: supports only single comprehension for now +struct DictComp : public Expr { + explicit DictComp(const TreeRef& tree) : Expr(tree) { + tree->match(TK_DICT_COMP); + } + Expr key() const { + return Expr(subtree(0)); + } + Expr value() const { + return Expr(subtree(1)); + } + Expr target() const { + return Expr(subtree(2)); + } + Expr iter() const { + return Expr(subtree(3)); + } + // TODO: no ifs for now + static DictComp create( + const SourceRange& range, + const Expr& key, + const Expr& value, + const Expr& target, + const Expr& iter) { + return DictComp( + Compound::create(TK_DICT_COMP, range, {key, value, target, iter})); + } +}; + +struct Global : public Stmt { + explicit Global(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_GLOBAL); + } + List names() { + return List(subtree(0)); + } + static Global create(const SourceRange& range, const List& names) { + return Global(Compound::create(TK_GLOBAL, range, {names})); + } +}; + +struct AugAssignKind : public TreeView { + explicit AugAssignKind(const TreeRef& tree) : TreeView(tree) { + switch (tree->kind()) { + case '+': + case '-': + case '*': + case '/': + case '%': + case '|': + case '&': + case '^': + case TK_POW: + case TK_LSHIFT: + case TK_RSHIFT: + return; + default: + throw(ErrorReport(tree) << "is not a valid AugAssignKind"); + } + } +}; + +// Augmented assignment, like "foo += bar" +struct AugAssign : public Stmt { + explicit AugAssign(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_AUG_ASSIGN); + } + static AugAssign create( + const SourceRange& range, + const Expr& lhs, + const AugAssignKind& aug_op, + const Expr& rhs) { + return AugAssign( + Compound::create(TK_AUG_ASSIGN, range, {lhs, aug_op, rhs})); + } + Expr lhs() const { + return Expr(subtree(0)); + } + int aug_op() const { + return subtree(1)->kind(); + } + Expr rhs() const { + return Expr(subtree(2)); + } +}; + +struct Assign : public Stmt { + explicit Assign(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_ASSIGN); + } + static Assign create( + const SourceRange& range, + const List& lhs, + const Maybe& rhs, + const Maybe& type) { + return Assign(Compound::create(TK_ASSIGN, range, {lhs, rhs, type})); + } + + List lhs_list() const { + return List(subtree(0)); + } + + Expr lhs() const { + const auto& li = lhs_list(); + TORCH_INTERNAL_ASSERT(li.size() == 1); + return *li.begin(); + } + + Maybe rhs() const { + return Maybe(subtree(1)); + } + + Maybe type() const { + return Maybe(subtree(2)); + } +}; + +struct Return : public Stmt { + explicit Return(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_RETURN); + } + Expr expr() const { + return Expr(subtree(0)); + } + static Return create(const SourceRange& range, const Expr& value) { + return Return(Compound::create(TK_RETURN, range, {value})); + } +}; + +struct Raise : public Stmt { + explicit Raise(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_RAISE); + } + Expr expr() const { + return Expr(subtree(0)); + } + static Raise create(const SourceRange& range, const Expr& expr) { + return Raise(Compound::create(TK_RAISE, range, {expr})); + } +}; + +struct Assert : public Stmt { + explicit Assert(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_ASSERT); + } + Expr test() const { + return Expr(subtree(0)); + } + Maybe msg() const { + return Maybe(subtree(1)); + } + static Assert create( + const SourceRange& range, + const Expr& test, + const Maybe& msg) { + return Assert(Compound::create(TK_ASSERT, range, {test, msg})); + } +}; + +struct Pass : public Stmt { + explicit Pass(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_PASS); + } + static Pass create(const SourceRange& range) { + return Pass(Compound::create(TK_PASS, range, {})); + } +}; + +struct Dots : public Expr { + explicit Dots(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_DOTS); + } + static Dots create(const SourceRange& range) { + return Dots(Compound::create(TK_DOTS, range, {})); + } +}; + +struct Break : public Stmt { + explicit Break(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_BREAK); + } + static Break create(const SourceRange& range) { + return Break(Compound::create(TK_BREAK, range, {})); + } +}; + +struct Continue : public Stmt { + explicit Continue(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_CONTINUE); + } + static Continue create(const SourceRange& range) { + return Continue(Compound::create(TK_CONTINUE, range, {})); + } +}; + +struct ExprStmt : public Stmt { + explicit ExprStmt(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_EXPR_STMT); + } + Expr expr() { + return Expr(subtree(0)); + } + static ExprStmt create(const SourceRange& range, const Expr& list) { + return ExprStmt(Compound::create(TK_EXPR_STMT, range, {list})); + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// Expressions +//////////////////////////////////////////////////////////////////////////////// + +struct BinOp : public Expr { + explicit BinOp(const TreeRef& tree) : Expr(tree) { + switch (tree->kind()) { + case TK_AND: + case TK_OR: + case '<': + case '>': + case TK_IS: + case TK_ISNOT: + case TK_EQ: + case TK_LE: + case TK_GE: + case TK_NE: + case '+': + case '*': + case '/': + case '-': + case '@': + case TK_POW: + case TK_LSHIFT: + case TK_RSHIFT: + case '%': + case '&': + case '^': + case '|': + case TK_FLOOR_DIV: + case TK_IN: + if (tree->trees().size() != 2) + throw( + ErrorReport(tree) + << "BinOp expected 2 subtrees, found " << tree->trees().size()); + return; + default: + throw( + ErrorReport(tree) + << kindToString(tree->kind()) << " is not a valid BinOp"); + } + } + Expr lhs() const { + return Expr(subtree(0)); + } + Expr rhs() const { + return Expr(subtree(1)); + } + static BinOp create( + const SourceRange& range, + int kind, + const Expr& lhs, + const Expr& rhs) { + return BinOp(Compound::create(kind, range, {lhs, rhs})); + } +}; + +struct UnaryOp : public Expr { + explicit UnaryOp(const TreeRef& tree) : Expr(tree) { + switch (tree->kind()) { + case TK_UNARY_MINUS: + case '~': + case TK_NOT: + if (tree->trees().size() != 1) + throw( + ErrorReport(tree) + << "UnaryOp expected 1 subtree, found " << tree->trees().size()); + return; + default: + throw( + ErrorReport(tree) + << kindToString(tree->kind()) << " is not a valid UnaryOp"); + } + } + static UnaryOp create(const SourceRange& range, int kind, const Expr& expr) { + return UnaryOp(Compound::create(kind, range, {expr})); + } +}; + +struct Const : public Expr { + explicit Const(const TreeRef& tree) : Expr(tree) { + tree_->matchNumSubtrees(TK_CONST, 1); + } + bool isFloatingPoint() const { + if (isComplex()) + return false; + + bool is_inf = subtree(0)->stringValue() == "inf"; + return is_inf || + subtree(0)->stringValue().find_first_of(".eE") != std::string::npos; + } + bool isIntegral() const { + return !isFloatingPoint() && !isComplex(); + } + bool isComplex() const { + return subtree(0)->stringValue().find_first_of('j') != std::string::npos; + } + int64_t asIntegral() const { + try { + return std::stoll(subtree(0)->stringValue(), nullptr, 0); + } catch (const std::out_of_range&) { + throw( + ErrorReport(range()) << "Integral constant out of range " + "(must fit in a signed 64 bit integer)"); + } + } + double asFloatingPoint() const { + // We can't pass in nullptr as the dummy pointer gets dereferenced for + // Android version of strtod_c(). + char* dummy = nullptr; + return torch::jit::strtod_c(subtree(0)->stringValue().c_str(), &dummy); + } + c10::complex asComplex() const { + char* dummy = nullptr; + auto str = subtree(0)->stringValue(); + // Complex numbers (a+bj, where a is non-zero) are parsed as an addition + // between float/int a and a complex number "bj". When a is 0, a complex + // number bj is created as above. So, while parsing the string, we don't + // have to worry about the real component of the complex number. + auto imag = + torch::jit::strtod_c(str.substr(0, str.size() - 1).c_str(), &dummy); + return c10::complex(0, imag); + } + const std::string& text() const { + return subtree(0)->stringValue(); + } + static Const create(const SourceRange& range, const std::string& value) { + return Const(Compound::create(TK_CONST, range, {String::create(value)})); + } +}; + +struct StringLiteral : public Expr { + explicit StringLiteral(const TreeRef& tree) : Expr(tree) { + tree_->matchNumSubtrees(TK_STRINGLITERAL, 1); + } + const std::string& text() const { + return subtree(0)->stringValue(); + } + static StringLiteral create( + const SourceRange& range, + const std::string& value) { + return StringLiteral( + Compound::create(TK_STRINGLITERAL, range, {String::create(value)})); + } +}; + +struct Apply : public Expr { + explicit Apply(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_APPLY); + } + Expr callee() const { + return Expr(subtree(0)); + } + List inputs() const { + return List(subtree(1)); + } + List attributes() const { + return List(subtree(2)); + } + static Apply create( + const SourceRange& range, + const Expr& callee, + const List& inputs, + const List& attributes) { + return Apply( + Compound::create(TK_APPLY, range, {callee, inputs, attributes})); + } +}; + +struct Select : public Expr { + explicit Select(const TreeRef& tree) : Expr(tree) { + tree_->match('.'); + } + Expr value() const { + return Expr(subtree(0)); + } + Ident selector() const { + return Ident(subtree(1)); + } + static Select create( + const SourceRange& range, + const Expr& value, + const Ident& selector) { + return Select(Compound::create('.', range, {value, selector})); + } +}; + +struct SliceExpr : public Expr { + explicit SliceExpr(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_SLICE_EXPR); + } + Maybe start() const { + return Maybe(subtree(0)); + } + Maybe end() const { + return Maybe(subtree(1)); + } + Maybe step() const { + return Maybe(subtree(2)); + } + Expr startOr(int64_t alternative) const { + const auto startOption = start(); + return startOption.present() ? startOption.get() : createInt(alternative); + } + Expr endOr(int64_t alternative) const { + const auto endOption = end(); + return endOption.present() ? endOption.get() : createInt(alternative); + } + Expr stepOr(int64_t alternative) const { + const auto stepOption = step(); + return stepOption.present() ? stepOption.get() : createInt(alternative); + } + static SliceExpr create( + const SourceRange& range, + const Maybe& start, + const Maybe& end, + const Maybe& step) { + return SliceExpr( + Compound::create(TK_SLICE_EXPR, range, {start, end, step})); + } + + private: + Expr createInt(int64_t value) const { + return Expr(Const::create(range(), std::to_string(value))); + } +}; + +struct Subscript : public Expr { + explicit Subscript(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_SUBSCRIPT); + } + Expr value() const { + return Expr(subtree(0)); + } + List subscript_exprs() const { + return List(subtree(1)); + } + static Subscript create( + const SourceRange& range, + const Expr& value, + const List& subscript_exprs) { + auto whole_range = SourceRange( + range.source(), range.start(), subscript_exprs.range().end() + 1); + return Subscript( + Compound::create(TK_SUBSCRIPT, whole_range, {value, subscript_exprs})); + } +}; + +struct Var : public Expr { + explicit Var(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_VAR); + } + Ident name() const { + return Ident(subtree(0)); + } + static Var create(const SourceRange& range, const Ident& name) { + return Var(Compound::create(TK_VAR, range, {name})); + } +}; + +// WithItem represents an item using with a WithStmt. +struct WithItem : public Expr { + explicit WithItem(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_WITH_ITEM); + } + + Expr target() const { + return Expr(subtree(0)); + } + + Maybe var() const { + return Maybe(subtree(1)); + } + + static WithItem create( + const SourceRange& range, + const Expr& target, + const Maybe& var) { + return WithItem(Compound::create(TK_WITH_ITEM, range, {target, var})); + } +}; + +// With represents a with statement consisting of a list of with items and a +// body of statements. +struct With : public Stmt { + explicit With(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_WITH); + } + + List targets() const { + return List(subtree(0)); + } + + List body() const { + return List(subtree(1)); + } + + static With create( + const SourceRange& range, + const List& targets, + const List& body) { + return With(Compound::create(TK_WITH, range, {targets, body})); + } +}; + +struct TernaryIf : public Expr { + explicit TernaryIf(const TreeRef& tree) : Expr(tree) { + tree_->matchNumSubtrees(TK_IF_EXPR, 3); + } + Expr cond() const { + return Expr(subtree(0)); + } + Expr true_expr() const { + return Expr(subtree(1)); + } + Expr false_expr() const { + return Expr(subtree(2)); + } + static TernaryIf create( + const SourceRange& range, + const Expr& cond, + const Expr& true_expr, + const Expr& false_expr) { + return TernaryIf( + Compound::create(TK_IF_EXPR, range, {cond, true_expr, false_expr})); + } +}; + +struct ListLiteral : public Expr { + explicit ListLiteral(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_LIST_LITERAL); + } + List inputs() const { + return subtree(0); + } + static ListLiteral create( + const SourceRange& range, + const List& inputs) { + return ListLiteral(Compound::create(TK_LIST_LITERAL, range, {inputs})); + } +}; + +struct TupleLiteral : public Expr { + explicit TupleLiteral(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_TUPLE_LITERAL); + } + List inputs() const { + return subtree(0); + } + static TupleLiteral create( + const SourceRange& range, + const List& inputs) { + return TupleLiteral(Compound::create(TK_TUPLE_LITERAL, range, {inputs})); + } +}; + +struct DictLiteral : public Expr { + explicit DictLiteral(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_DICT_LITERAL); + } + List key_inputs() const { + return subtree(0); + } + List value_inputs() const { + return subtree(1); + } + static DictLiteral create( + const SourceRange& range, + const List& keys, + const List& values) { + return DictLiteral( + Compound::create(TK_DICT_LITERAL, range, {keys, values})); + } +}; + +struct Starred : public Expr { + explicit Starred(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_STARRED); + } + Expr expr() const { + return Expr(subtree(0)); + } + static Starred create(const SourceRange& range, const Expr& expr) { + return Starred(Compound::create(TK_STARRED, range, {expr})); + } +}; + +struct Delete : public Stmt { + explicit Delete(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_DELETE); + } + List targets() const { + return subtree(0); + } + static Delete create(const SourceRange& range, const List& targets) { + return Delete(Compound::create(TK_DELETE, range, {targets})); + } +}; + +/* + * NOTE: transforming PEP 604 union into equivalent union type + * + * NOTE: Union[int, float] parses into: + * expr:(subscript + * (variable (ident Union)) + * (list + * (variable (ident int)) + * (variable (ident float)))) + * subscript + * + * NOTE: (int | float) parses into: + * expr:(| + * (variable (ident int)) + * (variable (ident float))) + * | + */ + +inline void _flatten_pep604_union( + const torch::jit::Expr& node, + std::vector* result) { + // flatten possibly nested union expressions like (int | (float | str)) + // into a flat list of expressions like [int, float, str] + if (node.kind() == '|') { + auto as_binop = torch::jit::BinOp(node); + _flatten_pep604_union(as_binop.lhs(), result); + _flatten_pep604_union(as_binop.rhs(), result); + } else { + result->push_back(node); + } +} + +inline std::vector get_pep604_union_members(const Expr& node) { + std::vector result; + _flatten_pep604_union(node, &result); + return result; +} + +// Flattens a PEP 604 union into a classical union. +// For example, ((x | y) | z) is transformed into Union[x, y, z]. +inline Expr pep604union_to_union(const Expr& expr) { + // noop if not a pep604 union + if (expr.kind() != '|') + return expr; + + // In order to support unions with more than 2 operands ((x|y)|z), we need to + // recursively flatten the tree of | expressions. + auto members = get_pep604_union_members(expr); + auto synthesised_union = Subscript::create( + expr.range(), + Var::create(expr.range(), Ident::create(expr.range(), "Union")), + List::create(expr.range(), members)); +#if defined(__clang__) + return std::move(synthesised_union); +#else + return synthesised_union; +#endif +} + +} // namespace torch::jit + +namespace std { + +template +struct iterator_traits> + : std::iterator_traits {}; + +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h new file mode 100644 index 0000000000000000000000000000000000000000..b8cb099cc27a3237256f2fa139e1973efc4f6ea7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace torch::jit { +// Maps the given symbol into an implementation of its behavior at the +// given version. +// See note [Versioned Symbols] +TORCH_API Symbol +get_symbol_for_version(const Symbol name, const uint64_t version); + +// Maps the given kind to the minimum version that supports it. +// See note [Dynamic Versions and torch.jit.save vs. torch.save] +TORCH_API uint64_t get_min_version_for_kind(const NodeKind& kind); +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/alias_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/alias_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..598426bd6807d67c4e9c8e00441bb0680e0ca91a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/alias_analysis.h @@ -0,0 +1,368 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +class ValueAndMemoryLocationSet; + +/** + * Alias analysis pass. + * + * This pass produces an AliasDb that contains aliasing and mutation + * information about the graph. Users can use this information to determine + * whether mutations to the graph are safe, i.e. they don't reorder/change + * nodes in a way that affects output. + * + * Every value with a mutable type (Tensors, Lists, Tuples, etc.) will be + * associated with one or more "alias sets". If two values share an alias set, + * that means they may alias, implying that a mutation to one value cannot be + * reordered past a use of the other. Only reordering two reads of an alias set + * is considered safe. + * + * There is a special alias set called the "wildcard set", which indicates that + * we're not sure what this value may alias. To be conservative, we consider the + * wildcard alias set as potentially aliasing any other wildcard value within + * the same type class. Whenever a value becomes contained by another value, + * such as when a Tensor is appended to a List[Tensor], the contained element + * becomes part of the wildcard set. + * + * Values that contain other mutable types, such as List[Tensor], are + * initialized as containing the Wildcard set for all contained mutable types. + * + * The AliasDb API references the idea of "mutable" vs "immutable" + * types. "Mutable" means that the object's value can change, while + * "immutable" means that the value is fixed. (For example, `List` is + * mutable, so you can add and delete elements from it. On the other + * hand, you can't modify a Tuple once you create it, making `Tuple` an + * immutable container.) + * + * `isFrozen` - if the Module is frozen then consider attributes as freshly + * created objects. Freezing API invokes alias analysis to check if they are + * mutated internally. + * + * `descendFunctionCalls` - recursively analyze function and method calls + * instead of conservative analysis. Generally analysis should be done after + * inlining so the implementation for recursive analysis is unoptimized. + */ +class AliasDb { + public: + TORCH_API explicit AliasDb( + std::shared_ptr graphi, + bool isFrozen = false, + bool descendFunctionCalls = false); + TORCH_API ~AliasDb(); + + // There are limitations to what effects the alias analysis can track. Two + // kinds of nodes may have untracked effects: + // 1. Nodes that write to a value that may alias the graph inputs (since + // the inputs can be used outside the graph). + // 2. Nodes that write to something in the wildcard set. + // + // These nodes are considered not safe to eliminate or mutate under any + // circumstances. + bool writesToWildcard(Node* n) const; + + // Does `n` write to an alias of one of the values in `vs`? + // if `recurseBlocks` is true, consider writes on the nodes in `n`s sub-blocks + TORCH_API bool writesToAlias(Node* n, const ValueSet& vs) const; + + // Does `n` write to any of the values in `vls`? + TORCH_API bool writesToAlias(Node* n, const ValueAndMemoryLocationSet& vls) + const; + + TORCH_API ValueAndMemoryLocationSet getValueAndMemoryLocationSet() const; + + // Does `a` and `b` potentially share a memory location or do either + // hold in memory any element that exists in the other + TORCH_API bool mayContainAlias(Value* a, Value* b) const; + + TORCH_API bool mayContainAlias(Value* a, const at::ArrayRef b) const; + + // Do any values in group `a` share a memory location or hold in memory + // any element that exists in group `b` + TORCH_API bool mayContainAlias( + const at::ArrayRef a, + const at::ArrayRef b) const; + + // Do `a` and `b` potentially share a memory location? + TORCH_API bool mayAlias(const Value* a, const Value* b) const; + // Do any values in group `a` potentially share a memory location with any + // value in group `b`? i.e. may they overlap? + TORCH_API bool mayAlias(const ValueSet& a, const ValueSet& b) const; + + // Do any nodes write to an alias set input to `n`? + TORCH_API bool hasInputWriters(const Node* n) const; + + // Do any nodes write to an alias set output by `n`? + TORCH_API bool hasOutputWriters(const Node* n) const; + + // Do any nodes write to an alias set inputted/outputted by `n`? + TORCH_API bool hasWriters(const Node* n) const; + + // Do any nodes write to `v`s memory location? + TORCH_API bool hasWriters(const Value* v) const; + + // Is the operation in-place? i.e. doesn't write anywhere but locations it + // reads from. + TORCH_API bool isMutable(Node* n) const; + + TORCH_API bool escapesScope(const at::ArrayRef& vs) const; + + // Is it safe to change whether `a` and `b` alias each other ? + TORCH_API bool safeToChangeAliasingRelationship( + const at::ArrayRef& a, + const at::ArrayRef& b) const; + + // Move `n` (already in the graph) after `movePoint` in the topological order. + // + // Tries to preserve value dependencies, so other nodes might be moved. We + // make two guarantees about the postcondition of the node list: + // - `n` is directly after `movePoint`. + // - only nodes between `n` and `movePoint` have been moved. + // + // Returns `false` if it's impossible to move `n` after `MovePoint` without + // violating dependencies, otherwise executes the move and returns `true` + TORCH_API bool moveAfterTopologicallyValid(Node* n, Node* movePoint); + TORCH_API bool moveBeforeTopologicallyValid(Node* n, Node* movePoint); + + bool couldMoveAfterTopologically(Node* n, Node* movePoint); + bool couldMoveBeforeTopologically(Node* n, Node* movePoint); + + // For debugging: print alias db state to stdout + TORCH_API void dump() const; + TORCH_API std::string toString() const; + + // Generates a DOT (www.graphviz.org) graph representation + // + // Returns `true` if the output file was successfully generated + // + // WARNING: The output dot file path can't include shell specific notations, + // for example you can't use "~/temp/aliasdb.dot" + // (instead, use "/home/user/temp/aliasdb.dot") + // + TORCH_API bool dumpToGraphvizFile(const char* filename) const; + TORCH_API std::string toGraphviz() const; + + // Returns `true` if the given element is mutable or if it is a + // container type with an internal mutable element (e.g. + // `Tuple[int, Tensor]` has an internal mutable type `Tensor`, so + // it would be considered a "mutable type" in AliasDb) + static bool isMutableType(const Value* v); + static bool isMutableType(const TypePtr& type); + + /** + * Mutation API + * + * These methods allow you to update AliasDb in-place if you are performing + * graph mutation. + * + * WARNING: These methods should be considered INTERNAL. They do not perform + * very many correctness checks, the user is responsible for making sure they + * are updating AliasDb correctly. `Lint()`ing the AliasDb can help with + * this. + */ + // Copy `existing`s aliasing info to `new_value`, and remove `existing`. + TORCH_API void replaceWithNewValue(Value* existing, Value* new_value); + // Copy `from`s aliasing info to `to`. + TORCH_API void copyValue(Value* from, Value* to); + // Create a new `value` that does not alias anything else. + TORCH_API void createValue(const Value* value); + + // Enable more precise treatment of prim::TupleConstruct. + void enablePreciseTupleContainerAnalysis(); + + friend struct MutationRemover; + friend class ValueAndMemoryLocationSet; + + private: + // Helper for topologically-safe node moves. + class WorkingSet; + enum class MoveSide { BEFORE, AFTER }; + bool tryMove(Node* toMove, Node* movePoint, MoveSide moveSide, bool dryRun); + void move(Node* toMove, Node* movePoint, MoveSide moveSide); + bool isBeforeOrAfter(const Node* n, MoveSide moveSide) const; + + bool isMutableTypeInternal(const Value* v) const; + bool isMutableTypeInternal(const TypePtr& type) const; + + /** + * Write and read internal API + */ + // Get all the values that `n` writes to. + // NOTE: this only returns values directly written to, not aliases thereof + // + // if `recurseBlocks` is true, gather writes on the nodes in `n`s sub-blocks + MemoryLocations getWrites(Node* n) const; + void getWritesImpl(Node* n, MemoryLocations& ret) const; + // Register the fact that `n` writes to `v`. + void registerWrite(const Value* v, Node* n, bool writeToContained = false); + // Get all the values that `n` reads from. + // if `recurseBlocks` is true, gather reads on the nodes in `n`s sub-blocks + MemoryLocations getReads(Node* n) const; + void getReadsImpl(Node* n, MemoryLocations& ret) const; + MemoryLocations getMemoryLocations(Value* v) const; + + /** + * Wildcard methods + */ + // Register `v` as a wildcard value. + std::optional setWildcard(const Value* v); + + // Is this a value which will not alias? + bool nonAliasingValue(const Value* elem) const; + + /** + * Special analysis methods + */ + void analyze(const std::shared_ptr& graph); + void analyze(Block* block); + void analyze(Node* node); + void analyzeImpl(Node* node); + void analyzeIf(Node* node); + void analyzeLoop(Node* node); + void analyzeSubgraph(Node* node, const std::shared_ptr& subgraph); + void analyzeSubgraph(Node* node); + void analyzeCreator(Node* node); + void analyzeExtractor(Node* node); + void analyzeChunk(Node* node); + void analyzeBroadcastingChunk(Node* node); + void analyzeFork(Node* node); + void analyzeWait(Node* node); + void analyzeAwaitable(Node* node); + void analyzeAwaitableWait(Node* node); + void analyzeRpcAsync(Node* node); + void analyzeBatchNorm(Node* node); + void analyzeInstanceNorm(Node* node); + void analyzeGradOf(Node* node); + void analyzeSetAttr(Node* node); + void analyzeConservative(Node* node); + void analyzeContainerConstruct(Node* node); + bool tryRegisteredAnalysis(Node* node); + + /** + * Alias manipulation methods + */ + void makeAllAlias(const std::vector& values); + void makePointerTo(const Value* value, const Value* to); + TORCH_API void addToContainedElements( + const Value* element, + const Value* container); + void mapAliases(at::ArrayRef to, at::ArrayRef from); + void giveFreshAlias( + const Value* value, + bool add_wildcard_to_contained_elems = true); + Element* getOrCreateElement(const Value* value); + + const AliasTypeSet* mapTypeToAliasTypeSetPtr(const TypePtr& type) const; + bool functionalNonEscapingListUse(const Use& use) const; + bool functionalNonEscapingTupleUse(const Use& use) const; + + std::shared_ptr graph_; + + // If the Module is frozen then consider attributes as freshly created + // objects. Freezing API invokes alias analysis to check if they are mutated + // internally. + bool isFrozen_; + + bool descend_function_calls_; + std::unordered_map>> + function_call_copies_; + + // The points-to graph that stores aliasing relationships + std::unique_ptr memoryDAGBuilder_; + std::unique_ptr memoryDAG_; + + // Mapping of values to MemoryDAG elements + ska::flat_hash_map elementMap_; + // All wildcard Elements (one for each unique mutable type) + ska::flat_hash_map wildcardIndex_; + Element* getWildcard(const TypePtr& type) const; + std::optional tryGetOrCreateWildcard(const TypePtr& type); + void addContainedTypesToFreshElement( + Element* container_elem, + const AliasTypeSet& mut_types); + void pointUnionTypeElementToAllContainedTypes( + Element* container_elem, + const AliasTypeSet& mut_types); + + std::vector getElements(at::ArrayRef vs) const; + bool mayAliasWildcard(const Value* v) const; + bool mayAliasWildcard(const at::ArrayRef vs) const; + bool hasWriters(const at::ArrayRef& values) const; + + // Cached mapping of type ptrs to their mutable types + mutable ska::flat_hash_map mapped_mutable_types_; + + /** + * State for tracking write info. + */ + // Write registry where the analysis can record the writes as it sees them. + // This information is later denormalized into various caches to improve query + // efficiency. + struct WriteRegistry; + std::unique_ptr writeRegistry_; + + // Map of nodes to the memory locations that they write to + using TWriteIndex = ska::flat_hash_map; + std::optional writeIndex_; + // Collection of all memory locations that are written to. + std::optional writtenToLocationsIndex_; + void buildWrittenToLocationsIndex(); + + std::unordered_set wildcards_; + + std::string getElementName(const Element* e) const; + + friend void Lint(const AliasDb* db); +}; + +// Helper check that invariants over AliasDb are maintained. +// Useful if you are using the AliasDb mutation API and want to check you did +// the right thing. +TORCH_API void Lint(const AliasDb* db); + +/** + * ValueAndMemoryLocationSet + * + * A insert-only set of values which also maintains a MemoryLocations bitset + * of the memory locations that the values alias. It is insert-only. It + * should be constructed by calling aliasDb.getValueAndMemoryLocationSet(). + * + * WARNING: + * * The AliasDb must not be mutated after construction of a + * ValueAndMemoryLocationsSet, or else the MemoryLocations stored in the + * ValueAndMemoryLocationSet will no longer be accurate. + * * A ValueAndMemoryLocationsSet is tied to an instance of AliasDb but + * does not own the AliasDb. It is the user's responsibility to ensure + * that the AliasDb outlives the ValuesAndMemoryLocationsSet. + * + * The use case for this is to be able to implement writesToAlias + * more efficiently for a set of values. + */ +class ValueAndMemoryLocationSet { + public: + TORCH_API void insert(Value* v); + TORCH_API ValueSet& getValueSet(); + + friend class AliasDb; + + private: + ValueAndMemoryLocationSet(const AliasDb* db) : aliasDb_(db) {} + + const AliasDb* aliasDb_; + ValueSet valueSet_; + MemoryLocations memoryLocations_; +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/attributes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/attributes.h new file mode 100644 index 0000000000000000000000000000000000000000..35dfe7a87642f60500ce791979e3f9d610e84994 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/attributes.h @@ -0,0 +1,185 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include + +#include + +namespace torch::jit { + +using ::c10::Symbol; + +constexpr int max_tensor_display_size = 10; + +enum class AttributeKind { + f, + fs, + c, + cs, + i, + is, + s, + ss, + t, + ts, + g, + gs, + ty, + tys, + ival +}; +static inline const char* toString(AttributeKind kind) { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + static constexpr const char* names[] = { + "f", + "c", + "cs", + "fs", + "i", + "is", + "s", + "ss", + "t", + "ts", + "g", + "gs", + "ty", + "tys", + "ival"}; + AT_ASSERT(size_t(kind) < sizeof(names) / sizeof(*names)); + return names[int(kind)]; +} + +struct AttributeValue { + AttributeValue(Symbol name) : name(name) {} + using Ptr = std::unique_ptr; + Symbol name; + virtual AttributeKind kind() const = 0; + virtual Ptr clone() const = 0; + virtual ~AttributeValue() = default; +}; + +template +struct ScalarAttributeValue : public AttributeValue { + using ConstructorType = T; + using ValueType = T; + ScalarAttributeValue(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + Ptr clone() const override { + return Ptr(new ScalarAttributeValue(name, value_)); + } + AttributeKind kind() const override { + return Kind; + } + + private: + ValueType value_; +}; + +template +struct VectorAttributeValue : public AttributeValue { + using ConstructorType = std::vector; + using ValueType = std::vector; + VectorAttributeValue(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + AttributeKind kind() const override { + return Kind; + } + std::unique_ptr clone() const override { + auto copy = value_; + return Ptr(new VectorAttributeValue(name, std::move(copy))); + } + + private: + ValueType value_; +}; + +using ComplexAttr = + ScalarAttributeValue, AttributeKind::c>; +using ComplexValsAttr = + VectorAttributeValue, AttributeKind::cs>; +using FloatAttr = ScalarAttributeValue; +using FloatsAttr = VectorAttributeValue; +using IntAttr = ScalarAttributeValue; +using IntsAttr = VectorAttributeValue; +using StringAttr = ScalarAttributeValue; +using StringsAttr = VectorAttributeValue; +using TensorAttr = ScalarAttributeValue; +using TensorsAttr = VectorAttributeValue; +using TypeAttr = ScalarAttributeValue; +using TypesAttr = VectorAttributeValue; +using IValueAttr = ScalarAttributeValue; + +struct Graph; + +// We special case Graph attributes like this because we want to ensure that +// Graph::copy() is called when we clone() these attributes. +struct TORCH_API GraphAttr : public AttributeValue { + using ConstructorType = std::shared_ptr; + using ValueType = std::shared_ptr; + GraphAttr(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + Ptr clone() const override; + AttributeKind kind() const override { + return AttributeKind::g; + } + + private: + std::shared_ptr value_; +}; + +struct TORCH_API GraphsAttr : public AttributeValue { + using ConstructorType = std::vector>; + using ValueType = std::vector>; + GraphsAttr(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + AttributeKind kind() const override { + return AttributeKind::gs; + } + std::unique_ptr clone() const override; + + private: + ValueType value_; +}; + +struct IRAttributeError : public std::exception { + IRAttributeError(Symbol name, bool defined) { + std::stringstream ss; + // NOLINTNEXTLINE(bugprone-branch-clone) + if (!defined) { + ss << "required keyword attribute '" << name.toUnqualString() + << "' is undefined"; + } else { + ss << "required keyword attribute '" << name.toUnqualString() + << "' has the wrong type"; + } + msg = ss.str(); + } + const char* what() const noexcept override { + return msg.c_str(); + } + + private: + std::string 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/constants.h new file mode 100644 index 0000000000000000000000000000000000000000..f7fd7f01304ca0fff41a52a4f1de7fd7b1e9ca6d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/constants.h @@ -0,0 +1,65 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +// helpers for handling constants in the IR +// - create constant nodes from ints, floats, complex, intlist, Tensors, and +// other types +// - implement primitive constant ops. + +namespace torch::jit { + +using ::c10::IValue; + +struct Graph; +struct Value; + +// thrown when insertConstant cannot encode the IValue into a graph +struct TORCH_API constant_not_supported_error : public std::runtime_error { + using runtime_error::runtime_error; +}; + +TORCH_API Value* insertConstant( + Graph& g, + const IValue& val, + std::optional loc = std::nullopt, + std::optional scope = std::nullopt); + +// note: prefer g.insertConsant(val, loc) which does exactly the same thing +// this function is only declared/defined here because its implementation is +// closely related to the implementation of prim::Constant that is also in +// constants.cpp. +// +// returns a std::nullopt if the IValue kind cannot be inserted as a constant +TORCH_API std::optional tryInsertConstant( + Graph& g, + const IValue& val, + std::optional loc = std::nullopt, + std::optional scope = std::nullopt); + +//////////////////////////////////////////////////////////////////////////////// +// Helper for retrieving constants +//////////////////////////////////////////////////////////////////////////////// + +// attempt to convert a (possibly constant) Value* into an interpreter value +// (IValue). returns std::nullopt if the Value* was not constant +TORCH_API std::optional toIValue(const Value* v); + +// if a value is a constant then try to turn into type T using the +// same rules as the interpreter +template +std::optional constant_as(const Value* v) { + if (auto ivalue = toIValue(v)) { + return ivalue->to(); + } + 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/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_node_list.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_node_list.h new file mode 100644 index 0000000000000000000000000000000000000000..e1ffa81efea513b2046ea9f86acc495b1f48e45c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_node_list.h @@ -0,0 +1,204 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Intrusive doubly linked lists with sane reverse iterators. +// The header file is named generic_graph_node_list.h because it is ONLY +// used for Graph's Node lists, and if you want to use it for other +// things, you will have to do some refactoring. +// +// At the moment, the templated type T must support a few operations: +// +// - It must have a field: T* next_in_graph[2] = { nullptr, nullptr }; +// which are used for the intrusive linked list pointers. +// +// - It must have a method 'destroy()', which removes T from the +// list and frees a T. +// +// In practice, we are only using it with Node and const Node. 'destroy()' +// needs to be renegotiated if you want to use this somewhere else. +// +// Regardless of the iteration direction, iterators always physically point +// to the element they logically point to, rather than +// the off-by-one behavior for all standard library reverse iterators like +// std::list. + +// The list is includes two sentinel nodes, one at the beginning and one at the +// end with a circular link between them. It is an error to insert nodes after +// the end sentinel node but before the beginning node: + +// Visualization showing only the next() links: +// HEAD -> first -> second -> ... -> last -> TAIL +// ^------------------------------------------ + +// Visualization showing only the prev() links: +// HEAD <- first <- second <- ... <- last <- TAIL +// ------------------------------------------^ + +static constexpr int kNextDirection = 0; +static constexpr int kPrevDirection = 1; + +template +struct generic_graph_node_list; + +template +struct generic_graph_node_list_iterator; + +struct Node; +using graph_node_list = generic_graph_node_list; +using const_graph_node_list = generic_graph_node_list; +using graph_node_list_iterator = generic_graph_node_list_iterator; +using const_graph_node_list_iterator = + generic_graph_node_list_iterator; + +template +struct generic_graph_node_list_iterator { + generic_graph_node_list_iterator() : cur(nullptr), d(kNextDirection) {} + generic_graph_node_list_iterator(T* cur, int d) : cur(cur), d(d) {} + generic_graph_node_list_iterator( + const generic_graph_node_list_iterator& rhs) = default; + generic_graph_node_list_iterator( + generic_graph_node_list_iterator&& rhs) noexcept = default; + generic_graph_node_list_iterator& operator=( + const generic_graph_node_list_iterator& rhs) = default; + generic_graph_node_list_iterator& operator=( + generic_graph_node_list_iterator&& rhs) noexcept = default; + T* operator*() const { + return cur; + } + T* operator->() const { + return cur; + } + generic_graph_node_list_iterator& operator++() { + AT_ASSERT(cur); + cur = cur->next_in_graph[d]; + return *this; + } + generic_graph_node_list_iterator operator++(int) { + generic_graph_node_list_iterator old = *this; + ++(*this); + return old; + } + generic_graph_node_list_iterator& operator--() { + AT_ASSERT(cur); + cur = cur->next_in_graph[reverseDir()]; + return *this; + } + generic_graph_node_list_iterator operator--(int) { + generic_graph_node_list_iterator old = *this; + --(*this); + return old; + } + + // erase cur without invalidating this iterator + // named differently from destroy so that ->/. bugs do not + // silently cause the wrong one to be called. + // iterator will point to the previous entry after call + void destroyCurrent() { + T* n = cur; + cur = cur->next_in_graph[reverseDir()]; + n->destroy(); + } + generic_graph_node_list_iterator reverse() { + return generic_graph_node_list_iterator(cur, reverseDir()); + } + + private: + int reverseDir() { + return d == kNextDirection ? kPrevDirection : kNextDirection; + } + T* cur; + int d; // direction 0 is forward 1 is reverse, see next_in_graph +}; + +template +struct generic_graph_node_list { + using iterator = generic_graph_node_list_iterator; + using const_iterator = generic_graph_node_list_iterator; + generic_graph_node_list_iterator begin() { + return generic_graph_node_list_iterator(head->next_in_graph[d], d); + } + generic_graph_node_list_iterator begin() const { + return generic_graph_node_list_iterator(head->next_in_graph[d], d); + } + generic_graph_node_list_iterator end() { + return generic_graph_node_list_iterator(head->next_in_graph[!d], d); + } + generic_graph_node_list_iterator end() const { + return generic_graph_node_list_iterator( + head->next_in_graph[!d], d); + } + generic_graph_node_list_iterator rbegin() { + return reverse().begin(); + } + generic_graph_node_list_iterator rbegin() const { + return reverse().begin(); + } + generic_graph_node_list_iterator rend() { + return reverse().end(); + } + generic_graph_node_list_iterator rend() const { + return reverse().end(); + } + generic_graph_node_list reverse() { + return generic_graph_node_list(head->next_in_graph[!d], !d); + } + const generic_graph_node_list reverse() const { + return generic_graph_node_list(head->next_in_graph[!d], !d); + } + T* front() { + return head->next_in_graph[d]; + } + const T* front() const { + return head->next_in_graph[d]; + } + T* back() { + return head->next_in_graph[!d]; + } + const T* back() const { + return head->next_in_graph[!d]; + } + generic_graph_node_list(T* head, int d) : head(head), d(d) {} + + private: + T* head; // both head and tail are sentinel nodes + // the first real node is head->next_in_graph[d] + // the tail sentinel is head->next_in_graph[!d] + int d; +}; + +template +static inline bool operator==( + generic_graph_node_list_iterator a, + generic_graph_node_list_iterator b) { + return *a == *b; +} + +template +static inline bool operator!=( + generic_graph_node_list_iterator a, + generic_graph_node_list_iterator b) { + return *a != *b; +} + +} // namespace torch::jit + +namespace std { + +template +struct iterator_traits> { + using difference_type = int64_t; + using value_type = T*; + using pointer = T**; + using reference = T*&; + using iterator_category = bidirectional_iterator_tag; +}; + +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..fe3c83f45e44792baf30e582f6cdbada415afc23 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_utils.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit { + +TORCH_API TypePtr getTensorType(const at::Tensor& t, bool complete); + +TORCH_API TypePtr inferShapeAndTypeForInput( + TypePtr input_type, + Stack::const_iterator& s_iter, + const Stack::const_iterator& s_iter_end, + bool complete); + +TORCH_API void setInputTensorTypes( + Graph& g, + const Stack& stack, + bool complete, + const std::vector& param_count_list = {}); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/ir.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/ir.h new file mode 100644 index 0000000000000000000000000000000000000000..00989ec278295179dd96543358322c3647825dd3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/ir.h @@ -0,0 +1,1836 @@ +#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 + +// Forward declare, the real meat is in python_ir.cpp +template +class THPPointer; +using THPObjectPtr = THPPointer; +using pyobj_list = std::vector; + +namespace torch::jit { +namespace utils { +TORCH_API std::string getNodesModuleHierarchy(const Node& n); +} // namespace utils +class AliasDb; + +using ::c10::Argument; +using ::c10::FunctionSchema; +using ::c10::Symbol; + +using ::c10::ivalue::Shared; + +using ::c10::IValue; +using ::c10::ivalue::Future; + +using ::c10::ivalue::ConstantString; + +#define C10_USING(T) using ::c10::T; +C10_FORALL_TYPES(C10_USING) +#undef C10_USING + +#define C10_USING(T) using ::c10::T##Ptr; +C10_FORALL_TYPES(C10_USING) +#undef C10_USING + +using ::c10::Type; +using ::c10::TypeEnv; +using ::c10::TypePtr; + +using ::c10::getTypePtr; +using ::c10::MatchTypeReturn; +using ::c10::TypeKind; + +using ::c10::fmap; + +namespace prim { +using namespace ::c10::prim; +} +namespace attr { +using namespace ::c10::attr; +} +namespace aten { +using namespace ::c10::aten; +} +namespace cuda { +using namespace ::c10::cuda; +} // namespace cuda + +struct Function; +struct GraphFunction; +struct MatchedSchema; + +// A Graph represents one "function" of computation. +// It uses a simple ownership model where the graph owns all the nodes inside +// it. All references inside the graph are raw pointers. Destroying the Graph +// will invalidate any pointers to nodes in the graph. +struct Graph; + +// Node is the base class of the IR graph. It represents one computation +// and dependencies on a list of Values. The "prim-ops", so to speak. +struct Node; + +// A Value represents an input or output to node that is either a +// Tensor or an opaque Handle object, as determined by type(). +struct Value; + +TORCH_API std::ostream& operator<<(std::ostream& out, const Graph& g); +TORCH_API std::ostream& operator<<(std::ostream& out, const Node& n); + +// A list of nodes, with inputs and outputs +struct Block; + +// Each use is represented by this type, see 'Node::uses()' +// 'user' is the consumer of the value, 'offset' is the index into +// 'user's input this where the producers will be found. +struct Use { + Use(Node* user, size_t offset) : user(user), offset(offset) {} + Node* user; + size_t offset; + + bool operator==(const Use& b) { + return user == b.user && offset == b.offset; + } +}; + +// Note [User node does not uniquely identify use] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// A while back, we wrote some code manipulating uses that looked like this: +// +// for (auto& use : used_val->uses_) { +// if (use.user == this_node) { +// use.offset += 1; +// break; +// } +// } +// +// This code is trying to find a particular use (our node's use) to update it. +// However, it's wrong: there may be *multiple* uses of a value %x in a node, +// as might be the case in this IR: +// +// %y = Add %x %x +// +// In this case, there are two uses of %x whose user is the node 'Add %x %x'. +// So, "use induced by this node" is not a well-formed concept. +// +// If you are looking for "use induced by an input", it's best to use +// findUseForInput() to get it. + +// the list types are intentionally simple, but we type-def +// them here so if we need to change them, refactoring will be easier +using node_list = std::vector; +using value_list = std::vector; +using use_list = std::vector; +template +using ArrayRef = at::ArrayRef; +using NodeKind = Symbol; +using topo_position_t = int64_t; +using ValueSet = std::unordered_set; + +struct OperatorSet; +template +struct OperatorMap; + +// This is a wrapper to allow invalidating the Python object +// safely when the C++ object for a Node/Value/Block is deleted +// like much of graph, it isn't safe for different threads to +// access the same graph +template +struct Wrap { + explicit Wrap(T* p) : elem(p) {} + void clear() { + if (clear_cb) { + clear_cb(elem); + } + elem = nullptr; + } + T* elem; + void (*clear_cb)(void*){nullptr}; +}; + +struct Value { + AT_DISALLOW_COPY_AND_ASSIGN(Value); + Value(Node* node_, size_t offset_); + + private: + friend struct Node; + friend struct Graph; + Node* node_; + size_t offset_; + size_t unique_ = 0; // unique id + use_list uses_; + std::string unique_name_; + TypePtr type_; + // a managing wrapper for Python to allow invalidation + std::shared_ptr> wrap_; + + public: + Value* setType(TypePtr type); + TORCH_API void inferTypeFrom(const at::Tensor& output); + TORCH_API void inferTypeFrom( + const c10::intrusive_ptr& output); + const TypePtr& type() const { + AT_ASSERT(type_ != nullptr); + return type_; + } + bool requires_grad() const { + return type()->requires_grad(); + } + bool isCompleteTensor() const { + if (auto pt = type()->cast()) { + return pt->isComplete(); + } + return false; + } + TORCH_API bool mustBeNone() const; + TORCH_API bool mustNotBeNone() const; + size_t unique() const { + return unique_; + } + bool hasDebugName() const { + return !unique_name_.empty(); + } + static bool isValidName(const std::string& name); + TORCH_API Value* setDebugName(const std::string& name); + std::string debugName() const { + if (hasDebugName()) { + return unique_name_; + } + return std::to_string(unique()); + } + TORCH_API std::string debugNameBase() const; + Node* node() { + return node_; + } + size_t offset() const { + return offset_; + } + void setOffset(size_t offset) { + offset_ = offset; + } + const Node* node() const { + return node_; + } + + /** + * @warning NEVER pass raw pointer of smart pointer managed Graph to Python. + * Check #87343 for details. + */ + Graph* owningGraph(); + const Graph* owningGraph() const; + // TODO: make this more const correct + const use_list& uses() const { + return uses_; + } + + bool hasUses() const { + return !uses().empty(); + } + + TORCH_API void replaceFirstUseWith(Value* newValue); + + // Replaces all uses of this value with 'newValue'. + // + // Given: %3 = f(%1, %2) + // %4 = g(%3) + // %5 = h(%3, %3) + // Execute: %3.replaceAllUsesWith(%6) + // Result: %3 = f(%1, %2) + // %4 = g(%6) + // %5 = h(%6, %6) + TORCH_API void replaceAllUsesWith(Value* newValue); + + // Replaces all uses of this value with 'newValue' after 'node'. + // Given: %3 = f(%1, %2) + // %4 = g(%3) + // %5 = inplace_(%3) + // %6 = h(%3, %3) + // Execute: %3.replaceAllUsesAfterNodeWith(%5.node(), %5) + // Result: %3 = f(%1, %2) + // %4 = g(%3) + // %5 = inplace_(%3) + // %6 = h(%5, %5) + // XXX: does not check scoping legality, consider using + // replaceAllUsesDominatedByNodeWith + TORCH_API void replaceAllUsesAfterNodeWith(const Node* node, Value* newValue); + + // Replaces all uses of this value with 'newValue' that are dominated by + // 'node'. Given: + // x = op(...). + // if cond: + // z = foo(..) + // bar(x) + // else: + // print(x) + // x.replaceAllUsesDominatedByNodeWith(foo, z) would replace bar(x) + // but not print(x) because print is not dominated by foo. + // replaceAllUsesAfterNode does not check domination, so in this example + // it would produce invalid IR. + TORCH_API void replaceAllUsesDominatedByNodeWith( + const Node* node, + Value* newValue); + + TORCH_API Value* copyMetadata(Value* from); + + TORCH_API std::shared_ptr> wrap() { + if (!wrap_) { + wrap_ = std::make_shared>(this); + } + return wrap_; + } + + virtual ~Value() { + if (wrap_) { + wrap_->clear(); + } + } +}; + +struct TORCH_API Node { + AT_DISALLOW_COPY_AND_ASSIGN(Node); + friend struct Graph; + friend struct Block; + friend struct Value; + friend graph_node_list; + friend const_graph_node_list; + friend graph_node_list_iterator; + friend const_graph_node_list_iterator; + + private: + const NodeKind kind_; + std::vector inputs_; + std::vector outputs_; + // subblocks + std::vector blocks_; + Graph* graph_; + Block* owning_block_; + std::optional source_range_; + ScopePtr scope_; + std::optional callstack_; + // Assumes FunctionSchemas are persistent, so we don't manage their lifetime. + // This field is effective a cache that's populated on attribute lookups and + // invalidated every time we perform an operation that could potentially + // change the schema. note: mutable because schema_ is effectively a cache + mutable const Operator* op_; + topo_position_t topo_position_ = 0; + // a managing wrapper for Python to allow invalidation + std::shared_ptr> wrap_; + // Stores the full schema name, if the operator is historic + // When the operator is deprecated or the name of the operator + // is changed, we need to rely on this name + // to retrieve old schemas to successfully apply upgraders + // for this operator. + std::optional historic_schema_name_ = std::nullopt; + + protected: + Node(Graph* graph_, NodeKind kind_); // defined after graph + public: + // Each Node but Return/Param Nodes are associated with exactly one + // place in the Node list of the Graph. The Graph itself is a circular + // doubly-linked list. The Return Node is used as the sentinel for the + // "beginning"/"end" of the list. This means that you can tell when + // you've traversed the entire list without means worrying about null + // pointers. `next_in_graph[0]` is the pointer to the next Node, while + // `next_in_graph[1]` is the pointer to the previous Node. The + // linked list is implemented as an array to allow the same iterator + // class for forward and reversed Node lists. Taken together, this + // list also represents a topological sort of the Nodes in the Graph. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,cppcoreguidelines-non-private-member-variables-in-classes,modernize-avoid-c-arrays) + Node* next_in_graph[2] = {nullptr, nullptr}; + + std::shared_ptr> wrap() { + if (!wrap_) { + wrap_ = std::make_shared>(this); + } + return wrap_; + } + + const std::optional getHistoricSchemaName() { + return historic_schema_name_; + } + + void setHistoricSchemaName(const std::string& name) { + historic_schema_name_ = name; + } + + Node*& next() { + return next_in_graph[kNextDirection]; + } + Node*& prev() { + return next_in_graph[kPrevDirection]; + } + Node* const& next() const { + return next_in_graph[kNextDirection]; + } + Node* const& prev() const { + return next_in_graph[kPrevDirection]; + } + + NodeKind kind() const { + return kind_; + } + Node* setSourceRange(SourceRange r) { + source_range_ = std::move(r); + return this; + } + SourceRange sourceRange() const; + + /** + * @warning NEVER pass raw pointer of smart pointer managed Graph to Python. + * Check #87343 for details. + */ + Graph* owningGraph() { + return graph_; + } + const Graph* owningGraph() const { + return graph_; + } + Block* owningBlock() { + return owning_block_; + } + const Block* owningBlock() const { + return owning_block_; + } + ScopePtr scope() { + return scope_; + } + void setScope(ScopePtr scope) { + scope_ = std::move(scope); + } + std::string scopeName() const { + if (!scope_) { + return ""; + } + return scope_->namesFromRoot(); + } + + // Copies the source range, scope and callstack from another node. + Node* copyMetadata(Node* from) { + this->setSourceRange(from->sourceRange()); + this->setScope(from->scope()); + if (auto cs = from->callstack()) { + this->setCallStack(*cs); + } + return this; + } + + std::optional callstack() const { + return callstack_; + } + void setCallStack(InlinedCallStackPtr cs) { + callstack_ = std::move(cs); + } + + // NB: This returns an ArrayRef; that means that it will + // get invalidated if you resize inputs (e.g., using addInput) + // We can't return a std::vector& because there's no + // way to soundly cast to std::vector (an insane + // implementation of std::vector could make this representationally + // different.) + at::ArrayRef inputs() { + return inputs_; + } + at::ArrayRef inputs() const { + // Vectors are not convertible in const-ness of elements, but + // raw pointers are. + return {inputs_.data(), inputs_.size()}; + } + // NB: This returns an ArrayRef; that means that it will + // get invalidated if you resize inputs (e.g., using addInput) + // We can't return a std::vector& because there's no + // way to soundly cast to std::vector (an insane + // implementation of std::vector could make this representationally + // different.) + at::ArrayRef outputs() { + return outputs_; + } + at::ArrayRef outputs() const { + // Vectors are not convertible in const-ness of elements, but + // raw pointers are. + return {outputs_.data(), outputs_.size()}; + } + Value* output(size_t i) const { + return outputs_.at(i); + } + bool hasUses() const { + for (auto o : outputs()) { + if (!o->uses().empty()) { + return true; + } + } + return false; + } + + void replaceAllUsesWith(Node* n); + + // replaces `this` with a new node with the same inputs and outputs + // but a new node symbol. does not destroy `this` + Node* replaceWithNewSymbol(Symbol new_symbol); + + // Checks if this node is dominated by `dominator` which means that + // `dominator` will always be executed before `this` and `dominator` + // is in scope of `this. + bool isDominatedBy(const Node* dominator) const; + + // lots of things like chunk have a single input or single output, so we have + // a helper to make accessing it easier + Value* input() { + AT_ASSERT(inputs_.size() == 1); + return inputs_.at(0); + } + Value* output() { + AT_ASSERT(outputs_.size() == 1); + return outputs_.at(0); + } + const Value* output() const { + AT_ASSERT(outputs_.size() == 1); + return outputs_.at(0); + } + const Value* input() const { + AT_ASSERT(inputs_.size() == 1); + return inputs_.at(0); + } + // Access a particular input. This is a checked index. + Value* input(size_t i) const { + return inputs_.at(i); + } + + bool hasNamedInput(const std::string& unqualName) const; + Value* namedInput(const std::string& unqualName) const; + Value* namedInput(Symbol name) const; + + std::optional get(Symbol name) const; + + template + std::optional get(Symbol name) const { + if (auto v = get(name)) { + return v->template to(); + } + return std::nullopt; + } + + // Returns true if the value of input name is statically known + bool is_constant(Symbol name) const { + return static_cast(get(name)); + } + bool mustBeNone() const; + + bool isNondeterministic() const; + bool hasSideEffects() const; + + // instructions lowered by the interpreter and not run in the optimized graph + bool notExecutedOp() const { + return kind_ == prim::Constant || kind_ == prim::profile || + kind_ == prim::profile_ivalue; + } + + // Graphs + + // Note [Topological invariant] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // We always maintain an up-to-date topological ordering of all nodes via + // the next()/prev() links. All transformations to graphs must preserve + // this topological ordering: for example, it is only valid to 'addInput' + // with an input which is topologically before the current node. + // + // Usually, it is obvious whether or not topological order is maintained; + // for example, if you are adding nodes to the end of the topsort, it's + // impossible for them to refer to inputs that are not in the topsort. + // If it is not obvious, please comment accordingly. + + // Add 'node' as an input to 'this' at the end of existing + // arguments. Returns the added node for ease of chaining. + // + // Given: %3 = f(%1, %2) + // Execute: %3.addInput(%4) + // Result: %3 = f(%1, %2, %4) + Value* addInput(Value* value); + + // Add 'value' as an input to 'this' at the specified position in the + // arguments. Returns the added value for ease of chaining. + Value* insertInput(size_t i, Value* value); + + // Replace the input of 'this' at position 'i' with + // 'newValue', returning the old node. + // + // Given: %3 = f(%1, %2) + // Execute: %3.replaceInput(1, %4) + // Result: %3 = f(%1, %4) + Value* replaceInput(size_t i, Value* newValue); + + // Replace all occurrences of 'from' in the inputs of this + // node with 'to'. Corresponds to llvm's replaceUsesOfWith. + // + // Given: %3 = f(%1, %2, %1) + // Execute: %3.replaceInputWith(%1, %4) + // Result: %3 = f(%4, %2, %4) + void replaceInputWith(Value* from, Value* to); + + Value* addOutput(); + + Value* insertOutput(size_t i); + + void eraseOutput(size_t i); + + Block* addBlock(); + void eraseBlock(size_t i); + + // Each Node can have a list of subblocks. These are used to define structured + // nested control flow operators such as If and Loop. + // The meaning of a block is specific to the kind of node it is in, but + // all blocks share these semantics: + // * Nested lexical scoping: If a node 'Parent' has a subblock which contains + // a node 'Child', Child can use any value that was in scope for the Parent + // node in addition to any values defined before 'Child' in the subblock. + // * The list of inputs to the block are in scope for the duration of the + // block + // * the outputs of the Parent node are not in scope for the subblocks + // Typically the inputs to a block that represents control flow act as + // as the equivalents phi-nodes in standard SSA form, + // defining a new Value to represent any term that has multiple + // definitions depending on how control flowed. Outputs of the node containing + // control flow serve a similar purpose defining new values for variables + // that would have different definitions depending on which way control + // flowed. + + at::ArrayRef blocks() { + return blocks_; + } + at::ArrayRef blocks() const { + // Vectors are not convertible in const-ness of elements, but + // raw pointers are. + return {blocks_.data(), blocks_.size()}; + } + + // Is 'this' before 'n' in the topological order? + bool isBefore(const Node* n) const; + + // Is 'this' after 'n' in the topological order? + bool isAfter(const Node* n) const; + + // Insert unattached 'this' node before 'n' in the topological order. + // Returns this (for chaining). + // + // Given: %3 = f(%1, %2) + // %4 = g(%3) + // and unattached: %5 = h(%1) + // Execute: %5.insertBefore(%4) + // Result: %3 = f(%1, %2) + // %5 = h(%1) + // %4 = g(%3) + Node* insertBefore(Node* n); + + // Insert unattached 'this' node after 'n' in the topological order. + // Returns this (for chaining). + // + // Given: %3 = f(%1, %2) + // %4 = g(%3) + // and unattached: %5 = h(%1) + // Execute: %5.insertAfter(%4) + // Result: %3 = f(%1, %2) + // %4 = g(%3) + // %5 = h(%1) + Node* insertAfter(Node* n); + + // Move 'this' (already in the graph) after 'n' in the topological order. + // + // NOTE: Does not check that value dependencies are preserved, see + // AliasDb::moveAfterTopologicallyValid + // + // Given: %2 = f(%1) + // %3 = g(%1) + // Execute: %2.moveAfter(%3) + // Result: %3 = g(%1) + // %2 = f(%1) + // + void moveAfter(Node* n); + + // Move a node 'n' (already in the graph) before 'this' in the topological + // order. + // + // NOTE: Does not check that value dependencies are preserved, see + // AliasDb::moveBeforeTopologicallyValid + // + // Given: %2 = f(%1) + // %3 = g(%1) + // Execute: %3.moveBefore(%2) + // Result: %3 = g(%1) + // %2 = f(%1) + void moveBefore(Node* n); + + // Remove the input at 'i' from this node. + // + // WARNING: This is O(n) in the number of inputs, so avoid repeatedly calling + // removeInput. + // + // Given: %3 = f(%1, %2) + // Execute: %3.removeInput(1) + // Result: %3 = f(%1) + void removeInput(size_t i); + + // Remove all inputs from a node. + // + // Given: %3 = f(%1, %2) + // Execute: %3.removeAllInputs() + // Result: %3 = f() + void removeAllInputs(); + + // Remove all outputs from a node. + // + // Given: %1, %2 = f() + // Execute:removeAllInputs() + // Result: = f() + void removeAllOutputs(); + + // Rearrange the ordering of inputs or outputs of a node + // Given: %3 = f(%1, %2) + // Execute: %3.permuteInputs({1, 0}) + // Result: %3 = f(%2, %1) + // Each index must appear exactly once + void permuteInputs(const std::vector& new_inputs); + void permuteOutputs(const std::vector& new_inputs); + + // iterators of the node list starting at this node + // useful for resuming a search starting at this node + inline graph_node_list_iterator iterator() { + return {this, 0}; + } + inline graph_node_list_iterator reverseIterator() { + return iterator().reverse(); + } + inline const_graph_node_list_iterator iterator() const { + return {this, 0}; + } + inline const_graph_node_list_iterator reverseIterator() const { + return iterator().reverse(); + } + + // Remove 'this' from the instruction list and deallocate it. + // + // Invariant: no outputs of 'this' may have any uses. + // + // Given: %2 = f(%1) + // %3 = g(%1) + // Execute: %2.destroy() + // Result: %3 = g(%1) + void destroy(); + + // Dynamically cast this node to the subclass indicated by the + // template variable, returning nullptr if the cast is invalid.. + // + // Example usage: if(auto s = n.cast