diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h new file mode 100644 index 0000000000000000000000000000000000000000..3fdcd61614f6cc6678661af4067d9ddff5af70a8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h @@ -0,0 +1,104 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API AdagradOptions + : public OptimizerCloneableOptions { + AdagradOptions(double lr = 1e-2); + TORCH_ARG(double, lr) = 1e-2; + TORCH_ARG(double, lr_decay) = 0; + TORCH_ARG(double, weight_decay) = 0; + TORCH_ARG(double, initial_accumulator_value) = 0; + TORCH_ARG(double, eps) = 1e-10; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdagradOptions& lhs, + const AdagradOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API AdagradParamState + : public OptimizerCloneableParamState { + TORCH_ARG(torch::Tensor, sum); + TORCH_ARG(int64_t, step) = 0; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdagradParamState& lhs, + const AdagradParamState& rhs); +}; + +class TORCH_API Adagrad : public Optimizer { + public: + explicit Adagrad( + const std::vector& param_groups, + AdagradOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK( + defaults.lr_decay() >= 0, + "Invalid lr_decay value: ", + defaults.lr_decay()); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + TORCH_CHECK( + defaults.initial_accumulator_value() >= 0, + "Invalid initial_accumulator_value value: ", + defaults.initial_accumulator_value()); + TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps()); + + for (const auto& group : param_groups_) { + for (const auto& p : group.params()) { + auto state = std::make_unique(); + state->step(0); + state->sum(torch::full_like( + p.data(), + defaults.initial_accumulator_value(), + at::MemoryFormat::Preserve)); + state_[p.unsafeGetTensorImpl()] = std::move(state); + } + } + } + + explicit Adagrad(std::vector params, AdagradOptions defaults = {}) + : Adagrad({OptimizerParamGroup(std::move(params))}, std::move(defaults)) { + } + + torch::Tensor step(LossClosure closure = nullptr) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(Adagrad); + } +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h new file mode 100644 index 0000000000000000000000000000000000000000..9fe0994a4a0d98d29c2d7f5b2e05d4fdbd01cc02 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h @@ -0,0 +1,91 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API AdamOptions : public OptimizerCloneableOptions { + AdamOptions(double lr = 1e-3); + TORCH_ARG(double, lr) = 1e-3; + typedef std::tuple betas_t; + TORCH_ARG(betas_t, betas) = std::make_tuple(0.9, 0.999); + TORCH_ARG(double, eps) = 1e-8; + TORCH_ARG(double, weight_decay) = 0; + TORCH_ARG(bool, amsgrad) = false; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdamOptions& lhs, + const AdamOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API AdamParamState + : public OptimizerCloneableParamState { + TORCH_ARG(int64_t, step) = 0; + TORCH_ARG(torch::Tensor, exp_avg); + TORCH_ARG(torch::Tensor, exp_avg_sq); + TORCH_ARG(torch::Tensor, max_exp_avg_sq); + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdamParamState& lhs, + const AdamParamState& rhs); +}; + +class TORCH_API Adam : public Optimizer { + public: + explicit Adam( + const std::vector& param_groups, + AdamOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps()); + auto betas = defaults.betas(); + TORCH_CHECK( + 0 <= std::get<0>(betas) && std::get<0>(betas) < 1.0, + "Invalid beta parameter at index 0: ", + std::get<0>(betas)); + TORCH_CHECK( + 0 <= std::get<1>(betas) && std::get<1>(betas) < 1.0, + "Invalid beta parameter at index 1: ", + std::get<1>(betas)); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + } + explicit Adam(std::vector params, AdamOptions defaults = {}) + : Adam({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {} + + torch::Tensor step(LossClosure closure = nullptr) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(Adam); + } +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h new file mode 100644 index 0000000000000000000000000000000000000000..349ea090b8947fe3fded870de16a4f3a99c4d780 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h @@ -0,0 +1,91 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API AdamWOptions : public OptimizerCloneableOptions { + AdamWOptions(double lr = 1e-3); + TORCH_ARG(double, lr) = 1e-3; + typedef std::tuple betas_t; + TORCH_ARG(betas_t, betas) = std::make_tuple(0.9, 0.999); + TORCH_ARG(double, eps) = 1e-8; + TORCH_ARG(double, weight_decay) = 1e-2; + TORCH_ARG(bool, amsgrad) = false; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdamWOptions& lhs, + const AdamWOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API AdamWParamState + : public OptimizerCloneableParamState { + TORCH_ARG(int64_t, step) = 0; + TORCH_ARG(torch::Tensor, exp_avg); + TORCH_ARG(torch::Tensor, exp_avg_sq); + TORCH_ARG(torch::Tensor, max_exp_avg_sq); + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdamWParamState& lhs, + const AdamWParamState& rhs); +}; + +class TORCH_API AdamW : public Optimizer { + public: + explicit AdamW( + const std::vector& param_groups, + AdamWOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps()); + auto betas = defaults.betas(); + TORCH_CHECK( + 0 <= std::get<0>(betas) && std::get<0>(betas) < 1.0, + "Invalid beta parameter at index 0: ", + std::get<0>(betas)); + TORCH_CHECK( + 0 <= std::get<1>(betas) && std::get<1>(betas) < 1.0, + "Invalid beta parameter at index 1: ", + std::get<1>(betas)); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + } + explicit AdamW(std::vector params, AdamWOptions defaults = {}) + : AdamW({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {} + + torch::Tensor step(LossClosure closure = nullptr) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(AdamW); + } +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h new file mode 100644 index 0000000000000000000000000000000000000000..0d33ff24b8ab4df4eeaedfa1ff4e12c2741816d0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h @@ -0,0 +1,105 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::optim { + +struct TORCH_API LBFGSOptions : public OptimizerCloneableOptions { + LBFGSOptions(double lr = 1); + TORCH_ARG(double, lr) = 1; + TORCH_ARG(int64_t, max_iter) = 20; + TORCH_ARG(std::optional, max_eval) = std::nullopt; + TORCH_ARG(double, tolerance_grad) = 1e-7; + TORCH_ARG(double, tolerance_change) = 1e-9; + TORCH_ARG(int64_t, history_size) = 100; + TORCH_ARG(std::optional, line_search_fn) = std::nullopt; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const LBFGSOptions& lhs, + const LBFGSOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API LBFGSParamState + : public OptimizerCloneableParamState { + TORCH_ARG(int64_t, func_evals) = 0; + TORCH_ARG(int64_t, n_iter) = 0; + TORCH_ARG(double, t) = 0; + TORCH_ARG(double, prev_loss) = 0; + TORCH_ARG(Tensor, d); + TORCH_ARG(Tensor, H_diag); + TORCH_ARG(Tensor, prev_flat_grad); + TORCH_ARG(std::deque, old_dirs); + TORCH_ARG(std::deque, old_stps); + TORCH_ARG(std::deque, ro); + TORCH_ARG(std::optional>, al) = std::nullopt; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const LBFGSParamState& lhs, + const LBFGSParamState& rhs); +}; + +class TORCH_API LBFGS : public Optimizer { + public: + explicit LBFGS( + const std::vector& param_groups, + LBFGSOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK( + param_groups_.size() == 1, + "LBFGS doesn't support per-parameter options (parameter groups)"); + if (defaults.max_eval() == std::nullopt) { + auto max_eval_val = (defaults.max_iter() * 5) / 4; + static_cast(param_groups_[0].options()) + .max_eval(max_eval_val); + static_cast(*defaults_).max_eval(max_eval_val); + } + _numel_cache = std::nullopt; + } + explicit LBFGS(std::vector params, LBFGSOptions defaults = {}) + : LBFGS({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {} + + Tensor step(LossClosure closure) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + std::optional _numel_cache; + int64_t _numel(); + Tensor _gather_flat_grad(); + void _add_grad(const double step_size, const Tensor& update); + std::tuple _directional_evaluate( + const LossClosure& closure, + const std::vector& x, + double t, + const Tensor& d); + void _set_param(const std::vector& params_data); + std::vector _clone_param(); + + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(LBFGS); + } +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h new file mode 100644 index 0000000000000000000000000000000000000000..26c71d19eae5ee6265ac76824956c6592282806b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h @@ -0,0 +1,228 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +// Forward declarations confuse Doxygen +#ifndef DOXYGEN_SHOULD_SKIP_THIS +namespace at { +class Tensor; +} // namespace at + +namespace torch { +using at::Tensor; +namespace serialize { +class OutputArchive; +class InputArchive; +} // namespace serialize +} // namespace torch +#endif // DOXYGEN_SHOULD_SKIP_THIS + +namespace torch::optim { + +class TORCH_API OptimizerParamState { + public: + OptimizerParamState() = default; + OptimizerParamState(const OptimizerParamState&) = default; + OptimizerParamState& operator=(const OptimizerParamState&) = default; + OptimizerParamState(OptimizerParamState&&) noexcept = default; + OptimizerParamState& operator=(OptimizerParamState&&) noexcept = default; + virtual std::unique_ptr clone() const; + virtual void serialize(torch::serialize::InputArchive& archive); + virtual void serialize(torch::serialize::OutputArchive& archive) const; + virtual ~OptimizerParamState() = default; +}; + +template +class OptimizerCloneableParamState : public OptimizerParamState { + std::unique_ptr clone() const override { + return std::make_unique(static_cast(*this)); + } +}; + +class TORCH_API OptimizerOptions { + public: + OptimizerOptions() = default; + OptimizerOptions(const OptimizerOptions&) = default; + OptimizerOptions& operator=(const OptimizerOptions&) = default; + OptimizerOptions(OptimizerOptions&&) noexcept = default; + OptimizerOptions& operator=(OptimizerOptions&&) noexcept = default; + virtual std::unique_ptr clone() const; + virtual void serialize(torch::serialize::InputArchive& archive); + virtual void serialize(torch::serialize::OutputArchive& archive) const; + virtual ~OptimizerOptions() = default; + virtual double get_lr() const; + virtual void set_lr(const double lr); +}; + +template +class OptimizerCloneableOptions : public OptimizerOptions { + private: + std::unique_ptr clone() const override { + return std::make_unique(static_cast(*this)); + } +}; + +/// Stores parameters in the param_group and stores a pointer to the +/// OptimizerOptions +class TORCH_API OptimizerParamGroup { + public: + // NOTE: In order to store `OptimizerParamGroup` in a `std::vector`, it has to + // be copy-constructible. + OptimizerParamGroup(const OptimizerParamGroup& param_group) + : params_(param_group.params()), + options_( + param_group.has_options() ? param_group.options().clone() + : nullptr) {} + OptimizerParamGroup(OptimizerParamGroup&& param_group) = default; + OptimizerParamGroup(std::vector params) + : params_(std::move(params)) {} + OptimizerParamGroup( + std::vector params, + std::unique_ptr options) + : params_(std::move(params)), options_(std::move(options)) {} + + OptimizerParamGroup& operator=(const OptimizerParamGroup& param_group) = + delete; + OptimizerParamGroup& operator=(OptimizerParamGroup&& param_group) noexcept = + default; + ~OptimizerParamGroup() = default; + bool has_options() const; + OptimizerOptions& options(); + const OptimizerOptions& options() const; + void set_options(std::unique_ptr options); + std::vector& params(); + const std::vector& params() const; + + protected: + std::vector params_; + std::unique_ptr options_; +}; + +class TORCH_API Optimizer { + public: + // The copy constructor is deleted, because the user should use the + // `state_dict` / `load_state_dict` API to copy an optimizer instead. + Optimizer(const Optimizer& optimizer) = delete; + Optimizer(Optimizer&& optimizer) = default; + Optimizer& operator=(const Optimizer& optimizer) = delete; + Optimizer& operator=(Optimizer&& optimizer) = default; + + explicit Optimizer( + const std::vector& param_groups, + std::unique_ptr defaults) + : defaults_(std::move(defaults)) { + for (const auto& param_group : param_groups) { + add_param_group(param_group); + } + } + + /// Constructs the `Optimizer` from a vector of parameters. + explicit Optimizer( + std::vector parameters, + std::unique_ptr defaults) + : Optimizer( + {OptimizerParamGroup(std::move(parameters))}, + std::move(defaults)) {} + + /// Adds the given param_group to the optimizer's param_group list. + void add_param_group(const OptimizerParamGroup& param_group); + + virtual ~Optimizer() = default; + + using LossClosure = std::function; + /// A loss function closure, which is expected to return the loss value. + virtual Tensor step(LossClosure closure = nullptr) = 0; + + /// Adds the given vector of parameters to the optimizer's parameter list. + void add_parameters(const std::vector& parameters); + + /// Zeros out the gradients of all parameters. + void zero_grad(bool set_to_none = true); + + /// Provides a const reference to the parameters in the first param_group this + /// optimizer holds. + const std::vector& parameters() const noexcept; + + /// Provides a reference to the parameters in the first param_group this + /// optimizer holds. + std::vector& parameters() noexcept; + + /// Returns the number of parameters referenced by the optimizer. + size_t size() const noexcept; + + OptimizerOptions& defaults() noexcept; + + const OptimizerOptions& defaults() const noexcept; + + /// Provides a reference to the param_groups this optimizer holds. + std::vector& param_groups() noexcept; + + /// Provides a const reference to the param_groups this optimizer holds. + const std::vector& param_groups() const noexcept; + + /// Provides a reference to the state this optimizer holds + ska::flat_hash_map>& + state() noexcept; + + /// Provides a const reference to the state this optimizer holds + const ska::flat_hash_map>& state() + const noexcept; + + /// Serializes the optimizer state into the given `archive`. + virtual void save(serialize::OutputArchive& archive) const; + + /// Deserializes the optimizer state from the given `archive`. + virtual void load(serialize::InputArchive& archive); + + protected: + std::vector param_groups_; + ska::flat_hash_map> state_; + std::unique_ptr defaults_; +}; + +/* How do we decide whether to serialize undefined tensors or + std::nullopt values into the output archive? +Answer: we strictly follow the behavior of Python API. To be more specific: + +For optimizer options: +a) For undefined tensor: currently no tensor is used as an options argument in +Python API, so we don't need to worry about it now. b) For std::nullopt value: +we serialize std::nullopt values into the output archive, to follow the exact +same behavior as Python API. + +For optimizer param state: +a) For undefined tensor: in param state, undefined tensor in C++ impl is +equivalent to missing key in Python impl. Since we don't serialize missing keys +in Python API, we skip undefined tensors when serializing the param state. b) +For std::nullopt value: in param state, std::nullopt value in C++ impl is +equivalent to missing key in Python impl. Since we don't serialize missing keys +in Python API, we skip std::nullopt values when serializing the param state. */ + +/// Serializes an `Optimizer` into an `OutputArchive`. +TORCH_API serialize::OutputArchive& operator<<( + serialize::OutputArchive& archive, + const Optimizer& optimizer); + +/// Deserializes a `Tensor` from an `InputArchive`. +TORCH_API serialize::InputArchive& operator>>( + serialize::InputArchive& archive, + Optimizer& optimizer); + +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/rmsprop.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/rmsprop.h new file mode 100644 index 0000000000000000000000000000000000000000..95871059563401b7729baba651fee2e052107492 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/rmsprop.h @@ -0,0 +1,96 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API RMSpropOptions + : public OptimizerCloneableOptions { + RMSpropOptions(double lr = 1e-2); + TORCH_ARG(double, lr) = 1e-2; + TORCH_ARG(double, alpha) = 0.99; + TORCH_ARG(double, eps) = 1e-8; + TORCH_ARG(double, weight_decay) = 0; + TORCH_ARG(double, momentum) = 0; + TORCH_ARG(bool, centered) = false; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const RMSpropOptions& lhs, + const RMSpropOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API RMSpropParamState + : public OptimizerCloneableParamState { + TORCH_ARG(int64_t, step) = 0; + TORCH_ARG(torch::Tensor, square_avg); + TORCH_ARG(torch::Tensor, momentum_buffer); + TORCH_ARG(torch::Tensor, grad_avg); + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const RMSpropParamState& lhs, + const RMSpropParamState& rhs); +}; + +class TORCH_API RMSprop : public Optimizer { + public: + explicit RMSprop( + const std::vector& param_groups, + RMSpropOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps()); + TORCH_CHECK( + defaults.momentum() >= 0, + "Invalid momentum value: ", + defaults.momentum()); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + TORCH_CHECK( + defaults.alpha() >= 0, "Invalid alpha value: ", defaults.alpha()); + } + + explicit RMSprop(std::vector params, RMSpropOptions defaults = {}) + : RMSprop({OptimizerParamGroup(std::move(params))}, std::move(defaults)) { + } + + torch::Tensor step(LossClosure closure = nullptr) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(RMSprop); + } +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..ee311911004afce099dbef5153bb3ea210341baf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::optim { + +class TORCH_API LRScheduler { + public: + // This class needs to take a reference of an optimizer from outside such that + // it can modify its learning rates; due to this the lifetime of said + // optimizer must be maintained + LRScheduler(torch::optim::Optimizer& optimizer); + + virtual ~LRScheduler() = default; + + void step(); + + protected: + // A vector of learning rates is calculated and returned from the specific + // subclass. A vector is returned with each element being a separate learning + // rate for each param group - although the normal use case would be to return + // a vector of identical elements. + virtual std::vector get_lrs() = 0; + + // Get current learning rates from the optimizer + std::vector get_current_lrs() const; + + unsigned step_count_{}; + + private: + void set_optimizer_lrs(const std::vector& learning_rates); + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + torch::optim::Optimizer& optimizer_; +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..6a379c8d0d518ec5dddc0730343cfd5ad2ea301a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +#include + +namespace torch::optim { + +class TORCH_API ReduceLROnPlateauScheduler { + public: + enum SchedulerMode { min, max }; + enum ThresholdMode { rel, abs }; + ReduceLROnPlateauScheduler( + Optimizer& optimizer, + SchedulerMode mode = min, + float factor = 0.1, + int patience = 10, + double threshold = 1e-4, + ThresholdMode threshold_mode = rel, + int cooldown = 0, + const std::vector& min_lr = std::vector(), + double eps = 1e-8, + bool verbose = false); + + virtual ~ReduceLROnPlateauScheduler() = default; + + void step(float metric); + + private: + void reset(); + void reduce_lr(int epoch); + bool in_cooldown() const; + bool is_better(float a); + void init_is_better( + SchedulerMode mode, + double threshold, + ThresholdMode threshold_mode); + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + Optimizer& optimizer; + SchedulerMode mode{}; + float mode_worse{}; + float factor; + int patience; + double threshold{}; + ThresholdMode threshold_mode{}; + int cooldown{}; + int cooldown_counter{}; + std::vector min_lrs; + double eps; + float best{}; + bool verbose; + int last_epoch{}; + int num_bad_epochs{}; +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h new file mode 100644 index 0000000000000000000000000000000000000000..7acdfe2a093c49e6018f4032b169b7949198391c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::optim { + +class TORCH_API StepLR : public LRScheduler { + public: + StepLR( + torch::optim::Optimizer& optimizer, + const unsigned step_size, + const double gamma = 0.1); + + private: + std::vector get_lrs() override; + + const unsigned step_size_; + const double gamma_; +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/serialize.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/serialize.h new file mode 100644 index 0000000000000000000000000000000000000000..2045ccf7ee658fb9c7e9362005a0f2e16dff4501 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/serialize.h @@ -0,0 +1,320 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::optim { +namespace detail { +// Utility function to save state +template +void serialize( + serialize::OutputArchive& archive, + const ska::flat_hash_map>& + state) { + for (const auto& item : state) { + serialize::OutputArchive param_state_archive(archive.compilation_unit()); + std::string tensorimpl_key = + std::to_string(reinterpret_cast(item.first)); + const DerivedOptimizerParamState& curr_state = + static_cast(*(item.second)); + curr_state.serialize(param_state_archive); + archive.write(tensorimpl_key, param_state_archive); + } +} + +// Utility function to load state +template +void serialize( + serialize::InputArchive& archive, + ska::flat_hash_map>& state) { + std::vector tensorimpl_keys = archive.keys(); + for (const std::string& tensorimpl_key : tensorimpl_keys) { + serialize::InputArchive param_state_archive; + archive.read(tensorimpl_key, param_state_archive); + DerivedOptimizerParamState param_state; + param_state.serialize(param_state_archive); + // NOLINTNEXTLINE(performance-no-int-to-ptr) + state[reinterpret_cast(std::stoull(tensorimpl_key))] = + std::make_unique(param_state); + } +} + +// Utility function to save param_groups +template +void serialize( + serialize::OutputArchive& archive, + const std::vector& param_groups) { + archive.write( + "param_groups/size", + torch::tensor(static_cast(param_groups.size()))); + for (const auto i : c10::irange(param_groups.size())) { + serialize::OutputArchive param_group_archive(archive.compilation_unit()); + std::vector params = param_groups[i].params(); + param_group_archive.write( + "params/size", torch::tensor(static_cast(params.size()))); + for (const auto index : c10::irange(params.size())) { + param_group_archive.write( + "params/" + std::to_string(index), + IValue(std::to_string( + reinterpret_cast(params[index].unsafeGetTensorImpl())))); + } + const DerivedOptimizerParamOptions& param_group_options = + static_cast( + param_groups[i].options()); + serialize::OutputArchive param_group_options_archive( + param_group_archive.compilation_unit()); + param_group_options.serialize(param_group_options_archive); + param_group_archive.write("options", param_group_options_archive); + archive.write("param_groups/" + std::to_string(i), param_group_archive); + } +} + +// Utility function to load param_groups +// We take as input vector of pair of string and unique_ptr to optimizer options +// so that we can retain the state for each param by using the old tensor impl +// keys (saved during serialization) and map the new tensor impl keys to the +// correct state for each param +template +void serialize( + serialize::InputArchive& archive, + std::vector< + std::pair, std::unique_ptr>>& + param_groups) { + torch::Tensor param_groups_size_tensor; + archive.read("param_groups/size", param_groups_size_tensor); + const int64_t param_groups_size = param_groups_size_tensor.item(); + for (const auto i : c10::irange(param_groups_size)) { + serialize::InputArchive param_group_archive; + archive.read("param_groups/" + std::to_string(i), param_group_archive); + torch::Tensor size_tensor; + param_group_archive.read("params/size", size_tensor); + const int64_t size = size_tensor.item(); + std::vector params; + for (const auto index : c10::irange(size)) { + IValue ivalue; + param_group_archive.read("params/" + std::to_string(index), ivalue); + std::string element = ivalue.toStringRef(); + params.emplace_back(element); + } + serialize::InputArchive param_group_options_archive; + param_group_archive.read("options", param_group_options_archive); + DerivedOptimizerParamOptions param_group_options(0); + param_group_options.serialize(param_group_options_archive); + param_groups.emplace_back(std::make_pair( + params, + std::make_unique(param_group_options))); + } +} +} // namespace detail + +// Note: These functions are all called `serialize()` so they can be called +// inside a template where the archive type is a template type and can thus be +// passed such that the appropriate overload is selected. + +/// Utility function to save a value of `int64_t` type. +void serialize( + serialize::OutputArchive& archive, + const std::string& key, + const int64_t& value); + +/// Utility function to load a value of `int64_t` type. +void serialize( + serialize::InputArchive& archive, + const std::string& key, + int64_t& value); + +/// Utility function to save a vector of step buffers. +void serialize( + serialize::OutputArchive& archive, + const std::string& key, + const std::vector& steps); + +/// Utility function to load a vector of step buffers. +void serialize( + serialize::InputArchive& archive, + const std::string& key, + std::vector& steps); + +// Utility function to save state and param_groups +template < + typename DerivedOptimizerParamState, + typename DerivedOptimizerParamOptions> +void serialize(serialize::OutputArchive& archive, const Optimizer& optimizer) { + archive.write("pytorch_version", IValue("1.5.0")); + serialize::OutputArchive state_archive(archive.compilation_unit()); + detail::serialize( + state_archive, optimizer.state()); + archive.write("state", state_archive); + + serialize::OutputArchive param_groups_archive(archive.compilation_unit()); + detail::serialize( + param_groups_archive, optimizer.param_groups()); + archive.write("param_groups", param_groups_archive); +} + +// Utility function to load state and param_groups and update state +template < + typename DerivedOptimizerParamState, + typename DerivedOptimizerParamOptions> +void serialize(serialize::InputArchive& archive, Optimizer& optimizer) { + IValue pytorch_version; + archive.read("pytorch_version", pytorch_version); + TORCH_INTERNAL_ASSERT(pytorch_version.toStringRef() == "1.5.0"); + serialize::InputArchive state_archive; + archive.read("state", state_archive); + ska::flat_hash_map> saved_state; + detail::serialize(state_archive, saved_state); + + serialize::InputArchive param_groups_archive; + archive.read("param_groups", param_groups_archive); + std::vector< + std::pair, std::unique_ptr>> + saved_param_groups; + detail::serialize( + param_groups_archive, saved_param_groups); + + // update state and optimizer options + TORCH_CHECK( + saved_param_groups.size() == optimizer.param_groups().size(), + "loaded state dict has a different number of parameter groups"); + for (const auto i : c10::irange(saved_param_groups.size())) { + std::vector param_group_old_keys = saved_param_groups[i].first; + std::vector params = optimizer.param_groups()[i].params(); + TORCH_CHECK( + param_group_old_keys.size() == params.size(), + "loaded state dict contains a parameter group that has a different size than the optimizer's parameter group"); + + for (const auto idx : c10::irange(params.size())) { + auto param_group_old_key = + // NOLINTNEXTLINE(performance-no-int-to-ptr) + reinterpret_cast(std::stoull(param_group_old_keys[idx])); + if (saved_state.find(param_group_old_key) != saved_state.end()) { + optimizer.state()[params[idx].unsafeGetTensorImpl()] = + std::move(saved_state[param_group_old_key]); + } + } + + auto& saved_options = reinterpret_cast( + *saved_param_groups[i].second); + auto& current_options = reinterpret_cast( + optimizer.param_groups()[i].options()); + current_options = saved_options; + } +} + +/// Utility function to save a vector of buffers. +template +void serialize( + serialize::OutputArchive& archive, + const std::string& key, + const BufferContainer& buffers) { + archive.write( + key + "/size", torch::tensor(static_cast(buffers.size()))); + for (const auto index : c10::irange(buffers.size())) { + archive.write( + key + "/" + std::to_string(index), buffers[index], /*is_buffer=*/true); + } +} + +/// Utility function to load a vector of buffers. +template +void serialize( + serialize::InputArchive& archive, + const std::string& key, + BufferContainer& buffers) { + buffers.clear(); + torch::Tensor size_tensor; + archive.read(key + "/size", size_tensor); + const size_t size = size_tensor.item(); + for (const auto index : c10::irange(size)) { + buffers.emplace_back(); + archive.read( + key + "/" + std::to_string(index), buffers.back(), /*is_buffer=*/true); + } +} + +template +c10::List deque_to_list(const std::deque& dq) { + c10::List list; + list.reserve(dq.size()); + for (const auto& e : dq) { + list.emplace_back(e); + } + return list; +} + +template +std::deque list_to_deque(const c10::List& list) { + std::deque dq; + for (const auto& e : list) { + dq.emplace_back(e); + } + return dq; +} + +#define _TORCH_OPTIM_SERIALIZE(name) \ + torch::optim::serialize(archive, #name, self.name) + +#define _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(OptimizerName) \ + torch::optim::serialize( \ + archive, self) + +#define _TORCH_OPTIM_SERIALIZE_TORCH_ARG(name) \ + { \ + auto ivalue = torch::IValue(name()); \ + /* do not serialize if name is an undefined tensor*/ \ + if (!(ivalue.isTensor() && \ + ivalue.unsafeToTensorImpl() == \ + at::UndefinedTensorImpl::singleton())) { \ + archive.write(#name, ivalue); \ + } \ + } + +#define _TORCH_OPTIM_SERIALIZE_TORCH_ARG_DEQUE(name) \ + { \ + c10::IValue ivalue = torch::IValue(deque_to_list(name())); \ + archive.write(#name, ivalue); \ + } + +#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(T, name) \ + { \ + c10::IValue ivalue; \ + bool exists = archive.try_read(#name, ivalue); \ + if (exists) { \ + name(ivalue.to()); \ + } else { \ + constexpr bool is_tensor_type = std::is_base_of_v; \ + TORCH_INTERNAL_ASSERT(is_tensor_type); \ + } \ + } + +#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG_OPTIONAL(T, name) \ + { \ + c10::IValue ivalue; \ + bool exists = archive.try_read(#name, ivalue); \ + if (exists) { \ + name(ivalue.toOptional()); \ + } \ + } + +#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG_DEQUE(T, name) \ + { \ + c10::IValue ivalue; \ + archive.read(#name, ivalue); \ + auto list = ivalue.to>(); \ + name(list_to_deque(list)); \ + } + +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h new file mode 100644 index 0000000000000000000000000000000000000000..a1875f052e27f7ac132103943591ad031befbcda --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h @@ -0,0 +1,90 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API SGDOptions : public OptimizerCloneableOptions { + SGDOptions(double lr); + TORCH_ARG(double, lr); + TORCH_ARG(double, momentum) = 0; + TORCH_ARG(double, dampening) = 0; + TORCH_ARG(double, weight_decay) = 0; + TORCH_ARG(bool, nesterov) = false; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const SGDOptions& lhs, + const SGDOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API SGDParamState + : public OptimizerCloneableParamState { + TORCH_ARG(torch::Tensor, momentum_buffer); + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const SGDParamState& lhs, + const SGDParamState& rhs); +}; + +class TORCH_API SGD : public Optimizer { + public: + explicit SGD( + const std::vector& param_groups, + SGDOptions defaults) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK( + defaults.momentum() >= 0, + "Invalid momentum value: ", + defaults.momentum()); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + TORCH_CHECK( + !defaults.nesterov() || + (defaults.momentum() > 0 && defaults.dampening() == 0), + "Nesterov momentum requires a momentum and zero dampening"); + } + + explicit SGD(std::vector params, SGDOptions defaults) + : SGD({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {} + + torch::Tensor step(LossClosure closure = nullptr) override; + + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(SGD); + } +}; +} // namespace torch::optim + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/python/init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/python/init.h new file mode 100644 index 0000000000000000000000000000000000000000..01f0a2bd4c7d6679c07d0047e5ce1f441a553e88 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/python/init.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::python { +/// Initializes Python bindings for the C++ frontend. +void init_bindings(PyObject* module); +} // namespace torch::python + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/archive.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/archive.h new file mode 100644 index 0000000000000000000000000000000000000000..7ac3b174751d9c651996479afb2ff7f852833667 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/archive.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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/input-archive.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/input-archive.h new file mode 100644 index 0000000000000000000000000000000000000000..64142d8818a04ea5525ff6f2ed4ebf139e810aa0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/input-archive.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 + +namespace at { +class Tensor; +} // namespace at + +namespace torch { +using at::Tensor; +namespace jit { +struct Module; +} // namespace jit +} // namespace torch + +namespace torch::serialize { + +/// A recursive representation of tensors that can be deserialized from a file +/// or stream. In most cases, users should not have to interact with this class, +/// and should instead use `torch::load`. +class TORCH_API InputArchive final { + public: + /// Default-constructs the `InputArchive`. + InputArchive(); + + // Move is allowed. + InputArchive(InputArchive&&) = default; + InputArchive& operator=(InputArchive&&) = default; + + // Copy is disallowed. + InputArchive(InputArchive&) = delete; + InputArchive& operator=(InputArchive&) = delete; + + ~InputArchive() = default; + + /// Reads an `IValue` associated with a given `key`. + void read(const std::string& key, c10::IValue& ivalue); + + /// Reads an `IValue` associated with a given `key`. If there is no `IValue` + /// associated with the `key`, this returns false, otherwise it returns true. + bool try_read(const std::string& key, c10::IValue& ivalue); + + /// Reads a `tensor` associated with a given `key`. If there is no `tensor` + /// associated with the `key`, this returns false, otherwise it returns true. + /// If the tensor is expected to be a buffer (not differentiable), `is_buffer` + /// must be `true`. + bool try_read(const std::string& key, Tensor& tensor, bool is_buffer = false); + + /// Reads a `tensor` associated with a given `key`. + /// If the tensor is expected to be a buffer (not differentiable), `is_buffer` + /// must be `true`. + void read(const std::string& key, Tensor& tensor, bool is_buffer = false); + + /// Reads a `InputArchive` associated with a given `key`. If there is no + /// `InputArchive` associated with the `key`, this returns false, otherwise + /// it returns true. + bool try_read(const std::string& key, InputArchive& archive); + + /// Reads an `InputArchive` associated with a given `key`. + /// The archive can thereafter be used for further deserialization of the + /// nested data. + void read(const std::string& key, InputArchive& archive); + + /// Loads the `InputArchive` from a serialized representation stored in the + /// file at `filename`. Storage are remapped using device option. If device + /// is not specified, the module is loaded to the original device. + void load_from( + const std::string& filename, + std::optional device = std::nullopt); + + /// Loads the `InputArchive` from a serialized representation stored in the + /// given `stream`. Storage are remapped using device option. If device + /// is not specified, the module is loaded to the original device. + void load_from( + std::istream& stream, + std::optional device = std::nullopt); + + // Loads given the specified flat array. + void load_from( + const char* data, + size_t size, + std::optional device = std::nullopt); + + // Loads given the specified read and size functions. + void load_from( + const std::function& + read_func, + const std::function& size_func, + std::optional device = std::nullopt); + + // Returns the vector of keys in the input archive. + std::vector keys(); + + /// Forwards all arguments to `read()`. + /// Useful for generic code that can be reused for both `InputArchive` and + /// `OutputArchive` (where `operator()` forwards to `write()`). + template + void operator()(Ts&&... ts) { + read(std::forward(ts)...); + } + + private: + jit::Module module_; + std::string hierarchy_prefix_; +}; +} // namespace torch::serialize + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/output-archive.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/output-archive.h new file mode 100644 index 0000000000000000000000000000000000000000..615892117abf1b7bfa505f3b0f3acce163632dae --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/output-archive.h @@ -0,0 +1,85 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace at { +class Tensor; +} // namespace at + +namespace torch { +using at::Tensor; +namespace jit { +struct Module; +} // namespace jit +} // namespace torch + +namespace torch::serialize { +class TORCH_API OutputArchive final { + public: + explicit OutputArchive(std::shared_ptr cu); + explicit OutputArchive() + : cu_(std::make_shared()), + module_("__torch__.Module", cu_) {} + + // Move is allowed. + OutputArchive(OutputArchive&&) = default; + OutputArchive& operator=(OutputArchive&&) = default; + + // Copy is disallowed. + OutputArchive(OutputArchive&) = delete; + OutputArchive& operator=(OutputArchive&) = delete; + + std::shared_ptr compilation_unit() const { + return cu_; + } + + /// Writes an `IValue` to the `OutputArchive`. + void write(const std::string& key, const c10::IValue& ivalue); + + /// Writes a `(key, tensor)` pair to the `OutputArchive`, and marks it as + /// being or not being a buffer (non-differentiable tensor). + void write( + const std::string& key, + const Tensor& tensor, + bool is_buffer = false); + + /// Writes a nested `OutputArchive` under the given `key` to this + /// `OutputArchive`. + void write(const std::string& key, OutputArchive& nested_archive); + + /// Saves the `OutputArchive` into a serialized representation in a file at + /// `filename`. + void save_to(const std::string& filename); + + /// Saves the `OutputArchive` into a serialized representation into the given + /// `stream`. + void save_to(std::ostream& stream); + + /// Saves the `OutputArchive` into a serialized representation using the + /// given writer function. + void save_to(const std::function& func); + + /// Forwards all arguments to `write()`. + /// Useful for generic code that can be reused for both `OutputArchive` and + /// `InputArchive` (where `operator()` forwards to `read()`). + template + void operator()(Ts&&... ts) { + write(std::forward(ts)...); + } + + private: + std::shared_ptr cu_; + jit::Module module_; +}; +} // namespace torch::serialize + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/tensor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..f6166613b3dfdb445315bc0fec4cfe3308286e3e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/tensor.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch { +inline serialize::OutputArchive& operator<<( + serialize::OutputArchive& archive, + const Tensor& tensor) { + archive.write("0", tensor); + return archive; +} + +inline serialize::InputArchive& operator>>( + serialize::InputArchive& archive, + Tensor& tensor) { + archive.read("0", tensor); + return archive; +} +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/FunctionsManual.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/FunctionsManual.h new file mode 100644 index 0000000000000000000000000000000000000000..ba1f74343e931ac91459fffea80141be1c7dc0d8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/FunctionsManual.h @@ -0,0 +1,1158 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// NB: Must be at the top of file to avoid including the deprecated "math.h". +// https://stackoverflow.com/questions/6563810/m-pi-works-with-math-h-but-not-with-cmath-in-visual-studio +#ifdef _MSC_VER +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES +#endif +#include +#endif + +#include +#include + +namespace torch::autograd::generated::details { + +extern const char* kCudnnDoubleBackwardMsg; + +// A simple way to imperatively compute index ranges for slots +// that have been flattened +struct TORCH_API IndexRangeGenerator { + IndexRange range(size_t range_size) { + i += range_size; + return {i - range_size, i}; + } + size_t size() { + return i; + } + + private: + size_t i = 0; +}; + +TORCH_API Tensor toNonOptFwGrad(const std::optional& t); +TORCH_API Tensor toNonOptPrimal(const std::optional& t); +TORCH_API Tensor toNonOptTensor(const std::optional& t); + +inline std::optional wrap_opt_if(const Tensor& t, const bool cond) { + using OptTensor = std::optional; + return cond ? OptTensor(t) : static_cast(std::nullopt); +} + +TORCH_API Tensor +apply_loss_reduction(const Tensor& unreduced, int64_t reduction); +TORCH_API bool any_variable_defined(const variable_list& variables); +TORCH_API void update_wrapped_number(Tensor& input, Tensor& output); +TORCH_API void copy_range( + variable_list& out, + IndexRange range, + const at::Tensor& t); +TORCH_API void copy_range( + variable_list& out, + IndexRange range, + at::ArrayRef t); +TORCH_API at::Tensor copysign_tensor_self_backward( + const Tensor& grad, + const Tensor& self, + const Tensor& result); +TORCH_API at::Tensor not_implemented(const char* name, const char* reason = ""); +TORCH_API std::vector not_implemented_list( + const char* name, + const char* reason = ""); +at::Tensor handle_r_to_c(ScalarType self_st, Tensor gradient_result); +at::Tensor maybe_multiply(const at::Tensor& t, const at::Scalar& s); +int64_t _safe_size(IntArrayRef sizes, IntArrayRef dim); +Tensor restore_reduced_dims( + const Tensor& output, + IntArrayRef dims, + bool keepdim); +Tensor scale_grad_by_count( + const Tensor& grad, + const Tensor& mask, + IntArrayRef dims); +at::Tensor norm_backward( + const at::Tensor& grad, + const at::Tensor& self, + const std::optional& p_, + const at::Tensor& norm); +at::Tensor norm_backward( + at::Tensor grad, + const at::Tensor& self, + const std::optional& p_, + at::Tensor norm, + at::IntArrayRef dim, + bool keepdim); +Tensor norm_jvp( + const Tensor& self_p, + const Tensor& self_t, + const std::optional& p_, + Tensor norm, + IntArrayRef dim, + bool keepdim); +Tensor norm_jvp( + const Tensor& grad, + const Tensor& self, + const std::optional& p_, + Tensor norm); +Tensor _nested_from_padded_backward( + const Tensor& grad, + const Tensor& input, + const bool do_transform_0213); +std::tuple linear_double_backward( + const variable_list& grads, + const Tensor& self, + const Tensor& grad_output, + const Tensor& weight); +Tensor linalg_vector_norm_jvp( + const Tensor& self_p, + const Tensor& self_t, + const Scalar& scalar_ord, + Tensor norm, + const at::OptionalIntArrayRef& opt_dim, + bool keepdim); +at::Tensor linalg_vector_norm_backward( + at::Tensor grad, + const at::Tensor& self, + const at::Scalar& ord, + at::Tensor norm, + const at::OptionalIntArrayRef& opt_dim, + bool keepdim); +at::Tensor pow_backward( + at::Tensor grad, + const at::Tensor& self, + const at::Scalar& exponent_); +at::Tensor pow_backward_self( + const at::Tensor& grad, + const at::Tensor& self, + const at::Tensor& exponent); +at::Tensor pow_backward_exponent( + const at::Tensor& grad, + const at::Tensor& self, + const at::Tensor& exponent, + const at::Tensor& result); +at::Tensor pow_backward_exponent( + const at::Tensor& grad, + const at::Scalar& base, + const at::Tensor& exponent, + const at::Tensor& result); +at::Tensor angle_backward(const at::Tensor& grad, const at::Tensor& self); +template +at::Tensor mul_tensor_backward(const Tensor& grad, T other, ScalarType self_st); +template +at::Tensor div_tensor_self_backward( + const Tensor& grad, + T other, + ScalarType self_st, + const std::optional& rounding_mode = std::nullopt); +at::Tensor div_tensor_other_backward( + const Tensor& grad, + const Tensor& self, + const Tensor& other, + const std::optional& rounding_mode = std::nullopt); +at::Tensor mvlgamma_backward( + const at::Tensor& grad, + const at::Tensor& self, + int64_t p); +at::Tensor permute_backwards(const at::Tensor& grad, at::IntArrayRef fwd_dims); +at::Tensor rad2deg_backward(const at::Tensor& grad); +at::Tensor deg2rad_backward(const at::Tensor& grad); +at::Tensor unsqueeze_multiple( + const at::Tensor& t, + at::OptionalIntArrayRef opt_dim, + size_t n_dims); +at::Tensor sum_backward( + const at::Tensor& grad, + at::SymIntArrayRef sizes, + at::OptionalIntArrayRef opt_dims, + bool keepdim); +at::Tensor sum_backward( + const at::Tensor& grad, + c10::SymIntArrayRef sizes, + c10::IntArrayRef dims, + bool keepdim); +at::Tensor nansum_backward( + const at::Tensor& grad, + const at::Tensor& self, + at::OptionalIntArrayRef dims, + bool keepdim); +std::vector reverse_list(const at::IntArrayRef list); +std::vector reverse_list_symint(const c10::SymIntArrayRef list); +at::Tensor reverse_dim(const at::Tensor& t, int64_t dim); +at::Tensor prod_safe_zeros_backward( + const at::Tensor& grad, + const at::Tensor& inp, + int64_t dim); +at::Tensor prod_backward( + const at::Tensor& grad, + const at::Tensor& input, + const at::Tensor& result); +at::Tensor prod_backward( + at::Tensor grad, + const at::Tensor& input, + at::Tensor result, + int64_t dim, + bool keepdim); +at::Tensor solve_jvp( + const Tensor& X, + const Tensor& A, + const Tensor& dA, + const Tensor& dB); +at::Tensor solve_backward_self( + const at::Tensor& grad, + const at::Tensor& self, + const at::Tensor& A); +at::Tensor solve_backward_A( + const at::Tensor& grad, + const at::Tensor& self, + const at::Tensor& A, + const at::Tensor& solution); +at::Tensor cumsum_backward(const at::Tensor& grad, int64_t dim); +at::Tensor logsumexp_backward( + at::Tensor grad, + const at::Tensor& self, + at::Tensor result, + at::IntArrayRef dim, + bool keepdim); +at::Tensor logsumexp_jvp( + const at::Tensor& self_p, + const at::Tensor& self_t, + IntArrayRef dim, + bool keepdim); +at::Tensor safe_logsumexp_jvp( + const at::Tensor& self_p, + const at::Tensor& self_t, + IntArrayRef dim, + bool keepdim); +at::Tensor logcumsumexp_backward( + at::Tensor grad, + const at::Tensor& self, + const at::Tensor& result, + int64_t dim); +at::Tensor logcumsumexp_jvp( + const at::Tensor& self_p, + const at::Tensor& self_t, + int64_t dim); +at::Tensor unbind_backward(const variable_list& grads, int64_t dim); +at::Tensor unbind_backward_nested( + const variable_list& grads, + const Tensor& nt_sizes, + int64_t dim, + const at::TensorOptions& options); +at::Tensor unbind_backward_nested_jagged( + const variable_list& grads, + const Tensor& self, + int64_t dim); +at::Tensor unsqueeze_to(const at::Tensor& self, c10::SymIntArrayRef sym_sizes); +at::Tensor unsqueeze_to( + const at::Tensor& self, + int64_t dim, + c10::SymIntArrayRef sym_sizes); +at::Tensor unsqueeze_to( + const at::Tensor& self, + IntArrayRef dim, + c10::SymIntArrayRef sym_sizes); +std::vector cat_tensors_backward( + const at::Tensor& grad, + const std::vector>& sizes, + const std::vector& dtypes, + int64_t dim); +std::vector stack_tensors_backward( + const at::Tensor& grad, + int64_t dim, + const std::vector& dtypes); +std::vector block_diag_backward( + const at::Tensor& grad, + const std::vector>& sizes, + const std::vector& dtypes); +at::Tensor clamp_backward( + const at::Tensor& grad, + const at::Tensor& self, + const std::optional& min, + const std::optional& max); +at::Tensor clamp_backward( + const at::Tensor& grad, + const at::Tensor& self, + const at::Tensor& min, + const at::Tensor& max); +std::tuple clamp_backward_min_max( + const at::Tensor& grad, + const at::Tensor& self, + const at::Tensor& min, + const at::Tensor& max, + const std::array& /*grad_input_mask*/); +at::Tensor clamp_jvp( + const Tensor& self_p, + const Tensor& self_t, + const Tensor& min_p, + const Tensor& min_t, + const Tensor& max_p, + const Tensor& max_t); +at::SymIntArrayRef strides_or_error( + const Tensor& input, + std::string_view const& input_name); +at::Tensor mm_mat1_backward( + const Tensor& grad, + const Tensor& mat2, + at::SymIntArrayRef mat1_sizes, + at::SymIntArrayRef mat1_strides, + c10::Layout mat1_layout, + const Scalar& alpha); +at::Tensor mm_mat2_backward( + const at::Tensor& grad, + const at::Tensor& mat1, + at::SymIntArrayRef sizes, + at::SymIntArrayRef strides, + c10::Layout layout, + const at::Scalar& alpha); +at::Tensor _grouped_mm_mat1_backward( + const Tensor& grad, + const Tensor& mat2, + at::SymIntArrayRef mat1_sizes, + at::SymIntArrayRef mat1_strides, + c10::Layout mat1_layout, + std::optional offs, + const Scalar& alpha); +at::Tensor _grouped_mm_mat2_backward( + const at::Tensor& grad, + const at::Tensor& mat1, + at::SymIntArrayRef sizes, + at::SymIntArrayRef strides, + c10::Layout layout, + std::optional offs, + const at::Scalar& alpha); +at::Tensor mm_mat1_sparse_backward( + const at::Tensor& grad, + const at::Tensor& mat1, + const at::Tensor& mat2, + const at::Scalar& alpha); +std::tuple sparse_sampled_addmm_backward( + const Tensor& grad, + const Tensor& self, + const std::optional& mat1, + const std::optional& mat2, + const Scalar& alpha, + const Scalar& beta, + const std::array& grad_input_mask); +at::Tensor sparse_mask_backward( + const at::Tensor& grad, + const at::Tensor& mask, + c10::Layout self_layout); +at::Tensor sparse_sparse_matmul_backward( + const at::Tensor& grad, + const at::Tensor& mat1, + const at::Tensor& mat2, + int64_t grad_order); +at::Tensor renorm_backward( + const at::Tensor& grad, + const at::Tensor& self, + const at::Scalar& p, + int64_t dim, + const at::Scalar& maxnorm); +at::Tensor renorm_jvp( + const at::Tensor& self_p, + const at::Tensor& self_t, + const at::Scalar& p, + int64_t dim, + const at::Scalar& maxnorm); +at::Tensor repeat_backward( + at::Tensor grad, + at::SymIntArrayRef repeats, + at::SymIntArrayRef input_shape); +at::Tensor _fused_dropout_backward( + const at::Tensor& grad, + const at::Tensor& mask, + double p1m); +at::Tensor infinitely_differentiable_native_dropout_backward( + const at::Tensor& grad, + const at::Tensor& mask, + double scale); +at::Tensor native_dropout_double_backward( + const at::Tensor& ggI, + const at::Tensor& grad, + const at::Tensor& mask, + double scale); +at::Tensor evenly_distribute_backward( + const at::Tensor& grad, + const at::Tensor& input, + const at::Tensor& value); +Tensor sgn_backward(const Tensor& x, const Tensor& gx, const Tensor& sgn); +Tensor masked_fill_backward(const Tensor& grad, const Tensor& mask); +at::Tensor var_backward( + at::Tensor grad, + const at::Tensor& self, + at::OptionalIntArrayRef dim, + const std::optional& correction, + bool keepdim); +at::Tensor var_jvp( + const at::Tensor& self_t, + const at::Tensor& self_p, + const at::Tensor& result, + at::OptionalIntArrayRef dim_opt, + const std::optional& correction, + bool keepdim); +at::Tensor std_backward( + const at::Tensor& result, + const at::Tensor& grad, + const at::Tensor& self, + at::OptionalIntArrayRef dim, + const std::optional& correction, + bool keepdim); +Tensor mean_backward( + const Tensor& grad, + c10::SymIntArrayRef shape, + at::OptionalIntArrayRef opt_dim, + c10::SymInt numel, + bool keepdim); +Tensor var_mean_backward( + const Tensor& gvar, + const Tensor& gmean, + const Tensor& self, + at::OptionalIntArrayRef dim_opt, + const std::optional& correction, + bool keepdim); +Tensor std_mean_backward( + const Tensor& gstd, + const Tensor& gmean, + const Tensor& self, + const Tensor& std, + at::OptionalIntArrayRef dim_opt, + const std::optional& correction, + bool keepdim); +at::Tensor cholesky_backward( + const at::Tensor& grad, + bool upper, + const at::Tensor& L); +at::Tensor cholesky_jvp( + const at::Tensor& input_tangent, + const at::Tensor& L, + bool upper); +at::Tensor cholesky_inverse_backward( + const at::Tensor& grad, + const at::Tensor& L, + bool upper, + const at::Tensor& inverse); +at::Tensor cholesky_inverse_jvp( + const at::Tensor& F, + const at::Tensor& dF, + const at::Tensor& X, + bool upper); +Tensor pinv_jvp(const Tensor& A, const Tensor& pinvA, const Tensor& dA); +Tensor pinv_backward(const Tensor& grad, const Tensor& pinvA, const Tensor& A); +Tensor chunk_backward_nested( + const std::vector& grads, + const Tensor& self, + int64_t chunks, + int64_t dim); +at::Tensor split_with_sizes_backward( + const std::vector& grads, + c10::SymIntArrayRef split_sizes, + int64_t dim, + c10::SymIntArrayRef sizes, + const at::TensorOptions& options); +at::Tensor _nested_split_with_sizes_backward( + const std::vector& grads, + c10::SymIntArrayRef split_sizes, + int64_t dim, + const Tensor& nt_sizes, + const at::TensorOptions& options); +at::Tensor split_backward( + const std::vector& grads, + const c10::SymInt& split_size, + int64_t dim, + c10::SymIntArrayRef sizes, + const at::TensorOptions& options); +at::Tensor max_pool_double_backward( + const at::Tensor& grad, + const at::Tensor& indices, + int dim); +at::Tensor error_for_max_pool2d_double_backward(); +at::Tensor glu_double_backward( + const at::Tensor& grad, + const at::Tensor& grad_output, + const at::Tensor& input, + int64_t dim); +at::Tensor glu_double_backward_grad_output( + const at::Tensor& grad, + const at::Tensor& input, + int64_t dim); +at::Tensor infinitely_differentiable_silu_backward( + const at::Tensor& grad_output, + const at::Tensor& input); +at::Tensor infinitely_differentiable_mish_backward( + const at::Tensor& grad_output, + const at::Tensor& input); +Tensor infinitely_differentiable_logit_backward( + const Tensor& grad, + const Tensor& self, + std::optional eps); +Tensor binary_cross_entropy_target_backward( + const Tensor& grad, + const Tensor& self, + const Tensor& target, + const std::optional& weight, + int64_t reduction); +Tensor binary_cross_entropy_double_backward_target( + const Tensor& grad, + const Tensor& grad_output, + const Tensor& self, + const Tensor& target, + const std::optional& weight, + int64_t reduction); +Tensor binary_cross_entropy_with_logits_backward( + const Tensor& grad, + const Tensor& input, + const Tensor& target, + const std::optional& weight_opt, + const std::optional& pos_weight_opt, + int64_t reduction); +at::Tensor binary_cross_entropy_with_logits_target_backward( + const at::Tensor& grad_output, + const at::Tensor& self, + const at::Tensor& target, + const std::optional& weight, + const std::optional& pos_weight, + int64_t reduction); +at::Tensor log_sigmoid_double_backward( + const at::Tensor& grad, + const at::Tensor& input); +at::Tensor softmax_double_backward( + const at::Tensor& grad, + const at::Tensor& grad_output, + int dim, + const at::Tensor& output); +at::Tensor binary_cross_entropy_double_backward( + const at::Tensor& grad_output, + const at::Tensor& grad, + const at::Tensor& input, + const at::Tensor& target, + const std::optional& weight, + int64_t reduction); +at::Tensor binary_cross_entropy_double_backward_grad_output( + const at::Tensor& grad, + const at::Tensor& input, + const at::Tensor& target, + const std::optional& weight, + int64_t reduction); +at::Tensor smooth_l1_loss_double_backward( + const at::Tensor& grad, + const at::Tensor& input, + const at::Tensor& target, + int64_t reduction, + double beta); +at::Tensor huber_loss_double_backward( + const at::Tensor& grad, + const at::Tensor& input, + const at::Tensor& target, + int64_t reduction, + double delta); +at::Tensor huber_loss_double_backward_grad_output( + const at::Tensor& grad, + const at::Tensor& grad_output, + const at::Tensor& input, + const at::Tensor& target, + int64_t reduction, + double delta); +at::Tensor mse_loss_double_backward( + const at::Tensor& grad, + const at::Tensor& input, + int64_t reduction); +at::Tensor soft_margin_loss_double_backward( + const at::Tensor& grad, + const at::Tensor& input, + const at::Tensor& target, + int64_t reduction); +at::Tensor soft_margin_loss_double_backward_grad_output( + const at::Tensor& grad, + const at::Tensor& grad_output, + const at::Tensor& input, + const at::Tensor& target, + int64_t reduction); +at::Tensor softplus_double_backward( + const at::Tensor& grad, + const at::Tensor& input, + const at::Scalar& beta, + const at::Scalar& threshold); +std::tuple slogdet_jvp( + const at::Tensor& LU, + const at::Tensor& pivots, + const at::Tensor& dA, + const at::Tensor& sign, + const bool use_A_T); +at::Tensor slogdet_backward( + const at::Tensor& grad_sign, + const at::Tensor& grad_logabsdet, + const at::Tensor& A, + const at::Tensor& signdet, + const at::Tensor& LU, + const at::Tensor& pivots); +at::Tensor log1p_backward(const at::Tensor& grad, const at::Tensor& self); +at::Tensor sinc_backward(const at::Tensor& grad, const at::Tensor& self); +at::Tensor sparse_constructor_values_backward( + const at::Tensor& sparse_grad_out, + const at::Tensor& indices); +at::Tensor embedding_dense_double_backward_symint( + const at::Tensor& grad, + const at::Tensor& indices, + const c10::SymInt& padding_idx); +at::Tensor index_backward( + at::Tensor zeros_like_self, + const torch::List>& indices, + const at::Tensor& grad); +at::Tensor _cudnn_ctc_loss_backward( + const at::Tensor& grad_out, + const at::Tensor& loss, + const at::Tensor& raw_grad, + bool zero_infinity); +at::Tensor elu_double_backward( + const Tensor& grad, + const Tensor& grad_output, + const Scalar& alpha, + const Scalar& scale, + const Scalar& input_scale, + bool is_result, + const Tensor& self_or_result); + +Tensor svd_backward( + const Tensor& gU, + const Tensor& gS, + const Tensor& gVh, + const Tensor& U, + const Tensor& S, + const Tensor& Vh); + +std::tuple linalg_svd_jvp( + const Tensor& dA, + const Tensor& U, + const Tensor& S, + const Tensor& Vh, + const bool full_matrices); +Tensor slice_backward_wrapper( + const at::Tensor& grad, + const c10::SymIntArrayRef& input_sizes, + int64_t dim, + std::optional start, + std::optional end, + c10::SymInt step); +std::tuple linalg_eig_jvp( + const Tensor& dA, + const Tensor& L, + const Tensor& V, + const bool is_hermitian); +Tensor linalg_eig_backward( + const Tensor& gL, + const Tensor& gV, + const Tensor& L, + const Tensor& V, + const bool is_hermitian, + const bool symeig_eigenvectors = true); +Tensor linalg_lstsq_solution_jvp( + const Tensor& A, + const Tensor& B_, + const Tensor& dA, + const Tensor& dB_); +Tensor linalg_lstsq_residuals_jvp( + const Tensor& A, + const Tensor& B_, + const Tensor& dA, + const Tensor& dB_, + const Tensor& X_, + const Tensor& L); +std::tuple triangular_solve_backward( + const Tensor& grad_x, + const Tensor& grad_m, + const Tensor& b, + const Tensor& a, + const Tensor& x, + const bool upper, + const bool transpose, + const bool unitriangular, + std::array output_mask); +Tensor triangular_solve_jvp( + const Tensor& X, + const Tensor& A, + const Tensor& dA, + const Tensor& dB, + const bool upper, + const bool transpose, + const bool unitriangular); +Tensor linalg_solve_triangular_forward_AD( + const Tensor& A_t, + const Tensor& B_t, + const Tensor& A, + const Tensor& X, + const bool upper, + const bool left, + const bool unitriangular); +std::tuple linalg_solve_triangular_backward( + const Tensor& grad, + const Tensor& A, + const Tensor& X, + const bool upper, + const bool left, + const bool unitriangular, + std::array output_mask); +std::tuple _trilinear_backward( + const Tensor& grad_out, + const std::optional& i1, + const std::optional& i2, + const std::optional& i3, + IntArrayRef expand1, + IntArrayRef expand2, + IntArrayRef expand3, + IntArrayRef sumdim, + std::array grad_mask); +std::tuple linalg_qr_jvp( + const Tensor& dA, + const Tensor& Q, + const Tensor& R, + const std::string_view mode); +Tensor linalg_qr_backward( + const Tensor& gQ, + const Tensor& gR, + const Tensor& Q, + const Tensor& R, + const std::string_view mode); +Tensor linalg_matrix_exp_differential( + const Tensor& self, + const Tensor& grad, + bool adjoint); +std::tuple batchnorm_double_backward( + const Tensor& input, + const std::optional& gamma, + const Tensor& ggI, + const Tensor& ggG, + const Tensor& ggB, + const Tensor& gO, + const std::optional& running_mean, + const std::optional& running_var, + bool training, + double eps, + const std::optional& save_mean, + const std::optional& save_invstd, + std::array output_mask); +std::tuple _euclidean_dist_backward( + const Tensor& grad, + const Tensor& x1, + const Tensor& x2, + const Tensor& res); +Tensor fft_backward( + const Tensor& self, + const Tensor& grad, + int64_t signal_ndim, + bool complex_input, + bool complex_output, + bool inverse, + IntArrayRef checked_signal_sizes, + int64_t normalization, + bool onesided, + IntArrayRef output_sizes); +Tensor fft_r2c_backward( + const Tensor& grad, + at::IntArrayRef dim, + int64_t normalization, + bool onesided, + const c10::SymInt& last_dim_size); +Tensor fft_c2r_backward( + const Tensor& grad, + IntArrayRef dim, + int64_t normalization); +Tensor constant_pad_nd_backward(const Tensor& grad, c10::SymIntArrayRef pad); +std::tuple cholesky_solve_backward( + const Tensor& grad_x, + const Tensor& self, + const Tensor& input2, + const Tensor& result, + const bool upper, + std::array output_mask); +Tensor cholesky_solve_jvp( + const Tensor& X, + const Tensor& U, + const Tensor& dU, + const Tensor& dB, + const bool upper); +std::tuple +infinitely_differentiable_native_group_norm_backward( + const Tensor& dY, + const Tensor& dmean, + const Tensor& drstd, + const Tensor& X, + const Tensor& mean, + const Tensor& rstd, + const std::optional& gamma, + c10::SymInt N, + const c10::SymInt& C, + c10::SymInt HxW, + int64_t group, + double eps, + std::array grad_input_mask); +Tensor gelu_double_backward( + const Tensor& ggI, + const Tensor& gO, + const Tensor& input, + std::string_view approximate); +Tensor as_strided_backward( + Tensor grad, + const TensorGeometry& input_geometry, + c10::SymIntArrayRef sizes, + c10::SymIntArrayRef strides, + const std::optional& storage_offset_); +Tensor as_strided_scatter_backward( + const Tensor& grad, + const TensorGeometry& input_geometry, + const TensorGeometry& src_geometry, + c10::SymIntArrayRef sizes, + c10::SymIntArrayRef strides, + std::optional storage_offset); +std::tuple atan2_backward( + const Tensor& grad, + const Tensor& self, + const Tensor& other, + std::array output_mask); +Tensor amaxamin_jvp( + const Tensor& x, + const Tensor& dx, + const Tensor& result, + IntArrayRef dim, + bool keepdim); +std::tuple layer_norm_double_backward( + const Tensor& input, + const std::optional& gamma, + const Tensor& ggI, + const Tensor& ggG, + const Tensor& ggB, + const Tensor& gO, + const Tensor& save_mean, + const Tensor& save_invstd, + c10::SymIntArrayRef normalized_shape, + std::array output_mask); + +std::tuple infinitely_differentiable_native_rms_norm_backward( + const Tensor& dY, + const Tensor& drstd, + const Tensor& input, + IntArrayRef normalized_shape, + const Tensor& rstd, + const std::optional& weight_opt, + std::array grad_input_mask); + +std::tuple householder_product_backward( + const Tensor& grad, + const Tensor& result, + const Tensor& input, + const Tensor& tau, + const bool flip_order = false); +Tensor householder_product_jvp( + const Tensor& dV, + const Tensor& dtau, + const Tensor& prod, + const Tensor& V, + const Tensor& tau); +std::tuple ormqr_backward( + const Tensor& grad, + const Tensor& result, + const Tensor& self, + const Tensor& tau, + const Tensor& other, + bool left, + bool transpose, + std::array grad_output_mask); +std::tuple polar_backward( + const Tensor& grad, + const Tensor& result); +Tensor i1_backward( + const Tensor& grad, + const Tensor& self, + const Tensor& result); +Tensor i1e_backward( + const Tensor& grad, + const Tensor& self, + const Tensor& result); +Tensor linalg_lu_solve_LU( + const Tensor& grad, + const Tensor& LU, + const Tensor& pivots, + const Tensor& X, + const bool left, + const bool adjoint); +Tensor linalg_lu_solve_jvp( + const Tensor& X, + const Tensor& LU, + const Tensor& pivots, + const Tensor& dLU, + const Tensor& dB, + const bool left, + const bool adjoint); +std::tuple linalg_solve_backward( + const Tensor& gX, + const Tensor& X, + const Tensor& A, + const Tensor& LU, + const Tensor& pivots, + const bool left, + const bool B_requires_grad); +Tensor linalg_solve_jvp( + const Tensor& dA, + const Tensor& dB, + const Tensor& X, + const Tensor& LU, + const Tensor& pivots, + const bool left, + const bool use_A_T); +Tensor lu_unpack_backward( + const Tensor& L_grad, + const Tensor& U_grad, + const c10::SymInt& m, + const c10::SymInt& n); + +Tensor linalg_det_backward( + const Tensor& grad, + const Tensor& det, + const Tensor& A, + const Tensor& LU, + const Tensor& pivots); +Tensor linalg_det_jvp( + const Tensor& dA, + const Tensor& det, + const Tensor& LU, + const Tensor& pivots, + const bool use_A_T); +std::tuple linalg_lstsq_backward( + const Tensor& gX_, + const Tensor& gL, + const Tensor& A, + const Tensor& B_, + const Tensor& X_, + const std::array& grad_input_mask); +Tensor linalg_lu_backward( + const Tensor& L_grad, + const Tensor& U_grad, + const Tensor& P, + const Tensor& L, + const Tensor& U, + const bool pivot); + +std::tuple linalg_lu_jvp( + const Tensor& dA, + const Tensor& P, + const Tensor& L, + const Tensor& U, + const bool pivot); + +Tensor lu_factor_ex_backward( + const Tensor& grad, + const Tensor& LU, + const Tensor& pivs, + const bool pivot); +Tensor lu_factor_ex_jvp( + const Tensor& dX, + const Tensor& LU, + const Tensor& pivs, + const bool pivot); + +Tensor batch_norm_jvp( + const Tensor& input_p, + const Tensor& input_t, + const Tensor& weight_p, + const Tensor& weight_t, + const Tensor& bias_p, + const Tensor& bias_t, + const std::optional& running_mean, + const std::optional& running_var, + const Tensor& saved_mean, + const Tensor& saved_invstd, + bool train, + double eps); + +Tensor layer_norm_jvp( + const Tensor& input_p, + const Tensor& input_t, + const Tensor& weight_p, + const Tensor& weight_t, + const Tensor& bias_p, + const Tensor& bias_t, + const Tensor& saved_mean, + const Tensor& saved_invstd, + c10::SymIntArrayRef normalized_shape); + +Tensor rms_norm_jvp( + const Tensor& input_p, + const Tensor& input_t, + const Tensor& weight_p, + const Tensor& weight_t, + const Tensor& saved_rstd, + IntArrayRef normalized_shape); + +Tensor rms_norm_rstd_jvp( + const Tensor& input_p, + const Tensor& input_t, + const Tensor& saved_rstd, + IntArrayRef normalized_shape); + +Tensor group_norm_jvp( + const Tensor& input_p, + const Tensor& input_t, + const Tensor& weight_p, + const Tensor& weight_t, + const Tensor& bias_p, + const Tensor& bias_t, + const Tensor& saved_mean, + const Tensor& saved_invstd, + int64_t groups); +Tensor group_norm_mean_jvp( + const Tensor& input_t, + const Tensor& mean_p, + int64_t groups); +Tensor group_norm_invstd_jvp( + const Tensor& input_p, + const Tensor& input_t, + const Tensor& mean_p, + const Tensor& invstd_p, + int64_t groups); + +Tensor convolution_jvp( + const Tensor& input_p, + const Tensor& input_t, + const Tensor& weight_p, + const Tensor& weight_t, + const Tensor& bias_p, + const Tensor& bias_t, + at::SymIntArrayRef stride, + at::SymIntArrayRef padding, + at::SymIntArrayRef dilation, + bool transposed, + at::SymIntArrayRef output_padding, + const c10::SymInt& groups); + +Tensor _convolution_jvp( + const Tensor& input_p, + const Tensor& input_t, + const Tensor& weight_p, + const Tensor& weight_t, + const Tensor& bias_p, + const Tensor& bias_t, + at::SymIntArrayRef stride, + at::SymIntArrayRef padding, + at::SymIntArrayRef dilation, + bool transposed, + at::SymIntArrayRef output_padding, + const c10::SymInt& groups, + bool benchmark, + bool deterministic, + bool cudnn_enabled, + bool allow_tf32); + +Tensor convolution_backward_jvp_grad_bias( + const Tensor& grad_out_t, + const Tensor& grad_bias); + +Tensor cat_jvp(const at::ITensorListRef& tensors, int64_t dim); +Tensor block_diag_jvp(at::TensorList tensors); +Tensor stack_jvp(at::TensorList tensors, int64_t dim); +Tensor cumprod_jvp( + const Tensor& self_t, + const Tensor& self_p, + const Tensor& result, + int dim); +Tensor gather_with_keepdimed_indices( + const Tensor& input, + int64_t dim, + const Tensor& indices, + bool keepdim); +Tensor evenly_read_jvp( + const Tensor& fw_grad, + const Tensor& input, + const Tensor& value); +Tensor warn_backwards(const Tensor& grad_output); + +std::tuple _cudnn_convolution_backward( + const at::Tensor& self, + const at::Tensor& grad_output, + const at::Tensor& weight, + at::SymIntArrayRef padding, + at::SymIntArrayRef output_padding, + at::SymIntArrayRef stride, + at::SymIntArrayRef dilation, + bool transposed, + c10::SymInt groups, + ::std::array output_mask); + +Tensor scatter_reduce_jvp( + const Tensor& self_p, + const Tensor& self_t, + int dim, + const Tensor& index, + const Tensor& src_p, + const Tensor& src_t, + std::string_view reduce, + bool include_self, + const Tensor& result); + +std::tuple scatter_reduce_backward( + const Tensor& grad, + const Tensor& self, + int dim, + const Tensor& index, + const Tensor& src, + std::string_view reduce, + bool include_self, + const Tensor& result); + +Tensor _to_copy_backward( + const Tensor& grad, + const c10::TensorOptions& self_options); + +std::tuple index_reduce_backward( + const Tensor& grad, + const Tensor& self, + int dim, + const Tensor& index, + const Tensor& source, + std::string_view reduce, + bool include_self, + const Tensor& result); + +Tensor take_backward( + const Tensor& grad, + const Tensor& self, + const Tensor& indices); + +Tensor to_sparse_backward( + const Tensor& grad, + const c10::Layout self_layout, + const c10::OptionalArrayRef& self_blocksize); + +std::tuple +mkldnn_rnn_layer_differentiable_backward( + const Tensor& input, + const Tensor& weight0, + const Tensor& weight1, + const Tensor& weight2, + const Tensor& weight3, + const Tensor& hx_, + const Tensor& cx_tmp, + const Tensor& output, + const Tensor& hy_, + const Tensor& cy_, + const std::optional& grad_output_r_opt, + const std::optional& grad_hy_r_opt, + const std::optional& grad_cy_r_opt, + bool reverse, + int64_t mode, + int64_t hidden_size, + int64_t num_layers, + bool has_biases, + bool train, + bool bidirectional, + at::IntArrayRef batch_sizes, + bool batch_first, + const at::Tensor& workspace); + +Tensor values_backward(const Tensor& grad, const Tensor& self); + +} // namespace torch::autograd::generated::details + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/InferenceMode.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/InferenceMode.h new file mode 100644 index 0000000000000000000000000000000000000000..5a400a8c1c609dd840625f757623584c1ae5248f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/InferenceMode.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::autograd { + +using InferenceMode = c10::InferenceMode; + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/VariableTypeUtils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/VariableTypeUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..ac92bd0fb7eecfabbe2fa5940f10dbe45c7a63ad --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/VariableTypeUtils.h @@ -0,0 +1,446 @@ +#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 + +#ifdef _MSC_VER +#ifdef Type +#undef Type +#endif +#endif + +namespace torch::autograd { +enum class can_mutate_inplace_result { + success, + non_default_backward_view, + view_of_leaf, + is_leaf, +}; + +// The requires_grad argument is used to know if the inplace operation needs +// gradient to be setup for it. +// In particular, we can have tensor.requires_grad() != requires_grad when +// writing a Tensor that requires gradients inplace into a Tensor that does not +// require gradients: a = torch.rand(2) b = torch.rand(2, requires_grad=True) +// a.copy_(b) +inline can_mutate_inplace_result can_mutate_inplace( + const at::Tensor& tensor, + bool requires_grad) { + if (!requires_grad || !GradMode::is_enabled()) { + return can_mutate_inplace_result::success; + } + auto diff_view_meta = impl::get_view_autograd_meta(tensor); + if (diff_view_meta && diff_view_meta->has_bw_view()) { + if (diff_view_meta->get_creation_meta() != CreationMeta::DEFAULT) { + return can_mutate_inplace_result::non_default_backward_view; + } + if (tensor.requires_grad() && tensor._base().is_leaf()) { + return can_mutate_inplace_result::view_of_leaf; + } + } + if (tensor.requires_grad() && tensor.is_leaf()) { + return can_mutate_inplace_result::is_leaf; + } + return can_mutate_inplace_result::success; +} + +inline void check_inplace(const at::Tensor& tensor, bool requires_grad) { + switch (can_mutate_inplace(tensor, requires_grad)) { + case can_mutate_inplace_result::success: + return; + case can_mutate_inplace_result::non_default_backward_view: { + return handle_view_on_rebase(impl::get_view_autograd_meta(tensor)); + } + case can_mutate_inplace_result::view_of_leaf: + TORCH_CHECK( + false, + "a view of a leaf Variable that requires grad is being used in an in-place operation."); + break; + + case can_mutate_inplace_result::is_leaf: + TORCH_CHECK( + false, + "a leaf Variable that requires grad is being used in an in-place operation."); + break; + } + TORCH_INTERNAL_ASSERT(false); +} + +inline void check_inplace(at::ITensorListRef tensors, bool requires_grad) { + for (const auto& tensor : tensors) { + check_inplace(tensor, requires_grad); + } +} + +inline void throw_error_out_requires_grad(const char* name) { + TORCH_CHECK( + false, + name, + "(): functions with out=... arguments don't support automatic differentiation, " + "but one of the arguments requires grad."); +} + +inline void throw_error_for_complex_autograd( + const at::Tensor& tensor, + const char* name) { + if (tensor.requires_grad()) { + TORCH_CHECK( + !tensor.is_complex(), + name, + " does not support automatic differentiation for outputs with complex dtype."); + } +} + +inline void throw_error_if_base_and_tensor_are_same( + const at::Tensor& base, + const at::Tensor& tensor) { + TORCH_CHECK( + base.unsafeGetTensorImpl() != tensor.unsafeGetTensorImpl(), + "View operation returned a tensor that is the same as the input base tensor. This " + "is no longer allowed; you must explicitly create a new tensor (e.g., using .detach()). " + "As a user, you could have made a mistake implementing __torch_dispatch__ or a Python " + "operator decomposition or meta registration; if that's not the case, please " + "report a bug to PyTorch or the backend you are using."); +} + +inline void throw_error_for_complex_autograd( + at::ITensorListRef tensorlist, + const char* name) { + for (const auto& tensor : tensorlist) { + throw_error_for_complex_autograd(tensor, name); + } +} + +// TODO: Blegh, bare references + +inline void rebase_history(const Variable& var, std::shared_ptr grad_fn) { + if (grad_fn && var.defined()) { + grad_fn->add_input_metadata(var); + impl::rebase_history(var, {std::move(grad_fn), 0}); + } +} + +inline void rebase_history( + const std::vector& vars, + const std::shared_ptr& grad_fn) { + if (grad_fn) { + for (auto& var : vars) { + if (var.defined()) { + auto output_nr = grad_fn->add_input_metadata(var); + impl::rebase_history(var, {grad_fn, output_nr}); + } else { + grad_fn->add_input_metadata(Node::undefined_input()); + } + } + } +} + +inline void increment_version(const at::Tensor& t) { + impl::bump_version(t); +} + +struct Flatten : IterArgs { + Flatten(variable_list& out) : out(out) {} + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + variable_list& out; + void operator()(const at::Tensor& x) { + out.emplace_back(x); + } + void operator()(const std::optional& x) { + if (x.has_value()) + out.emplace_back(x.value()); + } + void operator()(at::ArrayRef xs) { + out.insert(out.end(), xs.begin(), xs.end()); + } +}; + +template +inline variable_list flatten_tensor_args(Args&&... args) { + variable_list out; + out.reserve(count_tensors(std::forward(args)...)); + Flatten(out).apply(std::forward(args)...); + return out; // RVO +} + +// See NOTE [ Autograd View Variables ] for details. +inline at::Tensor as_view( + const at::Tensor& base, + const at::Tensor& tensor, + bool is_bw_differentiable, + bool is_fw_differentiable, + std::unique_ptr view_func = nullptr, + std::function rev_view_func = nullptr, + CreationMeta creation_meta = CreationMeta::DEFAULT, + bool allow_tensor_metadata_change = true) { + // Note [View of inference tensor] + // For inference tensor this code can only be hit outside InferenceMode + // since ADInplaceOrView is in the default_included_set. + // If Inplace and View were separate dispatch keys we can just put Inplace + // in the default_included_set, so that view ops on inference tensor doesn't + // have to go through as_view even outside InferenceMode. + if (base.is_inference()) + return tensor; + + auto diff_view_meta = torch::autograd::impl::get_view_autograd_meta(base); + + // To speed up the most common case, we specially handle when both the forward + // and backward view infos are the same, and so a single shared ViewInfo can + // be used for both of them. + if ((!diff_view_meta || diff_view_meta->shared_view_info()) && + is_bw_differentiable && is_fw_differentiable) { + throw_error_if_base_and_tensor_are_same(base, tensor); + if (diff_view_meta) { + creation_meta = propagate_creation_meta( + diff_view_meta->get_creation_meta(), creation_meta); + return make_variable_differentiable_view( + tensor, + diff_view_meta->get_backward_view().chain( + base, tensor, std::move(view_func), std::move(rev_view_func)), + std::nullopt, + /*shared_view_info*/ true, + creation_meta, + allow_tensor_metadata_change); + } else { + return make_variable_differentiable_view( + tensor, + ViewInfo(base, std::move(view_func), std::move(rev_view_func)), + std::nullopt, + /*shared_view_info*/ true, + creation_meta, + allow_tensor_metadata_change); + } + } + + // If they cannot be shared, create the required view infos + std::optional new_bw_info; + std::optional new_fw_info; + + if (is_bw_differentiable) { + auto bw_view_func = view_func ? view_func->clone_and_set() : nullptr; + if (diff_view_meta && diff_view_meta->has_bw_view()) { + const auto& base_bw_info = diff_view_meta->get_backward_view(); + new_bw_info = base_bw_info.chain( + base, tensor, std::move(bw_view_func), rev_view_func); + } else { + new_bw_info = ViewInfo(base, std::move(bw_view_func), rev_view_func); + } + } else { + TORCH_CHECK( + creation_meta == CreationMeta::DEFAULT, + "Non-backward differentiable views must have creation_meta=CreationMeta::DEFAULT"); + } + + if (is_fw_differentiable) { + // Check if base is a forward differentiable view + if (diff_view_meta && diff_view_meta->has_fw_view()) { + const auto& base_fw_info = diff_view_meta->get_forward_view(); + new_fw_info = base_fw_info.chain( + base, tensor, std::move(view_func), std::move(rev_view_func)); + } else { + new_fw_info = + ViewInfo(base, std::move(view_func), std::move(rev_view_func)); + } + } + + if (is_fw_differentiable || is_bw_differentiable) { + if (diff_view_meta && diff_view_meta->has_bw_view()) { + creation_meta = propagate_creation_meta( + diff_view_meta->get_creation_meta(), creation_meta); + } + throw_error_if_base_and_tensor_are_same(base, tensor); + return make_variable_differentiable_view( + tensor, + std::move(new_bw_info), + std::move(new_fw_info), + /*shared_view_info*/ false, + creation_meta, + allow_tensor_metadata_change); + } else { + return make_variable_non_differentiable_view( + base, tensor, allow_tensor_metadata_change); + } +} + +inline void check_no_requires_grad( + const at::Tensor& tensor, + const char* name, + const char* fn_name = "", + bool check_grad_mode = true) { + TORCH_CHECK( + !(tensor.defined() && tensor.requires_grad()) || + !(check_grad_mode && GradMode::is_enabled()), + "The function '", + fn_name, + "' is not differentiable with respect to argument '", + name, + "'. This input cannot have requires_grad True."); +} + +inline void check_no_requires_grad( + const std::optional& tensor, + const char* name, + const char* fn_name = "") { + if (tensor.has_value()) { + check_no_requires_grad(*tensor, name, fn_name); + } +} + +inline void check_no_requires_grad( + at::ITensorListRef tensors, + const char* name, + const char* fn_name = "") { + // GradMode check is expensive, so check it only once for TensorLists + if (!GradMode::is_enabled()) { + return; + } + for (auto& tensor : tensors) { + check_no_requires_grad(tensor, name, fn_name, /*check_grad_mode*/ false); + } +} + +inline void check_no_requires_grad( + const c10::List>& tensors, + const char* name, + const char* fn_name = "") { + // GradMode check is expensive, so check it only once for TensorLists + if (!GradMode::is_enabled()) { + return; + } + for (std::optional tensor : tensors) { + if (tensor.has_value()) { + check_no_requires_grad(*tensor, name, fn_name, /*check_grad_mode*/ false); + } + } +} + +// Assumed that saved tensor lists are never inplace outputs +inline std::vector make_saved_variable_list( + at::ITensorListRef tensors, + const bool is_output = false) { + return fmap(tensors, [&is_output](const at::Tensor& tensor) -> SavedVariable { + return SavedVariable{tensor, is_output /* is output */}; + }); +} + +// Assumed that saved tensor lists are never inplace outputs +inline std::vector make_saved_variable_list( + const c10::List>& tensors, + const bool is_output = false) { + return fmap( + tensors, + [&is_output](const std::optional& tensor) -> SavedVariable { + if (tensor.has_value()) { + return SavedVariable{*tensor, is_output /* is output */}; + } else { + return SavedVariable{at::Tensor(), is_output /* is output */}; + } + }); +} + +inline std::vector> to_args_sizes( + at::ITensorListRef tensors) { + std::vector> args_sizes(tensors.size()); + size_t i = 0; + for (const auto& t : tensors) { + args_sizes[i++] = t.sizes().vec(); + } + return args_sizes; +} + +inline std::vector> to_args_sizes_symint( + at::ITensorListRef tensors) { + std::vector> args_sizes(tensors.size()); + size_t i = 0; + for (const auto& t : tensors) { + args_sizes[i++] = t.sym_sizes().vec(); + } + return args_sizes; +} + +inline std::vector to_args_scalartypes( + at::ITensorListRef tensors) { + std::vector args_scalartypes(tensors.size()); + size_t i = 0; + for (const auto& t : tensors) { + args_scalartypes[i++] = t.scalar_type(); + } + return args_scalartypes; +} + +namespace impl { + +namespace { + +// If run_jit_decomposition were not a member function, we would be able +// to pass this as a template parameter to c10::Boxedkernel::makeFromFunction. +// However, member functions cannot be passed this way - instead we wrap our +// call in this functor so it can be passed to c10::BoxedKernel::makeFromFunctor +class WrapperFunctor final : public c10::OperatorKernel { + public: + WrapperFunctor(JitDecompInterface* impl) : impl_(impl) {} + + void operator()( + const c10::OperatorHandle& op, + c10::DispatchKeySet ks, + torch::jit::Stack* stack) { + impl_->run_jit_decomposition(op, stack); + } + JitDecompInterface* impl_; +}; + +} // namespace + +template +Return run_jit_decomposition_with_args_for_jvp( + std::string_view name, + const c10::OperatorHandle& opHandle, + c10::DispatchKeySet dispatchKeySet, + Args&&... args) { + // see NOTE: [Jit Decomposition Interface] + JitDecompInterface* impl = getJitDecompImpl(); + + TORCH_CHECK_NOT_IMPLEMENTED( + impl && impl->has_jit_decomposition(opHandle.schema()), + "Trying to use forward AD with ", + name, + " that does not support it because it has not been implemented yet.\nPlease file an issue " + "to PyTorch at https://github.com/pytorch/pytorch/issues/new?template=feature-request.yml " + "so that we can prioritize its implementation or submit a PR adding the implementation to " + "derivatives.yaml"); + + return c10::KernelFunction::makeFromBoxedKernel( + c10::BoxedKernel::makeFromFunctor( + std::make_unique(impl))) + .call( + opHandle, dispatchKeySet, std::forward(args)...); +} + +} // namespace impl + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/anomaly_mode.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/anomaly_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..84c3c1a2ab61ebd585d63596b382c97f92c58bb6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/anomaly_mode.h @@ -0,0 +1,76 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::autograd { + +// forward declaration of Node from function.h +struct Node; + +struct TORCH_API AnomalyMode { + static bool is_enabled() { + return _enabled; + } + static bool should_check_nan() { + return _check_nan; + } + static void set_enabled(bool enabled, bool check_nan = true) { + _enabled = enabled; + _check_nan = check_nan; + } + + private: + static bool _enabled; + static bool _check_nan; +}; + +/// A RAII guard that enables Anomaly Detection Mode. +/// +/// Anomaly detection mode is useful for debugging problems happening +/// in the backward, such as unexpectedly modified tensors or NaNs +/// occurring in the backward. +/// +/// The enabling of anomaly mode is global - as soon as there is one +/// such guard, it is enabled for all computation and threads. It also +/// comes with a significant performance penalty. +/// +/// Example: +/// @code +/// auto x = torch::tensor({1.}, torch::requires_grad()); +/// { +/// torch::autograd::DetectAnomalyGuard detect_anomaly; +/// auto x = torch::tensor({5.0}, torch::requires_grad()); +/// auto y = x * x; +/// auto z = y * y; +/// y += 1; +/// z.backward(); +/// } +/// @endcode +class TORCH_API DetectAnomalyGuard { + public: + DetectAnomalyGuard(bool check_nan = true); + ~DetectAnomalyGuard(); + + private: + bool prev_check_nan_; +}; + +struct TORCH_API AnomalyMetadata { + virtual ~AnomalyMetadata(); + virtual void store_stack(); + virtual void print_stack(const std::string& current_node_name); + virtual void assign_parent(const std::shared_ptr& parent_node); + + private: + std::string traceback_; + std::shared_ptr parent_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..a481d16e869cbe92a81d3b487212e24a19d7bd19 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd.h @@ -0,0 +1,109 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::autograd { + +/// Computes the sum of gradients of given tensors with respect to graph leaves. +/// +/// The graph is differentiated using the chain rule. If any of ``tensors`` +/// are non-scalar (i.e. their data has more than one element) and require +/// gradient, then the Jacobian-vector product would be computed, in this case +/// the function additionally requires specifying `grad_tensors`. It should be a +/// sequence of matching length, that contains the "vector" in the +/// Jacobian-vector product, usually the gradient of the differentiated function +/// w.r.t. corresponding tensors +/// (`torch::Tensor()` is an acceptable value for all tensors that don't need +/// gradient tensors). +/// +/// This function accumulates gradients in the leaves - you might need to zero +/// them before calling it. +/// +/// \param tensors Tensors of which the derivative will be computed. +/// \param grad_tensors The "vector" in the Jacobian-vector product, usually +/// gradients +/// w.r.t. each element of corresponding tensors. `torch::Tensor()` values +/// can be specified for scalar Tensors or ones that don't require grad. If +/// a `torch::Tensor()` value would be acceptable for all grad_tensors, then +/// this argument is optional. +/// \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. +/// Defaults to the value of `create_graph`. +/// \param create_graph If `true`, graph of the derivative will be constructed, +/// allowing +/// to compute higher order derivative products. Defaults to `false`. +/// \param inputs Inputs w.r.t. which the gradient will be accumulated into +/// `at::Tensor::grad`. All other Tensors will be ignored. If not provided, +/// the gradient is accumulated into all the leaf Tensors that were used to +/// compute param `tensors`. +// When inputs are provided and a given input is not a leaf, +// the current implementation will call its grad_fn (even though it is not +// strictly needed to get this gradients). It is an implementation detail +// on which the user should not rely. See +// https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for +// more details. +TORCH_API void backward( + const variable_list& tensors, + const variable_list& grad_tensors = {}, + std::optional retain_graph = std::nullopt, + bool create_graph = false, + const variable_list& inputs = {}); + +/// Computes and returns the sum of gradients of outputs with respect to the +/// inputs. +/// +/// ``grad_outputs`` should be a sequence of length matching ``output`` +/// containing the "vector" in Jacobian-vector product, usually the pre-computed +/// gradients w.r.t. each of the outputs. If an output doesn't require_grad, +/// then the gradient can be ``torch::Tensor()``). +/// +/// \param outputs outputs of the differentiated function. +/// \param inputs Inputs w.r.t. which the gradient will be +/// returned (and not accumulated into ``at::Tensor::grad``). +/// \param grad_outputs The "vector" in the Jacobian-vector product. +/// Usually gradients w.r.t. each output. `torch::Tensor()` values can be +/// specified for scalar Tensors or ones that don't require grad. If a +/// `torch::Tensor()` value would be acceptable for all grad_tensors, then +/// this argument is optional. Default: `{}`. +/// \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. Defaults to the value of ``create_graph``. +/// \param create_graph If ``true``, graph of the derivative will +/// be constructed, allowing to compute higher order derivative products. +/// Default: ``false``. +/// \param allow_unused If ``false``, specifying inputs that were not +/// used when computing outputs (and therefore their grad is always zero) +/// is an error. Defaults to ``false``. +TORCH_API variable_list grad( + const variable_list& outputs, + const variable_list& inputs, + const variable_list& grad_outputs = {}, + std::optional retain_graph = std::nullopt, + bool create_graph = false, + bool allow_unused = false); + +namespace forward_ad { + +/// Creates a new dual level and returns its index. This level index should then +/// be used to call into the other functions below. This API supports entering a +/// new level before the previous one is exited. We call them nested forward AD +/// levels. These can be used to compute higher order derivatives. +TORCH_API uint64_t enter_dual_level(); + +/// Exits the given level. This will clear up all the gradients from this level +/// and all dual Tensors that had gradients for this level will become regular +/// Tensors again. This function can only be used to exit the innermost nesting +/// level and so exiting must happen in reverse order compared to the entering +/// that was done with the function above. +TORCH_API void exit_dual_level(uint64_t level); + +} // namespace forward_ad +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd_not_implemented_fallback.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd_not_implemented_fallback.h new file mode 100644 index 0000000000000000000000000000000000000000..e8d08acc4409e48dc62057a05f0334c928677b76 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd_not_implemented_fallback.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::autograd { + +// Default DispatchKey::Autograd fallback for built-in operators. +// Can be registered for custom operators. +TORCH_API torch::CppFunction autogradNotImplementedFallback(); + +// Default DispatchKey::AdInplaceOrView fallback for built-in operators +// Can be registered for custom operators. +TORCH_API torch::CppFunction autogradNotImplementedInplaceOrViewFallback(); + +// Default DispatchKey::Autograd fallback for all other operators (i.e. custom +// operators) +TORCH_API torch::CppFunction basicAutogradNotImplementedFallback(); + +enum class AutogradFallbackMode { + Nothing, // Fallback is a redispatch + Warn, // Fallback raises a warning if backward is called + Error, // Fallback raises an error if backward is called +}; + +// Change the behavior of "basicAutogradNotImplementedFallback" +// In Python this is: +// - torch._C._set_autograd_fallback_mode(str) -> None +// - torch._C._get_autograd_fallback_mode() -> str +TORCH_API void setAutogradFallbackMode(AutogradFallbackMode mode); +TORCH_API AutogradFallbackMode getAutogradFallbackMode(); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/cpp_hook.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/cpp_hook.h new file mode 100644 index 0000000000000000000000000000000000000000..c3f0b209572e1b4692d118b02bd018a2397f2caf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/cpp_hook.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::autograd { + +using hooks_list = + std::vector>; + +struct CppFunctionTensorPreHook : public FunctionPreHook { + CppFunctionTensorPreHook(std::shared_ptr hooks, size_t value_idx); + variable_list operator()(const variable_list& values) override; + + std::shared_ptr hooks_; + size_t value_idx_; +}; + +struct CppFunctionSingleTensorPreHook : public FunctionPreHook { + CppFunctionSingleTensorPreHook( + std::function hook, + size_t value_idx); + variable_list operator()(const variable_list& values) override; + + void compiled_args( + torch::dynamo::autograd::CompiledNodeArgs& args) const override; + + std::function hook_; + size_t value_idx_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/custom_function.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/custom_function.h new file mode 100644 index 0000000000000000000000000000000000000000..85d3bbf4132f42428cf1602e825f0def5960591f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/custom_function.h @@ -0,0 +1,585 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::autograd { + +using optional_variable_list = std::vector>; +using _jvp_fn_t = std::function; +using _view_as_self_fn_t = std::function; + +TORCH_API std::vector> _wrap_outputs( + const variable_list& input_vars, + const std::unordered_set& non_differentiable, + const std::unordered_set& dirty_inputs, + const at::ArrayRef> raw_outputs, + const std::shared_ptr& cdata, + const _jvp_fn_t& jvp_user_function, + const std::unordered_set& to_save_if_setup_context, + const _view_as_self_fn_t& view_as_self_fn, + bool pure_view); + +TORCH_API void check_variable_result( + const at::TensorBase& original, + const at::TensorBase& result, + const std::string& hook_name); + +// Get the return type of the forward function of the custom Function class X +template +using forward_t = decltype(X::forward(nullptr, std::declval()...)); + +/// To use custom autograd operations, implement a Function subclass with +/// static forward and backward functions: +/// +/// `forward` can take as many arguments as you want and should return either a +/// variable list or a Variable. Use of any direct Variable arguments will be +/// registered in the graph but no vectors/sets or any other data structures +/// will be traversed. You can use std::optional as one of the arguments +/// and it will be registered as a variable in the graph if the argument has a +/// value. It should take a pointer to `torch::autograd::AutogradContext` as the +/// first argument. Variables can be saved in the `ctx` using +/// `ctx->save_for_backward` +/// (see `torch::autograd::AutogradContext::save_for_backward`) and other data +/// can be saved in the `ctx->saved_data` map +/// (see `torch::autograd::AutogradContext::saved_data`) +/// in the form of `` pairs. +/// +/// `backward` should take a pointer to `torch::autograd::AutogradContext` +/// and a variable list containing as many Variables as there were outputs from +/// `forward` as arguments. It should return as many Variables as there were +/// inputs with each of them containing the gradient w.r.t. its corresponding +/// input. Variables saved in `forward` can be accessed with +/// `ctx->get_saved_variables` (see +/// `torch::autograd::AutogradContext::get_saved_variables`) and other saved +/// data can be accessed from `ctx->saved_data`. +/// To enable compiled autograd support (torch.compile for backward) for your +/// custom autograd operation, you can set MyFunction::is_traceable +/// (see Function::istraceable notes below). +/// +/// For example: +/// ``` +/// class MyFunction : public Function { +/// public: +/// static constexpr bool is_traceable = true; +/// +/// static variable_list forward(AutogradContext *ctx, int n, Variable var) { +/// // Save data for backward in context +/// ctx->saved_data["n"] = n; +/// var.mul_(n); +/// // Mark var as modified by inplace operation +/// ctx->mark_dirty({var}); +/// return {var}; +/// } +/// +/// static variable_list backward(AutogradContext *ctx, variable_list +/// grad_output) { +/// // Use data saved in forward +/// auto n = ctx->saved_data["n"].toInt(); +/// return {grad_output[0]*n}; +/// } +/// }; +/// ``` +/// +/// To use `MyFunction`: +/// ``` +/// Variable x; +/// auto y = MyFunction::apply(6, x); +/// // Example backward call +/// y[0].sum().backward(); +/// ``` +template +struct TORCH_API Function { + // We need to use a different template parameter than T here because T will + // inherit from Function, and when Function is instantiated, T::forward + // is not declared yet. + // The enable_if check is to ensure that the user doesn't explicitly provide + // the parameter X. + template + static auto apply(Args&&... args) + -> std::enable_if_t, forward_t>; + + // This flag is for an experimental feature: compiled autograd. Not all + // built-in APIs are supported at the moment e.g. mark_dirty and + // mark_non_differentiable. Before setting this flag to enable tracing for + // your custom function , you need to ensure that the backward function is + // traceable i.e. any variables accessed in the backward other than the input + // arguments must be handled in a similar manner to built-ins in + // CppNode::compiled_args and CppNode::apply_with_saved. + static constexpr bool is_traceable = false; +}; + +/// Context to save information during `forward` that can be accessed in +/// `backward` in custom autograd operations (see `torch::autograd::Function` +/// for details). +struct TORCH_API AutogradContext { + AutogradContext() = default; + AutogradContext(const AutogradContext& other) = delete; + AutogradContext& operator=(const AutogradContext& other) = delete; + AutogradContext(AutogradContext&& other) = delete; + AutogradContext& operator=(AutogradContext&& other) = delete; + ~AutogradContext() = default; + + AutogradContext(PackedArgs& packed_args); + + /// Can be used to save non-variable data for `backward`. + ska::flat_hash_map saved_data; + + /// Saves the list of variables for a future call to `backward`. This + /// should be called at most once from inside of `forward`. + void save_for_backward(variable_list to_save); + /// Marks variables in the list as modified in an in-place operation. This + /// should be called at most once from inside of `forward` and all arguments + /// should be inputs. + void mark_dirty(const variable_list& inputs); + /// Marks outputs in the list as not requiring gradients. This should be + /// called at most once from inside of `forward` and all arguments should be + /// outputs. + void mark_non_differentiable(const variable_list& outputs); + // Sets whether undefined output grad tensors should be expanded to tensors + // full of zeros before calling backward function. Default value is true. + void set_materialize_grads(bool value); + + /// Get the list of variables that were saved in `forward` using + /// `save_for_backward()`. Before returning them to the user, a check is made + /// to ensure that they were not modified by any in-place operations. + variable_list get_saved_variables() const; + const std::unordered_set& get_and_bump_dirty() const; + const std::unordered_set& get_non_differentiable() const; + + /// Expose the Node's `task_should_compute_output` method to the cpp + /// custom autograd Function as `needs_input_grad`. + bool needs_input_grad(size_t output_edge_index) const; + bool needs_input_grad(std::initializer_list idxs) const; + + private: + std::unordered_set non_differentiable_; + std::unordered_set dirty_inputs_; + std::vector saved_variables_; + variable_list to_save_; + bool materialize_grads_{true}; + + // The CppNode in the autograd graph that owns this AutogradContext. We need a + // weak_ptr to avoid a refcycle. Since grad_fn_ owns this AutogradContext, it + // will always be alive when we want to use it. + std::weak_ptr grad_fn_; + bool has_freed_buffers_{false}; + + // Compiled autograd overrides saved_variables() and needs_input_grad(). + // We store the values we want to return here. + std::optional saved_variables_override_; + std::optional> needs_input_grad_override_; + + void save_variables(); + + template + friend struct CppNode; + template + friend variable_list CppNode_apply_functional( + variable_list&& inputs, + AutogradContext& ctx_, + const std::vector& is_variable_input_, + const std::vector& output_info_, + const std::string& name); +}; + +template +inline variable_list CppNode_apply_functional( + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) + variable_list&& inputs, + AutogradContext& ctx_, + const std::vector& is_variable_input_, + const std::vector& output_info_, + const std::string& name) { + at::OptionalDeviceGuard _device_guard; + + auto num_inputs = inputs.size(); + variable_list backward_inputs; + backward_inputs.reserve(num_inputs); + for (const auto i : c10::irange(num_inputs)) { + if (inputs[i].defined() || !ctx_.materialize_grads_) { + backward_inputs.emplace_back(std::move(inputs[i])); + } else { + backward_inputs.emplace_back(output_info_[i].zeros(_device_guard)); + } + } + + auto outputs = T::backward(&ctx_, backward_inputs); + + const auto num_forward_inputs = + static_cast(is_variable_input_.size()); + auto num_outputs = static_cast(outputs.size()); + // Returning too many results is ok, but only as long as they're all + // undefined. Truncate the result vector in that case. + if (num_outputs > num_forward_inputs) { + bool all_undef = true; + for (const auto i : c10::irange(num_forward_inputs, num_outputs)) { + all_undef &= (!outputs[i].defined()); + } + if (all_undef) { + outputs.resize(num_forward_inputs); + num_outputs = num_forward_inputs; + } + } + + TORCH_CHECK( + num_outputs == num_forward_inputs, + "function ", + name, + " returned an incorrect number of gradients (expected ", + num_forward_inputs, + ", got ", + num_outputs, + ")"); + + variable_list results; + results.reserve(num_outputs); + for (const auto i : c10::irange(num_outputs)) { + if (!is_variable_input_[i]) { + TORCH_CHECK( + outputs[i].defined() == false, + "function ", + name, + " returned a gradient different that is defined at position ", + i + 1, + ", std the corresponding forward input was not a Variable"); + continue; + } + results.emplace_back(outputs[i]); + } + + return results; +} + +template +inline variable_list CppNode_apply_functional_ivalue( + const variable_list& inputs, + const std::vector& args) { + auto packed_args = PackedArgs(args); + auto ctx = AutogradContext(packed_args); + auto output_info = packed_args.unpack>(); + auto is_variable_input = packed_args.unpack>(); + auto name = packed_args.unpack(); + return CppNode_apply_functional( + variable_list(inputs), ctx, is_variable_input, output_info, name); +} + +// CppNode is the Node in the autograd graph that represents the user defined +// backward function for Function. Calls to CppNode::apply are forward to +// T::backward(). +template +struct CppNode : public Node { + variable_list apply(variable_list&& inputs) override; + AutogradContext ctx_; + std::vector is_variable_input_; + std::vector input_info_; + std::vector output_info_; + + void release_variables() override; + + void set_ctx_grad_fn(const std::shared_ptr& node); + void save_variables_to_ctx(); + + void compiled_args(CompiledNodeArgs& args) const override { + // although neither of the 2 methods below have uniqueness guarantees + // it is unlikely for them to collide at the same time + args.collect(static_cast(typeid(T).hash_code())); + args.collect(std::string(typeid(T).name())); + + args.collect(ctx_.saved_data); + TORCH_INTERNAL_ASSERT(ctx_.non_differentiable_.empty()); + TORCH_INTERNAL_ASSERT(ctx_.dirty_inputs_.empty()); + args.collect( + ctx_.saved_variables_, true); // always unpacked as output in eager + TORCH_INTERNAL_ASSERT(ctx_.to_save_.empty()); + args.collect(ctx_.materialize_grads_); + args.collect(ctx_.has_freed_buffers_); + args.collect(is_variable_input_); + args.collect(input_info_); + args.collect(output_info_); + } + + variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) override { + saved.before(ctx_.saved_data); + TORCH_INTERNAL_ASSERT(ctx_.non_differentiable_.empty()); + TORCH_INTERNAL_ASSERT(ctx_.dirty_inputs_.empty()); + saved.before(ctx_.saved_variables_); + TORCH_INTERNAL_ASSERT(ctx_.to_save_.empty()); + saved.before(ctx_.materialize_grads_); + saved.before(ctx_.has_freed_buffers_); + saved.before(input_info_); + saved.before(output_info_); + + PackedArgs packed_args; + packed_args.pack_saved_data(ctx_.saved_data); + variable_list saved_variables = ctx_.get_saved_variables(); + packed_args.pack(saved_variables); + packed_args.pack(ctx_.materialize_grads_); + packed_args.pack(ctx_.has_freed_buffers_); + + std::vector needs_input_grad; + { + auto ptr = ctx_.grad_fn_.lock(); + TORCH_INTERNAL_ASSERT(ptr); + for (const auto i : c10::irange(ptr->next_edges().size())) { + needs_input_grad.push_back(ptr->task_should_compute_output(i)); + } + } + packed_args.pack(needs_input_grad); + + packed_args.pack(output_info_); + packed_args.pack(is_variable_input_); + packed_args.pack(name()); + auto args = std::move(packed_args).vec(); + + auto output_metadata = torch::dynamo::autograd:: + IValuePacker>>::pack( + torch::dynamo::autograd::get_input_metadata(next_edges())); + + const auto& pyinterface = torch::dynamo::autograd::getPyCompilerInterface(); + + // Each time apply_with_saved is called, we bind a new function to Python. + // This is because the schema might be different on compiled autograd cache + // misses. An alternative is to pass the schema to Python so that it can be + // an input to a function, but the schema can't be put into an FX graph + // right now. + std::vector schema; + schema.reserve(args.size()); + for (const auto& ivalue : args) { + if (ivalue.isTensor()) { + schema.emplace_back(at::TensorType::get()); + } else { + schema.emplace_back(ivalue.type()); + } + } + static_assert( + std::is_same_v, bool>); + auto fn_name = pyinterface->bind_function( + saved.get_py_compiler(), + std::string(typeid(T).name()), + CppNode_apply_functional_ivalue, + schema, + /*is_custom_function*/ true, + /*is_traceable*/ T::is_traceable); + + auto results = pyinterface->call_function( + saved.get_py_compiler(), + "apply_functional", + fn_name, + inputs, + args, + output_metadata); + + saved.after(ctx_.saved_data); + TORCH_INTERNAL_ASSERT(ctx_.non_differentiable_.empty()); + TORCH_INTERNAL_ASSERT(ctx_.dirty_inputs_.empty()); + saved.after(ctx_.saved_variables_); + TORCH_INTERNAL_ASSERT(ctx_.to_save_.empty()); + saved.after(ctx_.materialize_grads_); + saved.after(ctx_.has_freed_buffers_); + saved.after(input_info_); + saved.after(output_info_); + return results; + } +}; + +struct ExtractVariables : IterArgs { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + std::vector& is_var_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + variable_list& list_; + ExtractVariables(std::vector& is_var, variable_list& list) + : is_var_(is_var), list_(list) {} + void operator()(const std::optional& x) { + if (x.has_value() && x.value().defined()) { + is_var_.push_back(true); + list_.emplace_back(x.value()); + } else { + is_var_.push_back(false); + } + } + void operator()(const at::Tensor& x) { + is_var_.push_back(true); + list_.emplace_back(x); + } + void operator()(const at::TensorList& list) { + for (const at::Tensor& x : list) { + is_var_.push_back(true); + list_.emplace_back(x); + } + } + template + void operator()(const T& x) { + is_var_.push_back(false); + } +}; + +template +inline void extract_vars( + std::vector& is_var, + variable_list& list, + Args&&... args) { + ExtractVariables(is_var, list).apply(std::forward(args)...); +} + +template +std::enable_if_t, T> to_output_type( + std::vector>& output_list) { + variable_list result; + std::transform( + output_list.begin(), + output_list.end(), + std::back_inserter(result), + [](const std::optional& var) { return *var; }); + return result; +} + +template +std::enable_if_t, T> to_output_type( + std::vector>& output_list) { + return *output_list[0]; +} + +inline std::vector> to_optional(Variable& output) { + return std::vector>{output}; +} + +inline std::vector> to_optional(variable_list& output) { + std::vector> result; + std::transform( + output.begin(), + output.end(), + std::back_inserter(result), + [](const Variable& var) { return var; }); + return result; +} + +template +template +auto Function::apply(Args&&... args) + -> std::enable_if_t, forward_t> { + const auto& functorch_tls = at::functorch::functorchTLSAccessor(); + if (functorch_tls) { + // Function support for functorch is handled in Python. + // Here we are dealing with a (C++) Function, which is not supported. + // Let's raise an error instead of being silently incorrect. + functorch_tls->checkSupportsCppAutogradFunction(); + } + + std::shared_ptr> node(new CppNode(), deleteNode); + variable_list input_vars; + + const size_t num_inputs = sizeof...(Args); + input_vars.reserve(num_inputs); + node->is_variable_input_.reserve(num_inputs); + // TODO Add tracing here + extract_vars(node->is_variable_input_, input_vars, args...); + + bool is_executable = + GradMode::is_enabled() && any_variable_requires_grad(input_vars); + auto next_edges = + (is_executable ? collect_next_edges(input_vars) : edge_list()); + node->set_ctx_grad_fn(node); + node->set_next_edges(std::move(next_edges)); + node->clear_input_metadata(); + + node->input_info_.reserve(input_vars.size()); + for (auto& var : input_vars) { + node->input_info_.emplace_back(var); + } + + using forward_return_t = forward_t; + forward_return_t outputs; + { + AutoGradMode grad_mode(false); + outputs = T::forward(&node->ctx_, std::forward(args)...); + } + + _jvp_fn_t jvp_fn = [](const variable_list& inputs, + const variable_list& gI) -> variable_list { + TORCH_CHECK( + false, + "jvp is not implemented for the c++ API of custom Function yet.", + "Please open a feature request on GitHub if you need this."); + }; + + auto view_as_self_fn = [](const at::Tensor& x) -> at::Tensor { + return x.view_as(x); + }; + + auto wrapped_outputs = _wrap_outputs( + input_vars, + node->ctx_.get_non_differentiable(), + node->ctx_.get_and_bump_dirty(), + to_optional(outputs), + is_executable ? node : nullptr, + jvp_fn, + {}, + view_as_self_fn, + false); + + node->output_info_.reserve(wrapped_outputs.size()); + for (auto& output : wrapped_outputs) { + if (is_executable && output.has_value()) { + node->output_info_.emplace_back(output.value()); + } else if (is_executable) { + node->output_info_.emplace_back(); + } + } + + if (is_executable) { + node->save_variables_to_ctx(); + } + + // wrapped_outputs will be a variable_list so, convert it to the correct + // return type. Only Variable and variable_list are accepted as return types. + return to_output_type(wrapped_outputs); +} + +// The logic here is the same as PyNode::apply, so changes to it should be done +// in both the places +template +// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) +variable_list CppNode::apply(variable_list&& inputs) { + // Acquire lock to here protect thread safety on custom C++ Autograd Node + // This is needed for the custom Autograd Node since we don't know if the + // user defined Node will write to the shared data during backward. + // see Note [Thread Safety on Autograd Node] + std::lock_guard lock(mutex_); + return CppNode_apply_functional( + std::move(inputs), ctx_, is_variable_input_, output_info_, name()); +} + +template +void CppNode::release_variables() { + // lock to ensure thread safety, see [Thread Safety on Autograd Node] + std::lock_guard lock(mutex_); + ctx_.saved_variables_.clear(); + ctx_.has_freed_buffers_ = true; +} + +template +void CppNode::save_variables_to_ctx() { + ctx_.save_variables(); +} + +template +void CppNode::set_ctx_grad_fn(const std::shared_ptr& node) { + ctx_.grad_fn_ = node; +} + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/edge.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/edge.h new file mode 100644 index 0000000000000000000000000000000000000000..b6f1011fe236d637b82d3839bda87aa0c16fdb2a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/edge.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include + +namespace torch::autograd { + +struct Node; + +/// Represents a particular input of a function. +struct Edge { + Edge() noexcept : function(nullptr), input_nr(0) {} + + Edge(std::shared_ptr function_, uint32_t input_nr_) noexcept + : function(std::move(function_)), input_nr(input_nr_) {} + + /// Convenience method to test if an edge is valid. + bool is_valid() const noexcept { + return function != nullptr; + } + + // Required for use in associative containers. + bool operator==(const Edge& other) const noexcept { + return this->function == other.function && this->input_nr == other.input_nr; + } + + bool operator!=(const Edge& other) const noexcept { + return !(*this == other); + } + + /// The function this `Edge` points to. + std::shared_ptr function; + + /// The identifier of a particular input to the function. + uint32_t input_nr; +}; +} // namespace torch::autograd + +// The idiomatic way of enabling use of a custom type as the key of hash +// containers in C++11. This method removes the requirement of having to pass +// a custom hasher to std::unordered_{map, set}. +// See http://en.cppreference.com/w/cpp/utility/hash for more information. +namespace std { +template <> +struct hash { + // These type aliases are required by the standard. + using argument_type = torch::autograd::Edge; + using return_type = size_t; + return_type operator()(const argument_type& edge) const noexcept { + return c10::get_hash(edge.function, edge.input_nr); + } +}; +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/engine.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/engine.h new file mode 100644 index 0000000000000000000000000000000000000000..d7c65b90c38412fdb6289591d06fc492d444102b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/engine.h @@ -0,0 +1,294 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// Engine implements backpropagation from output variables and their gradients +// to "root" variables (variables created by the user with requires_grad=True). + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::autograd { +struct ReadyQueue; +} + +namespace torch::autograd { + +// Maximum reentrant backward depth before switching to a new thread +// This limit is based on the TSAN's deadlock detector, where it will +// fail if a program hold more than 65 locks in one thread at once. +// As we hold mutex in every of our custom C++ autograd Node, we would +// like to avoid TSAN complains on this when doing reentrant backwards +// For reference, see https://github.com/google/sanitizers/issues/950 +static constexpr int MAX_DEPTH = 60; + +void set_device(int device); +TORCH_API void validate_outputs( + const edge_list& edges, + variable_list& grads, + const std::function& format_error); +TORCH_API void validate_outputs( + const std::vector>& input_metadata, + variable_list& grads, + const std::function& format_error); +TORCH_API std::vector> collect_input_metadata( + const edge_list& edges); + +struct NodeTask { + std::weak_ptr base_; + std::shared_ptr fn_; + // This buffer serves as an implicit "addition" node for all of the + // gradients flowing here. Once all the dependencies are finished, we + // use the contents of this buffer to run the function. + InputBuffer inputs_; + // When worker receives a task with isShutdownTask = true, it will immediately + // exit. The engine sends a shutdown task to every queue upon its destruction. + bool isShutdownTask_; + + int getReentrantDepth() const; + + NodeTask( + std::weak_ptr base, + std::shared_ptr fn, + InputBuffer inputs, + bool isShutdownTask = false) + : base_(std::move(base)), + fn_(std::move(fn)), + inputs_(std::move(inputs)), + isShutdownTask_(isShutdownTask) {} +}; + +// Guard that sets and restores checkpoint_valid +class CheckpointValidGuard { + public: + explicit CheckpointValidGuard( + const std::shared_ptr& graph_task); + ~CheckpointValidGuard(); + + private: + bool prev_checkpoint_valid_state; +}; + +struct ReadyQueue { + private: + // Returns true when t2 should be (weakly) BEFORE t1 in the queue. + // Shutdown tasks are first and then empty NodeTask are next. + struct CompareNodeTaskTime { + bool operator()(NodeTask const& t1, NodeTask const& t2) { + // NOLINTNEXTLINE(bugprone-branch-clone) + if (t2.isShutdownTask_) { + return true; + } else if (!t1.fn_ || t1.isShutdownTask_) { + return false; + } else if (!t2.fn_) { + return true; + } else if (t1.getReentrantDepth() == t2.getReentrantDepth()) { + return t1.fn_->sequence_nr() < t2.fn_->sequence_nr(); + } else { + return t1.getReentrantDepth() < t2.getReentrantDepth(); + } + } + }; + + // To notify threads waiting on the ReadyQueue of available tasks on the heap_ + std::condition_variable not_empty_; + // To protect read and writes to heap_ + mutable std::mutex mutex_; + + std::priority_queue, CompareNodeTaskTime> + heap_; + + public: + // incrementOutstandingTasks indicates whether or not we should increment + // 'outstanding_tasks_' for the associated GraphTask. This should mostly + // always be true and is only set false in certain cases (see docs for + // DistEngine.execute_graph_task_until_ready_queue_empty) + void push(NodeTask item, bool incrementOutstandingTasks = true); + void pushShutdownTask(); + NodeTask pop(); + bool empty() const; + size_t size() const; +}; + +// A single instance of this struct should be created through the whole process +// lifetime. The worker thread creation logic and Engine's destructor rely on +// this. +struct TORCH_API Engine { + /// Returns a reference to a static `Engine` instance. + static Engine& get_default_engine(); + + static Engine& get_base_engine(); + + // compiled_autograd needs to live in a different .so file so that it + // can have python symbols, so we add a layer of indirection + // see [Note: Compiled Autograd] + typedef variable_list (*compiled_autograd_fn)( + const std::shared_ptr& graph_root, + const GraphTask& graph_task, + bool accumulate_grad, + const edge_list& outputs); + static void set_compiled_autograd(compiled_autograd_fn fn); + + Engine(const Engine&) = delete; + Engine(Engine&&) = delete; + virtual ~Engine(); + + // Given a list of (Node, input number) pairs computes the value of the graph + // by following next_edge references. + virtual variable_list execute( + const edge_list& roots, + const variable_list& inputs, + bool keep_graph, + bool create_graph, + bool accumulate_grad, + const edge_list& outputs = {}); + + // Given a pre-populated GraphTask and GraphRoot, computes the backward pass + // for the graph. + // + // NB: This API should only be used by internal autograd specific + // machinery and shouldn't be exposed to users in anyway. + virtual c10::intrusive_ptr execute_with_graph_task( + const std::shared_ptr& graph_task, + std::shared_ptr graph_root, + InputBuffer&& input_buffer); + + virtual std::unique_ptr make_anomaly_metadata() { + return std::make_unique(); + } + + virtual std::unique_ptr get_default_saved_variable_hooks() { + return nullptr; + } + + // We pass cpu_ready_queue to evaluate_function, so that it knows + // the correct ready queue to push to after a NodeTask is ready + void evaluate_function( + std::shared_ptr& graph_task, + Node* func, + InputBuffer& inputs, + const std::shared_ptr& cpu_ready_queue); + + void initialize_device_threads_pool(); + virtual void thread_on_exception( + const std::shared_ptr& graph_task, + const std::shared_ptr& fn, + std::exception& e); + + void queue_callback(std::function callback); + + bool is_checkpoint_valid(); + + // Should be called after fork to notify that worker threads are gone + void release_workers(); + + // Must be called by subclass before destructing to avoid a data-race-on-vptr. + void stop(); + + // Initializes a device thread for the autograd engine. + virtual void thread_init( + int device, + const std::shared_ptr& ready_queue, + bool should_increment = true); + + protected: + Engine(); + void compute_dependencies(Node* root, GraphTask& task, uint64_t min_topo_nr); + + // initialize the thread local ready queue with the ready queue that is + // created elsewhere (i.e. thread_init, Engine::execute, etc), or create a new + // ready queue if ready_queue is not provided. + void init_local_ready_queue( + std::shared_ptr ready_queue = nullptr); + + std::shared_ptr ready_queue( + std::shared_ptr cpu_ready_queue, + at::Device device); + std::shared_ptr ready_queue_by_index( + std::shared_ptr cpu_ready_queue, + int device_index); + // start device threads (CUDA, XLA, etc.) in Engine, + // note that it does NOT start CPU thread. + void start_device_threads(); + void increment_non_reentrant_thread_count(); + void decrement_non_reentrant_thread_count(); + virtual void thread_main(const std::shared_ptr& task); + void reentrant_thread_init(); + void add_thread_pool_task(const std::weak_ptr& graph_task); + + // Safe to read device_ready_queues_ without synchronization after + // initialization + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::vector> device_ready_queues_; + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::vector> final_callbacks_; + // To protect reads and writes to final_callbacks_ + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::mutex post_callbacks_lock_; + + // How many nested reentrant calls are allowed until a new thread is used + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + int max_recursion_depth_; + + struct ThreadPoolShared { + // Data structures used by the threads for executing reentrant backwards + // tasks. See Note [Reentrant backwards] + // Number of available threads for processing new GraphTasks. + unsigned int num_workers_{0}; + // The threads will wait on work_ to be notified of GraphTasks + std::condition_variable work_; + // To protect reads and writes to graphtask_queue_ and num_workers_ + // and for synchronizing creating new threads when needed + std::mutex mutex_; + // Workers will process the GraphTasks added to this queue. A GraphTask is + // allocated inside Engine::execute and lives for the duration of execute + std::queue> graphtasks_queue_; + + ThreadPoolShared() = default; + }; + + // Temporary workaround until shutting down threads is done + // We need shared ownership of all these objects because the threads are + // leaked when Engine shuts down, so there may be threads waiting on work_ for + // the graphtasks_queue_ to be nonempty. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr thread_pool_shared_; + + private: + // Number of non-reentrant threads + std::atomic non_reentrant_device_thread_count_; + // Destructor will wait for non-reentrant threads to finish + std::condition_variable non_reentrant_device_thread_condvar_; + std::mutex non_reentrant_device_thread_mutex_; + // stop() must be called before the destruction path goes down to the base + // class, in order to avoid a data-race-on-vptr. Use this boolean to guard + // whether stop() has already been called, so we can call this in every + // destructor of the class hierarchy. + bool stopped_{false}; +}; + +// allow python_engine to override the default engine when it loads +using EngineStub = Engine& (*)(); +TORCH_API void set_default_engine_stub(EngineStub stub); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/forward_grad.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/forward_grad.h new file mode 100644 index 0000000000000000000000000000000000000000..e31a4b1031feaf3d795bb3588f50ca76a4990971 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/forward_grad.h @@ -0,0 +1,215 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::autograd { + +// [ Using ForwardGrad ] +// ForwardGrad needs to be a shared_ptr to satisfy constraints of its inner +// design. But this shared_ptr must be uniquely associated with the object that +// stores it (as of writing, either AutogradMeta or SavedVariable). This object +// is called the "owning object" in the discussions below. This owning object +// must call `ForwardGrad::clear()` when it is destroyed to ensure that the +// ForwardGrad is properly de-allocated. + +struct ForwardGrad; + +// This file contains two classes that are used to store forward AD gradients +// and ensure that they are scoped properly. Because forward AD runs +// concurrently with the evaluation of the function, we need a mechanism to +// separate different forward AD invocations and be able to compute the right +// gradients. We model such invocations as levels here. The particular scoping +// issue mentioned above has two main drivers: +// - Ensure that we can conveniently use forward AD within a high level API +// without +// leaking the forward AD states outside. +// - Ensure that we can keep the level that we expose to the user API simple +// (an integer +// that represents the nesting depth) while avoiding confusions when the +// level index is reused. + +// The important external APIs from this file are: +// - ForwardADLevel::get_next_idx() that can be used to enter a new level and +// get its index +// - ForwardADLevel::release_idx() that can be used to exit a given level. +// - ForwardGrad() can be used to store a given forward gradient that will +// handle the level +// tracking automatically. + +// The basic implementation strategy is as follows: +// Every tensor has a ForwardGrad, maintaining a map from levels to tangents. +// ForwardGrad is responsible for registering itself to the appropriate +// ForwardADLevel when a new tangent is added to it via ForwardGrad::set_value +// and to un-register itself from this same level if that tangent is removed via +// ForwardGrad::reset. The ForwardADLevel is created when a new level is entered +// via ForwardADLevel::get_next_idx. A reference to the new ForwardADLevel is +// stored into a global (for the whole process) vector that ensure it can be +// accessed via ForwardADLevel::get_by_idx. This reference is deleted when the +// index is released by the user when calling ForwardADLevel::release_idx. When +// it is destructed, the ForwardADLevel is responsible for clearing all the +// tangents for its level stored in all the ForwardGrad that registered with it. +// +// This process-wide level design, compared to a thread local one, allows us to +// use very simple user facing handle for the level (an int) while enabling +// cross-thread forward AD. The only required synchronization for the user is +// when entering and exiting the levels. Some discussion on alternative design +// is in https://github.com/pytorch/pytorch/pull/49097#discussion_r543716453 and +// can be refined in the future. + +// Correctness of concurrency: +// Each class uses its own lock when reading or modifying internal storages. +// This allows in particular to safely remove tangents from ForwardGrad when the +// ForwardADLevel is being exited. We ensure no deadlock by ensuring that a +// methods never calls into another class's method while the local class's lock +// is held except in one single case: calling from ForwardADLevel's destructor +// into ForwardGrad::reset with update_level=false. + +// The lifetime of these objects is as follows: +// The ForwardADLevel can be in three states: +// - Initialized: where one of its reference is held by the global vector +// and there may be more +// references held by temporary variables in ForwardGrad's methods. +// - About to be destructed: where "release_idx" has been called and the +// only reason for the +// ForwardADLevel not to be destructed right away is that some methods in +// ForwardGrad have owning reference to it. This is done so that a +// ForwardADLevel can never be destructed when a ForwardGrad is +// registered with it and in the process of adding something to its +// internal state. +// - Being destructed: Here the ForwardADLevel is not referenced anymore +// and can be safely reset +// all of the ForwardGrad. Note that we can have more than one reset +// being called here (which is ok) but we are guaranteed that there is at +// least one. +// The ForwardGrad is simpler as there is no intermediary state and no special +// destructor for. The logic to unregister it from the different ForwardADLevel +// is done when the owning object (AutogradMeta or SavedVariable) is being +// destroyed. + +// Other considered design: +// To avoid having the ForwardGrad::clear, we considered storing weak_ptr inside +// the ForwardADLevel. While this would work, it would mean that the set inside +// the ForwardADLevel would only grow unless we do an expensive linear scan to +// remove all the dangling weak pointers. Hence this approach was not used. + +// Data structures in this file are optimized for this maximum number of levels. +// The number of levels corresponds to the degree of the gradient being +// computed using forward AD and we don't expect more than second order +// gradients to be common. +#define EXPECTED_MAX_LEVEL 2 + +struct TORCH_API ForwardADLevel { + ForwardADLevel(uint64_t idx) : idx_(idx) {} + ~ForwardADLevel(); + + static uint64_t get_next_idx(); + static void release_idx(uint64_t idx); + static std::shared_ptr get_by_idx(uint64_t idx); + static std::shared_ptr try_get_by_idx(uint64_t idx); + + void erase(const std::shared_ptr& grad) { + std::lock_guard lock(mutex_); + grads_.erase(grad); + } + + void insert(const std::shared_ptr& grad) { + std::lock_guard lock(mutex_); + grads_.insert(grad); + } + + private: + std::unordered_set> grads_; + std::mutex mutex_; + uint64_t idx_; +}; + +struct TORCH_API ForwardGrad : std::enable_shared_from_this { + ForwardGrad() = default; + + // This function must only be called when AutogradMeta or SavedVariable is + // being destructed as it ensures that: + // - The only (potential) other references to this ForwardGrad are the + // different level it is registered to + // - No other thread will try to call `set_value` or `value` ever from now + // on + // - Any of the ForwardADLevel that this ForwardGrad is registered with + // might + // call `reset` at any point during this function + void clear() { + c10::SmallVector levels_idx; + + { + std::lock_guard lock(mutex_); + for (auto& c : content_) { + levels_idx.push_back(c.first); + } + } + + for (auto l_idx : levels_idx) { + // Use "try" version here as another thread might have deleted this + // level before we got here + // This is an owning reference as we want to keep the level alive + // until we successfully unregister ourselves + auto level = ForwardADLevel::try_get_by_idx(l_idx); + if (level) { + level->erase(shared_from_this()); + } + } + } + + void set_value(const at::Tensor& value, uint64_t level) { + // Owning reference to ensure the forward_level is not destroyed + // while we are updating our internal state + auto forward_level = ForwardADLevel::get_by_idx(level); + forward_level->insert(shared_from_this()); + + std::lock_guard lock(mutex_); + content_.insert({level, value}); + } + + // This function removes the tangent for a given level from this ForwardGrad + // Use the update_level flag to disable notifying the level about this reset + // This flag is most notably used by the ForwardADLevel destructor. + void reset(uint64_t level, bool update_level = true) { + if (update_level) { + ForwardADLevel::get_by_idx(level)->erase(shared_from_this()); + } + + std::unique_lock lock(mutex_); + const auto& it = content_.find(level); + TORCH_INTERNAL_ASSERT( + it != content_.end(), "Resetting a non-existent level."); + // Keep the Tensor alive until we have released the lock + // This is needed as we can be in a case where this function is called by + // ForwardADLevel destructor + auto t = (*it).second; + content_.erase(level); + lock.unlock(); + } + + const at::Tensor& value(uint64_t level) const; + + bool contains(uint64_t level) { + std::lock_guard lock(mutex_); + return content_.count(level) > 0; + } + + bool empty() const { + return content_.empty(); + } + + static const at::Tensor& undef_grad(); + + private: + // TODO(albanD): replace this with a SmallVector + std::unordered_map content_; + mutable std::mutex mutex_; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function.h new file mode 100644 index 0000000000000000000000000000000000000000..73368eb6ddac74d7c4f63fe1a203fbb972d13c9a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function.h @@ -0,0 +1,796 @@ +#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 + +namespace torch::autograd { + +struct Edge; +struct FunctionPostHook; +struct FunctionPreHook; + +using tensor_list = std::vector; +using variable_list = std::vector; +using edge_list = std::vector; +using saved_variable_list = std::vector; +using ivalue_list = std::vector; +using functional_apply_t = std::function< + variable_list(const variable_list&, const std::vector&)>; +using IndexRange = std::pair; +using torch::dynamo::autograd::CompiledNodeArgs; +using torch::dynamo::autograd::PackedArgs; +using torch::dynamo::autograd::SwapSavedVariables; + +// Custom deleter to prevent stack overflows. +TORCH_API void deleteNode(Node* function); + +// Guard that sets and restores the evaluating node +class NodeGuard { + public: + explicit NodeGuard(std::shared_ptr node); + ~NodeGuard(); + + private: + std::shared_ptr last_evaluating_node_; +}; + +// Return the Node currently being evaluated (if any) +// This is only set during the backward pass while a Node is being +// executed. +TORCH_API std::shared_ptr get_current_node(); + +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Node +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// A `Node` is an abstract class that represents an operation taking zero +// or more input `Variable`s and producing zero or more output `Variable`s. All +// functions in PyTorch's autograd machinery derive from this class and +// override its `apply` method. Instances of such subclasses will then be +// invocable via the call operator. +// +// Nodes in the Autograd Graph +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// When viewing the autograd system as a graph, `Node`s are the vertices or +// nodes, connected to each other via (directed) `Edge`s, which themselves are +// represented via (`Node`, input_nr) pairs. `Variable`s are the outputs to +// and inputs of `Node`s, and travel between these edges during execution +// of the graph. When two or more `Edge`s (from different sources) point at the +// same input to a `Node`, the values produced along all of these edges are +// implicitly summed prior to being forwarded to the target `Node`. +// +// Hierarchy +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Subclasses usually represent differentiable functions as well as their +// gradient operators. Note, however, that due to the very general definition +// of a `Node` taking *zero* or more inputs and producing *zero* or more +// outputs, uses of `Node`s are flexible and extend beyond purely +// mathematical operations. For example, the `AccumulateGrad` function is a +// *sink*: it takes one input, but produces no outputs, instead accumulating +// the input as a side effect. At the other extreme, the `GraphRoot` function +// receives no inputs from other functions, but produces multiple outputs. +// +// Interface +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// The most important method on `Node` is the call operator, which takes in +// a list of variables and produces a list of variables. The precise size of +// these lists can be determined with `num_inputs()` and `num_outputs()`. +// `Node`s are stitched together via their `next_edge` interface, which let +// you manipulate the set of outgoing edges of a `Node`. You can add an +// edge with `add_next_edge()`, retrieve an edge with `next_edge(index)` and +// iterate over them via the `next_edges()` method. Other methods exist for +// integration with the JIT and other parts of PyTorch. Every `Node` has a +// *sequence number* that increases monotonically in the order of `Node` +// construction. It can be retrieved via the `sequence_nr()` method. Note that +// this sequence number is *thread local*. This means that when `Node`s +// `A`, `B` and `C` are created consecutively in the same thread, their +// sequence numbers will be ordered `A` < `B` < `C`. If, however, `A` and `B` +// are created in one thread and `C` is created in a new thread, there are *no +// guarantees* w.r.t. the ordering of `C` relative to `A` or `B`. +// See NOTE [ Sequence Number] for more details on the usages of sequence +// number. +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +struct TORCH_API Node : std::enable_shared_from_this { + public: + /// Construct a new `Node` with the given `next_edges` + explicit Node(uint64_t sequence_nr, edge_list&& next_edges = edge_list()) + : sequence_nr_(sequence_nr), next_edges_(std::move(next_edges)) { + for (const Edge& edge : next_edges_) { + update_topological_nr(edge); + } + + if (AnomalyMode::is_enabled()) { + metadata()->store_stack(); + + // If anomaly mode is enabled and graph is constructed, then assign the + // currently evaluating node as the parent of this node. + // A parent is a Node where this Node is created. + // We are tracking the parents to track multiple backward operations. + assign_parent(); + } + + // Store the thread_id of the forward operator. + // See NOTE [ Sequence Numbers ] + thread_id_ = at::RecordFunction::currentThreadId(); + } + + explicit Node(edge_list&& next_edges = edge_list()) + : Node( + /*sequence_nr=*/at::sequence_number::get_and_increment(), + std::move(next_edges)) {} + + /// Nodes are neither copyable nor moveable. + Node(const Node& other) = delete; + Node(Node&& other) = delete; + Node& operator=(const Node& other) = delete; + Node& operator=(Node&& other) = delete; + virtual ~Node() = default; + + std::shared_ptr getptr() { + return shared_from_this(); + } + /// Evaluates the function on the given inputs and returns the result of the + /// function call. + variable_list operator()(variable_list&& inputs) { + // In the first iteration of named tensors, autograd ignores names and + // operates on unnamed tensors. In the long term, autograd should + // probably operate with names. + at::NoNamesGuard no_names_guard; + +#ifdef USE_ROCM + // Keep track of backward pass for rocblas. + at::ROCmBackwardPassGuard in_backward; +#endif + + auto step_callbacks = + at::getStepCallbacksUnlessEmpty(at::RecordScope::BACKWARD_FUNCTION); + if (C10_UNLIKELY(step_callbacks.has_value())) { + at::RecordFunction guard(std::move(*step_callbacks)); + // Using sequence number and thread id to correlate with + // the forward pass function + guard.setForwardThreadId(thread_id_); + if (guard.needsInputs()) { + std::vector inputs_vec(inputs.begin(), inputs.end()); + guard.before( + name(), + c10::ArrayRef( + inputs_vec.data(), inputs_vec.size()), + static_cast(sequence_nr())); + } else { + guard.before(name(), static_cast(sequence_nr())); + } + return apply(std::move(inputs)); + } else { + return apply(std::move(inputs)); + } + } + + // Graph Connectivity API + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // Inputs. NOTE: inputs of the grad_fn correspond to Tensor outputs of the + // forward function. + + // Marker for expected undefined input + struct undefined_input {}; + + /// Adds the type and shape metadata for a new input. Returns the index of + /// of the new input. + uint32_t add_input_metadata( + const at::TensorOptions& options, + c10::SymIntArrayRef shape, + bool is_tensor_subclass, + bool is_nested, + std::optional grad_dtype) noexcept { + uint32_t input_nr = input_metadata_.size(); + auto meta_shape = MetadataShape{std::in_place_type, shape}; + input_metadata_.emplace_back( + options, meta_shape, is_tensor_subclass, is_nested, grad_dtype); + return input_nr; + } + + uint32_t add_input_metadata(const at::Tensor& t) noexcept { + uint32_t input_nr = input_metadata_.size(); + input_metadata_.emplace_back(t); + return input_nr; + } + + /// Adds a placeholder for an input that will not be used. + uint32_t add_input_metadata(undefined_input u) noexcept { + uint32_t input_nr = input_metadata_.size(); + input_metadata_.emplace_back(); + return input_nr; + } + + uint32_t num_inputs() const noexcept { + return input_metadata_.size(); + } + + const InputMetadata& input_metadata(size_t index) const { + return input_metadata_[index]; + } + + // Danger: not thread safe, caller must protect with lock + InputMetadata& mutable_input_metadata(size_t index) { + return input_metadata_[index]; + } + + /** + * Note: Function Streams + * A function's stream (for a given device type) is the stream of the first + * element of its input buffer on a device of that type. + * + * If all elements are on the same device they MUST share a stream. If + * elements are on different devices (across multiple GPUs, for example) + * they may have different streams. + */ + std::optional stream() { + auto opt_device_type = at::getAccelerator(); + if (!opt_device_type.has_value()) { + return std::nullopt; + } + for (const auto& metadata : input_metadata_) { + if (metadata.device().type() == opt_device_type.value()) + return metadata.stream(); + } + + return std::nullopt; + } + + // Used by the engine to determine what device thread to run on + at::Device device() { + // Since we pick the first non-CPU tensor, this won't work with + // mixed device-type operations (e.g., an op that is both CUDA + // and XLA). This is *incredibly* unlikely, so we don't worry + // about it. + for (const auto& metadata : input_metadata_) { + auto device = metadata.device(); + if (device.type() != at::kCPU) { + return device; + } + } + // Only report to the CPU thread if there really were no tensors + // from other devices. + return at::kCPU; + } + + void clear_input_metadata() { + input_metadata_.clear(); + } + + // Outputs ("Next Edges") + + void update_topological_nr(const Edge& edge) { + TORCH_INTERNAL_ASSERT( + !has_parent_, + "Cannot update a node's topological_nr after it already has a parent." + " If we allow this, we can no longer guarantee that a parent's" + " topo_nr is always greater than those of all its children") + Node* node = edge.function.get(); + if (node) { + auto topo_nr = node->topological_nr(); + if (topological_nr_ <= topo_nr) { + topological_nr_ = topo_nr + 1; + } + } + } + + void set_next_edge(size_t index, Edge edge) { + update_topological_nr(edge); + next_edges_[index] = std::move(edge); + } + + void add_next_edge(Edge edge) { + update_topological_nr(edge); + next_edges_.emplace_back(std::move(edge)); + } + + void set_next_edges(edge_list&& next_edges) { + next_edges_ = std::move(next_edges); + for (const auto& next_edge : next_edges_) { + update_topological_nr(next_edge); + } + } + + const Edge& next_edge(size_t index) const noexcept { + return next_edges_[index]; + } + + const edge_list& next_edges() const noexcept { + return next_edges_; + } + + edge_list& next_edges() noexcept { + return next_edges_; + } + + uint32_t num_outputs() const noexcept { + return next_edges_.size(); + } + + // Miscellaneous Methods + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + /// NOTE [ Sequence Number] + /// + /// The sequence_nr has two main usages in autograd: + /// + /// 1) Helps determine the node's execution priority in the engine. + /// All else being equal, nodes with higher priority numbers are executed + /// first. Thus, nodes corresponding to ops executed later are the first to + /// be executed in the backward pass. One caveat is that we prioritize + /// AccumulateGrad nodes by explicitly setting its sequence_nr to be + /// UINT64_MAX. + /// 2) The sequence number of this `Node` is paired with with thread_id it was + /// created in + /// as a unique identifier by the profiler to annotate recorded events. + /// The purpose of this is to help users (and possibly programs) + /// interpreting the profiler's output to correlate backward nodes with its + /// forward ops. We need both sequence_nr and thread_id to identify a node + /// because sequence_nr is thread_local, i.e., starts counting up from zero + /// in a new thread + uint64_t sequence_nr() const noexcept { + return sequence_nr_; + } + + void set_sequence_nr(uint64_t sequence_nr) { + sequence_nr_ = sequence_nr; + } + + // NOTE [ Topological Number ] + // + // topological_nr is used to prune branches in the DAG during autograd + // discovery as maintaining topological_nr helps us check in O(1) if there + // does NOT exist a directed path between two nodes. + // + // The topological order number of this `Node` representing the length of the + // longest possible path from this Node to any leaf node. If you are leaf + // node, aka AccumulateGrad, this will be zero. This value has the property + // that For every pair of nodes X, Y in G, existence of a directed path from X + // to Y implies topo_nr(X) > topo_nr(Y). The converse is not true, however, so + // we cannot prove existence of a path from X to Y, only non-existence. + // + // One assumption we make when using topo_nr is that once a node + // has been used, i.e., has a parent node, its own topo_nr does not change + // we have added some checks with the `has_parent_` field to enforce this. + // + // What NOT to do: + // + // 1) 2 -> 1 -> 0 In this diagram we label nodes with their + // topo_nr. + // 2 -> 1 -> 0 We have two simple graphs that can each + // arise from + // `t.exp().exp()`, for example. + // 2) 2 -> 1 -> 0 + // / + // 2 -> 1 -> 0 We add 2 as a next edge to 1 even though 1 + // already + // has a parent. + // 3) 2 -> 1 -> 0 + // / + // 2 -> 3 -> 0 2 < 3, yet there exists a path from 2 to 3! + // + uint64_t topological_nr() const noexcept { + has_parent_ = true; + return topological_nr_; + } + + // assigning a node as a parent to this node + void assign_parent(); + + /// Id of the thread that created Node + uint64_t thread_id() const noexcept { + return thread_id_; + } + + /// Returns the name of the dynamic type of the function, for debugging. + virtual std::string name() const; + + /// The difference between functions `should_compute_output` and + /// `task_should_compute_output`: + /// - `should_compute_output` should only be used during graph construction + /// and takes into account only requires_grad information + /// - `task_should_compute_output` should only be called during the backward + /// pass (unless called directly through grad_fn) and takes into account the + /// current graph task. Specifically, the autograd engine trims unnecessary + /// edges when `inputs` are specified, and during backward untrimmed nodes + /// left on the graph can/should check `task_should_compute_output` to see if + /// any outgoing edges have been trimmed by the engine. If that is the case, + /// gradient computation wrt those edges can be omitted. + /// + /// Returns true if the particular output edge is active, and that particular + /// output of this function should be computed. + bool should_compute_output(size_t output_edge_index) const { + TORCH_CHECK(output_edge_index < num_outputs(), "Index out of range"); + return next_edges_[output_edge_index].is_valid(); + } + + /// Returns true if any of the output edges in any of the ranges are active. + bool should_compute_output(std::initializer_list idxs) const { + return std::any_of(idxs.begin(), idxs.end(), [this](IndexRange range) { + for (const auto i : c10::irange(range.first, range.second)) { + if (should_compute_output(i)) + return true; + } + return false; + }); + } + + /// Same as the above `should_compute_output` function but will also + /// check whether this edge is needed within the current graph task. + bool task_should_compute_output(size_t output_edge_index) const { + TORCH_CHECK(output_edge_index < num_outputs(), "Index out of range"); + const auto& next = next_edges_[output_edge_index]; + if (next.is_valid()) { + const auto exec_info = get_current_graph_task_exec_info(); + if (exec_info && !exec_info->empty()) { + auto it = exec_info->find(next.function.get()); + if (it == exec_info->end() || !it->second.should_execute()) { + return false; // this edge is not needed for the current graph_task + } + } + return true; + } + return false; + } + + /// Returns true if any of the output edges in any of the ranges are active + /// and should be computed in the current graph task. + bool task_should_compute_output( + std::initializer_list idxs) const { + return std::any_of(idxs.begin(), idxs.end(), [this](IndexRange range) { + for (const auto i : c10::irange(range.first, range.second)) { + if (task_should_compute_output(i)) + return true; + } + return false; + }); + } + + /// Returns the `PyObject` stored for this `Node` (for Python + /// interaction). + PyObject* pyobj() const noexcept { + return pyobj_; + } + + /// Sets the `PyObject` stored for this `Node` (for Python interaction). + void set_pyobj(PyObject* pyobj) noexcept { + pyobj_ = pyobj; + } + + /// Returns the anomaly metadata stored for this `Node`. + /// If none exist, creates a new empty one. + AnomalyMetadata* metadata() noexcept; + + // Hook API + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + uintptr_t add_post_hook(std::unique_ptr&& post_hook) { + post_hooks_.emplace_back(std::move(post_hook)); + // Use the raw pointer as the unique key to identify this hook. This key + // can then be used in del_post_hook(key) to remove this hook. + return reinterpret_cast(post_hooks_.back().get()); + } + + const std::vector>& post_hooks() + const noexcept { + return post_hooks_; + } + + // delete a post hook matching the key + bool del_post_hook(const uintptr_t& key) { + for (auto it = post_hooks_.begin(); it != post_hooks_.end(); ++it) { + if (key == reinterpret_cast(it->get())) { + post_hooks_.erase(it); + return true; + } + } + return false; + } + + std::vector>& post_hooks() noexcept { + return post_hooks_; + } + + void add_pre_hook(std::unique_ptr&& pre_hook) { + pre_hooks_.emplace_back(std::move(pre_hook)); + } + + void add_tensor_pre_hook(std::unique_ptr&& pre_hook) { + tensor_pre_hooks_.emplace_back(std::move(pre_hook)); + } + + void add_retains_grad_hook( + std::unique_ptr&& pre_hook, + size_t output_idx) { + retains_grad_hooks_[output_idx] = std::move(pre_hook); + } + + std::unique_ptr pop_retains_grad_hook(size_t output_idx) { + auto ret = std::move(retains_grad_hooks_[output_idx]); + retains_grad_hooks_.erase(output_idx); + return ret; + } + + const std::vector>& pre_hooks() + const noexcept { + return pre_hooks_; + } + + std::vector>& pre_hooks() noexcept { + return pre_hooks_; + } + + virtual std::vector>& + tensor_pre_hooks() noexcept { + return tensor_pre_hooks_; + } + + virtual std::unique_ptr& tensor_post_acc_grad_hooks() + const noexcept { + static std::unique_ptr empty = nullptr; + return empty; + } + + std::unordered_map>& + retains_grad_hooks() noexcept { + return retains_grad_hooks_; + } + + // Customization Points for Subclasses + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + /// Releases saved variables if the operation won't be reused. + virtual void release_variables() {} + + /// Called before an apply if `release_variables()` is going to be called. + /// Allows larger ops like `InterpreterAutogradFunction` to incrementally + /// release variables as they run. + virtual void will_release_variables() {} + + /// Returns true if this function is traceable. An op is traceable if all + /// operations happening within `apply()` are performed on autograd + /// `Variables` (i.e. apply mostly instantiates and applies other functions). + virtual bool is_traceable() { + return false; + } + + /// A `Node` is said to pass state transparently to backward, if the + /// state consists only of (Saved)Variables and only non-variable objects + /// that parameterize the operation in some way that defines the graph + /// structure AND the backward function is traceable. In particular, + /// parametrization MUST NOT depend on the data of any `Variable`. + /// TODO: it might be possible to handle cases where backward is + /// non-traceable but state passing could be considered transparent. This + /// will probably depend on saved_variable_list being mutable. + /// NOTE: this value matters only if is_traceable() returns false. + virtual bool passes_state_transparently() { + return false; + } + + // see [Note: Compiled Autograd] + // Used by compiled autograd to + // 1) Extract tensors/symint args + // 2) Collect node information for specialization and caching + // Implementations in subclasses should call args.collect() with all node + // attrs. These functions are only called during backward. + virtual void compiled_args(CompiledNodeArgs& args) const { + TORCH_CHECK_NOT_IMPLEMENTED( + false, std::string("compiled_args not implemented: ") + name()); + } + + // Used by compiled autograd to call apply() with different saved tensors + // Implementations should call saved.before() on all attrs, then apply(), then + // saved.after() on all attrs in the same order. + virtual variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) { + TORCH_CHECK_NOT_IMPLEMENTED( + false, std::string("apply_with_saved not implemented: ") + name()); + } + + // If this node is the AOTBackward node produced by torch.compile. + // Compiled Autograd special-cases on this information. + virtual bool is_aot_backward() const { + return false; + } + + protected: + /// Performs the `Node`'s actual operation. + virtual variable_list apply(variable_list&& inputs) = 0; + + /// Calls `apply()`, but instruments it with tracing machinery. + variable_list traced_apply(variable_list inputs); + + // Sequence number used to correlate backward nodes with forward ops in the + // profiler and provide determinism in the engine. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + uint64_t sequence_nr_; + + // See NOTE [ Topological Number ] + uint64_t topological_nr_ = 0; + + // Tracks whether this node has been added as the next_edge of another node + // via set_next_edge(s), which always calls topological_nr() of all its + // children See NOTE [ Topological Number ] for why we need this. + mutable bool has_parent_ = false; + + // Id of the thread that created the instance + uint64_t thread_id_ = 0; + + // Note [Thread Safety on Autograd Node] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Autograd Engine let the owning thread which calls Engine::execute to drive + // the GraphTask execution, there might be cases that part of the GraphTask is + // shared across different `backward()` or `grad()` calls, i.e. fork new + // threads in the middle of the forward and call `backward()` separately from + // different threads. We need to protect the thread safety on NodeTask to + // prevent data racing on shared variables read/write. + // + // NB: This is only needed for Autograd Nodes that runs on CPU, technically + // "CUDA", "XLA" nodes don't need locking because device threads are always + // single threaded. + // + // Here we add a thread mutex to help protect the Node's thread safety, so + // that different threads cannot race the shared data when executing the same + // NodeTask from multiple CPU threads. It IS the user/developer responsibility + // to take advantage of this mutex to protect the thread safety of their + // autograd Node. The general strategy of thread safety on autograd Node: + // + // 1. User should lock the mutex during Node::release_variables() if the Node + // needs + // to release the variables on the fly, this serve the purpose that when we + // release saved_variables from one thread, no other threads can release + // the saved variables concurrently. call the Node::apply(), + // 2. User should lock the mutex during Node::apply(), this is to ensure Node + // that + // writing to the shared variable are not racing across threads (i.e. + // AccumulateGrad and custom C++ Autograd Node if writing to shared + // variables ) + // 3. item 2 and item 3 should work together so that when we release saved + // variables + // from one thread, no other threads can call Node::apply(), this ensures + // the variable references from other threads aren't dangling. + // 4. if the Node don't release any variables and no shared data read/write in + // the Node + // i.e. purely functional, user don't need to lock the mutex + // + // This way we could protect the thread safety on Autograd Node, but we could + // still not protect the thread safety on Node pre/post C++ hooks (python + // hooks are automatically thread safe), we rely on the user to write thread + // safe C++ hooks if they want the hook to be correctly applied in + // multithreading environment. + std::mutex mutex_; + + edge_list next_edges_; + PyObject* pyobj_ = nullptr; // weak reference + std::unique_ptr anomaly_metadata_ = nullptr; + + // NOTE [Hooks ordering] + // We have 3 separate fields for pre hooks registered to the autograd nodes + // because the conditions under which they execute are different, and we + // want more fine-grained control over the order in which different types + // of hooks are executed. + // - pre_hooks are only executed when the node itself is executed + // - tensor_pre_hook is executed as long as the engine traverses over it + // even if that node won't be executed. + // - retains_grad_hook are like tensor_pre_hooks except they are always + // ordered after all other tensor pre hooks + std::vector> pre_hooks_; + std::vector> tensor_pre_hooks_; + std::unordered_map> + retains_grad_hooks_; + std::vector> post_hooks_; + at::SmallVector input_metadata_; +}; + +/// See Node::is_traceable() for definition. +struct TraceableFunction : public Node { + using Node::Node; + bool is_traceable() final { + return true; + } +}; + +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Associated Free Nodes +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +namespace detail { +// Implementation of `collect_next_edges` (see below). +struct MakeNextFunctionList : IterArgs { + edge_list next_edges; + using IterArgs::operator(); + void operator()(const Variable& variable) { + if (variable.defined()) { + next_edges.emplace_back(impl::gradient_edge(variable)); + } else { + next_edges.emplace_back(); + } + } + void operator()(const Variable* variable) { + operator()(*variable); + } + void operator()(const std::optional& variable) { + if (variable.has_value()) { + operator()(*variable); + } else { + next_edges.emplace_back(); + } + } +}; +} // namespace detail + +/// Create an `Edge` between the given `variable` and the `function`, which is +/// assumed to be the gradient function of this variable (i.e. the function +/// through which this variable is backpropagated during the backward pass). +/// This sets the `grad_fn` property of the `variable`. This function assumes +/// that the `Variable` is a new input to the gradient function and its +/// `input_nr` thus equal to `function->num_inputs()`. Additionally, it +/// increments the `Node`'s number of inputs by one. Approximately +/// equivalent to `variable.set_gradient_edge(function, +/// function->add_input_metadata(variable.dispatch_type(), variable.sizes()))`. +/// If you don't want the `Node`'s `num_inputs` to be incremented, use +/// `set_gradient_edge` directly. +inline void create_gradient_edge( + Variable& variable, + std::shared_ptr function) { + // Copy before move. + const auto input_nr = function->add_input_metadata(variable); + impl::set_gradient_edge(variable, {std::move(function), input_nr}); +} + +/// Return true if any of the variables in the list require a gradient. +inline bool any_variable_requires_grad(const variable_list& variables) { + return std::any_of( + variables.begin(), variables.end(), [](const Variable& variable) { + return variable.defined() && variable.requires_grad(); + }); +} + +/// Return the next edges of all the given variables, or tuples of variables. +template +edge_list collect_next_edges(Variables&&... variables) { + detail::MakeNextFunctionList make; + make.apply(std::forward(variables)...); + return std::move(make.next_edges); +} + +struct TypeAndSize { + TypeAndSize() = default; + /* implicit */ + TypeAndSize(const at::Tensor& t) + : sym_sizes(t.sym_sizes().vec()), options(t.options()) {} + + at::Tensor zeros(); + + std::vector sym_sizes; + at::TensorOptions options; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function_hook.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function_hook.h new file mode 100644 index 0000000000000000000000000000000000000000..b5270b6c5d2da5f608938e86bfdf8b7144e8835a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function_hook.h @@ -0,0 +1,77 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::dynamo::autograd { +class CompiledNodeArgs; +class SwapSavedVariables; +struct PackedArgs; +} // namespace torch::dynamo::autograd + +// A hook that's called on gradients + +namespace torch::autograd { + +using Variable = at::Tensor; +using variable_list = std::vector; + +struct TORCH_API FunctionPreHook { + virtual ~FunctionPreHook() = default; + virtual variable_list operator()(const variable_list& grads) = 0; + // only implemented for python hooks, registers hook with compiled autograd + virtual void compiled_args( + torch::dynamo::autograd::CompiledNodeArgs& args) const { + TORCH_CHECK_NOT_IMPLEMENTED( + false, + std::string("compiled_args nyi, see [Note: Compiled Autograd] ") + + typeid(*this).name()); + } +}; + +struct TORCH_API FunctionPostHook { + virtual ~FunctionPostHook() = default; + virtual variable_list operator()( + const variable_list& outputs /* grad_inputs */, + const variable_list& inputs /* grad_outputs */) = 0; + // only implemented for python hooks, registers hook with compiled autograd + virtual void compiled_args( + torch::dynamo::autograd::CompiledNodeArgs& args) const { + TORCH_CHECK_NOT_IMPLEMENTED( + false, + std::string("compiled_args nyi, see [Note: Compiled Autograd] ") + + typeid(*this).name()); + } +}; + +struct TORCH_API PostAccumulateGradHook { + virtual ~PostAccumulateGradHook() = default; + virtual void operator()(const Variable& tensor) = 0; + // only implemented for python hooks on nodes, registers hook with compiled + // autograd + virtual void compiled_args( + torch::dynamo::autograd::CompiledNodeArgs& args) const { + TORCH_CHECK_NOT_IMPLEMENTED( + false, + std::string("compiled_args nyi, see [Note: Compiled Autograd] ") + + typeid(*this).name()); + } + + virtual void apply_with_saved( + Variable& /*unused*/, + torch::dynamo::autograd::SwapSavedVariables& /*unused*/) { + TORCH_CHECK_NOT_IMPLEMENTED( + false, + std::string("compiled_args nyi, see [Note: Compiled Autograd] ") + + typeid(*this).name()); + } +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/comm.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/utils.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/grad_mode.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/grad_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..244205657050b00bb60908f054111f9608ea8b99 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/grad_mode.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::autograd { + +using GradMode = at::GradMode; +using AutoGradMode = at::AutoGradMode; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/graph_task.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/graph_task.h new file mode 100644 index 0000000000000000000000000000000000000000..7c86d7438a020e8f6ebe91d41b32783d03958e60 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/graph_task.h @@ -0,0 +1,234 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include + +namespace torch::autograd { + +using edge_list = std::vector; +struct ReadyQueue; + +static constexpr int NO_DEVICE = -2; +static constexpr int CPU_DEVICE = -1; + +// GraphTask holds metadata needed for a single execution of backward() +struct GraphTask : std::enable_shared_from_this { + std::atomic outstanding_tasks_{0}; + // Indicates if an error occurred while executing any task. When this is + // true, it signals all threads to stop executing. + std::atomic_bool has_error_{false}; + std::atomic_bool future_completed_{false}; + // It is safe to read keep_graph_ without synchronization + bool keep_graph_; + + // To protect reads/writes to not_ready_, dependencies_, captured_vars_, + // has_error_, future_result_, cpu_ready_queue_, and leaf_streams. + std::mutex mutex_; + std::unordered_map not_ready_; + std::unordered_map dependencies_; + + // Records the nodes that are in the graph + std::unordered_set nodes_in_graph_; + c10::SmallVector graph_roots_; + // Note [Exec info] + // Exec info is created for each GraphTask, which allows filtering paths on + // the graph that are not needed. It has a bit complicated semantics. If it's + // empty, it means the task is run in a "default" mode, which means that all + // next_edges we encounter should get executed. If it's not empty, only + // functions that have an entry and this entry has needed == True should be + // executed. exec_info is only empty when the graph is executed via + // .backward() and the inputs parameter is not passed. Otherwise, when + // executed through .grad(), or when inputs arg is specified for .backward(), + // exec_info will be non-empty. + // + struct ExecInfo { + struct Capture { + Capture(const Capture&) = delete; + Capture(Capture&&) = default; + Capture& operator=(const Capture&) = delete; + Capture& operator=(Capture&&) = default; + ~Capture() = default; + + Capture(int input_idx, int output_idx) + : input_idx_(input_idx), output_idx_(output_idx) {} + int input_idx_; // within Node inputs + int output_idx_; // within the output vector of a GraphTask + + // This hook will be executed after a grad is captured. The captured + // grad will be replaced by the return value of the hook. + struct GradCaptureHook { + virtual ~GradCaptureHook() = default; + virtual at::Tensor operator()(const at::Tensor& grad) = 0; + }; + // NOTE [Deprecated capture hooks] + // + // The current status of capture hooks is that we continue to support + // the single usage of it by distributed in the dist_engine. If anyone + // else needs to use it for other purposes, they should file an issue. + // + // Capture hooks were originally created because there did not exist + // any way to register pre/post hooks to grad_fn in a way such that it + // would still be executed even if that is the grad_fn of a Tensor + // passed as input= of .grad. As far as I know, only dist_engine uses + // this hook. + // + // However, there are other alternatives today like tensor hooks that can + // replace the usage that originally motivated its creation. Also, + // Captures hooks are an outlier in terms of the types of hook that + // autograd offers in how it is registered and behaves, e.g. it is a hook + // registered not to the graph, but to a particular graph_task! This makes + // it a burden to maintain. + // + // It would be very nice to clean up/do a migration from pre/post + // hooks used in distributed to use tensor hooks, but for now we just + // mark this method as deprecated to prevent additional usage. + // + // If you still think you really need to capture hooks, please file an + // issue (and tag autograd). + const std::vector>& + DO_NOT_USE_DEPRECATED_get_capture_hooks() const { + return hooks_; + } + // See NOTE [deprecated capture hooks] + void DO_NOT_USE_DEPRECATED_register_capture_hook( + std::unique_ptr hook) { + hooks_.push_back(std::move(hook)); + } + + private: + // The hooks will be called one by one in the order as they were added. + // The input grad of a hook will be the output of its preceding hook. The + // first hook will take the captured grad as the input. The output of the + // last hook will replace the captured grad. + std::vector> hooks_; + }; + + bool should_execute() const { + return needed_ || captures_; + } + + bool needed_ = false; + std::unique_ptr> captures_; + }; + // exec_info_ is safe to read without synchronization + std::unordered_map exec_info_; + // Captures variables are grads captured that we return to the user. After + // execution of the GraphTask is completed, the captured_vars_ are moved + // out of the GraphTask and are no longer valid. + std::vector captured_vars_; + + // Note: this field is not ready to be used until the proper + // `thread_locals_.set_grad_mode()` call in the constructor. + at::ThreadLocalState thread_locals_; + + std::unordered_set leaf_streams; + + // Per-device current streams of the execute() that called this GraphTask. + // These will be synced with leaf_streams in exec_post_processing. + std::vector> caller_current_streams_; + + // Collects caller_current_streams_ for the accelerator device. + void stash_current_streams(); + + void init_to_execute( + Node& graph_root, + const edge_list& outputs, + bool accumulate_grad, + uint64_t min_topo_nr); + + // The value of worker_device in the thread that created this task. + // See Note [Reentrant backwards] + // Safe to read owner_ and reentrant_depth_ without synchronization + int owner_; + // The number of parent graph tasks for this graph task + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const int reentrant_depth_; + + bool can_checkpoint() const { + return exec_info_.empty(); + } + + // check if the GraphTask is completed or not + bool completed(); + // mark the graph task as completed and trigger post processing + void mark_as_completed_and_run_post_processing(); + + // Set an appropriate exception on this graph_task which was encountered while + // running the provided function. + void set_exception(std::exception_ptr eptr, const std::shared_ptr& fn); + + // Set an appropriate exception on this graph_task which was encountered while + // running the provided function. But doesn't signal completion on + // 'future_result_' right away. The user needs to explicitly mark + // 'future_result_' completed with an appropriate exception. + void set_exception_without_signal(const std::shared_ptr& fn); + + // Whether or not to stop execution for this GraphTask when an error is + // encountered. When set to true, this would cause Engine::execute() to throw + // an exception as soon as the autograd engine receives an exception. + bool exit_on_error_; + + // CPU threads are dedicated to processing CPU work for the backward they + // invoked. So any given graph task maintains its own cpu_ready_queue_ where + // you should send work for it to be done. We memoize the cpu_ready_queue_ per + // GraphTask so that we know which ready queue we should push to if we are on + // device thread (i.e. GPU) and but next NodeTask should be run on CPU. + std::shared_ptr cpu_ready_queue_; + + // Future representing the completion of the graph task. Notified when all + // tasks are done. + c10::intrusive_ptr future_result_; + + // Final callbacks installed during execution of this GraphTask + std::vector> final_callbacks_; + // To protect reads and writes to final_callbacks_. Intentionally no reusing + // mutex_ as the two are protecting different data structures. + std::mutex final_callbacks_lock_; + + utils::DelayWarningHandler warning_handler_; + + uint64_t id_; + + GraphTask( + bool keep_graph, + bool grad_mode, + int reentrant_depth, + std::shared_ptr cpu_ready_queue, + c10::SmallVector graph_roots, + bool exit_on_error = false); + + private: + // run GraphTask post processing + void exec_post_processing(); +}; + +// The guard that sets and restores current_graph_task. +class GraphTaskGuard { + public: + explicit GraphTaskGuard(std::shared_ptr graph_task); + ~GraphTaskGuard(); + + void restore_current_graph_task(); + + private: + std::shared_ptr last_graph_task_; +}; + +TORCH_API const std::unordered_map* +get_current_graph_task_exec_info(); +TORCH_API const std::unordered_set* +get_current_graph_task_nodes_in_graph(); +TORCH_API bool get_current_graph_task_keep_graph(); +TORCH_API std::vector get_current_graph_task_execution_order(); +TORCH_API int get_current_graph_task_id(); +void add_node_to_current_graph_task_exec_info(Node* 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_buffer.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..73475e821a81c2473edaf67f47bf538398352e02 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_buffer.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// The InputBuffer class accumulates a list of Variables for use by a +// function. It implements logic to avoid modifying the passed +// values in-place (adding an input twice will accumulate the result). +// This behaviour is needed and used only in backward graphs. + +#include +#include + +#include +#include +#include + +namespace torch::autograd { + +struct InputBuffer { + explicit InputBuffer(size_t size) + : buffer(size), + opt_accum_streams(size), + ready_events(size), + ready_streams(size) {} + InputBuffer(const InputBuffer& other) = delete; + InputBuffer(InputBuffer&& other) = default; + explicit InputBuffer(variable_list&& inputs) : buffer(std::move(inputs)) {} + InputBuffer& operator=(InputBuffer&& other) = default; + + // Accumulates the variable at a specified index. + // The optional CUDA streams determine which stream the accumulation + // is run on and how the addition is synchronized. + TORCH_API void add( + size_t pos, + Variable&& var, + const std::optional& opt_producer_stream, + const std::optional& opt_consumer_stream, + Node* fn); + + Variable operator[](size_t pos) { + return buffer[pos]; + } + + // Returns the inputs as a list of variables. Destroys given InputBuffer. + static std::vector variables(InputBuffer&& g); + + std::vector buffer; + // The stream used for accumulation when a variable is used multiple times. + std::vector> opt_accum_streams; + // The events you need to wait for to ensure the corresponding buffers + // are ready. The events are updated as we accumulate into the buffer. + std::vector> ready_events; + // The streams corresponding to the events above. This is only used to + // check if more synchronization is needed or not. + std::vector> ready_streams; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_metadata.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..efecdefea746139b993c3d29f0052fadaaa35e56 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_metadata.h @@ -0,0 +1,137 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace torch::autograd { + +using SymIntSmallVec = c10::SmallVector; +using MetadataShape = std::variant; + +/** + * Records TensorOptions, shape of the tensor, whether or not the Python + * dispatch key is set (tensor subclass), and, where applicable, the stream the + * corresponding operation took place on. + * + * If is_valid() is false, then the corresponding input is not used and may be + * an undefined tensor. + */ +struct TORCH_API InputMetadata { + InputMetadata() = default; + InputMetadata( + const at::TensorOptions& options, + MetadataShape input_shape, + bool is_tensor_subclass, + bool is_nested, + std::optional grad_dtype); + InputMetadata(const at::Tensor& t); + + const at::TensorOptions& options() const { + return options_; + } + + caffe2::TypeMeta dtype() const { + return options_.dtype(); + } + + at::Device device() const { + return options_.device(); + } + + at::Layout layout() const { + return options_.layout(); + } + + c10::Stream stream() const { + return stream_; + } + + bool is_tensor_subclass() const { + return is_tensor_subclass_; + } + + at::Tensor zeros_like() const; + + bool is_same_shape(const at::Tensor& grad) const; + + bool is_expandable_to_shape(const at::Tensor& grad) const; + + at::Tensor reduce_grad(at::Tensor& grad) const; + + at::Tensor maybe_reduce( + const size_t index, + at::Tensor grad, + const std::function& format_error) const; + + std::stringstream incompatible_shape_error_message( + const size_t index, + const at::Tensor& grad) const; + + bool was_default_constructed() const { + return was_default_constructed_; + } + + bool is_cpp_nested_tensor() const; + + bool is_nested_tensor() const { + return is_nested_; + } + + c10::SymIntArrayRef shape_as_dim_vector() const; + + // Danger: not thread safe, caller must protect with lock + SymIntSmallVec& mutable_shape_as_dim_vector(); + + std::optional grad_dtype() const { + TORCH_INTERNAL_ASSERT(!was_default_constructed_); + return grad_dtype_; + } + + void set_grad_dtype(const std::optional& grad_dtype) { + TORCH_INTERNAL_ASSERT(!was_default_constructed_); + grad_dtype_ = grad_dtype; + } + + private: + at::Tensor shape_as_tensor() const; + bool is_nestedness_same(const at::Tensor& grad) const; + bool maybe_expandable_to(const at::Tensor& grad) const; + + // NB: The engine does not use the dtype from the options, but rather the + // grad_dtype_ field to validate grad_output dtype. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const at::TensorOptions options_; + MetadataShape shape_; + c10::Stream stream_ = c10::Stream(c10::Stream::Default::DEFAULT, device()); + bool is_tensor_subclass_ = false; + bool is_nested_ = false; + bool was_default_constructed_ = true; + + // The grad_dtype_ field is the dtype that the engine expects the grad to be. + // When nullopt, grad_dtype_ is allowed to be any dtype. + // This field is mutated if THPVariable_set_grad_dtype is called + // and the AccumulateGrad has already been created. + std::optional grad_dtype_; +}; +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/jit_decomp_interface.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/jit_decomp_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..89b6d13d1dfb93e71447607858c6990f46c33364 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/jit_decomp_interface.h @@ -0,0 +1,55 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +// NOTE: [Jit Decomposition Interface] +// +// For some context of why we need this at all, see NOTE: [forward-mode AD +// decompositions mechanism] +// +// Introducing that mechanism from the NOTE is problematic because: +// - it relies on TorchScript, so now VariableTypeX.cpp depends on TorchScript. +// - there exist internal builds like lite_trainer, which depend on VariableType +// but do not depend on TorchScript. +// +// For internal builds like lite_trainer builds to pass, and for OSS builds that +// do depend on TorchScript to still support the forward AD decomp mechanism, we +// implement a PImpl pattern to avoid a static dependency in favor of a dynamic +// one +// - during static initialization time, if the library is built with TorchScript +// setJitDecompImpl is called in decomposition_registry.cpp setting a global +// ptr to the impl +// - when the program is run,if getJitDecompImpl returns a non null ptr, we can +// carry on normally, otherwise we gracefully error out +// +// For extra context, see VariableHooksInterface.h, where a similar technique +// is used + +namespace torch::autograd::impl { + +struct TORCH_API JitDecompInterface { + virtual ~JitDecompInterface() = default; + virtual bool has_jit_decomposition( + const c10::FunctionSchema& schema) const = 0; + virtual void run_jit_decomposition( + const c10::OperatorHandle& op, + jit::Stack* stack) const = 0; +}; + +TORCH_API void setJitDecompImpl(JitDecompInterface* impl); +TORCH_API JitDecompInterface* getJitDecompImpl(); + +struct TORCH_API JitDecompRegisterer{explicit JitDecompRegisterer( + JitDecompInterface * impl){setJitDecompImpl(impl); +} // namespace torch::autograd::impl +} +; + +} // namespace torch::autograd::impl + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler.h new file mode 100644 index 0000000000000000000000000000000000000000..8e74893b2cf1cf4c8f49da6d200ec68c0e9f0dcc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler.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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_kineto.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_kineto.h new file mode 100644 index 0000000000000000000000000000000000000000..ac8a73070a5d9f0753103a87d7b33cc98679736a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_kineto.h @@ -0,0 +1,230 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace torch { + +namespace profiler::impl { +struct Result; +namespace kineto { +struct ActivityTraceWrapper; +} // namespace kineto +} // namespace profiler::impl + +namespace autograd::profiler { +using experimental_event_t = std::shared_ptr; +using extra_meta_t = std::unordered_map; + +struct TORCH_API KinetoEvent { + KinetoEvent( + const std::shared_ptr& /*result*/, + const bool verbose); + + uint64_t startThreadId() const; + uint64_t endThreadId() const; + uint8_t activityType() const; + uint64_t fwdThreadId() const; + bool hasShapes() const; + const c10::ArrayRef> shapes() const; + bool hasTypes() const; + const c10::ArrayRef dtypes() const; + bool hasConcreteInputs() const; + const c10::ArrayRef concreteInputs() const; + bool hasKwinputs() const; + bool isHiddenEvent() const; + const std::unordered_map kwinputs() const; + uint64_t flops() const; + int64_t sequenceNr() const; + bool hasStack() const; + const c10::ArrayRef stack() const; + uint8_t scope() const; + bool hasModuleHierarchy() const; + const c10::ArrayRef moduleHierarchy() const; + int64_t debugHandle() const; + std::string name() const; + std::string overload_name() const; + c10::DeviceType deviceType() const; + int deviceIndex() const; + int64_t nBytes() const; + uint64_t startNs() const; + uint64_t endNs() const; + uint64_t durationNs() const; + bool isAsync() const; + uint64_t correlationId() const; + uint64_t linkedCorrelationId() const; + int64_t deviceResourceId() const; + std::string backend() const; + bool isPythonFunction() const; + int64_t cudaElapsedUs() const; + int64_t privateuse1ElapsedUs() const; + void getPerfEventCounters(torch::profiler::perf_counters_t& /*in*/) const; + extra_meta_t extraMeta() const; + std::string metadataJson() const; + + private: + torch::profiler::impl::ProfilerVoidEventStub fallbackStart() const; + torch::profiler::impl::ProfilerVoidEventStub fallbackEnd() const; + + std::shared_ptr result_; + std::vector python_stack_; + + // Copy fields from result so we can return ArrayRefs. + std::vector> shapes_; + std::vector dtypes_; + std::vector concrete_inputs_; + std::unordered_map kwinputs_; +}; + +// Consolidating events returned directly from Kineto +// with events manually created by us (e.g. start/stop marks, +// memory allocation events) +struct TORCH_API ProfilerResult { + ProfilerResult(); + ProfilerResult( + uint64_t start_time, + std::vector events, + std::unique_ptr&& + trace, + std::vector&& event_tree); + ~ProfilerResult(); + + uint64_t trace_start_ns() const { + return trace_start_ns_; + } + + const std::vector& events() const { + return events_; + } + + const std::vector& event_tree() const { + return event_tree_; + } + + void save(const std::string& path); + + private: + uint64_t trace_start_ns_ = 0; + std::vector events_; + std::unique_ptr trace_; + std::vector event_tree_; +}; + +/* + * This API is used by backends to record latency of events that + * happened in the backend but were not visible to pytorch runtime. + * For example, if part of the model is lowered to a dsp backend, then + * the execution of that part of the model is delegated to the backend. + * When backend finishes execution it has an option to provide profiling + * information (latency only at the moment) corresponding to different operators + * that were executed in the backend. + * When such events are recorded by backend using this API, the event + * records will be collected by active kineto profiler. If no kineto profiler + * is active then the event is ignored. + * This provides us with a way to generate all the profiling information + * for a model regardless of where model (or part of it) executed. + * @param start_time_us: start time in us of the event + * @param end_time_us: end time in us of the event + * @param debug_handle: debug handle to correlate this event/op with + * model level module/source information + * @param scope: scope of the event, e.g. LITE_INTERPRETER, RECORD_FN etc. + * @param event_name: name of the event, e.g. op name + * @param backend_name: name of the backend where the event took place. + */ +TORCH_API void reportBackendEventToActiveKinetoProfiler( + const int64_t start_time_us, + const int64_t end_time_us, + const int64_t debug_handle, + const at::RecordScope scope, + const std::string& event_name, + const std::string& backend_name); + +TORCH_API void enableProfiler( + const torch::profiler::impl::ProfilerConfig& config, + const std::set& activities, + const std::unordered_set& scopes = {}); + +/* + * Same as enableProfiler but with callback to do post-processing of + * KinetoEvents. + * enableProfilerWithEventPostProcess enables profiler to capture + * specified activities, with specified RecordFunction scope, if any. + * Additionally, it takes a functor that does in-place post processing of + * events, e.g. populate stack trace or module hierarchy information lazily + * using debug_handle. + * Example usage is with lite interpreter that has recording scope of + * LITE_INTERPRETER. In this case lite interpreter runtime, records debug + * handles in RecordFunction, along with other information. Debug handles are + * eventually passed down to KinetoEvent and recorded as part of the event. + * KinetoEdgeCPUProfiler, in torch/csrc/jit/mobile/profiler_edge.cpp, enables + * profiler using post-processing callback, via + * enableProfilerWithEventPostProcess, that takes these debug handles and + * generates stack trace and module hierarchy information, once profiling is + * done. + */ +using post_process_t = std::function&, + /*jit_modules */ std::vector&)>; +TORCH_API void enableProfilerWithEventPostProcess( + const torch::profiler::impl::ProfilerConfig& config, + const std::set& activities, + post_process_t&& cb, + const std::unordered_set& scopes = {}); + +TORCH_API std::unique_ptr disableProfiler(); + +TORCH_API void prepareProfiler( + const torch::profiler::impl::ProfilerConfig& config, + const std::set& activities); + +TORCH_API void toggleCollectionDynamic( + const bool enable, + const std::set& activities); + +TORCH_API void startMemoryProfile(); +TORCH_API void stopMemoryProfile(); +TORCH_API void exportMemoryProfile(const std::string& path); + +/** + * When a C++ thread really has no control over how the profiler was enabled, + * for example, by some unreachable Python code, it can call these functions + * to test/join/unjoin itself into the collection set of a profiler, if any. + * Without calling these functions, the symptom may be "not seeing GPU events + * from some child C++ threads". This is an example on how to use them, + * + * using namespace torch::autograd::profiler; + * bool enabled = isProfilerEnabledInMainThread(); + * if (enabled != saved_enabled_state) { + * if (enabled) { + * enableProfilerInChildThread(); + * } else { + * disableProfilerInChildThread(); + * } + * saved_enabled_state = enabled; + * } + */ +TORCH_API bool isProfilerEnabledInMainThread(); +TORCH_API void enableProfilerInChildThread(); +TORCH_API void disableProfilerInChildThread(); + +} // namespace autograd::profiler + +namespace profiler::impl { + +// Experimental. +TORCH_API void _reportVulkanEventToProfiler(vulkan_id_t id); + +} // namespace profiler::impl + +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_legacy.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_legacy.h new file mode 100644 index 0000000000000000000000000000000000000000..3f4de054501704034e3d36fccffe29b3b79e8e7c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_legacy.h @@ -0,0 +1,407 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace torch::autograd::profiler { + +enum class C10_API_ENUM EventKind : uint16_t { + Mark, + PushRange, + PopRange, + MemoryAlloc, +}; + +// To be deprecated, once we switch to Kineto profiling +struct TORCH_API LegacyEvent { + LegacyEvent( + EventKind kind, + at::StringView name, + uint16_t thread_id, + bool record_cuda, + at::RecordFunctionHandle handle = 0, + std::vector>&& shapes = {}, + int64_t node_id = -1, + bool is_async = false) + : name_(std::move(name)), + kind_(kind), + thread_id_(thread_id), + handle_(handle), + shapes_(std::move(shapes)), + node_id_(node_id), + is_async_(is_async) { + record(record_cuda); + } + + // Constructor to be used in conjunction with LegacyEvent::fromIValue. + LegacyEvent( + EventKind kind, + at::StringView name, + uint16_t thread_id, + at::RecordFunctionHandle handle, + std::vector>&& shapes, + int64_t node_id, + bool is_remote, + int64_t cpu_memory_usage, + int64_t cpu_ns, + bool cuda_recorded, + int64_t cuda_memory_usage = 0, + c10::DeviceIndex device = -1, + double cuda_us = -1) + : cpu_ns_(cpu_ns), + name_(std::move(name)), + kind_(kind), + thread_id_(thread_id), + handle_(handle), + shapes_(std::move(shapes)), + cpu_memory_usage_(cpu_memory_usage), + cuda_memory_usage_(cuda_memory_usage), + device_(device), + node_id_(node_id), + is_remote_(is_remote), + cuda_us_(static_cast(cuda_us)) { + // Sanity check values that were deserialized + TORCH_INTERNAL_ASSERT(cpu_ns_ > 0); + if (cuda_recorded) { + TORCH_INTERNAL_ASSERT(device_ >= 0); + TORCH_INTERNAL_ASSERT(cuda_us_ >= 0); + } + } + + // Returns IValues corresponding to event structure, to be used for + // serialization. + at::IValue toIValue() const; + + // Reconstructs an event from IValues given by toIValue. + static LegacyEvent fromIValue(const at::IValue& eventIValue); + + void record(bool record_cuda); + + std::string kindStr() const { + switch (kind_) { + case EventKind::Mark: + return "mark"; + case EventKind::PushRange: + return "push"; + case EventKind::PopRange: + return "pop"; + case EventKind::MemoryAlloc: + return "memory_alloc"; + default: + TORCH_CHECK(false, "unknown event kind"); + } + } + + EventKind kind() const { + return kind_; + } + + const char* name() const { + return name_.str(); + } + + uint64_t threadId() const { + return thread_id_; + } + + std::vector> shapes() const { + return shapes_; + } + + double cpuElapsedUs(const LegacyEvent& e) const { + return static_cast(e.cpu_ns_ - cpu_ns_) / 1000.0; + } + + void setCpuUs(int64_t cpu_us) { + cpu_ns_ = cpu_us * 1000; + } + + double cpuUs() const { + return static_cast(cpu_ns_) / 1000.0; + } + + double cudaElapsedUs(const LegacyEvent& e) const; + + bool hasCuda() const { + return cuda_event != nullptr || (isRemote() && device_ != -1); + } + + c10::DeviceIndex device() const { + return device_; + } + + void updateMemoryStats(int64_t alloc_size, c10::Device device) { + if (device.is_cuda() || device.type() == c10::DeviceType::HIP) { + cuda_memory_usage_ = alloc_size; + } else if ( + device.is_cpu() || device.type() == c10::DeviceType::MKLDNN || + device.type() == c10::DeviceType::IDEEP) { + cpu_memory_usage_ = alloc_size; + } else { + LOG(WARNING) << "Unsupported memory profiling device: " << device; + } + } + + int64_t cpuMemoryUsage() const { + return cpu_memory_usage_; + } + + int64_t cudaMemoryUsage() const { + return cuda_memory_usage_; + } + + at::RecordFunctionHandle handle() const { + return handle_; + } + + // Node ID corresponding to this event. + int64_t nodeId() const { + return node_id_; + } + + // Set Node ID on this event. + void setNodeId(int64_t node_id) { + node_id_ = node_id; + } + + void setName(at::StringView newName_) { + name_ = std::move(newName_); + } + + bool isRemote() const { + return is_remote_; + } + + void setCudaUs(int64_t cuda_us) { + cuda_us_ = cuda_us; + } + + void setSequenceNr(int64_t sequence_nr) { + sequence_nr_ = sequence_nr; + } + + int64_t sequenceNr() const { + return sequence_nr_; + } + + void setCorrelationId(uint64_t correlation_id) { + correlation_id_ = correlation_id; + } + + uint64_t correlationId() const { + return correlation_id_; + } + + const std::vector& stack() const { + return stack_; + } + + void setStack(const std::vector& stack) { + stack_ = stack; + } + + uint64_t fwdThreadId() const { + return fwd_thread_id_; + } + + void setFwdThreadId(uint64_t fwd_thread_id) { + fwd_thread_id_ = fwd_thread_id; + } + + uint8_t scope() const { + return scope_; + } + + void setScope(uint8_t scope) { + scope_ = scope; + } + + const std::unordered_map& extraArgs() const { + return extra_args_; + } + + void setExtraArgs(std::unordered_map&& save_args) { + extra_args_ = std::move(save_args); + } + + uint64_t flops() { + return flops_; + } + + bool isAsync() { + return is_async_; + } + + void setFlops(uint64_t flops) { + flops_ = flops; + } + + private: + // signed to allow for negative intervals, initialized for safety. + int64_t cpu_ns_ = 0; + at::StringView name_; + EventKind kind_; + uint64_t thread_id_; + uint64_t fwd_thread_id_{0}; + at::RecordFunctionHandle handle_{0}; + std::vector> shapes_; + int64_t cpu_memory_usage_ = 0; + int64_t cuda_memory_usage_ = 0; + c10::DeviceIndex device_ = -1; + torch::profiler::impl::ProfilerVoidEventStub cuda_event = nullptr; + int64_t node_id_ = 0; + bool is_remote_ = false; + int64_t cuda_us_ = -1; + int64_t sequence_nr_ = -1; + bool is_async_ = false; + + std::vector stack_; + uint8_t scope_{0}; + uint64_t correlation_id_{0}; + // Extra arguments for computing op flops + std::unordered_map extra_args_; + uint64_t flops_ = 0; +}; + +// a linked-list of fixed sized vectors, to avoid +// a std::vector resize from taking a large amount of time inside +// a profiling event +struct RangeEventList { + RangeEventList() { + events_.reserve(kReservedCapacity); + } + + template + void record(Args&&... args) { + std::lock_guard guard(mutex_); + events_.emplace_back(std::forward(args)...); + } + + std::vector consolidate() { + std::lock_guard lock(mutex_); + std::vector result; + result.insert( + result.begin(), + std::make_move_iterator(events_.begin()), + std::make_move_iterator(events_.end())); + events_.erase(events_.begin(), events_.end()); + return result; + } + + size_t size() { + std::lock_guard lock(mutex_); + return events_.size(); + } + + private: + // This mutex is used to serialize access when different threads are writing + // to the same instance of RangeEventList. + std::mutex mutex_; + std::vector events_; + + static const size_t kReservedCapacity = 1024; +}; + +// A struct to control settings of disableProfiler options. +struct TORCH_API ProfilerDisableOptions { + ProfilerDisableOptions() = default; + ProfilerDisableOptions(bool shouldCleanupTLSState, bool shouldConsolidate) + : cleanupTLSState(shouldCleanupTLSState), + consolidate(shouldConsolidate) {} + // Whether we should clean up profiler states that are thread local, such as + // ThreadLocalDebugInfo and thread local RecordFunction callbacks. + bool cleanupTLSState = true; + // Whether we should consolidate all currently recorded profiled events. If + // false, will not consolidate and other threads can continue to write to the + // event lists. + bool consolidate = true; +}; + +// NOTE: profiler mode is thread local, with automatic propagation +// across thread boundary (e.g. at::launch tasks) +TORCH_API void enableProfilerLegacy( + const torch::profiler::impl::ProfilerConfig& /*new_config*/); +using thread_event_lists = std::vector>; +TORCH_API thread_event_lists disableProfilerLegacy( + std::optional profilerDisableOptions = + std::nullopt); + +// adds profiledEvents to the current thread local recorded events. Each event +// will be marked with node ID given by fromNodeId. +TORCH_API void addEventList(std::vector&& profiledEvents); +// Writes profiled events to a stream. +TORCH_API void writeProfilerEventsToStream( + std::ostream& out, + const std::vector& events); + +// Usage: +// { +// RecordProfile guard("filename.trace"); +// // code you want to profile +// } +// Then open filename.trace in chrome://tracing +struct TORCH_API RecordProfile { + RecordProfile(std::ostream& out); + RecordProfile(const std::string& filename); + + ~RecordProfile(); + + private: + void init(); + std::unique_ptr file_; + std::ostream& out_; + void processEvents(const std::vector& events); +}; + +// A guard that enables the legacy profiler, taking in an optional callback to +// process the results Usage: +// { +// TLSLegacyProfilerGuard g([](thread_event_lists profilerResults) { +// // process profilerResults +// }); +// Code to profile +// } +struct TORCH_API TLSLegacyProfilerGuard { + explicit TLSLegacyProfilerGuard( + const torch::profiler::impl::ProfilerConfig& cfg, + std::optional> + resultCallback = std::nullopt, + std::optional profilerDisableOptions = + std::nullopt) + : cb_(std::move(resultCallback)), + profilerDisableOptions_(profilerDisableOptions) { + enableProfilerLegacy(cfg); + } + ~TLSLegacyProfilerGuard() { + thread_event_lists event_lists = + disableProfilerLegacy(profilerDisableOptions_); + if (cb_) { + try { + (*cb_)(event_lists); + } catch (const std::exception& e) { + LOG(ERROR) << "Got error processing profiler events: " << e.what(); + } + } + } + + private: + std::optional> cb_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional profilerDisableOptions_; +}; + +} // namespace torch::autograd::profiler + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_python.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_python.h new file mode 100644 index 0000000000000000000000000000000000000000..d0be6b9a6c11b0aa4755e7568c040d1a2ad225af --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_python.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::autograd::profiler::python_tracer { + +void init(); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_anomaly_mode.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_anomaly_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..c110e07ae1967629270138b13d6db02af74eda84 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_anomaly_mode.h @@ -0,0 +1,48 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::autograd { + +struct PyAnomalyMetadata : public AnomalyMetadata { + static constexpr const char* ANOMALY_TRACE_KEY = "traceback_"; + static constexpr const char* ANOMALY_PARENT_KEY = "parent_"; + + PyAnomalyMetadata() { + pybind11::gil_scoped_acquire gil; + // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer) + dict_ = PyDict_New(); + } + // NOLINTNEXTLINE(bugprone-exception-escape) + ~PyAnomalyMetadata() override { + // If python is already dead, leak the wrapped python objects + if (Py_IsInitialized()) { + pybind11::gil_scoped_acquire gil; + Py_DECREF(dict_); + } + } + void store_stack() override; + void print_stack(const std::string& current_node_name) override; + void assign_parent(const std::shared_ptr& parent_node) override; + + PyObject* dict() { + return dict_; + } + + private: + PyObject* dict_{nullptr}; +}; +void _print_stack( + PyObject* trace_stack, + const std::string& current_node_name, + bool is_parent); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_autograd.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..67eb992d88767907fea1bdd02d0177c1c028f164 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_autograd.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#ifndef THP_AUTOGRAD_H +#define THP_AUTOGRAD_H +#include + +PyObject* THPAutograd_initExtension(PyObject* _unused, PyObject* unused); +void THPAutograd_initFunctions(); + +namespace torch::autograd { + +PyMethodDef* python_functions(); + +} + +#include +#include +#include + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_cpp_function.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_cpp_function.h new file mode 100644 index 0000000000000000000000000000000000000000..2c0ba68e1953695bc79163c0e6db0db5416203d8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_cpp_function.h @@ -0,0 +1,136 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::autograd { + +struct THPCppFunction { + PyObject_HEAD + std::shared_ptr cdata; +}; + +template +TORCH_PYTHON_API PyObject* CppFunction_pynew( + PyTypeObject* type, + PyObject* args, + PyObject* kwds) { + THPObjectPtr obj(type->tp_alloc(type, 0)); + if (!obj) + return nullptr; + THPCppFunction* f = (THPCppFunction*)obj.get(); + HANDLE_TH_ERRORS + new (&f->cdata) std::shared_ptr(Ctor()(args)); + END_HANDLE_TH_ERRORS + if (!f->cdata) { + return nullptr; + } + return obj.release(); +} + +#define THP_FUNCTION_DEFAULT_METHODS \ + {(char*)"_register_hook_dict", \ + THPCppFunction_register_hook_dict, \ + METH_O, \ + nullptr}, \ + {(char*)"register_hook", THPCppFunction_register_hook, METH_O, nullptr}, \ + {(char*)"register_prehook", \ + THPCppFunction_register_prehook, \ + METH_O, \ + nullptr}, \ + {(char*)"name", THPCppFunction_name, METH_NOARGS, nullptr}, \ + {(char*)"_sequence_nr", \ + THPCppFunction_sequence_nr, \ + METH_NOARGS, \ + nullptr}, \ + { \ + (char*)"_set_sequence_nr", THPCppFunction_set_sequence_nr, METH_O, nullptr \ + } + +#define THP_FUNCTION_DEFAULT_PROPERTIES \ + {(char*)"next_functions", \ + THPCppFunction_next_functions, \ + nullptr, \ + nullptr, \ + nullptr}, \ + {(char*)"requires_grad", \ + THPCppFunction_requires_grad, \ + nullptr, \ + nullptr, \ + nullptr}, \ + {(char*)"metadata", THPCppFunction_metadata, nullptr, nullptr, nullptr}, \ + { \ + (char*)"_input_metadata", THPCppFunction_input_metadata, nullptr, nullptr, \ + nullptr \ + } + +TORCH_PYTHON_API PyObject* THPCppFunction_next_functions( + PyObject* self, + void* _unused); +TORCH_PYTHON_API PyObject* THPCppFunction_metadata( + PyObject* self, + void* _unused); +TORCH_PYTHON_API PyObject* THPCppFunction_requires_grad( + PyObject* self, + void* _unused); +TORCH_PYTHON_API PyObject* THPCppFunction_register_hook_dict( + PyObject* self, + PyObject* _var); +TORCH_PYTHON_API PyObject* THPCppFunction_register_hook( + PyObject* self, + PyObject* hook); +TORCH_PYTHON_API PyObject* THPCppFunction_register_prehook( + PyObject* self, + PyObject* hook); + +TORCH_PYTHON_API PyObject* THPCppFunction_name( + PyObject* self, + PyObject* noargs); +TORCH_PYTHON_API PyObject* THPCppFunction_sequence_nr( + PyObject* self, + PyObject* noargs); +TORCH_PYTHON_API PyObject* THPCppFunction_input_metadata( + PyObject* self, + void* _unused); + +TORCH_PYTHON_API PyTypeObject* _initFunctionPyTypeObject( + PyTypeObject& type, + const char* name, + PyGetSetDef* function_properties, + PyMethodDef* function_methods); + +TORCH_PYTHON_API PyObject* registerFunctionHook(Node& fn, PyObject* hook); + +TORCH_PYTHON_API PyObject* registerFunctionPreHook(Node& fn, PyObject* hook); + +template +TORCH_PYTHON_API PyTypeObject* createForwardFunctionPyTypeObject( + PyTypeObject& type, + const char* name, + PyGetSetDef* function_properties = nullptr, + PyMethodDef* function_methods = nullptr) { + type.tp_new = &CppFunction_pynew; + return _initFunctionPyTypeObject( + type, name, function_properties, function_methods); +} + +TORCH_PYTHON_API void registerCppFunction( + const std::type_info& type, + PyTypeObject* pytype); +TORCH_PYTHON_API PyObject* functionToPyObject( + const std::shared_ptr& cdata); + +TORCH_PYTHON_API bool THPCppFunction_Check(PyObject* obj); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_engine.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..e0652bd0f9964ac9213e7f1225b2e8fbff998ac0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_engine.h @@ -0,0 +1,49 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +bool THPEngine_initModule(PyObject* module); + +namespace torch::autograd::python { + +struct PythonEngine : public Engine { + static Engine& get_python_engine(); + ~PythonEngine() override; + void thread_init( + int device, + const std::shared_ptr& ready_queue, + bool should_increment) override; + void thread_on_exception( + const std::shared_ptr& graph_task, + const std::shared_ptr& fn, + std::exception& e) override; + variable_list execute( + const edge_list& roots, + const variable_list& inputs, + bool keep_graph, + bool create_graph, + bool accumulate_grad, + const edge_list& outputs = {}) override; + + c10::intrusive_ptr execute_with_graph_task( + const std::shared_ptr& graph_task, + std::shared_ptr graph_root, + InputBuffer&& input_buffer) override; + + std::unique_ptr make_anomaly_metadata() override; + std::unique_ptr get_default_saved_variable_hooks() + override; + + private: + PythonEngine(); +}; + +} // namespace torch::autograd::python + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_enum_tag.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_enum_tag.h new file mode 100644 index 0000000000000000000000000000000000000000..6f66f41d10d49dd13ce00589017ef623699e9c88 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_enum_tag.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::autograd { +void initEnumTag(PyObject* module); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_fft_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_fft_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..284a7153e02bde767a1fb6b08266f298d6694ef3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_fft_functions.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::autograd { + +void initFFTFunctions(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_function.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_function.h new file mode 100644 index 0000000000000000000000000000000000000000..1c44b1dfb64e98cd8e53d3022a9c2c428349d7c7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_function.h @@ -0,0 +1,160 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace torch::jit { +struct Graph; +} + +namespace torch::autograd { + +// A Function which is implemented by a Python object (i.e., a THPFunction). +// Calls to 'apply' are forwarded to the Python method implementation. +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) +struct PyNode : public Node { + PyNode(THPObjectPtr obj) : obj(obj.release()) {} + + PyObject* to_py_args( + const variable_list& inputs, + at::OptionalDeviceGuard* device_guard); + variable_list to_variable_list( + const PyObject* r, + const std::vector& is_variable_input); + + variable_list apply(variable_list&& inputs) override; + variable_list apply_with_saved_impl( + const variable_list& inputs, + const SwapSavedVariables& saved); + + void release_variables() override; + std::string name() const override; + bool is_traceable() override; + + bool is_aot_backward() const override; + + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved( + const variable_list& inputs, + SwapSavedVariables& saved) override; + + // THPFunction this Function is wrapping. Owning! + PyObject* obj; + + // NOLINTNEXTLINE(bugprone-exception-escape) + ~PyNode() override { + // Can't use THPObjectPtr as a field in this class; destructor won't take + // out GIL! When I forgot to do this by hand + // TestAutograd.test_inplace_view_python called me out about it. + // If python is already dead, leak the wrapped python objects + if (Py_IsInitialized()) { + pybind11::gil_scoped_acquire gil; + Py_DECREF(obj); + } + } +}; + +/** + * Cast an object into a tuple, if it is not a tuple already. Returns true + * if the original object was not a tuple. + */ +inline bool ensure_tuple(THPObjectPtr& obj) { + if (PyTuple_Check(obj.get())) + return false; + + PyObject* tuple = PyTuple_New(1); + if (!tuple) + throw python_error(); + PyTuple_SET_ITEM(tuple, 0, obj.release()); + obj = tuple; + return true; +} + +} // namespace torch::autograd + +// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) +struct THPFunction { + PyObject_HEAD + + PyObject* needs_input_grad; + + // Python tuple of tensors whose variables we should save. Set + // by Python with 'save_for_backward'. If nullptr, no tensors were + // saved. + PyObject* to_save; + // Python tuple of tensors which are not differentiable. Set by + // Python with 'mark_non_differentiable'. If nullptr, no tensors were + // non-differentiable. + PyObject* non_differentiable; + // Python tuple of tensors which had inplace updates in the forward() + // pass. Set by Python with 'mark_dirty'. If nullptr, no tensors were + // modified inplace. + PyObject* dirty_tensors; + + // boolean indicating whether to materialize undefined output grad tensors + // into tensors full of zeros. Set by Python with 'set_materialize_grads'. + // Default is true. + bool materialize_grads; + + // boolean indicating whether the function is a "pure view", meaning that + // replaying the view is enough to get a correct backward. + bool pure_view; + + // boolean indicating whether to materialize output grad tensors + // corresponding to non-differentiable outputs. Normally, someone would + // already get this behavior by switching off materialize_grads, + // but there are certain use cases where that is not feasible: + // https://github.com/pytorch/pytorch/pull/98659#pullrequestreview-1376822560 + bool materialize_non_diff_grads; + + PyObject* compiled_autograd_backward_state; + std::vector compiled_autograd_symints; + + std::vector output_info; + std::vector input_info; + std::vector saved_variables; + // For each input, true if the input is a THPVariable + std::vector is_variable_input; + char has_freed_buffers; + + PyObject* saved_for_forward; + // The actual PyNode (in the autograd graph) that this data was + // saved for. This field may be NULL (because a user can construct + // a THPFunction directly from Python), but when this field is non-NULL, + // it is guaranteed that cdata.lock()->obj == this + // + // In most ordinary use, this field should always be non-NULL; e.g., + // when we allocate a THPFunction because we are running Node.apply, + // after constructing a THPFunction, we immediately allocate a PyNode + // for it. We can't enforce this directly in the constructor of + // THPFunction though, because there's no way to keep it live long enough + // to save an owning reference to PyNode into the grad_fn of a Variable. + std::weak_ptr cdata; +}; + +bool THPFunction_initModule(PyObject* module); +TORCH_PYTHON_API extern PyTypeObject THPFunctionType; +TORCH_PYTHON_API extern PyObject* THPFunctionClass; +TORCH_PYTHON_API extern PyObject* THPGradientEdgeClass; + +inline bool THPFunction_Check(PyObject* obj) { + return PyObject_IsInstance(obj, (PyObject*)&THPFunctionType); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_hook.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_hook.h new file mode 100644 index 0000000000000000000000000000000000000000..d320b940c8645fe4c4b7912efcf363bee25c42cb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_hook.h @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::dynamo::autograd { +class SwapSavedVariables; +} // namespace torch::dynamo::autograd + +namespace torch::autograd { + +struct PyFunctionTensorPreHook : public FunctionPreHook { + PyFunctionTensorPreHook(PyObject* dict, size_t value_idx); + ~PyFunctionTensorPreHook() override; + variable_list operator()(const variable_list& values) override; + void compiled_args( + torch::dynamo::autograd::CompiledNodeArgs& args) const override; + PyObject* dict; + size_t value_idx; +}; + +struct PyFunctionPreHook : public FunctionPreHook { + PyFunctionPreHook(PyObject* dict); + ~PyFunctionPreHook() override; + variable_list operator()(const variable_list& values) override; + void compiled_args( + torch::dynamo::autograd::CompiledNodeArgs& args) const override; + PyObject* dict; +}; + +struct PyFunctionPostHook : public FunctionPostHook { + PyFunctionPostHook(PyObject* dict); + ~PyFunctionPostHook() override; + variable_list operator()( + const variable_list& outputs, + const variable_list& inputs) override; + void compiled_args( + torch::dynamo::autograd::CompiledNodeArgs& args) const override; + PyObject* dict; +}; + +// PyFunctionTensorPostAccGradHooks is a dictionary of PostAccumulateGradHooks, +// and it is understandable if you are confused by why it's a subclass. We are +// simply following the precedent of PyFunctionPreHook and PyFunctionPostHook +// above to easily enroll into existing infrastructure. +struct PyFunctionTensorPostAccGradHooks : public PostAccumulateGradHook { + PyFunctionTensorPostAccGradHooks(PyObject* dict); + ~PyFunctionTensorPostAccGradHooks() override; + void operator()(const Variable& tensor) override; + void compiled_args( + torch::dynamo::autograd::CompiledNodeArgs& args) const override; + void apply_with_saved( + Variable& tensor, + torch::dynamo::autograd::SwapSavedVariables& saved) override; + PyObject* dict; +}; + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_legacy_variable.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_legacy_variable.h new file mode 100644 index 0000000000000000000000000000000000000000..10b316d8bbe5c410a4a16e5c1fef43e0e2547381 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_legacy_variable.h @@ -0,0 +1,17 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// Instantiates torch._C._LegacyVariableBase, which defines the Python +// constructor (__new__) for torch.autograd.Variable. + +#include + +namespace torch::autograd { + +void init_legacy_variable(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_linalg_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_linalg_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..106b7a917e45d950f033070686af5110d557595f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_linalg_functions.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::autograd { + +void initLinalgFunctions(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_nested_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_nested_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..27eacb5d09e6a3674e33f3e8ba8c4df3bccbad6c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_nested_functions.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +namespace torch::autograd { + +PyMethodDef* get_nested_functions_manual(); + +void initNestedFunctions(PyObject* module); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_nn_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_nn_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..41b2f582b7bca8de05c2adc0ec5bd77ae3b021f7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_nn_functions.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +namespace torch::autograd { + +void initNNFunctions(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_saved_variable_hooks.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_saved_variable_hooks.h new file mode 100644 index 0000000000000000000000000000000000000000..6fd2786d08f75da939f8952f4486efb3eba7a779 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_saved_variable_hooks.h @@ -0,0 +1,41 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace py = pybind11; + +namespace torch::autograd { + +struct PySavedVariableHooks : public SavedVariableHooks { + PySavedVariableHooks(py::function& pack_hook, py::function& unpack_hook); + void call_pack_hook(const at::Tensor& tensor) override; + at::Tensor call_unpack_hook() override; + ~PySavedVariableHooks() override; + std::optional> + retrieve_unpack_hook_data() const override; + + private: + PyObject* pack_hook_; + PyObject* unpack_hook_; + PyObject* data_ = nullptr; +}; + +struct PyDefaultSavedVariableHooks { + static void push_hooks(py::function& pack_hook, py::function& unpack_hook); + static void pop_hooks(); + static std::unique_ptr get_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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_sparse_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_sparse_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..d580889f93433385c826a9e5ae9c17ddfa7d872b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_sparse_functions.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::autograd { + +void initSparseFunctions(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_special_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_special_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..76afa413d82d9758dff1a34f0575e53b940cf6df --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_special_functions.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +namespace torch::autograd { + +void initSpecialFunctions(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_torch_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_torch_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..13557fe6f7e85f047bf02b8eb78146406b4e2ca6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_torch_functions.h @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::autograd { + +extern PyObject* THPVariableFunctionsModule; + +// Wrapper converts a raised TypeError into returning NotImplemented +// Used to implement binary arithmetic operators +template +inline PyObject* TypeError_to_NotImplemented_( + PyObject* self, + PyObject* args, + PyObject* kwargs) { + PyObject* ret = Func(self, args, kwargs); + if (!ret && PyErr_ExceptionMatches(PyExc_TypeError)) { + PyErr_Clear(); + Py_INCREF(Py_NotImplemented); + ret = Py_NotImplemented; + } + return ret; +} + +void initTorchFunctions(PyObject* module); + +} // 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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_variable.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_variable.h new file mode 100644 index 0000000000000000000000000000000000000000..8f04b42703978cc3bd3405ee3b364002f7f9ad03 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_variable.h @@ -0,0 +1,132 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace py = pybind11; + +// Python object that backs torch.autograd.Variable +struct THPVariable { + PyObject_HEAD + // Payload + at::Tensor cdata; + // Hooks to be run on backwards pass (corresponds to Python attr + // '_backwards_hooks', set by 'register_hook') + PyObject* backward_hooks = nullptr; + // Hooks to be run in the backwards pass after accumulate grad, + // i.e., after the .grad has been set (corresponds to Python attr + // '_post_accumulate_grad_hooks', set by 'register_post_accumulate_grad_hook') + PyObject* post_accumulate_grad_hooks = nullptr; +}; + +TORCH_PYTHON_API void registerPythonTensorClass( + const std::string& device, + PyObject* python_tensor_class); + +TORCH_PYTHON_API void activateGPUTrace(); + +TORCH_PYTHON_API extern PyObject* THPVariableClass; +TORCH_PYTHON_API extern PyObject* ParameterClass; + +bool THPVariable_initModule(PyObject* module); +TORCH_PYTHON_API PyObject* THPVariable_Wrap(at::TensorBase&& var); +TORCH_PYTHON_API PyObject* THPVariable_Wrap(const at::TensorBase& var); +TORCH_PYTHON_API PyObject* THPVariable_Wrap( + const at::TensorBase& var, + PyTypeObject* type); + +inline bool THPVariable_CheckTypeExact(PyTypeObject* tp) { + // Check that a python object is a `Tensor`, but not a `Tensor` subclass. + // (A subclass could have different semantics.) The one exception is + // Parameter, which is used for Python bookkeeping but is equivalent to + // Tensor as far as C++ is concerned. + return ( + tp == (PyTypeObject*)THPVariableClass || + tp == (PyTypeObject*)ParameterClass); +} + +inline bool THPVariable_CheckExact(PyObject* obj) { + return THPVariable_CheckTypeExact(Py_TYPE(obj)); +} + +inline bool THPVariable_Check(PyObject* obj) { + if (!THPVariableClass) + return false; + + // Fast path + if (THPVariable_CheckExact(obj)) { + return true; + } + + const auto result = PyObject_IsInstance(obj, THPVariableClass); + if (result == -1) + throw python_error(); + return result; +} + +inline const at::Tensor& THPVariable_Unpack(THPVariable* var) { + return var->cdata; +} + +inline const at::Tensor& THPVariable_Unpack(PyObject* obj) { + return THPVariable_Unpack(reinterpret_cast(obj)); +} + +std::pair parseIValuesToPyArgsKwargs( + const c10::OperatorHandle& op, + const std::vector& arguments); + +void pushPyOutToStack( + const c10::OperatorHandle& op, + torch::jit::Stack* stack, + py::object out, + const char* msg); + +py::handle get_dtensor_class(); + +py::object dispatchDTensorOp( + const c10::OperatorHandle& op, + py::handle py_op, + py::handle args, + py::handle kwargs, + torch::jit::Stack* stack); + +inline PyObject* THPVariable_WrapList( + const torch::autograd::variable_list& inputs) { + PyObject* pyinput = PyList_New(static_cast(inputs.size())); + for (const auto i : c10::irange(inputs.size())) { + PyList_SET_ITEM(pyinput, i, THPVariable_Wrap(inputs[i])); + } + return pyinput; +} + +inline torch::autograd::variable_list THPVariable_UnpackList( + PyObject* pyresult) { + TORCH_CHECK(PyList_CheckExact(pyresult)); + auto result_len = PyList_GET_SIZE(pyresult); + torch::autograd::variable_list result; + result.reserve(result_len); + for (const auto i : c10::irange(result_len)) { + PyObject* item = PyList_GET_ITEM(pyresult, i); + if (!Py_IsNone(item)) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(THPVariable_Check(item)); + result.emplace_back(THPVariable_Unpack(item)); + } else { + result.emplace_back(); + } + } + return result; +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/python_variable_indexing.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/record_function_ops.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/saved_variable.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/saved_variable_hooks.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/symbolic.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/symbolic.h new file mode 100644 index 0000000000000000000000000000000000000000..62e235e5f4ef304d86cbe6155b3c228bd8d7d1c8 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/error_messages.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/grad_layout_contract.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/lambda_post_hook.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/python_arg_parsing.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/warnings.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/utils/wrap_outputs.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable.h new file mode 100644 index 0000000000000000000000000000000000000000..a2282a184d36df55656b102e2dd9cb094d96f24a --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/variable_info.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cpu/Module.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cpu/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..debcbb08d142cbfdf7aeddf7e4cff4bc2e67bcc9 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..d2fc6195e20d0c9b9c3548917c8310ac6c15ba34 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Event.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Event.h new file mode 100644 index 0000000000000000000000000000000000000000..2ce6656b45470bedd99022f77fac4fccadf92478 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/GdsFile.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/GdsFile.h new file mode 100644 index 0000000000000000000000000000000000000000..231e335875e3da19689f3e5675a1c7bbfd8b9052 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Module.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..53aeb483bb8a3c0fa3746901aec785d2b5984074 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Stream.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Stream.h new file mode 100644 index 0000000000000000000000000000000000000000..a391e9e519d82106cbe7d21236fe7d49be43c5eb --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/THCP.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/THCP.h new file mode 100644 index 0000000000000000000000000000000000000000..f6a031a30bd634229250b0b41ca6ab19e924cbb2 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/comm.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/comm.h new file mode 100644 index 0000000000000000000000000000000000000000..dffa548a07a51025cd39231c90399b89b3211c9c --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/device_set.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/memory_snapshot.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/nccl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/nccl.h new file mode 100644 index 0000000000000000000000000000000000000000..f7970e441d853f97c27c29fc824a306eeac217dc --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_comm.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_nccl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..3803c7c90e18edb3ca4138105aa8669539c113c9 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/Placement.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/Placement.h new file mode 100644 index 0000000000000000000000000000000000000000..70bc90c0f0c47908103ddefbe58468774fbcc628 --- /dev/null +++ b/miniconda3/envs/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/autograd.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/container.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/engine/dist_engine.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/sendrpc_backward.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/python_autograd.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_req.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_autograd.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_req.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/utils.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Backend.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Backoff.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FakeProcessGroup.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FileStore.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FlightRecorder.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/FlightRecorderDetail.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Functional.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/GlooDeviceFactory.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/GroupRegistry.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/HashStore.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/NCCLUtils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/NanCheck.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ParamCommsUtils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/PrefixStore.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroup.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGloo.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGlooDetail.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupMPI.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupUCC.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/PyProcessGroup.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Store.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStoreBackend.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TraceUtils.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCTracing.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UnixSockUtils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Utils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_collectives/ControlCollectives.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_collectives/StoreCollectives.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/Handlers.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/WaitCounterHandler.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/control_plane/WorkerServer.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/CUDAEventCache.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/StreamBlock.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/cuda/utils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/debug.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/default_comm_hooks.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/error.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/logger.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/logging.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/python_callback_work.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/python_comm_hook.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization_gpu.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/quantization/quantization_utils.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/reducer.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/reducer_timer.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket_fmt.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory-inl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryTypes.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryUtils.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/DMAConnectivity.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/SymmetricMemory.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/env.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/intra_node_comm.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/symm_mem/nvshmem_team_manager.hpp b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/python_placement.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/message.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/py_rref.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h b/miniconda3/envs/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h b/miniconda3/envs/ladir/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/ladir/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)